This commit is contained in:
natib21
2026-07-03 22:43:45 +00:00
parent cad4b84b8c
commit 1d8f095831
8 changed files with 120 additions and 518 deletions

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);
}
}