mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 21:50:57 +00:00
fix issue
This commit is contained in:
@@ -1,15 +1,19 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { WagonStatus } from '@edr/types';
|
||||
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { FindOptionsOrder, FindOptionsWhere, ILike, Repository } from 'typeorm';
|
||||
import { DataSource, FindOptionsOrder, FindOptionsWhere, ILike, Repository } from 'typeorm';
|
||||
import { CreateTrainDto } from './dto/create-train.dto';
|
||||
import { UpdateTrainDto } from './dto/update-train.dto';
|
||||
import { TrainLocomotive } from './entities/train-locomotive.entity';
|
||||
import { Train } from './entities/train.entity';
|
||||
import { Wagon } from '../wagons/entities/wagon.entity';
|
||||
|
||||
@Injectable()
|
||||
export class TrainsService {
|
||||
constructor(
|
||||
@InjectRepository(Train)
|
||||
private readonly trainRepo: Repository<Train>,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
create(dto: CreateTrainDto): Promise<Train> {
|
||||
@@ -54,8 +58,40 @@ export class TrainsService {
|
||||
return this.trainRepo.save(train);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a built train. Blocked while it still has a live (DRAFT/SCHEDULED/
|
||||
* DISPATCHED) schedule; otherwise its wagons are freed (back to AVAILABLE)
|
||||
* and its locomotive links dropped so nothing is stranded, then the train is
|
||||
* soft-deleted. Mirrors TrainBuilderService.disband but prefers softRemove.
|
||||
*/
|
||||
async remove(id: string): Promise<void> {
|
||||
const train = await this.findById(id);
|
||||
await this.trainRepo.remove(train);
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
const train = await manager.getRepository(Train).findOne({ where: { id } });
|
||||
if (!train) throw new NotFoundException(`Train ${id} not found`);
|
||||
|
||||
const active: { count: string }[] = await manager.query(
|
||||
`SELECT COUNT(*)::text AS count
|
||||
FROM freight.train_schedules ts
|
||||
JOIN freight.train_sets tset ON tset.id = ts.train_set_id
|
||||
WHERE tset.train_id = $1
|
||||
AND ts.deleted_at IS NULL
|
||||
AND ts.status IN ('DRAFT', 'SCHEDULED', 'DISPATCHED')`,
|
||||
[id],
|
||||
);
|
||||
if (Number(active[0]?.count ?? 0) > 0) {
|
||||
throw new ConflictException(
|
||||
'Train has active schedules; cancel them before deleting the train',
|
||||
);
|
||||
}
|
||||
|
||||
await manager
|
||||
.getRepository(Wagon)
|
||||
.update(
|
||||
{ trainId: train.id },
|
||||
{ trainId: null, sequenceNumber: null, status: WagonStatus.Available },
|
||||
);
|
||||
await manager.getRepository(TrainLocomotive).delete({ trainId: train.id });
|
||||
await manager.getRepository(Train).softRemove(train);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user