diff --git a/apps/edr-freight-api/src/app.module.ts b/apps/edr-freight-api/src/app.module.ts index b675a3072..9277eb540 100644 --- a/apps/edr-freight-api/src/app.module.ts +++ b/apps/edr-freight-api/src/app.module.ts @@ -61,6 +61,7 @@ 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'; +import { LastMileModule } from './modules/last-mile/last-mile.module'; @Module({ imports: [ @@ -122,6 +123,7 @@ import { FirstMileModule } from './modules/first-mile/first-mile.module'; VehiclesModule, DriversModule, FirstMileModule, + LastMileModule, ], providers: [ EdrOrgSeeder, diff --git a/apps/edr-freight-api/src/migrations/1810000000001-CreateLastMile.ts b/apps/edr-freight-api/src/migrations/1810000000001-CreateLastMile.ts new file mode 100644 index 000000000..3c0ee8dfc --- /dev/null +++ b/apps/edr-freight-api/src/migrations/1810000000001-CreateLastMile.ts @@ -0,0 +1,106 @@ +import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm'; + +/** + * Create the freight.last_mile table — one row per booking's last-mile + * (terminal → door) leg, with payment split and an optional assigned vehicle. + */ +export class CreateLastMile1810000000001 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + const exists = await queryRunner.hasTable('freight.last_mile'); + if (exists) return; + + await queryRunner.createTable( + new Table({ + name: 'freight.last_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: 'estimated_km', + type: 'numeric', + precision: 10, + scale: 2, + isNullable: true, + }, + { + name: 'exact_km', + type: 'numeric', + precision: 10, + scale: 2, + isNullable: true, + }, + { 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.last_mile', + new TableForeignKey({ + columnNames: ['booking_id'], + referencedTableName: 'freight.bookings', + referencedColumnNames: ['id'], + onDelete: 'CASCADE', + }), + ); + + await queryRunner.createForeignKey( + 'freight.last_mile', + new TableForeignKey({ + columnNames: ['vehicle_id'], + referencedTableName: 'freight.vehicles', + referencedColumnNames: ['id'], + onDelete: 'SET NULL', + }), + ); + + await queryRunner.query( + `CREATE INDEX "IDX_last_mile_booking_id" ON "freight"."last_mile" ("booking_id")`, + ); + await queryRunner.query( + `CREATE INDEX "IDX_last_mile_status" ON "freight"."last_mile" ("status")`, + ); + await queryRunner.query( + `CREATE INDEX "IDX_last_mile_vehicle_id" ON "freight"."last_mile" ("vehicle_id")`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + const exists = await queryRunner.hasTable('freight.last_mile'); + if (exists) { + await queryRunner.dropTable('freight.last_mile'); + } + } +} diff --git a/apps/edr-freight-api/src/modules/last-mile/dto/create-last-mile.dto.ts b/apps/edr-freight-api/src/modules/last-mile/dto/create-last-mile.dto.ts new file mode 100644 index 000000000..b47eb0479 --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/dto/create-last-mile.dto.ts @@ -0,0 +1,60 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; +import { IsIn, IsNumber, IsOptional, IsUUID, Min } from 'class-validator'; + +import { LAST_MILE_STATUSES, LastMileStatus } from '../entities/last-mile.entity'; + +const toNumber = ({ value }: { value: unknown }) => + value === '' || value == null ? undefined : Number(value); + +export class CreateLastMileDto { + @ApiProperty({ description: 'Booking this last-mile leg belongs to (FK → bookings.id)' }) + @IsUUID() + bookingId!: string; + + @ApiPropertyOptional({ + enum: LAST_MILE_STATUSES, + default: 'PAYMENT_PENDING', + }) + @IsOptional() + @IsIn(LAST_MILE_STATUSES as unknown as string[]) + status?: LastMileStatus; + + @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: 'Planned distance for the leg, in km', example: 42.5 }) + @IsOptional() + @Transform(toNumber) + @IsNumber() + @Min(0) + estimatedKm?: number; + + @ApiPropertyOptional({ description: 'Actual distance travelled, in km', example: 44.1 }) + @IsOptional() + @Transform(toNumber) + @IsNumber() + @Min(0) + exactKm?: number; + + @ApiPropertyOptional({ + type: String, + format: 'uuid', + description: 'Assigned vehicle (FK → vehicles.id). May be null until assigned.', + nullable: true, + }) + @IsOptional() + @IsUUID() + vehicleId?: string | null; +} diff --git a/apps/edr-freight-api/src/modules/last-mile/dto/update-last-mile.dto.ts b/apps/edr-freight-api/src/modules/last-mile/dto/update-last-mile.dto.ts new file mode 100644 index 000000000..9d0c4262d --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/dto/update-last-mile.dto.ts @@ -0,0 +1,5 @@ +import { PartialType } from '@nestjs/mapped-types'; + +import { CreateLastMileDto } from './create-last-mile.dto'; + +export class UpdateLastMileDto extends PartialType(CreateLastMileDto) {} diff --git a/apps/edr-freight-api/src/modules/last-mile/entities/last-mile.entity.ts b/apps/edr-freight-api/src/modules/last-mile/entities/last-mile.entity.ts new file mode 100644 index 000000000..3bfe2cd19 --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/entities/last-mile.entity.ts @@ -0,0 +1,49 @@ +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 LAST_MILE_STATUSES = [ + 'PAYMENT_PENDING', + 'READY_TO_TRANSIT', + 'IN_TRANSIT', + 'DELIVERED', +] as const; + +export type LastMileStatus = (typeof LAST_MILE_STATUSES)[number]; + +@Entity({ name: 'last_mile', schema: 'freight' }) +@Index(['bookingId']) +@Index(['status']) +@Index(['vehicleId']) +export class LastMile 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!: LastMileStatus; + + @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: 'estimated_km', type: 'numeric', precision: 10, scale: 2, nullable: true }) + estimatedKm?: number | null; + + @Column({ name: 'exact_km', type: 'numeric', precision: 10, scale: 2, nullable: true }) + exactKm?: number | null; + + @Column({ name: 'vehicle_id', type: 'uuid', nullable: true }) + vehicleId?: string | null; + + @ManyToOne(() => Vehicle, { nullable: true, eager: false }) + @JoinColumn({ name: 'vehicle_id' }) + vehicle?: Vehicle | null; +} diff --git a/apps/edr-freight-api/src/modules/last-mile/last-mile.controller.ts b/apps/edr-freight-api/src/modules/last-mile/last-mile.controller.ts new file mode 100644 index 000000000..e6cc1e7ee --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/last-mile.controller.ts @@ -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 { CreateLastMileDto } from './dto/create-last-mile.dto'; +import { UpdateLastMileDto } from './dto/update-last-mile.dto'; +import { LastMileStatus } from './entities/last-mile.entity'; +import { LastMileService } from './last-mile.service'; + +@ApiTags('last-mile') +@ApiBearerAuth() +@Controller('last-mile') +@TrainSchedulingView() +export class LastMileController { + constructor(private readonly lastMileService: LastMileService) {} + + @Get() + @ApiOperation({ summary: 'List last-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.lastMileService.findAll({ + status: status as LastMileStatus | undefined, + bookingId, + vehicleId, + page: page ? parseInt(page, 10) : undefined, + pageSize: pageSize ? parseInt(pageSize, 10) : undefined, + sortBy, + sortOrder, + }); + } + + @Get(':id') + @ApiOperation({ summary: 'Get a last-mile leg by ID' }) + findOne(@Param('id', ParseUUIDPipe) id: string) { + return this.lastMileService.findById(id); + } + + @Post() + @TrainSchedulingManage() + @ApiOperation({ summary: 'Create a last-mile leg' }) + create(@Body() dto: CreateLastMileDto) { + return this.lastMileService.create(dto); + } + + @Patch(':id') + @TrainSchedulingManage() + @ApiOperation({ summary: 'Update a last-mile leg' }) + update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateLastMileDto) { + return this.lastMileService.update(id, dto); + } + + @Delete(':id') + @TrainSchedulingManage() + @HttpCode(HttpStatus.NO_CONTENT) + @ApiOperation({ summary: 'Soft-delete a last-mile leg' }) + remove(@Param('id', ParseUUIDPipe) id: string) { + return this.lastMileService.remove(id); + } +} diff --git a/apps/edr-freight-api/src/modules/last-mile/last-mile.module.ts b/apps/edr-freight-api/src/modules/last-mile/last-mile.module.ts new file mode 100644 index 000000000..a3662debe --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/last-mile.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; + +import { LastMile } from './entities/last-mile.entity'; +import { LastMileController } from './last-mile.controller'; +import { LastMileRepository } from './last-mile.repository'; +import { LastMileService } from './last-mile.service'; + +@Module({ + imports: [TypeOrmModule.forFeature([LastMile])], + controllers: [LastMileController], + providers: [LastMileRepository, LastMileService], + exports: [LastMileRepository, LastMileService], +}) +export class LastMileModule {} diff --git a/apps/edr-freight-api/src/modules/last-mile/last-mile.repository.ts b/apps/edr-freight-api/src/modules/last-mile/last-mile.repository.ts new file mode 100644 index 000000000..3d6f1b643 --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/last-mile.repository.ts @@ -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 { LastMile } from './entities/last-mile.entity'; + +@Injectable() +export class LastMileRepository extends BaseRepository { + constructor( + @InjectRepository(LastMile) + repository: Repository, + ) { + super(repository); + } +} diff --git a/apps/edr-freight-api/src/modules/last-mile/last-mile.service.ts b/apps/edr-freight-api/src/modules/last-mile/last-mile.service.ts new file mode 100644 index 000000000..55b8fee24 --- /dev/null +++ b/apps/edr-freight-api/src/modules/last-mile/last-mile.service.ts @@ -0,0 +1,113 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { FindOptionsWhere } from 'typeorm'; + +import { CreateLastMileDto } from './dto/create-last-mile.dto'; +import { UpdateLastMileDto } from './dto/update-last-mile.dto'; +import { LastMile, LastMileStatus } from './entities/last-mile.entity'; +import { LastMileRepository } from './last-mile.repository'; + +type LastMileListFilter = { + status?: LastMileStatus; + bookingId?: string; + vehicleId?: string; + page?: number; + pageSize?: number; + sortBy?: string; + sortOrder?: string; +}; + +const SORTABLE_FIELDS: (keyof LastMile)[] = [ + 'status', + 'advancedPayment', + 'remainingPayment', + 'createdAt', +]; + +@Injectable() +export class LastMileService { + constructor(private readonly lastMileRepository: LastMileRepository) {} + + async findAll(filter: LastMileListFilter = {}): Promise<{ + data: LastMile[]; + 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 LastMile) + ? (filter.sortBy as keyof LastMile) + : 'createdAt'; + const sortOrder = filter.sortOrder?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + + const where: FindOptionsWhere = {}; + 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.lastMileRepository.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 { + const record = await this.lastMileRepository.findById(id, { + relations: { booking: true, vehicle: true }, + }); + + if (!record) { + throw new NotFoundException(`Last-mile record ${id} not found`); + } + + return record; + } + + async create(dto: CreateLastMileDto): Promise { + return this.lastMileRepository.create({ + bookingId: dto.bookingId, + status: dto.status ?? 'PAYMENT_PENDING', + advancedPayment: dto.advancedPayment ?? 0, + remainingPayment: dto.remainingPayment ?? 0, + estimatedKm: dto.estimatedKm ?? null, + exactKm: dto.exactKm ?? null, + vehicleId: dto.vehicleId ?? null, + }); + } + + async update(id: string, dto: UpdateLastMileDto): Promise { + await this.findById(id); + + const updated = await this.lastMileRepository.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.estimatedKm !== undefined ? { estimatedKm: dto.estimatedKm } : {}), + ...(dto.exactKm !== undefined ? { exactKm: dto.exactKm } : {}), + ...(dto.vehicleId !== undefined ? { vehicleId: dto.vehicleId } : {}), + }); + + if (!updated) { + throw new NotFoundException(`Last-mile record ${id} not found`); + } + + return updated; + } + + async remove(id: string): Promise { + await this.findById(id); + await this.lastMileRepository.softDelete(id); + } +}