feat(last-mile): per-truck EDR arrival/exit, exit paper, bulk drawdown, departure notify

EDR last-mile is multi-truck but was modelled as one: setVehicles accepted any
number of trucks with no validation, arrival/delivery were stamped once per
last_mile record (N trucks shared one timestamp), EDR trucks got no exit paper,
and the per-truck EDR handover never happened because deliver() resolved the
plate via last_mile_container_allocations — a table nothing writes.

- Migration 2260000000000: per-truck arrived_at/departed_at/gross_weight_tons/
  net_weight_tons on last_mile_vehicle_assignments, plus a
  last_mile_vehicle_containers child table (a truck holds 1x40ft OR 2x20ft, so
  the single container_number scalar could not express a load). Weights are
  TONNES and named accordingly — the older gross_weight_kg lies about its unit.
- setVehicles: enforce the size rule (one 40ft, or two 20ft), container
  membership, one-container-one-truck, and never more trucks than containers.
  Bulk carries no containers and is instead gated on tonnage remaining.
- Bulk drawdown: remainingTonsForBooking = booking VGM minus the net weighed off
  every departed truck (both tonnes, no conversion), exposed as
  GET /last-mile/booking/:bookingId/remaining-tons.
- release() now stamps the EDR truck's own arrival and exit (matched by plate, so
  it works for bulk too) alongside the existing customer-truck stamp. The exit
  weighing itself is untouched.
- New GET /warehouse-inventory/edr-truck-exit-paper/:assignmentId — per-truck
  exit paper for EDR trucks. Deliberately not signature-gated: EDR handovers are
  generated at delivery, after the truck has left.
- deliver(): resolve the handover plate from the truck's own containers instead
  of the dead allocations table, so EDR handovers are genuinely per-truck.
- Notify the customer (portal inbox + SMS/email) when a truck leaves — one hook
  in release() covers both self-haul and EDR, since it is the single exit path.

Self-haul is intentionally unchanged (one booking-level handover signed once).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Hagernesh
2026-07-16 08:30:18 +00:00
parent a85bae1002
commit ff49554cc2
9 changed files with 547 additions and 29 deletions

View File

@@ -1,16 +1,36 @@
import { IsArray, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator';
import {
ArrayMaxSize,
ArrayUnique,
IsArray,
IsOptional,
IsString,
IsUUID,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';
export class LastMileVehicleInput {
@IsUUID()
vehicleId!: string;
/**
* Containers this truck carries: one 40ft, or up to two 20ft. Omit for bulk
* (the truck hauls loose tonnage and is weighed out on exit).
*/
@IsOptional()
@IsArray()
@ArrayMaxSize(2)
@ArrayUnique()
@IsString({ each: true })
containerNumbers?: string[];
/** @deprecated Single-container form — use `containerNumbers`. Still accepted. */
@IsOptional()
@IsString()
containerNumber?: string;
}
/** Replace the full set of vehicles (with their container numbers) on a delivery. */
/** Replace the full set of vehicles (with their containers) on a delivery. */
export class SetVehiclesDto {
@IsArray()
@ValidateNested({ each: true })

View File

@@ -1,8 +1,9 @@
import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne, Unique } from 'typeorm';
import { Column, Entity, Index, JoinColumn, ManyToOne, OneToMany, Unique } from 'typeorm';
import { Vehicle } from '../../vehicles/entities/vehicle.entity';
import { LastMile } from './last-mile.entity';
import { LastMileVehicleContainer } from './last-mile-vehicle-container.entity';
/**
* One row per vehicle assigned to a last-mile delivery. A delivery can be
@@ -28,12 +29,34 @@ export class LastMileVehicleAssignment extends BaseEntity {
@JoinColumn({ name: 'vehicle_id' })
vehicle?: Vehicle;
/** Container this truck carries — auto-filled from the booking's container
* number when known, else entered manually at assignment time. */
/** Legacy single container this truck carries. Kept in sync with the FIRST
* entry of `containers` for backward compatibility — a truck can hold 1x40ft
* or 2x20ft, so `containers` is the authoritative list. */
@Column({ name: 'container_number', type: 'varchar', nullable: true })
containerNumber?: string | null;
/** Containers riding this truck (1x40ft, or up to 2x20ft). */
@OneToMany(() => LastMileVehicleContainer, (c) => c.assignment, { cascade: true })
containers?: LastMileVehicleContainer[];
/** Actual distance driven by this truck (km), entered per vehicle. */
@Column({ name: 'distance_km', type: 'numeric', precision: 10, scale: 2, nullable: true })
distanceKm?: number | null;
/** This truck reached the warehouse (stamped by the arrival weighing step). */
@Column({ name: 'arrived_at', type: 'timestamptz', nullable: true })
arrivedAt?: Date | null;
/** This truck left the warehouse (stamped by the exit weighing step). */
@Column({ name: 'departed_at', type: 'timestamptz', nullable: true })
departedAt?: Date | null;
/** Weighed gross on exit, in TONNES (not kg — see the migration note). */
@Column({ name: 'gross_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
grossWeightTons?: number | null;
/** Cargo actually taken by this truck (gross tare), in TONNES. Drives the
* bulk drawdown: remaining = booking VGM SUM(net) over departed trucks. */
@Column({ name: 'net_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
netWeightTons?: number | null;
}

View File

@@ -0,0 +1,30 @@
import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { LastMileVehicleAssignment } from './last-mile-vehicle-assignment.entity';
/**
* A container riding a specific EDR last-mile truck. A truck carries 1x40ft OR
* 2x20ft, so the assignment needs more than the single legacy `container_number`
* scalar. Mirrors the self-haul `customer_truck_containers` child table.
*/
@Entity({ schema: 'freight', name: 'last_mile_vehicle_containers' })
@Index(['assignmentId'])
export class LastMileVehicleContainer extends BaseEntity {
@Column({ name: 'assignment_id', type: 'uuid' })
assignmentId!: string;
@ManyToOne(() => LastMileVehicleAssignment, (a) => a.containers, {
nullable: false,
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'assignment_id' })
assignment?: LastMileVehicleAssignment;
/** Denormalised for the "one container, one truck per delivery" unique index. */
@Column({ name: 'last_mile_id', type: 'uuid' })
lastMileId!: string;
@Column({ name: 'container_number', type: 'varchar', length: 32 })
containerNumber!: string;
}

View File

@@ -73,6 +73,12 @@ export class LastMileController {
return this.lastMileService.arrivalTrucksForBooking(bookingId);
}
@Get('booking/:bookingId/remaining-tons')
@ApiOperation({ summary: 'Bulk drawdown: tonnage still to be hauled (total departed trucks)' })
remainingTons(@Param('bookingId', ParseUUIDPipe) bookingId: string) {
return this.lastMileService.remainingTonsForBooking(bookingId);
}
@Post('accept/:reference')
@BookingStaff(FREIGHT_PERMS.lastMile.accept)
@ApiOperation({ summary: 'Accept a paid booking and create a last-mile leg' })

View File

@@ -10,6 +10,7 @@ import { VehiclesModule } from '../vehicles/vehicles.module';
import { LastMile } from './entities/last-mile.entity';
import { LastMileContainerAllocation } from './entities/last-mile-container-allocation.entity';
import { LastMileVehicleAssignment } from './entities/last-mile-vehicle-assignment.entity';
import { LastMileVehicleContainer } from './entities/last-mile-vehicle-container.entity';
import { LastMileController } from './last-mile.controller';
import { LastMileInvoiceService } from './last-mile-invoice.service';
import { LastMileRepository } from './last-mile.repository';
@@ -17,7 +18,12 @@ import { LastMileService } from './last-mile.service';
@Module({
imports: [
TypeOrmModule.forFeature([LastMile, LastMileContainerAllocation, LastMileVehicleAssignment]),
TypeOrmModule.forFeature([
LastMile,
LastMileContainerAllocation,
LastMileVehicleAssignment,
LastMileVehicleContainer,
]),
BillingModule,
forwardRef(() => BookingsModule),
VehiclesModule,

View File

@@ -1,4 +1,10 @@
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { DataSource, FindOptionsWhere, In, IsNull, Not } from 'typeorm';
import { BookingsRepository } from '../bookings/bookings.repository';
@@ -12,6 +18,7 @@ import { RecordProofOfDeliveryDto } from './dto/record-proof-of-delivery.dto';
import { LastMile, LastMileStatus } from './entities/last-mile.entity';
import { LastMileContainerAllocation } from './entities/last-mile-container-allocation.entity';
import { LastMileVehicleAssignment } from './entities/last-mile-vehicle-assignment.entity';
import { LastMileVehicleContainer } from './entities/last-mile-vehicle-container.entity';
import { LastMileRepository } from './last-mile.repository';
import { FilesService } from '../files/files.service';
import { BillingService, InvoiceEventPayload } from '../billing/billing.service';
@@ -552,22 +559,164 @@ export class LastMileService {
* for each added/removed vehicle. The first vehicle is mirrored onto the legacy
* `vehicleId` column for back-compat with single-vehicle readers.
*/
/** Container numbers on the booking (upper-cased). */
private async bookingContainerNumbers(bookingId: string): Promise<string[]> {
const rows: Array<{ containerNumber: string }> = await this.dataSource.query(
`SELECT bcu.container_number AS "containerNumber"
FROM freight.booking_container_units bcu
JOIN freight.booking_container bc
ON bc.id = bcu.booking_container_id AND bc.deleted_at IS NULL
WHERE bc.booking_id = $1 AND bcu.deleted_at IS NULL`,
[bookingId],
);
return rows.map((r) => r.containerNumber.trim().toUpperCase());
}
/** Contract container sizes (e.g. "20ft" / "40ft") for the given numbers. */
private async containerSizes(bookingId: string, numbers: string[]): Promise<string[]> {
if (!numbers.length) return [];
const rows: Array<{ size: string | null }> = await this.dataSource.query(
`SELECT bc.container_size AS "size"
FROM freight.booking_container_units bcu
JOIN freight.booking_container bc
ON bc.id = bcu.booking_container_id AND bc.deleted_at IS NULL
WHERE bc.booking_id = $1
AND UPPER(bcu.container_number) = ANY($2)
AND bcu.deleted_at IS NULL`,
[bookingId, numbers],
);
return rows.map((r) => (r.size ?? '').trim());
}
/**
* Bulk drawdown: how much of the booking's tonnage is still to be hauled —
* the booking VGM total minus the net weighed off every EDR truck that has
* already left. Both sides are tonnes, so no conversion.
*/
async remainingTonsForBooking(bookingId: string): Promise<{
totalTons: number;
hauledTons: number;
remainingTons: number;
complete: boolean;
}> {
const [row]: Array<{ totalTons: string | null; hauledTons: string | null }> =
await this.dataSource.query(
`SELECT COALESCE(b.cargo_total_weight_vgm, 0) AS "totalTons",
COALESCE((
SELECT SUM(va.net_weight_tons)
FROM freight.last_mile_vehicle_assignments va
JOIN freight.last_mile lm
ON lm.id = va.last_mile_id AND lm.deleted_at IS NULL
WHERE lm.booking_id = b.id
AND va.deleted_at IS NULL
AND va.departed_at IS NOT NULL
), 0) AS "hauledTons"
FROM freight.bookings b
WHERE b.id = $1 AND b.deleted_at IS NULL`,
[bookingId],
);
const totalTons = Number(row?.totalTons ?? 0);
const hauledTons = Number(row?.hauledTons ?? 0);
const remainingTons = Math.max(0, Math.round((totalTons - hauledTons) * 1000) / 1000);
return { totalTons, hauledTons, remainingTons, complete: totalTons > 0 && remainingTons <= 0 };
}
/**
* Truck capacity rules for a last-mile delivery.
* - CONTAINER: a truck carries ONE 40ft or up to TWO 20ft; every container
* must belong to the booking and ride exactly one truck; never more trucks
* than containers.
* - BULK: no containers — trucks haul loose tonnage, so the only limit is
* that there is tonnage left to haul.
*/
private async assertVehicleLoads(
bookingId: string,
desired: string[],
loads: Map<string, string[]>,
): Promise<void> {
if (!desired.length) return;
const [booking]: Array<{ freightType: string | null }> = await this.dataSource.query(
`SELECT freight_type AS "freightType"
FROM freight.bookings WHERE id = $1 AND deleted_at IS NULL`,
[bookingId],
);
if ((booking?.freightType ?? '').toUpperCase() === 'BULK') {
const { remainingTons, totalTons } = await this.remainingTonsForBooking(bookingId);
if (totalTons > 0 && remainingTons <= 0) {
throw new BadRequestException(
'This bulk booking is fully hauled — no tonnage left to assign trucks for',
);
}
return;
}
const bookingNumbers = await this.bookingContainerNumbers(bookingId);
if (!bookingNumbers.length) return; // nothing to validate against
const seen = new Set<string>();
for (const vehicleId of desired) {
const load = loads.get(vehicleId) ?? [];
if (load.length > 2) {
throw new BadRequestException('A truck carries at most 2 containers');
}
for (const n of load) {
if (!bookingNumbers.includes(n)) {
throw new BadRequestException(`Container ${n} is not one of this booking's containers`);
}
if (seen.has(n)) {
throw new ConflictException(`Container ${n} is already assigned to another truck`);
}
seen.add(n);
}
// A 40ft container fills the truck; only two 20ft share one.
if (load.length > 1) {
const sizes = await this.containerSizes(bookingId, load);
if (sizes.some((s) => s.includes('40'))) {
throw new BadRequestException(
'A 40ft container fills the truck — assign only 1 container to this truck',
);
}
}
}
if (desired.length > bookingNumbers.length) {
throw new BadRequestException(
`Cannot assign more trucks than containers — this booking has ${bookingNumbers.length} container(s) and ${desired.length} truck(s) requested.`,
);
}
}
async setVehicles(
id: string,
inputs: Array<{ vehicleId: string; containerNumber?: string | null }>,
inputs: Array<{
vehicleId: string;
containerNumbers?: string[] | null;
containerNumber?: string | null;
}>,
): Promise<LastMile> {
const existing = await this.findById(id);
// Dedupe by vehicleId, keeping the container number; preserve order.
const desiredMap = new Map<string, string | null>();
// Dedupe by vehicleId, keeping the container load; preserve order. Accepts
// the legacy single `containerNumber` as a one-element load.
const desiredMap = new Map<string, string[]>();
for (const inp of inputs) {
if (inp.vehicleId) desiredMap.set(inp.vehicleId, inp.containerNumber ?? null);
if (!inp.vehicleId) continue;
const load = (inp.containerNumbers ?? (inp.containerNumber ? [inp.containerNumber] : []))
.map((n) => String(n).trim().toUpperCase())
.filter(Boolean);
desiredMap.set(inp.vehicleId, load);
}
const desired = [...desiredMap.keys()];
const desiredSet = new Set(desired);
// Capacity + membership rules (a truck holds one 40ft or two 20ft; bulk
// hauls tonnage until the booking is drawn down).
await this.assertVehicleLoads(existing.bookingId, desired, desiredMap);
const manager = this.dataSource.manager;
const current = await manager.find(LastMileVehicleAssignment, {
where: { lastMileId: id },
relations: { containers: true },
});
const junctionSet = new Set(current.map((a) => a.vehicleId));
// Fold the legacy vehicleId into the release set — a vehicle assigned via the
@@ -588,33 +737,58 @@ export class LastMileService {
);
}
}
// Vehicles that stay but whose container number changed.
// Vehicles that stay but whose container load changed (order-insensitive).
const loadKey = (list: string[]) => [...list].sort().join('|');
const currentLoad = (a: LastMileVehicleAssignment) =>
(a.containers ?? []).map((c) => c.containerNumber.trim().toUpperCase());
const changed = current.filter(
(a) =>
desiredMap.has(a.vehicleId) &&
(a.containerNumber ?? null) !== (desiredMap.get(a.vehicleId) ?? null),
loadKey(desiredMap.get(a.vehicleId) ?? []) !== loadKey(currentLoad(a)),
);
await this.dataSource.transaction(async (tx) => {
if (removed.length) {
// Child containers cascade on delete.
await tx.delete(LastMileVehicleAssignment, {
lastMileId: id,
vehicleId: In(removed),
});
}
for (const vehicleId of added) {
await tx.insert(LastMileVehicleAssignment, {
const load = desiredMap.get(vehicleId) ?? [];
const inserted = await tx.insert(LastMileVehicleAssignment, {
lastMileId: id,
vehicleId,
containerNumber: desiredMap.get(vehicleId) ?? null,
// Legacy scalar stays in sync with the first container.
containerNumber: load[0] ?? null,
});
const assignmentId = inserted.identifiers[0]?.id as string | undefined;
if (assignmentId && load.length) {
await tx.insert(
LastMileVehicleContainer,
load.map((containerNumber) => ({ assignmentId, lastMileId: id, containerNumber })),
);
}
}
for (const row of changed) {
const load = desiredMap.get(row.vehicleId) ?? [];
await tx.update(
LastMileVehicleAssignment,
{ lastMileId: id, vehicleId: row.vehicleId },
{ containerNumber: desiredMap.get(row.vehicleId) ?? null },
{ containerNumber: load[0] ?? null },
);
await tx.delete(LastMileVehicleContainer, { assignmentId: row.id });
if (load.length) {
await tx.insert(
LastMileVehicleContainer,
load.map((containerNumber) => ({
assignmentId: row.id,
lastMileId: id,
containerNumber,
})),
);
}
}
});