fix search

This commit is contained in:
natib21
2026-07-17 15:01:30 +00:00
parent a29689772b
commit 6ee771c953
8 changed files with 89 additions and 28 deletions

View File

@@ -44,13 +44,13 @@ export class SeedEdrWagonFleetErNumbering2260000000000 implements MigrationInter
// train_set_wagons null their link, wagon_movements cascade.
await queryRunner.query(`DELETE FROM freight.wagons;`);
// Wagon.wagonNumber declares `unique: true`, but some environments never got
// the constraint. Repair it here — the table is empty at this point, so the
// index build cannot fail on pre-existing duplicates.
await queryRunner.query(`
CREATE UNIQUE INDEX IF NOT EXISTS wagons_wagon_number_key
ON freight.wagons (wagon_number);
`);
// Deliberately does NOT create a unique index on wagon_number. It once did,
// to satisfy an ON CONFLICT clause that no longer exists (the DELETE above
// makes collisions impossible). Recreating the plain index here would undo
// WagonNumberPartialUnique2280000000000, which replaces it with a PARTIAL
// unique index so soft-deleted wagons stop reserving their number — this
// seeder is run directly by scripts/seed-edr-wagons.ts, which would
// otherwise resurrect the plain index on an already-migrated database.
for (const row of FLEET) {
if (row.end - row.start + 1 !== row.count) {

View File

@@ -29,6 +29,13 @@ export class ListWagonsQueryDto {
@IsUUID()
trainId?: string;
@ApiPropertyOptional({
description: 'Filter by run number — matches export OR import run (e.g. 8001).',
})
@IsOptional()
@IsString()
trainNumber?: string;
@ApiPropertyOptional({ default: 'wagonNumber' })
@IsOptional()
@IsString()

View File

@@ -6,7 +6,7 @@ import {
ConflictException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, FindOptionsOrder, FindOptionsWhere, ILike, In } from 'typeorm';
import { Repository, DataSource, In } from 'typeorm';
import { CreateWagonDto } from './dto/create-wagon.dto';
import { ListWagonsQueryDto } from './dto/list-wagons-query.dto';
import { UpdateWagonDto } from './dto/update-wagon.dto';
@@ -44,22 +44,41 @@ export class WagonsService {
}
async findAll(query: ListWagonsQueryDto = {}): Promise<Wagon[]> {
const where: FindOptionsWhere<Wagon>[] | FindOptionsWhere<Wagon> = [];
const search = query.search?.trim();
const trainId = query.trainId?.trim();
const wagonTypeId = query.wagonTypeId?.trim();
const filters: FindOptionsWhere<Wagon> = {
...(query.status ? { status: query.status } : {}),
...(query.currentYardId ? { currentYardId: query.currentYardId } : {}),
...(trainId ? { trainId } : {}),
...(wagonTypeId ? { wagonTypeId } : {}),
};
const trainNumber = query.trainNumber?.trim();
// QueryBuilder (not find) because both search and the trainNumber filter span
// two columns each (export/import run) — an OR that FindOptions cannot express
// without cross-producting into conflicting branches. Soft-deleted rows are
// still excluded automatically (BaseEntity's @DeleteDateColumn).
const qb = this.wagonRepo
.createQueryBuilder('w')
.leftJoinAndSelect('w.currentYard', 'currentYard')
.leftJoinAndSelect('w.wagonType', 'wagonType');
if (query.status) qb.andWhere('w.status = :status', { status: query.status });
if (query.currentYardId)
qb.andWhere('w.currentYardId = :currentYardId', { currentYardId: query.currentYardId });
if (trainId) qb.andWhere('w.trainId = :trainId', { trainId });
if (wagonTypeId) qb.andWhere('w.wagonTypeId = :wagonTypeId', { wagonTypeId });
// Filter by run: the odd export run identifies the pair, so match either
// column — a wagon carries export on one, import on the other.
if (trainNumber) {
qb.andWhere(
'(w.exportTrainNumber = :trainNumber OR w.importTrainNumber = :trainNumber)',
{ trainNumber },
);
}
// Search matches the wagon number or either run number.
if (search) {
where.push({
wagonNumber: ILike(`%${search}%`),
...filters,
});
qb.andWhere(
'(w.wagonNumber ILIKE :search OR w.exportTrainNumber ILIKE :search OR w.importTrainNumber ILIKE :search)',
{ search: `%${search}%` },
);
}
// Spec columns (tare, payload) are no longer sortable here — they live on the
@@ -75,14 +94,14 @@ export class WagonsService {
? (query.sortBy as keyof Wagon)
: 'wagonNumber';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
qb.orderBy(`w.${sortBy}`, sortOrder);
return this.wagonRepo.find({
where: search ? where : filters,
relations: { currentYard: true, wagonType: true },
order: { [sortBy]: sortOrder } as FindOptionsOrder<Wagon>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined,
});
if (query.page && query.limit) {
qb.skip((Number(query.page) - 1) * Number(query.limit));
}
if (query.limit) qb.take(Number(query.limit));
return qb.getMany();
}
async findById(id: string): Promise<Wagon> {

View File

@@ -2,6 +2,7 @@ import { AppDataSource } from '../data-source';
import { SeedEdrWagonFleetErNumbering2260000000000 } from '../migrations/2260000000000-SeedEdrWagonFleetErNumbering';
import { AddWagonTrainNumbers2270000000000 } from '../migrations/2270000000000-AddWagonTrainNumbers';
import { SeedWagonRunNumbers2280000000000 } from '../migrations/2280000000000-SeedWagonRunNumbers';
import { WagonNumberPartialUnique2280000000000 } from '../migrations/2280000000000-WagonNumberPartialUnique';
import { SeedWagonYardDoraleh2290000000000 } from '../migrations/2290000000000-SeedWagonYardDoraleh';
async function seedEdRWagons() {
@@ -19,6 +20,10 @@ async function seedEdRWagons() {
// migrate agree.
await new SeedEdrWagonFleetErNumbering2260000000000().up(queryRunner);
await new AddWagonTrainNumbers2270000000000().up(queryRunner);
// Not a wagon seed, but it owns wagon_number uniqueness — included so this
// script leaves the same schema a real `migration:run` would, rather than a
// database missing the partial unique index.
await new WagonNumberPartialUnique2280000000000().up(queryRunner);
await new SeedWagonRunNumbers2280000000000().up(queryRunner);
await new SeedWagonYardDoraleh2290000000000().up(queryRunner);