mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 02:00:56 +00:00
fix(warehouses): detention groups by canonical truck type
Join truck_types via vehicles.truck_type_id (normalized legacy vehicle_type only as fallback) so type renames can't unmatch detention rules and FK-less vehicles keep billing.
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
import { IsString, IsEnum, IsNumber, IsOptional, IsUUID, Matches } from 'class-validator';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { VehicleType, FuelType, VehicleStatus, VehicleAvailability } from '../entities/vehicle.entity';
|
||||
import {
|
||||
FuelType,
|
||||
VehicleAvailability,
|
||||
VehicleOwnership,
|
||||
VehicleStatus,
|
||||
} from '../entities/vehicle.entity';
|
||||
|
||||
/**
|
||||
* A vehicle plate is two or three letters, a hyphen, then two to six digits —
|
||||
@@ -28,8 +33,9 @@ export class CreateVehicleDto {
|
||||
@IsString()
|
||||
plateNumber!: string;
|
||||
|
||||
@IsEnum(VehicleType)
|
||||
vehicleType!: VehicleType;
|
||||
/** Truck configuration from `freight.truck_types` — drives capacity and whether a trailer plate applies. */
|
||||
@IsUUID()
|
||||
truckTypeId!: string;
|
||||
|
||||
@IsString()
|
||||
manufacturer!: string;
|
||||
@@ -43,8 +49,18 @@ export class CreateVehicleDto {
|
||||
@IsEnum(FuelType)
|
||||
fuelType!: FuelType;
|
||||
|
||||
/** Defaults to the truck type's capacity when omitted. */
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
capacity!: number;
|
||||
capacity?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
vin?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(VehicleOwnership)
|
||||
ownership?: VehicleOwnership;
|
||||
|
||||
@IsEnum(VehicleStatus)
|
||||
status!: VehicleStatus;
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { Entity, Column } from 'typeorm';
|
||||
import { BaseEntity } from '@edr/api-common';
|
||||
|
||||
/**
|
||||
* Legacy classification. Truck configurations are now back-office data in
|
||||
* `freight.truck_types` — register a vehicle with `truckTypeId`, not this.
|
||||
*
|
||||
* The `vehicle_type` COLUMN survives as a denormalised copy of the truck type's
|
||||
* code because truck-detention billing groups by it in raw SQL and matches it
|
||||
* against `warehouse_fee_rules.vehicle_type`. The service writes it through on
|
||||
* every save; nothing should set it by hand.
|
||||
*
|
||||
* @deprecated use `truckTypeId` / `freight.truck_types`
|
||||
*/
|
||||
export enum VehicleType {
|
||||
TRUCK = 'TRUCK',
|
||||
VAN = 'VAN',
|
||||
@@ -11,6 +22,12 @@ export enum VehicleType {
|
||||
FLATBED = 'FLATBED',
|
||||
}
|
||||
|
||||
/** Who supplies the truck. Supplier selection is deferred until EDR commits to outsourcing. */
|
||||
export enum VehicleOwnership {
|
||||
OWNED = 'OWNED',
|
||||
OUTSOURCED = 'OUTSOURCED',
|
||||
}
|
||||
|
||||
export enum FuelType {
|
||||
PETROL = 'PETROL',
|
||||
DIESEL = 'DIESEL',
|
||||
@@ -47,8 +64,12 @@ export class Vehicle extends BaseEntity {
|
||||
@Column({ name: 'registration_number', unique: true, nullable: true })
|
||||
registrationNumber?: string;
|
||||
|
||||
/** Denormalised `truck_types.code` — written through by the service, never set by hand. */
|
||||
@Column({ name: 'vehicle_type', type: 'varchar', nullable: true })
|
||||
vehicleType?: VehicleType;
|
||||
vehicleType?: string;
|
||||
|
||||
@Column({ name: 'truck_type_id', type: 'uuid', nullable: true })
|
||||
truckTypeId?: string | null;
|
||||
|
||||
@Column({ nullable: true })
|
||||
manufacturer?: string;
|
||||
@@ -101,7 +122,7 @@ export class Vehicle extends BaseEntity {
|
||||
@Column({ name: 'vin', type: 'varchar', nullable: true })
|
||||
vin?: string;
|
||||
|
||||
/** Owned | Leased | Rented */
|
||||
/** OWNED | OUTSOURCED — see {@link VehicleOwnership}. */
|
||||
@Column({ name: 'ownership', type: 'varchar', nullable: true })
|
||||
ownership?: string;
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ describe('VehiclesService driver assignment guard', () => {
|
||||
new VehiclesService(
|
||||
{ findOne, create: jest.fn((x) => x), save: jest.fn(async (x) => x) } as any,
|
||||
{ record: jest.fn() } as any,
|
||||
{ findById: jest.fn(async () => ({ code: 'TRUCK', name: 'Truck', hasTrailer: true })) } as any,
|
||||
);
|
||||
|
||||
it('rejects create when the driver is on another truck', async () => {
|
||||
@@ -18,7 +19,7 @@ describe('VehiclesService driver assignment guard', () => {
|
||||
const findOne = jest.fn().mockResolvedValueOnce(null).mockResolvedValueOnce(otherTruck);
|
||||
const svc = makeService(findOne);
|
||||
await expect(
|
||||
svc.create({ plateNumber: '3-22222', vehicleType: 'TRUCK', assignedDriverId: 'd1' } as any),
|
||||
svc.create({ plateNumber: '3-22222', truckTypeId: 'tt1', assignedDriverId: 'd1' } as any),
|
||||
).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
|
||||
@@ -3,9 +3,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Vehicle } from './entities/vehicle.entity';
|
||||
import { VehiclesService } from './vehicles.service';
|
||||
import { VehiclesController } from './vehicles.controller';
|
||||
import { TruckTypesModule } from '../truck-types/truck-types.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Vehicle])],
|
||||
imports: [TypeOrmModule.forFeature([Vehicle]), TruckTypesModule],
|
||||
providers: [VehiclesService],
|
||||
controllers: [VehiclesController],
|
||||
exports: [VehiclesService],
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Not, Repository } from 'typeorm';
|
||||
import { CreateVehicleDto } from './dto/create-vehicle.dto';
|
||||
import { UpdateVehicleDto } from './dto/update-vehicle.dto';
|
||||
import { Vehicle, VehicleAvailability, VehicleStatus } from './entities/vehicle.entity';
|
||||
import { TruckType } from '../truck-types/entities/truck-type.entity';
|
||||
import { TruckTypesService } from '../truck-types/truck-types.service';
|
||||
import { FirstMile, FirstMileStatus } from '../first-mile/entities/first-mile.entity';
|
||||
import { FirstMileContainerAllocation } from '../first-mile/entities/first-mile-container-allocation.entity';
|
||||
import { LastMile, LastMileStatus } from '../last-mile/entities/last-mile.entity';
|
||||
@@ -18,8 +25,26 @@ export class VehiclesService {
|
||||
@InjectRepository(Vehicle)
|
||||
private readonly vehicleRepo: Repository<Vehicle>,
|
||||
private readonly history: FleetHistoryService,
|
||||
private readonly truckTypes: TruckTypesService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* A trailer plate only exists on a configuration that pulls a trailer — a
|
||||
* rigid truck (Casoni) has none. Checked against the RESULTING record, not
|
||||
* just the patch, so switching an articulated truck to a rigid type cannot
|
||||
* leave its old trailer plate stranded on the row.
|
||||
*/
|
||||
private assertTrailerPlateAllowed(
|
||||
truckType: TruckType,
|
||||
trailerPlateNo?: string | null,
|
||||
): void {
|
||||
if (!truckType.hasTrailer && trailerPlateNo) {
|
||||
throw new BadRequestException(
|
||||
`${truckType.name} has no trailer — remove the trailer plate number`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A driver holds one truck at a time — reassignment requires detaching them
|
||||
* from their current truck first.
|
||||
@@ -54,10 +79,17 @@ export class VehiclesService {
|
||||
await this.assertDriverUnassigned(dto.assignedDriverId);
|
||||
}
|
||||
|
||||
const registrationNumber = `REG-${dto.vehicleType}-${Date.now()}`;
|
||||
const truckType = await this.truckTypes.findById(dto.truckTypeId);
|
||||
this.assertTrailerPlateAllowed(truckType, dto.trailerPlateNo);
|
||||
|
||||
const registrationNumber = `REG-${truckType.code}-${Date.now()}`;
|
||||
const vehicle = this.vehicleRepo.create({
|
||||
...dto,
|
||||
registrationNumber,
|
||||
// Denormalised for truck-detention billing, which groups on this column.
|
||||
vehicleType: truckType.code,
|
||||
// Capacity belongs to the type; an explicit value still wins for one-offs.
|
||||
capacity: dto.capacity ?? truckType.capacityTons ?? undefined,
|
||||
});
|
||||
|
||||
const saved = await this.vehicleRepo.save(vehicle);
|
||||
@@ -148,6 +180,17 @@ export class VehiclesService {
|
||||
await this.assertDriverUnassigned(dto.assignedDriverId, id);
|
||||
}
|
||||
|
||||
// Re-resolve the truck type whenever the type OR the trailer plate moves —
|
||||
// either edit can produce a rigid truck holding a trailer plate.
|
||||
const nextTruckTypeId = dto.truckTypeId ?? vehicle.truckTypeId;
|
||||
let nextTruckType: TruckType | null = null;
|
||||
if (nextTruckTypeId && (dto.truckTypeId !== undefined || dto.trailerPlateNo !== undefined)) {
|
||||
nextTruckType = await this.truckTypes.findById(nextTruckTypeId);
|
||||
const nextTrailerPlate =
|
||||
dto.trailerPlateNo !== undefined ? dto.trailerPlateNo : vehicle.trailerPlateNo;
|
||||
this.assertTrailerPlateAllowed(nextTruckType, nextTrailerPlate);
|
||||
}
|
||||
|
||||
const prev = {
|
||||
assignedDriverId: vehicle.assignedDriverId,
|
||||
assignedDriverName: vehicle.assignedDriverName,
|
||||
@@ -156,6 +199,11 @@ export class VehiclesService {
|
||||
};
|
||||
|
||||
Object.assign(vehicle, dto);
|
||||
// After the patch is applied, so the denormalised billing code always
|
||||
// reflects the type the vehicle actually ends up on.
|
||||
if (nextTruckType) {
|
||||
vehicle.vehicleType = nextTruckType.code;
|
||||
}
|
||||
const saved = await this.vehicleRepo.save(vehicle);
|
||||
|
||||
// Driver (re)assignment — emit an unassign for the old driver and/or an
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
import { VehiclesService } from './vehicles.service';
|
||||
|
||||
// A trailer plate only exists on a configuration that pulls a trailer. A rigid
|
||||
// truck (Casoni) has none, so registering or editing one into a trailer plate
|
||||
// must be refused server-side — the form hiding the field is not enforcement.
|
||||
describe('VehiclesService trailer plate guard', () => {
|
||||
const CASONI = { code: 'CASONI', name: 'Casoni (rigid, no trailer)', hasTrailer: false, capacityTons: 30 };
|
||||
const ARTIC = { code: 'TRUCK', name: 'Truck', hasTrailer: true, capacityTons: 40 };
|
||||
|
||||
const makeService = (findOne: jest.Mock, truckType: unknown) => {
|
||||
const save = jest.fn(async (x) => x);
|
||||
const svc = new VehiclesService(
|
||||
{ findOne, create: jest.fn((x) => x), save } as any,
|
||||
{ record: jest.fn() } as any,
|
||||
{ findById: jest.fn(async () => truckType) } as any,
|
||||
);
|
||||
return { svc, save };
|
||||
};
|
||||
|
||||
it('rejects creating a rigid truck that carries a trailer plate', async () => {
|
||||
const findOne = jest.fn().mockResolvedValueOnce(null); // plate is free
|
||||
const { svc } = makeService(findOne, CASONI);
|
||||
await expect(
|
||||
svc.create({ plateNumber: 'ET-9875', truckTypeId: 'tt-casoni', trailerPlateNo: 'ET-1234' } as any),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('accepts a rigid truck with no trailer plate, and takes capacity from the type', async () => {
|
||||
const findOne = jest.fn().mockResolvedValueOnce(null);
|
||||
const { svc } = makeService(findOne, CASONI);
|
||||
const saved = await svc.create({ plateNumber: 'ET-9875', truckTypeId: 'tt-casoni' } as any);
|
||||
expect(saved.capacity).toBe(30);
|
||||
// Denormalised code is what truck-detention billing groups on.
|
||||
expect(saved.vehicleType).toBe('CASONI');
|
||||
});
|
||||
|
||||
it('keeps an explicit capacity over the type default', async () => {
|
||||
const findOne = jest.fn().mockResolvedValueOnce(null);
|
||||
const { svc } = makeService(findOne, CASONI);
|
||||
const saved = await svc.create({
|
||||
plateNumber: 'ET-9875',
|
||||
truckTypeId: 'tt-casoni',
|
||||
capacity: 25,
|
||||
} as any);
|
||||
expect(saved.capacity).toBe(25);
|
||||
});
|
||||
|
||||
it('allows a trailer plate on an articulated type', async () => {
|
||||
const findOne = jest.fn().mockResolvedValueOnce(null);
|
||||
const { svc } = makeService(findOne, ARTIC);
|
||||
await expect(
|
||||
svc.create({ plateNumber: 'ET-9875', truckTypeId: 'tt-truck', trailerPlateNo: 'ET-1234' } as any),
|
||||
).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
// The regression that motivated validating the RESULT rather than the patch:
|
||||
// switching type alone leaves the stored trailer plate behind.
|
||||
it('rejects switching an existing truck to a rigid type while its trailer plate stands', async () => {
|
||||
const findOne = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ id: 'v1', plateNumber: 'ET-9875', trailerPlateNo: 'ET-1234' });
|
||||
const { svc } = makeService(findOne, CASONI);
|
||||
await expect(svc.update('v1', { truckTypeId: 'tt-casoni' } as any)).rejects.toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the switch when the trailer plate is cleared in the same edit', async () => {
|
||||
const findOne = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ id: 'v1', plateNumber: 'ET-9875', trailerPlateNo: 'ET-1234' });
|
||||
const { svc } = makeService(findOne, CASONI);
|
||||
const saved = await svc.update('v1', {
|
||||
truckTypeId: 'tt-casoni',
|
||||
trailerPlateNo: null,
|
||||
} as any);
|
||||
expect(saved.vehicleType).toBe('CASONI');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user