mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-26 18:42:49 +00:00
last mile
This commit is contained in:
@@ -60,6 +60,7 @@ import { FacilitiesModule } from './modules/facilities/facilities.module';
|
||||
import { OverviewModule } from './modules/overview/overview.module';
|
||||
import { VehiclesModule } from './modules/vehicles/vehicles.module';
|
||||
import { DriversModule } from './modules/drivers/drivers.module';
|
||||
import { FirstMileModule } from './modules/first-mile/first-mile.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -120,6 +121,7 @@ import { DriversModule } from './modules/drivers/drivers.module';
|
||||
OverviewModule,
|
||||
VehiclesModule,
|
||||
DriversModule,
|
||||
FirstMileModule,
|
||||
],
|
||||
providers: [
|
||||
EdrOrgSeeder,
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';
|
||||
|
||||
/**
|
||||
* Create the freight.first_mile table — one row per booking's first-mile
|
||||
* (door → terminal) leg, with payment split and an optional assigned vehicle.
|
||||
*/
|
||||
export class CreateFirstMile1810000000000 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const exists = await queryRunner.hasTable('freight.first_mile');
|
||||
if (exists) return;
|
||||
|
||||
await queryRunner.createTable(
|
||||
new Table({
|
||||
name: 'freight.first_mile',
|
||||
columns: [
|
||||
{
|
||||
name: 'id',
|
||||
type: 'uuid',
|
||||
isPrimary: true,
|
||||
default: 'gen_random_uuid()',
|
||||
},
|
||||
{ name: 'booking_id', type: 'uuid', isNullable: false },
|
||||
{
|
||||
name: 'status',
|
||||
type: 'varchar',
|
||||
length: '30',
|
||||
default: `'PAYMENT_PENDING'`,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: 'advanced_payment',
|
||||
type: 'numeric',
|
||||
precision: 14,
|
||||
scale: 2,
|
||||
default: 0,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: 'remaining_payment',
|
||||
type: 'numeric',
|
||||
precision: 14,
|
||||
scale: 2,
|
||||
default: 0,
|
||||
isNullable: false,
|
||||
},
|
||||
{ name: 'vehicle_id', type: 'uuid', isNullable: true },
|
||||
{ name: 'created_at', type: 'timestamptz', default: 'now()' },
|
||||
{ name: 'updated_at', type: 'timestamptz', default: 'now()' },
|
||||
{ name: 'deleted_at', type: 'timestamptz', isNullable: true },
|
||||
],
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
await queryRunner.createForeignKey(
|
||||
'freight.first_mile',
|
||||
new TableForeignKey({
|
||||
columnNames: ['booking_id'],
|
||||
referencedTableName: 'freight.bookings',
|
||||
referencedColumnNames: ['id'],
|
||||
onDelete: 'CASCADE',
|
||||
}),
|
||||
);
|
||||
|
||||
await queryRunner.createForeignKey(
|
||||
'freight.first_mile',
|
||||
new TableForeignKey({
|
||||
columnNames: ['vehicle_id'],
|
||||
referencedTableName: 'freight.vehicles',
|
||||
referencedColumnNames: ['id'],
|
||||
onDelete: 'SET NULL',
|
||||
}),
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX "IDX_first_mile_booking_id" ON "freight"."first_mile" ("booking_id")`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX "IDX_first_mile_status" ON "freight"."first_mile" ("status")`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX "IDX_first_mile_vehicle_id" ON "freight"."first_mile" ("vehicle_id")`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
const exists = await queryRunner.hasTable('freight.first_mile');
|
||||
if (exists) {
|
||||
await queryRunner.dropTable('freight.first_mile');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsIn, IsNumber, IsOptional, IsUUID, Min } from 'class-validator';
|
||||
|
||||
import { FIRST_MILE_STATUSES, FirstMileStatus } from '../entities/first-mile.entity';
|
||||
|
||||
const toNumber = ({ value }: { value: unknown }) =>
|
||||
value === '' || value == null ? undefined : Number(value);
|
||||
|
||||
export class CreateFirstMileDto {
|
||||
@ApiProperty({ description: 'Booking this first-mile leg belongs to (FK → bookings.id)' })
|
||||
@IsUUID()
|
||||
bookingId!: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: FIRST_MILE_STATUSES,
|
||||
default: 'PAYMENT_PENDING',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsIn(FIRST_MILE_STATUSES as unknown as string[])
|
||||
status?: FirstMileStatus;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Amount already paid in advance', example: 4200 })
|
||||
@IsOptional()
|
||||
@Transform(toNumber)
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
advancedPayment?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Outstanding balance to be collected', example: 1800 })
|
||||
@IsOptional()
|
||||
@Transform(toNumber)
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
remainingPayment?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Assigned vehicle (FK → vehicles.id). May be null until assigned.',
|
||||
nullable: true,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
vehicleId?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
|
||||
import { CreateFirstMileDto } from './create-first-mile.dto';
|
||||
|
||||
export class UpdateFirstMileDto extends PartialType(CreateFirstMileDto) {}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { BaseEntity } from '@edr/api-common';
|
||||
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
|
||||
|
||||
import { Booking } from '../../bookings/entities/booking.entity';
|
||||
import { Vehicle } from '../../vehicles/entities/vehicle.entity';
|
||||
|
||||
export const FIRST_MILE_STATUSES = [
|
||||
'PAYMENT_PENDING',
|
||||
'READY_TO_TRANSIT',
|
||||
'IN_TRANSIT',
|
||||
'RECEIVED_TO_PORT',
|
||||
] as const;
|
||||
|
||||
export type FirstMileStatus = (typeof FIRST_MILE_STATUSES)[number];
|
||||
|
||||
@Entity({ name: 'first_mile', schema: 'freight' })
|
||||
@Index(['bookingId'])
|
||||
@Index(['status'])
|
||||
@Index(['vehicleId'])
|
||||
export class FirstMile extends BaseEntity {
|
||||
@Column({ name: 'booking_id', type: 'uuid' })
|
||||
bookingId!: string;
|
||||
|
||||
@ManyToOne(() => Booking, { nullable: false, eager: false })
|
||||
@JoinColumn({ name: 'booking_id' })
|
||||
booking?: Booking;
|
||||
|
||||
@Column({ name: 'status', type: 'varchar', length: 30, default: 'PAYMENT_PENDING' })
|
||||
status!: FirstMileStatus;
|
||||
|
||||
@Column({ name: 'advanced_payment', type: 'numeric', precision: 14, scale: 2, default: 0 })
|
||||
advancedPayment!: number;
|
||||
|
||||
@Column({ name: 'remaining_payment', type: 'numeric', precision: 14, scale: 2, default: 0 })
|
||||
remainingPayment!: number;
|
||||
|
||||
@Column({ name: 'vehicle_id', type: 'uuid', nullable: true })
|
||||
vehicleId?: string | null;
|
||||
|
||||
@ManyToOne(() => Vehicle, { nullable: true, eager: false })
|
||||
@JoinColumn({ name: 'vehicle_id' })
|
||||
vehicle?: Vehicle | null;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { TrainSchedulingManage, TrainSchedulingView } from '../../common/booking-guards';
|
||||
|
||||
import { CreateFirstMileDto } from './dto/create-first-mile.dto';
|
||||
import { UpdateFirstMileDto } from './dto/update-first-mile.dto';
|
||||
import { FirstMileStatus } from './entities/first-mile.entity';
|
||||
import { FirstMileService } from './first-mile.service';
|
||||
|
||||
@ApiTags('first-mile')
|
||||
@ApiBearerAuth()
|
||||
@Controller('first-mile')
|
||||
@TrainSchedulingView()
|
||||
export class FirstMileController {
|
||||
constructor(private readonly firstMileService: FirstMileService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List first-mile legs' })
|
||||
findAll(
|
||||
@Query('status') status?: string,
|
||||
@Query('bookingId') bookingId?: string,
|
||||
@Query('vehicleId') vehicleId?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
@Query('sortBy') sortBy?: string,
|
||||
@Query('sortOrder') sortOrder?: 'ASC' | 'DESC',
|
||||
) {
|
||||
return this.firstMileService.findAll({
|
||||
status: status as FirstMileStatus | undefined,
|
||||
bookingId,
|
||||
vehicleId,
|
||||
page: page ? parseInt(page, 10) : undefined,
|
||||
pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
|
||||
sortBy,
|
||||
sortOrder,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get a first-mile leg by ID' })
|
||||
findOne(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.firstMileService.findById(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@TrainSchedulingManage()
|
||||
@ApiOperation({ summary: 'Create a first-mile leg' })
|
||||
create(@Body() dto: CreateFirstMileDto) {
|
||||
return this.firstMileService.create(dto);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@TrainSchedulingManage()
|
||||
@ApiOperation({ summary: 'Update a first-mile leg' })
|
||||
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateFirstMileDto) {
|
||||
return this.firstMileService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@TrainSchedulingManage()
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
@ApiOperation({ summary: 'Soft-delete a first-mile leg' })
|
||||
remove(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.firstMileService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { FirstMile } from './entities/first-mile.entity';
|
||||
import { FirstMileController } from './first-mile.controller';
|
||||
import { FirstMileRepository } from './first-mile.repository';
|
||||
import { FirstMileService } from './first-mile.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([FirstMile])],
|
||||
controllers: [FirstMileController],
|
||||
providers: [FirstMileRepository, FirstMileService],
|
||||
exports: [FirstMileRepository, FirstMileService],
|
||||
})
|
||||
export class FirstMileModule {}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { BaseRepository } from '@edr/api-common';
|
||||
|
||||
import { FirstMile } from './entities/first-mile.entity';
|
||||
|
||||
@Injectable()
|
||||
export class FirstMileRepository extends BaseRepository<FirstMile> {
|
||||
constructor(
|
||||
@InjectRepository(FirstMile)
|
||||
repository: Repository<FirstMile>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { FindOptionsWhere } from 'typeorm';
|
||||
|
||||
import { CreateFirstMileDto } from './dto/create-first-mile.dto';
|
||||
import { UpdateFirstMileDto } from './dto/update-first-mile.dto';
|
||||
import { FirstMile, FirstMileStatus } from './entities/first-mile.entity';
|
||||
import { FirstMileRepository } from './first-mile.repository';
|
||||
|
||||
type FirstMileListFilter = {
|
||||
status?: FirstMileStatus;
|
||||
bookingId?: string;
|
||||
vehicleId?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
sortBy?: string;
|
||||
sortOrder?: string;
|
||||
};
|
||||
|
||||
const SORTABLE_FIELDS: (keyof FirstMile)[] = [
|
||||
'status',
|
||||
'advancedPayment',
|
||||
'remainingPayment',
|
||||
'createdAt',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class FirstMileService {
|
||||
constructor(private readonly firstMileRepository: FirstMileRepository) {}
|
||||
|
||||
async findAll(filter: FirstMileListFilter = {}): Promise<{
|
||||
data: FirstMile[];
|
||||
meta: { total: number; page: number; pageSize: number; totalPages: number };
|
||||
}> {
|
||||
const page = filter.page ?? 1;
|
||||
const pageSize = filter.pageSize ?? 50;
|
||||
const sortBy = SORTABLE_FIELDS.includes(filter.sortBy as keyof FirstMile)
|
||||
? (filter.sortBy as keyof FirstMile)
|
||||
: 'createdAt';
|
||||
const sortOrder = filter.sortOrder?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
const where: FindOptionsWhere<FirstMile> = {};
|
||||
if (filter.status) where.status = filter.status;
|
||||
if (filter.bookingId) where.bookingId = filter.bookingId;
|
||||
if (filter.vehicleId) where.vehicleId = filter.vehicleId;
|
||||
|
||||
const [data, total] = await this.firstMileRepository.findAndCount({
|
||||
where,
|
||||
relations: { booking: true, vehicle: true },
|
||||
order: { [sortBy]: sortOrder },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.max(1, Math.ceil(total / pageSize)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<FirstMile> {
|
||||
const record = await this.firstMileRepository.findById(id, {
|
||||
relations: { booking: true, vehicle: true },
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
throw new NotFoundException(`First-mile record ${id} not found`);
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
async create(dto: CreateFirstMileDto): Promise<FirstMile> {
|
||||
return this.firstMileRepository.create({
|
||||
bookingId: dto.bookingId,
|
||||
status: dto.status ?? 'PAYMENT_PENDING',
|
||||
advancedPayment: dto.advancedPayment ?? 0,
|
||||
remainingPayment: dto.remainingPayment ?? 0,
|
||||
vehicleId: dto.vehicleId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateFirstMileDto): Promise<FirstMile> {
|
||||
await this.findById(id);
|
||||
|
||||
const updated = await this.firstMileRepository.update(id, {
|
||||
...(dto.bookingId !== undefined ? { bookingId: dto.bookingId } : {}),
|
||||
...(dto.status !== undefined ? { status: dto.status } : {}),
|
||||
...(dto.advancedPayment !== undefined ? { advancedPayment: dto.advancedPayment } : {}),
|
||||
...(dto.remainingPayment !== undefined ? { remainingPayment: dto.remainingPayment } : {}),
|
||||
...(dto.vehicleId !== undefined ? { vehicleId: dto.vehicleId } : {}),
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
throw new NotFoundException(`First-mile record ${id} not found`);
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.findById(id);
|
||||
await this.firstMileRepository.softDelete(id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user