Merge pull request #435 from Tria-plc/freight/feature/first_mile_invoice

Freight/feature/first mile invoice
This commit is contained in:
yaschalew10
2026-07-04 01:57:06 +03:00
committed by GitHub
20 changed files with 879 additions and 1219 deletions

View File

@@ -307,6 +307,16 @@ export class BillingService {
});
}
/** Invoices for a batch of source records (e.g. many last-mile legs), so a
* list can show which records already have an invoice without N+1 queries. */
findBySourceIds(source: string, sourceIds: string[]): Promise<Invoice[]> {
if (!sourceIds.length) return Promise.resolve([]);
return this.invoices.findAll({
where: { source, sourceId: In(sourceIds) },
order: { createdAt: "DESC" },
});
}
/** Invoices for the signed-in customer; empty when they have no company. */
async findForUser(
userId: string,

View File

@@ -1,8 +0,0 @@
export class FirstMileContainerAllocationDto {
containerId!: string;
vehicleId!: string;
}
export class AllocateFirstMileContainersDto {
allocations!: FirstMileContainerAllocationDto[];
}

View File

@@ -17,13 +17,9 @@ import { TrainSchedulingManage, TrainSchedulingView } from '../../common/booking
import { CreateFirstMileDto } from './dto/create-first-mile.dto';
import { UpdateFirstMileDto } from './dto/update-first-mile.dto';
import { AllocateFirstMileContainersDto } from './dto/allocate-containers.dto';
import { FirstMileStatus } from './entities/first-mile.entity';
import { FirstMileService } from './first-mile.service';
import { FirstMileInvoiceService } from './first-mile-invoice.service';
import { BillingService } from '../billing/billing.service';
import { BookingsService } from '../bookings/bookings.service';
import { Freight } from '@edr/types';
@ApiTags('first-mile')
@ApiBearerAuth()
@@ -33,8 +29,6 @@ export class FirstMileController {
constructor(
private readonly firstMileService: FirstMileService,
private readonly firstMileInvoiceService: FirstMileInvoiceService,
private readonly billingService: BillingService,
private readonly bookingsService: BookingsService
) { }
@Get()
@@ -89,40 +83,17 @@ export class FirstMileController {
@TrainSchedulingManage()
@ApiOperation({ summary: 'Update a first-mile leg' })
async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateFirstMileDto) {
const record = await this.firstMileService.update(id, dto);
// Auto-generate invoice if distance or payment was updated
const booking = await this.bookingsService.findById(record.bookingId);
const currency = booking.paymentCurrency || "ETB";
if (dto.exactKm !== undefined || dto.exactKm != record.exactKm || dto.remainingPayment !== undefined || dto.remainingPayment !== record.remainingPayment) {
await this.billingService.generateInvoice({
source: Freight.InvoiceSource.FirstMile,
sourceId: record.id,
type: "FIRST_MILE",
companyId: booking.companyId,
companyProfileId: booking.companyProfileId,
currency,
// No invoice side-effects — invoices are generated only via the explicit
// POST :id/invoice endpoint (the "Generate Invoice" action).
return this.firstMileService.update(id, dto);
}
lines: [
{
chargeType: "FIRST_MILE",
description: "First Mile Transportation Service",
quantity: 1,
unitRate: record.remainingPayment,
amount: record.remainingPayment,
currency,
},
],
subtotalAmount: record.remainingPayment,
taxAmount: 0, // Replace if VAT/tax applies
totalAmount: record.remainingPayment,
dueInDays: 7,
status: Freight.InvoiceStatus.Pending,
});
await this.firstMileInvoiceService.ensureInvoiceFor(record);
}
return record;
@Post(':id/invoice')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Generate the first-mile delivery-fee invoice' })
async generateInvoice(@Param('id', ParseUUIDPipe) id: string) {
const record = await this.firstMileService.findById(id);
return this.firstMileInvoiceService.ensureInvoiceFor(record);
}
@Delete(':id')
@@ -132,14 +103,4 @@ export class FirstMileController {
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.firstMileService.remove(id);
}
@Post(':firstMileId/allocate-containers')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Allocate containers to vehicles for a first-mile leg' })
allocateContainers(
@Param('firstMileId', ParseUUIDPipe) firstMileId: string,
@Body() dto: AllocateFirstMileContainersDto,
) {
return this.firstMileService.allocateContainers(firstMileId, dto.allocations);
}
}

View File

@@ -1,5 +1,5 @@
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { FindOptionsWhere, In, IsNull, Not } from 'typeorm';
import { FindOptionsWhere, IsNull, Not } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { VehicleAvailability } from '../vehicles/entities/vehicle.entity';
@@ -13,7 +13,7 @@ import { FirstMile, FirstMileStatus } from "./entities/first-mile.entity";
import { FirstMileContainerAllocation } from "./entities/first-mile-container-allocation.entity";
import { FirstMileRepository } from "./first-mile.repository";
import { OnEvent } from "@nestjs/event-emitter";
import { InvoiceEventPayload } from "../billing/billing.service";
import { BillingService, InvoiceEventPayload } from "../billing/billing.service";
import { FleetHistoryService } from "../fleet-history/fleet-history.service";
import { FleetEventType } from "../fleet-history/entities/fleet-event.entity";
@@ -46,8 +46,27 @@ export class FirstMileService {
private readonly driversService: DriversService,
private readonly smsClient: SmsClientService,
private readonly history: FleetHistoryService,
private readonly billing: BillingService,
) { }
/** Attach real invoice info so the UI shows an invoice link only when one
* exists — not merely because distance was entered. Batched (no N+1). */
private async attachInvoices(records: FirstMile[]): Promise<void> {
const invoices = await this.billing.findBySourceIds(
'first_mile',
records.map((r) => r.id),
);
const byId = new Map<string, { id: string; number: string; status: string }>();
for (const inv of invoices) {
if (!byId.has(inv.sourceId)) {
byId.set(inv.sourceId, { id: inv.id, number: inv.invoiceNumber, status: String(inv.status) });
}
}
for (const r of records) {
(r as FirstMile & { invoice?: unknown }).invoice = byId.get(r.id) ?? null;
}
}
/** Resolve a vehicle's driver + human labels, for stamping mile events onto
* the driver's timeline and naming the vehicle. Best-effort — never throws. */
private async vehicleInfo(
@@ -191,6 +210,8 @@ export class FirstMileService {
take: pageSize,
});
await this.attachInvoices(data);
return {
data,
meta: {
@@ -236,6 +257,8 @@ export class FirstMileService {
throw new NotFoundException(`First-mile record ${id} not found`);
}
await this.attachInvoices([record]);
return record;
}
@@ -537,84 +560,18 @@ export class FirstMileService {
}
async remove(id: string): Promise<void> {
await this.findById(id);
const existing = await this.findById(id);
// Can't delete once billed.
const invoices = await this.billing.findBySourceIds('first_mile', [id]);
if (invoices.length) {
throw new BadRequestException(
'Cannot delete a first-mile leg after its invoice is generated',
);
}
await this.firstMileRepository.softDelete(id);
}
async allocateContainers(
firstMileId: string,
allocations: Array<{ containerId: string; vehicleId: string }>,
) {
const firstMile = await this.findById(firstMileId);
if (!firstMile) {
throw new NotFoundException(`First-mile record ${firstMileId} not found`);
}
const previousAllocations = await this.dataSource.manager.find(FirstMileContainerAllocation, {
where: {
firstMileId,
containerId: In(allocations.map((a) => a.containerId)),
},
});
const previousVehicleIds = previousAllocations
.map((a) => a.vehicleId)
.filter((id): id is string => Boolean(id));
await this.dataSource.transaction(async (manager) => {
for (const allocation of allocations) {
await manager.delete(FirstMileContainerAllocation, {
firstMileId,
containerId: allocation.containerId,
});
await manager.insert(FirstMileContainerAllocation, {
firstMileId,
containerId: allocation.containerId,
vehicleId: allocation.vehicleId,
containerType: "CONTAINER",
quantity: 1,
});
}
});
const vehicleIds = new Set(allocations.map((a) => a.vehicleId));
await Promise.all(
[...vehicleIds].map((vehicleId) => this.vehiclesService.setAvailability(vehicleId, VehicleAvailability.BUSY)),
);
await this.vehiclesService.releaseIfUnused(
previousVehicleIds.filter((id) => !vehicleIds.has(id)),
);
// History: one event per vehicle actually added or removed by this
// multi-car (re)allocation, so reassignments show on every timeline.
const prevSet = new Set(previousVehicleIds);
const bookingRef = await this.resolveBookingRef(firstMile);
for (const vehicleId of vehicleIds) {
if (prevSet.has(vehicleId)) continue;
const info = await this.vehicleInfo(vehicleId);
await this.history.record({
eventType: FleetEventType.MILE_VEHICLE_ASSIGNED,
vehicleId,
firstMileId,
driverId: info.driverId,
label: firstMile.status,
metadata: { mile: 'FIRST', bookingRef, vehiclePlate: info.plate, driverName: info.driverName },
});
}
for (const vehicleId of previousVehicleIds) {
if (vehicleIds.has(vehicleId)) continue;
const info = await this.vehicleInfo(vehicleId);
await this.history.record({
eventType: FleetEventType.MILE_VEHICLE_RELEASED,
vehicleId,
firstMileId,
driverId: info.driverId,
metadata: { mile: 'FIRST', bookingRef, vehiclePlate: info.plate, driverName: info.driverName },
});
}
return {
success: true,
allocated: allocations.length,
};
// Free the trucks it was holding (direct + container), unless still in use.
await this.releaseVehicles(existing);
}
}

View File

@@ -1,17 +0,0 @@
import { IsArray, IsUUID, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
export class LastMileContainerAllocationDto {
@IsUUID()
containerId!: string;
@IsUUID()
vehicleId!: string;
}
export class AllocateLastMileContainersDto {
@IsArray()
@ValidateNested({ each: true })
@Type(() => LastMileContainerAllocationDto)
allocations!: LastMileContainerAllocationDto[];
}

View File

@@ -0,0 +1,24 @@
import { IsArray, IsNumber, IsOptional, IsUUID, Min, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
export class VehicleDistanceInput {
@IsUUID()
vehicleId!: string;
@IsNumber()
@Min(0)
distanceKm!: number;
}
/** Per-vehicle actual distances for a last-mile delivery (multi-truck). */
export class SetDistancesDto {
@IsArray()
@ValidateNested({ each: true })
@Type(() => VehicleDistanceInput)
distances!: VehicleDistanceInput[];
/** Recomputed remaining payment (total km × rate), from the client. */
@IsOptional()
@IsNumber()
remainingPayment?: number;
}

View File

@@ -1,8 +1,19 @@
import { IsArray, IsUUID } from 'class-validator';
import { IsArray, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
/** Replace the full set of vehicles assigned to a last-mile delivery. */
export class LastMileVehicleInput {
@IsUUID()
vehicleId!: string;
@IsOptional()
@IsString()
containerNumber?: string;
}
/** Replace the full set of vehicles (with their container numbers) on a delivery. */
export class SetVehiclesDto {
@IsArray()
@IsUUID('4', { each: true })
vehicleIds!: string[];
@ValidateNested({ each: true })
@Type(() => LastMileVehicleInput)
vehicles!: LastMileVehicleInput[];
}

View File

@@ -24,7 +24,7 @@ export class LastMileContainerAllocation extends BaseEntity {
@Column('uuid', { name: 'vehicle_id', nullable: true })
vehicleId?: string | null;
@Column('text')
@Column('text', { name: 'container_type' })
containerType!: string;
@Column('integer', { default: 1 })

View File

@@ -27,4 +27,13 @@ export class LastMileVehicleAssignment extends BaseEntity {
@ManyToOne(() => Vehicle, { nullable: false, eager: false })
@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. */
@Column({ name: 'container_number', type: 'varchar', nullable: true })
containerNumber?: string | null;
/** 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;
}

View File

@@ -17,14 +17,11 @@ import { TrainSchedulingManage, TrainSchedulingView } from '../../common/booking
import { CreateLastMileDto } from './dto/create-last-mile.dto';
import { UpdateLastMileDto } from './dto/update-last-mile.dto';
import { AllocateLastMileContainersDto } from './dto/allocate-containers.dto';
import { SetVehiclesDto } from './dto/set-vehicles.dto';
import { SetDistancesDto } from './dto/set-distances.dto';
import { LastMileStatus } from './entities/last-mile.entity';
import { LastMileService } from './last-mile.service';
import { LastMileInvoiceService } from './last-mile-invoice.service';
import { Freight } from '@edr/types';
import { BillingService } from '../billing/billing.service';
import { BookingsService } from '../bookings/bookings.service';
@ApiTags('last-mile')
@ApiBearerAuth()
@@ -34,8 +31,6 @@ export class LastMileController {
constructor(
private readonly lastMileService: LastMileService,
private readonly lastMileInvoiceService: LastMileInvoiceService,
private readonly billingService: BillingService,
private readonly bookingsService: BookingsService
) {}
@Get()
@@ -84,40 +79,9 @@ export class LastMileController {
@TrainSchedulingManage()
@ApiOperation({ summary: 'Update a last-mile leg' })
async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateLastMileDto) {
const record = await this.lastMileService.update(id, dto);
// Auto-generate invoice if distance or payment was updated
const booking = await this.bookingsService.findById(record.bookingId);
const currency = booking.paymentCurrency || "ETB";
if (dto.exactKm !== undefined || dto.exactKm != record.exactKm || dto.remainingPayment !== undefined || dto.remainingPayment !== record.remainingPayment) {
await this.billingService.generateInvoice({
source: Freight.InvoiceSource.LastMile,
sourceId: record.id,
type: "LAST_MILE",
companyId: booking.companyId,
companyProfileId: booking.companyProfileId,
currency,
lines: [
{
chargeType: "LAST_MILE",
description: "Last Mile Transportation Service",
quantity: 1,
unitRate: record.remainingPayment,
amount: record.remainingPayment,
currency,
},
],
subtotalAmount: record.remainingPayment,
taxAmount: 0, // Replace if VAT/tax applies
totalAmount: record.remainingPayment,
dueInDays: 7,
status: Freight.InvoiceStatus.Pending,
});
await this.lastMileInvoiceService.ensureInvoiceFor(record);
}
return record;
// No invoice side-effects here — invoices are generated only via the
// explicit POST :id/invoice endpoint (the "Generate Invoice" action).
return this.lastMileService.update(id, dto);
}
@Delete(':id')
@@ -128,15 +92,6 @@ export class LastMileController {
return this.lastMileService.remove(id);
}
@Post(':id/allocate-containers')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Allocate containers to vehicles' })
async allocateContainers(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: AllocateLastMileContainersDto,
) {
return this.lastMileService.allocateContainers(id, dto.allocations);
}
@Post(':id/vehicles')
@TrainSchedulingManage()
@@ -145,6 +100,24 @@ export class LastMileController {
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: SetVehiclesDto,
) {
return this.lastMileService.setVehicles(id, dto.vehicleIds);
return this.lastMileService.setVehicles(id, dto.vehicles);
}
@Post(':id/distances')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Set per-vehicle actual distances (does not generate an invoice)' })
async setDistances(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: SetDistancesDto,
) {
return this.lastMileService.setDistances(id, dto.distances, dto.remainingPayment);
}
@Post(':id/invoice')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Generate the delivery-fee invoice for a last-mile leg' })
async generateInvoice(@Param('id', ParseUUIDPipe) id: string) {
const record = await this.lastMileService.findById(id);
return this.lastMileInvoiceService.ensureInvoiceFor(record);
}
}

View File

@@ -12,7 +12,7 @@ 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 { LastMileRepository } from './last-mile.repository';
import { InvoiceEventPayload } from '../billing/billing.service';
import { BillingService, InvoiceEventPayload } from '../billing/billing.service';
import { OnEvent } from '@nestjs/event-emitter';
import { FleetHistoryService } from '../fleet-history/fleet-history.service';
import { FleetEventType } from '../fleet-history/entities/fleet-event.entity';
@@ -46,8 +46,28 @@ export class LastMileService {
private readonly smsClient: SmsClientService,
private readonly dataSource: DataSource,
private readonly history: FleetHistoryService,
private readonly billing: BillingService,
) {}
/** Attach real invoice info (number/status) to records so the UI can show an
* invoice link only when one actually exists — NOT merely because distance
* was entered. Batched to avoid N+1. */
private async attachInvoices(records: LastMile[]): Promise<void> {
const invoices = await this.billing.findBySourceIds(
'last_mile',
records.map((r) => r.id),
);
const byId = new Map<string, { id: string; number: string; status: string }>();
for (const inv of invoices) {
if (!byId.has(inv.sourceId)) {
byId.set(inv.sourceId, { id: inv.id, number: inv.invoiceNumber, status: String(inv.status) });
}
}
for (const r of records) {
(r as LastMile & { invoice?: unknown }).invoice = byId.get(r.id) ?? null;
}
}
/** Resolve a vehicle's driver + human labels, for stamping mile events onto
* the driver's timeline and naming the vehicle. Best-effort — never throws. */
private async vehicleInfo(
@@ -159,6 +179,8 @@ export class LastMileService {
take: pageSize,
});
await this.attachInvoices(data);
return {
data,
meta: {
@@ -183,6 +205,8 @@ export class LastMileService {
throw new NotFoundException(`Last-mile record ${id} not found`);
}
await this.attachInvoices([record]);
return record;
}
@@ -219,14 +243,16 @@ export class LastMileService {
return record;
}
@OnEvent("lastmile.invoice.paid")
@OnEvent("last_mile.invoice.paid")
async onBookingInvoicePaid(payload: InvoiceEventPayload): Promise<void> {
try {
await this.lastMileRepository.update(payload.sourceId, { paid: true } as any);
this.logger.log(`Marked last-mile record ${payload.sourceId} as paid (invoice ${payload.invoiceId})`);
// Invoice paid → the delivery is complete. Route through update() so it
// also frees the trucks + records history (same as "Mark Delivered").
await this.update(payload.sourceId, { status: 'DELIVERED', paid: true } as unknown as UpdateLastMileDto);
this.logger.log(`Last-mile ${payload.sourceId} marked DELIVERED on invoice ${payload.invoiceId} payment`);
} catch (err) {
this.logger.error(
`Failed to update last-mile payment status for record ${payload.sourceId}: ${String(err)}`,
`Failed to deliver last-mile ${payload.sourceId} on payment: ${String(err)}`,
);
}
}
@@ -339,20 +365,28 @@ export class LastMileService {
}
/**
* Free every vehicle held by this record (direct assignment + container
* allocations), unless still in use by another active trip.
* Free every vehicle held by this record — junction assignments, the legacy
* direct vehicle, and container allocations unless still used by another
* active trip.
*/
private async releaseVehicles(record: LastMile): Promise<void> {
const recordAllocations = await this.dataSource.manager.find(
LastMileContainerAllocation,
{ where: { lastMileId: record.id } },
);
const vehicleIds = recordAllocations
.map((a) => a.vehicleId)
.filter((id): id is string => Boolean(id));
if (record.vehicleId) {
vehicleIds.push(record.vehicleId);
}
const [assignments, recordAllocations] = await Promise.all([
this.dataSource.manager.find(LastMileVehicleAssignment, {
where: { lastMileId: record.id },
}),
this.dataSource.manager.find(LastMileContainerAllocation, {
where: { lastMileId: record.id },
}),
]);
const vehicleIds = [
...new Set(
[
...assignments.map((a) => a.vehicleId),
...recordAllocations.map((a) => a.vehicleId),
record.vehicleId ?? null,
].filter((id): id is string => Boolean(id)),
),
];
await this.vehiclesService.releaseIfUnused(vehicleIds);
}
@@ -362,19 +396,37 @@ 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.
*/
async setVehicles(id: string, vehicleIds: string[]): Promise<LastMile> {
async setVehicles(
id: string,
inputs: Array<{ vehicleId: string; containerNumber?: string | null }>,
): Promise<LastMile> {
const existing = await this.findById(id);
const desired = [...new Set(vehicleIds.filter(Boolean))];
// Dedupe by vehicleId, keeping the container number; preserve order.
const desiredMap = new Map<string, string | null>();
for (const inp of inputs) {
if (inp.vehicleId) desiredMap.set(inp.vehicleId, inp.containerNumber ?? null);
}
const desired = [...desiredMap.keys()];
const desiredSet = new Set(desired);
const manager = this.dataSource.manager;
const current = await manager.find(LastMileVehicleAssignment, {
where: { lastMileId: id },
});
const currentIds = current.map((a) => a.vehicleId);
const currentSet = new Set(currentIds);
const desiredSet = new Set(desired);
const added = desired.filter((v) => !currentSet.has(v));
const removed = currentIds.filter((v) => !desiredSet.has(v));
const junctionSet = new Set(current.map((a) => a.vehicleId));
// Fold the legacy vehicleId into the release set — a vehicle assigned via the
// old single-vehicle path has no junction row but must still be freed.
const releaseIds = [...new Set(
current.map((a) => a.vehicleId).concat(existing.vehicleId ? [existing.vehicleId] : []),
)];
const added = desired.filter((v) => !junctionSet.has(v));
const removed = releaseIds.filter((v) => !desiredSet.has(v));
// Vehicles that stay but whose container number changed.
const changed = current.filter(
(a) =>
desiredMap.has(a.vehicleId) &&
(a.containerNumber ?? null) !== (desiredMap.get(a.vehicleId) ?? null),
);
await this.dataSource.transaction(async (tx) => {
if (removed.length) {
@@ -384,7 +436,18 @@ export class LastMileService {
});
}
for (const vehicleId of added) {
await tx.insert(LastMileVehicleAssignment, { lastMileId: id, vehicleId });
await tx.insert(LastMileVehicleAssignment, {
lastMileId: id,
vehicleId,
containerNumber: desiredMap.get(vehicleId) ?? null,
});
}
for (const row of changed) {
await tx.update(
LastMileVehicleAssignment,
{ lastMileId: id, vehicleId: row.vehicleId },
{ containerNumber: desiredMap.get(row.vehicleId) ?? null },
);
}
});
@@ -420,6 +483,41 @@ export class LastMileService {
return this.findById(id);
}
/**
* Record each truck's actual distance. The delivery total (exact_km) is their
* sum and drives billing; `remainingPayment` (total km × rate) is recomputed
* client-side. Does NOT generate an invoice — that's a separate explicit step.
*/
async setDistances(
id: string,
distances: Array<{ vehicleId: string; distanceKm: number }>,
remainingPayment?: number,
): Promise<LastMile> {
await this.findById(id);
// Distances are locked once the invoice exists.
const invoices = await this.billing.findBySourceIds('last_mile', [id]);
if (invoices.length) {
throw new BadRequestException(
'Distances cannot be changed after the invoice is generated',
);
}
for (const d of distances) {
await this.dataSource.manager.update(
LastMileVehicleAssignment,
{ lastMileId: id, vehicleId: d.vehicleId },
{ distanceKm: d.distanceKm },
);
}
const total = distances.reduce((s, d) => s + (Number(d.distanceKm) || 0), 0);
await this.lastMileRepository.update(id, {
exactKm: total,
...(remainingPayment != null ? { remainingPayment } : {}),
} as any);
return this.findById(id);
}
private async notifyDriverAssignment(vehicleId: string, record: LastMile): Promise<void> {
try {
const vehicle = await this.vehiclesService.findById(vehicleId);
@@ -460,93 +558,54 @@ export class LastMileService {
}
async remove(id: string): Promise<void> {
await this.findById(id);
await this.lastMileRepository.softDelete(id);
}
const existing = await this.findById(id);
async allocateContainers(
lastMileId: string,
allocations: Array<{ containerId: string; vehicleId: string }>,
) {
const lastMile = await this.findById(lastMileId);
if (!lastMile) {
throw new NotFoundException(`Last-mile record ${lastMileId} not found`);
// Can't delete once billed.
const invoices = await this.billing.findBySourceIds('last_mile', [id]);
if (invoices.length) {
throw new BadRequestException(
'Cannot delete a last-mile delivery after its invoice is generated',
);
}
// Capture the vehicles currently on these containers so a reallocation can
// be diffed into assigned/released history events below.
const previousAllocations = await this.dataSource.manager.find(
LastMileContainerAllocation,
{
where: {
lastMileId,
containerId: In(allocations.map((a) => a.containerId)),
},
},
);
const previousVehicleIds = previousAllocations
.map((a) => a.vehicleId)
.filter((id): id is string => Boolean(id));
// Every vehicle this delivery holds — junction + legacy + container rows.
const assignments = await this.dataSource.manager.find(LastMileVehicleAssignment, {
where: { lastMileId: id },
});
const allocations = await this.dataSource.manager.find(LastMileContainerAllocation, {
where: { lastMileId: id },
});
const vehicleIds = [
...new Set(
[
...assignments.map((a) => a.vehicleId),
...allocations.map((a) => a.vehicleId),
existing.vehicleId ?? null,
].filter((v): v is string => Boolean(v)),
),
];
await this.dataSource.transaction(async (manager) => {
for (const allocation of allocations) {
await manager.delete(LastMileContainerAllocation, {
lastMileId,
containerId: allocation.containerId,
});
await manager.insert(LastMileContainerAllocation, {
lastMileId,
containerId: allocation.containerId,
vehicleId: allocation.vehicleId,
containerType: 'CONTAINER',
quantity: 1,
await this.lastMileRepository.softDelete(id);
if (assignments.length) {
await this.dataSource.manager.softDelete(LastMileVehicleAssignment, { lastMileId: id });
}
// Free every vehicle no longer held by another active trip (releaseIfUnused
// ignores this now soft-deleted record) and audit the release.
if (vehicleIds.length) {
await this.vehiclesService.releaseIfUnused(vehicleIds);
const bookingRef = await this.resolveBookingRef(existing);
for (const vehicleId of vehicleIds) {
const info = await this.vehicleInfo(vehicleId);
await this.history.record({
eventType: FleetEventType.MILE_VEHICLE_RELEASED,
vehicleId,
lastMileId: id,
driverId: info.driverId,
metadata: { mile: 'LAST', bookingRef, vehiclePlate: info.plate, driverName: info.driverName },
});
}
});
// Keep vehicle availability in sync: newly-allocated cars go BUSY, cars no
// longer on any of these containers are freed if unused elsewhere.
const vehicleIds = new Set(allocations.map((a) => a.vehicleId));
await Promise.all(
[...vehicleIds].map((id) =>
this.vehiclesService.setAvailability(id, VehicleAvailability.BUSY),
),
);
await this.vehiclesService.releaseIfUnused(
previousVehicleIds.filter((id) => !vehicleIds.has(id)),
);
// History: one event per vehicle actually added or removed by this
// multi-car (re)allocation, so reassignments show on every timeline.
const prevSet = new Set(previousVehicleIds);
const bookingRef = await this.resolveBookingRef(lastMile);
for (const vehicleId of vehicleIds) {
if (prevSet.has(vehicleId)) continue;
const info = await this.vehicleInfo(vehicleId);
await this.history.record({
eventType: FleetEventType.MILE_VEHICLE_ASSIGNED,
vehicleId,
lastMileId,
driverId: info.driverId,
label: lastMile.status,
metadata: { mile: 'LAST', bookingRef, vehiclePlate: info.plate, driverName: info.driverName },
});
}
for (const vehicleId of previousVehicleIds) {
if (vehicleIds.has(vehicleId)) continue;
const info = await this.vehicleInfo(vehicleId);
await this.history.record({
eventType: FleetEventType.MILE_VEHICLE_RELEASED,
vehicleId,
lastMileId,
driverId: info.driverId,
metadata: { mile: 'LAST', bookingRef, vehiclePlate: info.plate, driverName: info.driverName },
});
}
return {
success: true,
allocated: allocations.length,
};
}
}