Merge branch 'dev' into freight/feat/fixes-v1

This commit is contained in:
Nathnael
2026-07-10 08:54:34 +00:00
139 changed files with 8644 additions and 1557 deletions

View File

@@ -400,8 +400,18 @@ export class BookingPricingService {
* All three components are produced by RuleEngineService.evaluate, so submit
* simply re-runs the engine — there is no extra submit-time inflation.
*/
async computeSubmitPriorityScore(booking: Booking): Promise<number> {
async computeSubmitPriorityScore(
booking: Booking,
totalWagonsOverride?: number,
): Promise<number> {
const evalInput = await this.buildEvalInputForBooking(booking);
// BULK bookings have no container lines, so buildEvalInputForBooking yields
// totalWagons = 0 and every wagon-range priority config misses. The batch
// engine derives a bulk booking's wagon footprint from tonnage vs. live
// wagon capacity and passes it here to score the booking properly.
if (totalWagonsOverride != null && totalWagonsOverride > 0) {
evalInput.totalWagons = totalWagonsOverride;
}
const ruleResult = await this.ruleEngineService.evaluate(evalInput);
return ruleResult.priorityScore;
}

View File

@@ -11,6 +11,7 @@ import { RuleEngineModule } from '../rule-engine/rule-engine.module';
import { FileUploadSettingsModule } from '../file-upload-settings/file-upload-settings.module';
import { SignaturesModule } from '../signatures/signatures.module';
import { BillingModule } from '../billing/billing.module';
import { DocumentsModule } from '../billing/documents/documents.module';
import { FirstMileModule } from '../first-mile/first-mile.module';
import { LastMileModule } from '../last-mile/last-mile.module';
import { BookingContractService } from './booking-contract.service';
@@ -68,6 +69,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
CustomerTruckContainer,
]),
BillingModule,
DocumentsModule,
NotificationsModule,
NotificationInboxModule,
forwardRef(() => FirstMileModule),

View File

@@ -44,6 +44,11 @@ export interface BookingListFilterOptions {
customsClearingEnabled?: boolean;
createdFrom?: string;
createdTo?: string;
scheduledFrom?: string;
scheduledTo?: string;
originYardId?: string;
destinationYardId?: string;
isGovernment?: 'true' | 'false';
consolidationPaired?: string;
}
@@ -814,6 +819,32 @@ export class BookingsRepository extends BaseRepository<Booking> {
createdTo: options.createdTo,
});
}
if (options.scheduledFrom) {
qb.andWhere('booking.scheduled_date >= :scheduledFrom', {
scheduledFrom: options.scheduledFrom,
});
}
if (options.scheduledTo) {
// Inclusive end-of-day: callers pass a date; include the whole day.
qb.andWhere('booking.scheduled_date <= :scheduledTo', {
scheduledTo: options.scheduledTo,
});
}
if (options.originYardId) {
qb.andWhere('booking.origin_yard_id = :originYardId', {
originYardId: options.originYardId,
});
}
if (options.destinationYardId) {
qb.andWhere('booking.destination_yard_id = :destinationYardId', {
destinationYardId: options.destinationYardId,
});
}
if (options.isGovernment === 'true') {
qb.andWhere('booking.is_government = TRUE');
} else if (options.isGovernment === 'false') {
qb.andWhere('booking.is_government = FALSE');
}
if (options.tradeDirection) {
qb.andWhere('booking.trade_direction = :tradeDirection', {
tradeDirection: options.tradeDirection,
@@ -999,6 +1030,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
.andWhere('sb.id IS NULL')
@@ -1030,6 +1062,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
.where('booking.origin_yard_id = :originYardId', { originYardId })
.andWhere('booking.destination_yard_id = :destinationYardId', {
@@ -1069,6 +1102,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
.where('booking.origin_yard_id IN (:...corridorYardIds)', { corridorYardIds })
.andWhere('booking.destination_yard_id IN (:...corridorYardIds)', {
@@ -1134,6 +1168,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
.orderBy('booking.is_government', 'DESC')
.addOrderBy('booking.priority_score', 'DESC')
@@ -1148,6 +1183,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
.andWhere(`booking.status IN ('SELECTED_FOR_BATCH', 'AWAITING_PAYMENT')`)
.getMany();
@@ -1177,6 +1213,8 @@ export class BookingsRepository extends BaseRepository<Booking> {
return this.repository
.createQueryBuilder('booking')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.innerJoin(
TrainScheduleBooking,
'sb',

View File

@@ -50,7 +50,8 @@ import { Booking } from './entities/booking.entity';
import { BookingContainerAllocation } from './entities/booking-container-allocation.entity';
import { FileRecord } from '../files/entities/file.entity';
import { CustomerTruckAssignmentDto } from './dto/customer-truck-assignment.dto';
import { ContractPdfService } from '../../contracts/contract-pdf.service';
import { PdfRenderService } from '../billing/documents/pdf-render.service';
import { buildTabularFallbackPdf } from '../billing/documents/styled-pdf.util';
/** Paginated booking list: flat `total` (backoffice) + `meta` block (portal). */
export interface PaginatedBookings {
@@ -99,7 +100,7 @@ export class BookingsService {
private readonly containerTypesService: ContainerTypesService,
private readonly consolidationService: ConsolidationService,
private readonly vehiclesService: VehiclesService,
private readonly contractPdfService: ContractPdfService,
private readonly pdfRender: PdfRenderService,
private readonly events: EventEmitter2,
) {}
@@ -170,7 +171,12 @@ export class BookingsService {
);
const html = this.buildCustomerTruckFreightOrderHtml(booking, trucks);
const buffer = await this.contractPdfService.htmlToPdfBuffer(html);
// Chromium when available; otherwise the styled tabular fallback (never the
// generic text dump — the freight order is an outward-facing gate document).
const buffer = await this.pdfRender.htmlToPdfBuffer(html, {
label: 'freight order',
fallback: (prepared) => buildTabularFallbackPdf(prepared),
});
return {
filename: `freight-order-${booking.reference.replace(/[^a-zA-Z0-9_-]+/g, '-')}.pdf`,
buffer,
@@ -262,21 +268,10 @@ export class BookingsService {
containers: string | null;
}>,
): string {
const esc = (v: unknown) => this.escapeHtml(String(v ?? '-'));
const assignedAt = booking.customerTruckAssignedAt
? new Date(booking.customerTruckAssignedAt).toLocaleString('en-GB')
: '-';
const bookingRows: Array<[string, string | null | undefined]> = [
['Booking Reference', booking.reference],
['Client Name', booking.company?.name],
['Client ID', booking.companyId],
['Trade Direction', booking.tradeDirection],
['Freight Type', booking.freightType],
['Assigned At', assignedAt],
['Booking Status', booking.status],
];
const bookingRowHtml = bookingRows
.map(([label, value]) => `<tr><th>${this.escapeHtml(label)}</th><td>${this.escapeHtml(value || '-')}</td></tr>`)
.join('');
// Fall back to the legacy single-truck booking columns when there are no
// multi-truck rows (bookings assigned before the multi-truck feature).
@@ -297,44 +292,63 @@ export class BookingsService {
]
: [];
const truckBlocks = truckList
.map((t, i) => {
const rows: Array<[string, string | null | undefined]> = [
['Truck Plate Number', t.plateNumber],
['Driver Name', t.driverName],
['Truck Type', t.truckType],
['Containers Loaded', t.containers],
[
'Arrival',
t.arrivedAt ? new Date(t.arrivedAt).toLocaleString('en-GB') : 'Awaiting arrival',
],
];
const html = rows
.map(
([label, value]) =>
`<tr><th>${this.escapeHtml(label)}</th><td>${this.escapeHtml(value || '-')}</td></tr>`,
)
.join('');
return `<div class="truck"><h2>Truck ${i + 1}</h2><table>${html}</table></div>`;
})
const truckRows = truckList
.map(
(t, i) => `<tr>
<td class="num">${i + 1}</td>
<td>${esc(t.plateNumber)}</td>
<td>${esc(t.driverName)}</td>
<td>${esc(t.truckType)}</td>
<td>${esc(t.containers)}</td>
<td>${t.arrivedAt ? esc(new Date(t.arrivedAt).toLocaleString('en-GB')) : 'Awaiting arrival'}</td>
</tr>`,
)
.join('');
const copy = (watermark: string) => `
<section class="copy">
<div class="watermark">${this.escapeHtml(watermark)}</div>
<header>
<div class="watermark">${esc(watermark)}</div>
<div class="top">
<div>
<div class="brand">Ethio-Djibouti Railway S.C.</div>
<h1>Freight Order</h1>
<p>Customer external truck assignment — ${truckList.length} truck${truckList.length !== 1 ? 's' : ''}</p>
<div class="subtitle">Customer external truck assignment — ${truckList.length} truck${truckList.length !== 1 ? 's' : ''}</div>
</div>
<strong>${this.escapeHtml(booking.reference)}</strong>
</header>
<table>${bookingRowHtml}</table>
${truckBlocks}
<div class="meta">
Booking
<strong>${esc(booking.reference)}</strong>
Generated: ${esc(new Date().toLocaleString('en-GB'))}
</div>
</div>
<div class="summary">
<div class="tile"><span>Client</span><strong>${esc(booking.company?.name)}</strong></div>
<div class="tile"><span>Client ID</span><strong>${esc(booking.companyId)}</strong></div>
<div class="tile"><span>Trade direction</span><strong>${esc(booking.tradeDirection)}</strong></div>
<div class="tile"><span>Freight type</span><strong>${esc(booking.freightType)}</strong></div>
<div class="tile"><span>Assigned at</span><strong>${esc(assignedAt)}</strong></div>
<div class="tile"><span>Booking status</span><strong>${esc(booking.status)}</strong></div>
</div>
<table>
<thead>
<tr>
<th class="num">#</th>
<th>Truck plate</th>
<th>Driver</th>
<th>Truck type</th>
<th>Containers loaded</th>
<th>Arrival</th>
</tr>
</thead>
<tbody>${truckRows}</tbody>
</table>
<div class="notice">
Present this freight order at the warehouse gate. Each truck may only collect the
containers listed against it; the handover must be signed before any truck leaves.
</div>
<div class="signatures">
<div>Customer / Carrier Signature</div>
<div>Port Operations Verification</div>
<div>Gate Security Verification</div>
<div class="line">Customer / Carrier signature — date</div>
<div class="line">Port operations verification — date</div>
<div class="line">Gate security verification — date</div>
</div>
</section>`;
@@ -342,21 +356,30 @@ export class BookingsService {
<html>
<head>
<meta charset="utf-8" />
<title>Freight Order</title>
<style>
body { font-family: Arial, sans-serif; color: #10202f; margin: 0; }
.copy { position: relative; min-height: 46vh; padding: 28px 32px; page-break-inside: avoid; border-bottom: 1px dashed #94a3b8; }
.watermark { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 34px; font-weight: 800; color: rgba(16, 32, 47, 0.08); transform: rotate(-18deg); pointer-events: none; }
header { display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 3px solid #0a9f6a; padding-bottom: 14px; margin-bottom: 18px; }
h1 { margin: 0; font-size: 28px; letter-spacing: 0; }
h2 { margin: 18px 0 8px; font-size: 14px; color: #0a6f4d; }
p { margin: 4px 0 0; color: #64748b; }
strong { font-size: 16px; color: #0a9f6a; }
table { width: 100%; border-collapse: collapse; position: relative; z-index: 1; margin-bottom: 6px; }
th, td { border: 1px solid #cbd5e1; padding: 9px 10px; text-align: left; font-size: 12px; }
th { width: 34%; background: #f1f5f9; }
.truck { page-break-inside: avoid; }
.signatures { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 34px; font-size: 11px; color: #475569; position: relative; z-index: 1; }
.signatures div { border-top: 1px solid #334155; padding-top: 8px; min-height: 28px; }
@page { size: A4 portrait; margin: 10mm; }
* { box-sizing: border-box; }
body { margin: 0; color: #0f172a; font-family: Arial, sans-serif; }
.copy { position: relative; padding: 24px 28px; page-break-inside: avoid; border-bottom: 1px dashed #94a3b8; }
.watermark { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 30px; font-weight: 800; color: rgba(15, 23, 42, 0.07); transform: rotate(-18deg); pointer-events: none; }
.top { display: flex; justify-content: space-between; border-bottom: 3px solid #0f766e; padding-bottom: 10px; gap: 24px; }
.brand { font-size: 11px; color: #475569; text-transform: uppercase; letter-spacing: .08em; font-weight: 700; }
h1 { margin: 6px 0 0; font-size: 25px; line-height: 1.05; }
.subtitle { margin-top: 4px; color: #64748b; font-size: 12px; }
.meta { text-align: right; font-size: 11px; color: #475569; min-width: 210px; }
.meta strong { display: block; margin: 4px 0; color: #0f172a; font-size: 15px; }
.summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 14px 0; }
.tile { border: 1px solid #cbd5e1; padding: 8px; min-height: 48px; }
.tile span { display: block; color: #64748b; font-size: 9px; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 4px; }
.tile strong { font-size: 11px; }
table { width: 100%; border-collapse: collapse; position: relative; z-index: 1; }
th { background: #f8fafc; color: #475569; text-align: left; }
th, td { border: 1px solid #cbd5e1; padding: 6px 7px; font-size: 10.5px; vertical-align: top; }
.num { text-align: right; width: 26px; }
.notice { margin-top: 10px; border-left: 4px solid #0f766e; background: #f0fdfa; padding: 8px 10px; font-size: 10px; color: #134e4a; }
.signatures { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; margin-top: 30px; position: relative; z-index: 1; }
.line { border-top: 1px solid #334155; padding-top: 7px; font-size: 9px; color: #475569; min-height: 30px; }
</style>
</head>
<body>
@@ -1125,6 +1148,30 @@ export class BookingsService {
);
}
/**
* Batched version of the findById flag: marks each page item whose booking
* has a generated-but-unsigned SELF_HAUL handover, so list rows (portal
* dashboard) can show "Approve delivery" for exactly the generated→signed
* window. One query for the whole page.
*/
private async attachHandoverFlags(bookings: Booking[]): Promise<void> {
const ids = bookings.map((b) => b.id);
if (!ids.length) return;
const rows: Array<{ bookingId: string }> = await this.dataSource.query(
`SELECT DISTINCT booking_id AS "bookingId"
FROM freight.booking_handovers
WHERE booking_id = ANY($1::uuid[])
AND signed_at IS NULL AND deleted_at IS NULL
AND mile_type = 'SELF_HAUL'`,
[ids],
);
const pending = new Set(rows.map((r) => r.bookingId));
for (const b of bookings) {
(b as Booking & { handoverAwaitingSignature?: boolean }).handoverAwaitingSignature =
pending.has(b.id);
}
}
async findAll(
filter: FilterBookingDto,
forceCompanyId?: string,
@@ -1135,7 +1182,7 @@ export class BookingsService {
const statusFilter = this.parseStatusFilter(filter);
const schedulingStatusFilter = this.parseSchedulingStatusFilter(filter);
return this.bookingsRepository.findAllPaginated({
const result = await this.bookingsRepository.findAllPaginated({
page,
pageSize,
...statusFilter,
@@ -1158,10 +1205,17 @@ export class BookingsService {
paymentStatus: filter.paymentStatus,
createdFrom: filter.createdFrom,
createdTo: filter.createdTo,
scheduledFrom: filter.scheduledFrom,
scheduledTo: filter.scheduledTo,
originYardId: filter.originYardId,
destinationYardId: filter.destinationYardId,
isGovernment: filter.isGovernment,
consolidationPaired: filter.consolidationPaired,
sortBy: filter.sortBy,
sortOrder: filter.sortOrder,
});
await this.attachHandoverFlags(result.items ?? []);
return result;
}
/** Booking statuses at which a customer can pay (mirrors booking-payment.service). */
@@ -1371,11 +1425,17 @@ export class BookingsService {
serviceTypeId: filter.serviceTypeId,
cargoTypeId: filter.cargoTypeId,
freightType: filter.freightType,
bookingType: filter.bookingType,
tradeDirection: filter.tradeDirection,
paymentCurrency: filter.paymentCurrency,
paymentStatus: filter.paymentStatus,
createdFrom: filter.createdFrom,
createdTo: filter.createdTo,
scheduledFrom: filter.scheduledFrom,
scheduledTo: filter.scheduledTo,
originYardId: filter.originYardId,
destinationYardId: filter.destinationYardId,
isGovernment: filter.isGovernment,
consolidationPaired: filter.consolidationPaired,
};

View File

@@ -81,6 +81,31 @@ export class FilterBookingDto {
@IsDateString()
createdTo?: string;
@ApiPropertyOptional({ description: 'Filter bookings scheduled on/after this date (ISO)' })
@IsOptional()
@IsDateString()
scheduledFrom?: string;
@ApiPropertyOptional({ description: 'Filter bookings scheduled on/before this date (ISO)' })
@IsOptional()
@IsDateString()
scheduledTo?: string;
@ApiPropertyOptional({ format: 'uuid', description: 'Filter by origin yard' })
@IsOptional()
@IsUUID()
originYardId?: string;
@ApiPropertyOptional({ format: 'uuid', description: 'Filter by destination yard' })
@IsOptional()
@IsUUID()
destinationYardId?: string;
@ApiPropertyOptional({ enum: ['true', 'false'], description: 'Filter government vs private bookings' })
@IsOptional()
@IsIn(['true', 'false'])
isGovernment?: 'true' | 'false';
@ApiPropertyOptional({ enum: TRADE_DIRECTIONS })
@IsOptional()
@IsIn([...TRADE_DIRECTIONS])

View File

@@ -0,0 +1,97 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Put,
} from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { FreightAdmin } from "../../common/booking-guards";
import { ContractTemplatesService } from "./contract-templates.service";
import {
CreateArticleDto,
PreviewContractTemplateDto,
ReplaceArticlesDto,
UpdateArticleDto,
UpdateContractTemplateDto,
} from "./dto/contract-template.dto";
@ApiTags("contract-templates")
@Controller("contract-templates")
export class ContractTemplatesController {
constructor(private readonly service: ContractTemplatesService) {}
// Reads stay open to authenticated staff (the backoffice Templates tab);
// writes are admin-guarded like other freight configuration resources.
@Get()
@ApiOperation({ summary: "List the six contract document templates" })
list() {
return this.service.list();
}
@Get(":code")
@ApiOperation({ summary: "Get one contract template by code" })
getByCode(@Param("code") code: string) {
return this.service.getByCode(code);
}
@Patch(":code")
@FreightAdmin()
@ApiOperation({ summary: "Update template metadata (name, title, recitals, active flag)" })
update(@Param("code") code: string, @Body() dto: UpdateContractTemplateDto) {
return this.service.update(code, dto);
}
@Post(":code/preview")
@ApiOperation({
summary: "Render an HTML preview of the template against mock contract data",
})
preview(
@Param("code") code: string,
@Body() dto: PreviewContractTemplateDto,
) {
return this.service.preview(code, dto);
}
/* ------------------------- article routes ------------------------- */
@Put(":code/articles")
@FreightAdmin()
@ApiOperation({ summary: "Replace the full ordered article list (used for reorder)" })
replaceArticles(@Param("code") code: string, @Body() dto: ReplaceArticlesDto) {
return this.service.replaceArticles(code, dto.articles);
}
@Post(":code/articles")
@FreightAdmin()
@ApiOperation({ summary: "Add an article to the template" })
addArticle(@Param("code") code: string, @Body() dto: CreateArticleDto) {
return this.service.addArticle(code, dto);
}
@Patch(":code/articles/:articleId")
@FreightAdmin()
@ApiOperation({ summary: "Update an article's title or body" })
updateArticle(
@Param("code") code: string,
@Param("articleId") articleId: string,
@Body() dto: UpdateArticleDto,
) {
return this.service.updateArticle(code, articleId, dto);
}
@Delete(":code/articles/:articleId")
@FreightAdmin()
@ApiOperation({ summary: "Remove an article from the template" })
removeArticle(
@Param("code") code: string,
@Param("articleId") articleId: string,
) {
return this.service.removeArticle(code, articleId);
}
}

View File

@@ -0,0 +1,21 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ContractRendererService } from "../../contracts/contract-renderer.service";
import { ContractTemplatesController } from "./contract-templates.controller";
import { ContractTemplatesRepository } from "./contract-templates.repository";
import { ContractTemplatesService } from "./contract-templates.service";
import { ContractTemplate } from "./entities/contract-template.entity";
@Module({
imports: [TypeOrmModule.forFeature([ContractTemplate])],
controllers: [ContractTemplatesController],
providers: [
ContractTemplatesRepository,
ContractTemplatesService,
// Stateless Handlebars renderer reused from src/contracts for previews.
ContractRendererService,
],
exports: [ContractTemplatesService],
})
export class ContractTemplatesModule {}

View File

@@ -0,0 +1,31 @@
import { BaseRepository } from "@edr/api-common";
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
ContractTemplate,
ContractTemplateCode,
} from "./entities/contract-template.entity";
@Injectable()
export class ContractTemplatesRepository extends BaseRepository<ContractTemplate> {
constructor(
@InjectRepository(ContractTemplate)
repository: Repository<ContractTemplate>,
) {
super(repository);
}
findByCode(code: ContractTemplateCode): Promise<ContractTemplate | null> {
return this.repository.findOne({ where: { code } });
}
override findAll(): Promise<ContractTemplate[]> {
return this.repository.find({ order: { code: "ASC" } });
}
async saveTemplate(template: ContractTemplate): Promise<ContractTemplate> {
return this.repository.save(template);
}
}

View File

@@ -0,0 +1,66 @@
import { ContractRendererService } from "../../contracts/contract-renderer.service";
import { CONTRACT_TEMPLATE_DEFAULTS } from "../../seed/data/contract-template-defaults";
import { ContractTemplatesService } from "./contract-templates.service";
import { ContractTemplatesRepository } from "./contract-templates.repository";
import {
ContractTemplate,
contractTemplateCodeFor,
} from "./entities/contract-template.entity";
function seededTemplate(code: string): ContractTemplate {
const seed = CONTRACT_TEMPLATE_DEFAULTS.find((t) => t.code === code)!;
return {
id: "00000000-0000-0000-0000-000000000001",
code: seed.code,
name: seed.name,
description: seed.description,
documentTitle: seed.documentTitle,
whereasClauses: seed.whereasClauses,
articles: seed.articles.map((article, index) => ({ ...article, order: index + 1 })),
isActive: true,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
} as ContractTemplate;
}
describe("contractTemplateCodeFor", () => {
it("maps every direction/freight pair to one of the six codes", () => {
expect(contractTemplateCodeFor("IMPORT", "BULK")).toBe("IMPORT_BULK");
expect(contractTemplateCodeFor("EXPORT", "CONTAINER")).toBe("EXPORT_CONTAINER");
expect(contractTemplateCodeFor("DOMESTIC", "CONTAINER")).toBe("INTERCITY_CONTAINER");
expect(contractTemplateCodeFor("DOMESTIC", "BULK")).toBe("INTERCITY_BULK");
expect(contractTemplateCodeFor(null, null)).toBe("INTERCITY_CONTAINER");
});
});
describe("ContractTemplatesService.preview", () => {
const renderer = new ContractRendererService();
renderer.onModuleInit();
const repository = {
findByCode: jest.fn((code: string) => Promise.resolve(seededTemplate(code))),
} as unknown as ContractTemplatesRepository;
const service = new ContractTemplatesService(repository, renderer);
it.each(CONTRACT_TEMPLATE_DEFAULTS.map((t) => [t.code] as const))(
"renders a complete mock preview for %s",
async (code) => {
const { html } = await service.preview(code);
expect(html).toContain("Article 1");
expect(html).toContain("Article 13");
expect(html).toContain("Abyssinia Trading PLC");
expect(html).toContain("Annex A — Commercial Schedule");
// No unrendered handlebars placeholders may leak into the document.
expect(html).not.toContain("{{");
// Greenish theme applied.
expect(html).toContain("#1b9e7a");
},
);
it("interpolates {{contractYear}} inside seeded article bodies", async () => {
const { html } = await service.preview("IMPORT_BULK");
expect(html).toContain(`August 31, ${new Date().getFullYear()}`);
});
});

View File

@@ -0,0 +1,276 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { randomUUID } from "node:crypto";
import { ContractRendererService } from "../../contracts/contract-renderer.service";
import { getTemplateMeta } from "../../contracts/contract-template.registry";
import {
ContractDynamicTemplateView,
ContractViewModel,
} from "../../contracts/contract-view-model.builder";
import { ContractTemplatesRepository } from "./contract-templates.repository";
import {
CreateArticleDto,
PreviewContractTemplateDto,
ReplaceArticleDto,
UpdateArticleDto,
UpdateContractTemplateDto,
} from "./dto/contract-template.dto";
import {
CONTRACT_TEMPLATE_CODES,
ContractTemplate,
ContractTemplateArticle,
ContractTemplateCode,
contractTemplateCodeFor,
} from "./entities/contract-template.entity";
/** Registry keys used to derive labels for the mock preview per template code. */
const PREVIEW_TEMPLATE_KEYS: Record<ContractTemplateCode, string> = {
IMPORT_BULK: "IMP_BULK_USD_FORWARDING",
EXPORT_BULK: "EXP_BULK_USD_TRANSPORT_ONLY",
INTERCITY_BULK: "DOM_BULK_USD_TRANSPORT_ONLY",
IMPORT_CONTAINER: "IMP_CON_USD_TRANSPORT_ONLY",
EXPORT_CONTAINER: "EXP_CON_USD_FORWARDING",
INTERCITY_CONTAINER: "DOM_CON_USD_TRANSPORT_ONLY",
};
@Injectable()
export class ContractTemplatesService {
constructor(
private readonly repository: ContractTemplatesRepository,
private readonly renderer: ContractRendererService,
) {}
async list(): Promise<ContractTemplate[]> {
const templates = await this.repository.findAll();
const rank = new Map(CONTRACT_TEMPLATE_CODES.map((code, i) => [code, i] as const));
return templates.sort(
(a, b) => (rank.get(a.code) ?? 99) - (rank.get(b.code) ?? 99),
);
}
async getByCode(code: string): Promise<ContractTemplate> {
const template = await this.repository.findByCode(this.assertCode(code));
if (!template) {
throw new NotFoundException(`Contract template ${code} not found`);
}
return template;
}
/**
* The active template used when generating a contract document for the given
* direction/freight pair; null when missing or deactivated (the renderer then
* falls back to the built-in generic layout).
*/
async findActiveForContract(
tradeDirection?: string | null,
freightType?: string | null,
): Promise<ContractTemplate | null> {
const code = contractTemplateCodeFor(tradeDirection, freightType);
const template = await this.repository.findByCode(code);
return template?.isActive ? template : null;
}
async update(code: string, dto: UpdateContractTemplateDto): Promise<ContractTemplate> {
const template = await this.getByCode(code);
if (dto.name !== undefined) template.name = dto.name;
if (dto.description !== undefined) template.description = dto.description;
if (dto.documentTitle !== undefined) template.documentTitle = dto.documentTitle;
if (dto.whereasClauses !== undefined) template.whereasClauses = dto.whereasClauses;
if (dto.isActive !== undefined) template.isActive = dto.isActive;
return this.repository.saveTemplate(template);
}
async addArticle(code: string, dto: CreateArticleDto): Promise<ContractTemplate> {
const template = await this.getByCode(code);
const articles = this.sorted(template.articles);
const article: ContractTemplateArticle = {
id: randomUUID(),
title: dto.title,
body: dto.body,
order: 0,
};
const index =
dto.position && dto.position <= articles.length ? dto.position - 1 : articles.length;
articles.splice(index, 0, article);
template.articles = this.renumber(articles);
return this.repository.saveTemplate(template);
}
async updateArticle(
code: string,
articleId: string,
dto: UpdateArticleDto,
): Promise<ContractTemplate> {
const template = await this.getByCode(code);
const article = template.articles.find((item) => item.id === articleId);
if (!article) {
throw new NotFoundException(`Article ${articleId} not found on template ${code}`);
}
if (dto.title !== undefined) article.title = dto.title;
if (dto.body !== undefined) article.body = dto.body;
template.articles = this.renumber(this.sorted(template.articles));
return this.repository.saveTemplate(template);
}
async removeArticle(code: string, articleId: string): Promise<ContractTemplate> {
const template = await this.getByCode(code);
const remaining = template.articles.filter((item) => item.id !== articleId);
if (remaining.length === template.articles.length) {
throw new NotFoundException(`Article ${articleId} not found on template ${code}`);
}
template.articles = this.renumber(this.sorted(remaining));
return this.repository.saveTemplate(template);
}
/** Replace the full ordered article list (also how the editor reorders). */
async replaceArticles(
code: string,
articles: ReplaceArticleDto[],
): Promise<ContractTemplate> {
const template = await this.getByCode(code);
template.articles = this.renumber(
articles.map((item) => ({
id: item.id ?? randomUUID(),
title: item.title,
body: item.body,
order: 0,
})),
);
return this.repository.saveTemplate(template);
}
/**
* Render the template against a representative mock contract so admins can
* see the final document without touching a real contract. Draft overrides
* allow previewing unsaved editor state.
*/
async preview(
code: string,
overrides?: PreviewContractTemplateDto,
): Promise<{ html: string }> {
const template = await this.getByCode(code);
const dynamicTemplate: ContractDynamicTemplateView = {
code: template.code,
name: overrides?.name ?? template.name,
documentTitle: overrides?.documentTitle ?? template.documentTitle,
whereasClauses: overrides?.whereasClauses ?? template.whereasClauses,
articles: overrides?.articles
? overrides.articles.map((item, index) => ({
id: item.id ?? randomUUID(),
title: item.title,
body: item.body,
order: index + 1,
}))
: this.sorted(template.articles),
};
const view = this.buildMockView(template.code, dynamicTemplate);
return { html: this.renderer.render(view) };
}
private buildMockView(
code: ContractTemplateCode,
dynamicTemplate: ContractDynamicTemplateView,
): ContractViewModel {
const meta = getTemplateMeta(PREVIEW_TEMPLATE_KEYS[code]);
const isBulk = code.endsWith("_BULK");
const now = new Date();
const unitRates = isBulk
? [
{ label: "Rail transport — per metric ton", unitPrice: 59.4, unit: "ton", currency: "USD" },
{ label: "Origin handling and documentation", unitPrice: 18, unit: "ton", currency: "USD" },
{ label: "Lashing material (when provided by EDR)", unitPrice: 150, unit: "unit", currency: "USD" },
]
: [
{ label: "Rail transport — 40ft container", unitPrice: 1916, unit: "container", currency: "USD" },
{ label: "Rail transport — 2 × 20ft containers", unitPrice: 1944, unit: "container", currency: "USD" },
{ label: "Excess tonnage surcharge", unitPrice: 10, unit: "ton", currency: "USD" },
];
return {
bookingId: "00000000-0000-0000-0000-000000000000",
reference: "EDR/CT/2026/0042",
status: "CONTRACT_READY",
templateKey: PREVIEW_TEMPLATE_KEYS[code],
template: { ...meta, title: dynamicTemplate.name, templateFile: "edr-dynamic.hbs" },
contractDate: now.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric",
}),
contractYear: now.getFullYear(),
client: {
companyName: "Abyssinia Trading PLC",
companyAddress: "Bole Sub-city, Woreda 03, H.No 1234, Addis Ababa",
companyLocation: "Ethiopia",
phone: "+251 91 123 4567",
email: "logistics@abyssiniatrading.et",
tinNumber: "0011223344",
vatNumber: "VAT-556677",
fanNumber: "FAN-889900",
businessLicense: "BL/AA/12/345678",
},
provider: {
name: "Ethio-Djibouti Standard Gauge Railway Share Company",
address: "Nifas Silk Lafto Sub City, Addis Ababa, Ethiopia",
phone: "+251 11 872 0000",
email: "info@edr.gov.et",
tinNumber: "—",
},
schedule: {
originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station",
destinationLabel: "Galaan Multipurpose Port (GMP)",
tradeDirection: code.startsWith("IMPORT")
? "IMPORT"
: code.startsWith("EXPORT")
? "EXPORT"
: "DOMESTIC",
freightType: isBulk ? "BULK" : "CONTAINER",
serviceType: "Rail transport and customs clearance",
scheduledDate: "—",
contractType: "GENERAL",
cargoDescription: isBulk ? "Steel billets — 2,800 MT" : "40ft containers — FMCG cargo",
totalWeightVgm: "—",
equipmentReturn: isBulk ? "—" : "With empty return",
hazardousLabel: "No",
firstMilePickupAddress: "—",
lastMileDeliveryAddress: "—",
},
pricing: {
displayMode: "UNIT_RATES",
unitRates,
currency: "USD",
equipmentReturn: isBulk ? "—" : "With empty return",
originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station",
destinationLabel: "Galaan Multipurpose Port (GMP)",
} as unknown as ContractViewModel["pricing"],
signatures: [],
canSignCustomer: false,
canSignStaff: false,
hasContractDocument: false,
hasCustomerSignature: false,
hasStaffSignature: false,
dynamicTemplate,
};
}
private assertCode(code: string): ContractTemplateCode {
const upper = code?.toUpperCase() as ContractTemplateCode;
if (!CONTRACT_TEMPLATE_CODES.includes(upper)) {
throw new BadRequestException(
`Unknown contract template code "${code}". Valid codes: ${CONTRACT_TEMPLATE_CODES.join(", ")}`,
);
}
return upper;
}
private sorted(articles: ContractTemplateArticle[]): ContractTemplateArticle[] {
return [...(articles ?? [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
}
private renumber(articles: ContractTemplateArticle[]): ContractTemplateArticle[] {
return articles.map((article, index) => ({ ...article, order: index + 1 }));
}
}

View File

@@ -0,0 +1,134 @@
import { ApiPropertyOptional, ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
IsBoolean,
IsInt,
IsOptional,
IsString,
MaxLength,
Min,
MinLength,
ValidateNested,
} from "class-validator";
export class UpdateContractTemplateDto {
@ApiPropertyOptional({ description: "Display name of the template" })
@IsOptional()
@IsString()
@MinLength(3)
@MaxLength(200)
name?: string;
@ApiPropertyOptional({ description: "Short description shown on the template card" })
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional({ description: "Cover-page service title of the generated document" })
@IsOptional()
@IsString()
@MinLength(3)
@MaxLength(300)
documentTitle?: string;
@ApiPropertyOptional({ description: "WHEREAS recitals", type: [String] })
@IsOptional()
@IsArray()
@IsString({ each: true })
whereasClauses?: string[];
@ApiPropertyOptional({ description: "Whether the template is used for generation" })
@IsOptional()
@IsBoolean()
isActive?: boolean;
}
export class CreateArticleDto {
@ApiProperty({ description: "Article heading (without the Article N prefix)" })
@IsString()
@MinLength(2)
@MaxLength(200)
title!: string;
@ApiProperty({
description:
'Article body. One clause per line; prefix a line with "- " to nest it as a bullet under the previous clause.',
})
@IsString()
@MinLength(2)
body!: string;
@ApiPropertyOptional({ description: "1-based position to insert at (appends when omitted)" })
@IsOptional()
@IsInt()
@Min(1)
position?: number;
}
export class UpdateArticleDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MinLength(2)
@MaxLength(200)
title?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MinLength(2)
body?: string;
}
export class ReplaceArticleDto {
@ApiPropertyOptional({ description: "Existing article id (new id assigned when omitted)" })
@IsOptional()
@IsString()
id?: string;
@ApiProperty()
@IsString()
@MinLength(2)
@MaxLength(200)
title!: string;
@ApiProperty()
@IsString()
@MinLength(2)
body!: string;
}
export class ReplaceArticlesDto {
@ApiProperty({ type: [ReplaceArticleDto], description: "Full ordered article list" })
@IsArray()
@ValidateNested({ each: true })
@Type(() => ReplaceArticleDto)
articles!: ReplaceArticleDto[];
}
/** Optional draft overrides so the editor can preview unsaved changes. */
export class PreviewContractTemplateDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
name?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
documentTitle?: string;
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
@IsString({ each: true })
whereasClauses?: string[];
@ApiPropertyOptional({ type: [ReplaceArticleDto] })
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ReplaceArticleDto)
articles?: ReplaceArticleDto[];
}

View File

@@ -0,0 +1,77 @@
import { BaseEntity } from "@edr/api-common";
import { Column, Entity, Index } from "typeorm";
/**
* The six canonical contract document templates, one per
* (trade direction × freight type) combination. Contracts store DOMESTIC for
* intercity movements; the template layer labels those INTERCITY to match the
* commercial vocabulary used on the printed documents.
*/
export const CONTRACT_TEMPLATE_CODES = [
"IMPORT_BULK",
"EXPORT_BULK",
"INTERCITY_BULK",
"IMPORT_CONTAINER",
"EXPORT_CONTAINER",
"INTERCITY_CONTAINER",
] as const;
export type ContractTemplateCode = (typeof CONTRACT_TEMPLATE_CODES)[number];
/**
* One dynamic article on a contract template. `body` is plain multiline text:
* each non-empty line renders as a numbered clause; lines prefixed with "- "
* render as bullet points nested under the preceding clause. A single-line
* body renders as an unnumbered paragraph. Handlebars placeholders (e.g.
* {{client.companyName}}, {{contractDate}}, {{contractYear}}, {{reference}})
* are interpolated against the contract view model at render time.
*/
export interface ContractTemplateArticle {
id: string;
title: string;
body: string;
order: number;
}
/** Map a contract's stored direction/freight pair onto a template code. */
export function contractTemplateCodeFor(
tradeDirection?: string | null,
freightType?: string | null,
): ContractTemplateCode {
const direction =
tradeDirection === "IMPORT"
? "IMPORT"
: tradeDirection === "EXPORT"
? "EXPORT"
: "INTERCITY";
const freight =
(freightType ?? "").toUpperCase().includes("BULK") ? "BULK" : "CONTAINER";
return `${direction}_${freight}` as ContractTemplateCode;
}
@Entity({ schema: "freight", name: "contract_templates" })
@Index(["code"], { unique: true })
export class ContractTemplate extends BaseEntity {
@Column({ name: "code", type: "varchar", length: 40, unique: true })
code!: ContractTemplateCode;
@Column({ name: "name", type: "varchar", length: 200 })
name!: string;
@Column({ name: "description", type: "text", nullable: true })
description?: string | null;
/** Cover-page service line, e.g. "Steel Billet Transportation and Customs Clearance Services". */
@Column({ name: "document_title", type: "varchar", length: 300 })
documentTitle!: string;
/** WHEREAS recitals rendered between the parties block and the articles. */
@Column({ name: "whereas_clauses", type: "jsonb", default: () => "'[]'" })
whereasClauses!: string[];
@Column({ name: "articles", type: "jsonb", default: () => "'[]'" })
articles!: ContractTemplateArticle[];
@Column({ name: "is_active", type: "boolean", default: true })
isActive!: boolean;
}

View File

@@ -51,6 +51,11 @@ export class BookingRequestService {
const contract = await this.contractsService.findById(contractId);
await this.contractsService.assertCustomerCanAccessContract(userId, contract);
this.assertGeneralCustoms(contract);
if (contract.status === 'CONTRACT_CLOSED') {
throw new ConflictException(
'This contract is completed — the full contracted quantity has been booked.',
);
}
if (contract.status !== 'CONTRACT_ACTIVE') {
throw new ConflictException(
'The contract must be active before requesting a shipment.',

View File

@@ -0,0 +1,149 @@
import { BadRequestException } from '@nestjs/common';
import { ContractBookingService } from './contract-booking.service';
import { Contract } from './entities/contract.entity';
/**
* Contract auto-completion by quantity cap. Once a GENERAL contract's capped
* scope is fully consumed (e.g. a split remainder rebooked), the contract moves
* to CONTRACT_CLOSED even inside its validity window, and further bookings are
* blocked — including while a booking window is open. Released capacity
* (cancelled/expired booking) reopens the contract on the next attempt.
*/
describe('ContractBookingService — quantity-cap completion', () => {
function makeService() {
const contractsRepository = {
findByIdWithRelations: jest.fn(),
update: jest.fn().mockResolvedValue(undefined),
};
const service = new ContractBookingService(
contractsRepository as never,
{} as never, // bookingsRepository
{} as never, // bookingPricingService
{} as never, // consolidationService
{} as never, // containerTypesService
{} as never, // ruleEngineService
{} as never, // milestoneService
{} as never, // workflowService
{} as never, // invoiceService
{} as never, // dataSource
{} as never, // trainSchedulingService
);
return { service, contractsRepository };
}
type WithPrivate = {
maybeCompleteContract: (c: Contract) => Promise<void>;
};
const generalContract = (status: string): Contract =>
({
id: 'c-1',
reference: 'CTR-1',
contractKind: 'GENERAL',
status,
}) as Contract;
it('closes a GENERAL contract when every capped line is exhausted', async () => {
const { service, contractsRepository } = makeService();
jest.spyOn(service, 'computeCapacity').mockResolvedValue([
{ containerSize: '20FT', cap: 10, booked: 10, remaining: 0 },
{ containerSize: '40FT', cap: 4, booked: 4, remaining: 0 },
]);
await (service as never as WithPrivate).maybeCompleteContract(
generalContract('CONTRACT_ACTIVE'),
);
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
status: 'CONTRACT_CLOSED',
});
});
it('absorbs bulk-ton float dust when judging exhaustion', async () => {
const { service, contractsRepository } = makeService();
jest
.spyOn(service, 'computeCapacity')
.mockResolvedValue([{ cap: 100, booked: 99.9995, remaining: 0.0005 }]);
await (service as never as WithPrivate).maybeCompleteContract(
generalContract('FULLY_EXECUTED'),
);
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
status: 'CONTRACT_CLOSED',
});
});
it('keeps the contract open while any capped line has capacity left', async () => {
const { service, contractsRepository } = makeService();
jest.spyOn(service, 'computeCapacity').mockResolvedValue([
{ containerSize: '20FT', cap: 10, booked: 10, remaining: 0 },
{ containerSize: '40FT', cap: 4, booked: 3, remaining: 1 },
]);
await (service as never as WithPrivate).maybeCompleteContract(
generalContract('CONTRACT_ACTIVE'),
);
expect(contractsRepository.update).not.toHaveBeenCalled();
});
it('never closes an uncapped contract', async () => {
const { service, contractsRepository } = makeService();
jest.spyOn(service, 'computeCapacity').mockResolvedValue([]);
await (service as never as WithPrivate).maybeCompleteContract(
generalContract('CONTRACT_ACTIVE'),
);
expect(contractsRepository.update).not.toHaveBeenCalled();
});
it('never closes a ONE_TIME contract (single-slot rule governs it)', async () => {
const { service, contractsRepository } = makeService();
const spy = jest.spyOn(service, 'computeCapacity');
await (service as never as WithPrivate).maybeCompleteContract({
id: 'c-1',
contractKind: 'ONE_TIME',
status: 'FULLY_EXECUTED',
} as Contract);
expect(spy).not.toHaveBeenCalled();
expect(contractsRepository.update).not.toHaveBeenCalled();
});
it('rejects a new booking on a completed contract even inside an open window', async () => {
const { service, contractsRepository } = makeService();
contractsRepository.findByIdWithRelations.mockResolvedValue(
generalContract('CONTRACT_CLOSED'),
);
jest
.spyOn(service, 'computeCapacity')
.mockResolvedValue([{ cap: 10, booked: 10, remaining: 0 }]);
await expect(
service.createUnderContract('c-1', {} as never, null, null),
).rejects.toThrow(BadRequestException);
expect(contractsRepository.update).not.toHaveBeenCalled();
});
it('reopens a completed contract when capacity was released', async () => {
const { service, contractsRepository } = makeService();
contractsRepository.findByIdWithRelations.mockResolvedValue(
generalContract('CONTRACT_CLOSED'),
);
jest
.spyOn(service, 'computeCapacity')
.mockResolvedValue([{ cap: 10, booked: 8, remaining: 2 }]);
// The create path continues past the gate and dies later on the bare mocks —
// only the reopen transition is under test here.
await service.createUnderContract('c-1', {} as never, null, null).catch(() => undefined);
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
status: 'CONTRACT_ACTIVE',
});
});
});

View File

@@ -83,6 +83,24 @@ export class ContractBookingService {
const contract = await this.contractsRepository.findByIdWithRelations(contractId);
if (!contract) throw new NotFoundException(`Contract ${contractId} not found`);
// A contract whose quantity cap was fully booked is completed — no further
// bookings, even while contract validity and a booking window are still
// open. Capacity released after closure (a cancelled/expired booking)
// reopens the contract on the next booking attempt.
if (contract.status === 'CONTRACT_CLOSED') {
const capacity = await this.computeCapacity(contract);
const hasRoom = capacity.some((c) => c.remaining == null || c.remaining > 0);
if (!hasRoom) {
throw new BadRequestException(
'This contract is completed — the full contracted quantity has been booked.',
);
}
await this.contractsRepository.update(contract.id, {
status: 'CONTRACT_ACTIVE',
} as never);
contract.status = 'CONTRACT_ACTIVE';
}
// GL Ethiopia is identified by the dedicated contract create-booking permission
// (granted to the edr_gl_ethiopia preset).
const isGlActor =
@@ -291,6 +309,9 @@ export class ContractBookingService {
if (!parked.paired) {
// Waiting for a partner — stop here. The booking sits in
// PENDING_CONSOLIDATION, unbilled and unscheduled, until it pairs.
// A parked booking still holds contract capacity, so the cap may
// already be exhausted by it.
await this.maybeCompleteContract(contract);
const pendingResult = await this.bookingsRepository.findByIdWithFiles(
booking.id,
);
@@ -304,6 +325,8 @@ export class ContractBookingService {
generalCustoms,
);
await this.maybeCompleteContract(contract);
const result = await this.bookingsRepository.findByIdWithFiles(booking.id);
return { booking: result ?? booking, warnings };
}
@@ -606,6 +629,44 @@ export class ContractBookingService {
});
}
/**
* Complete the contract once its quantity cap is fully consumed. Runs after
* every booking created under a GENERAL contract (including a split remainder
* being rebooked): when no capped scope line has capacity left, the contract
* moves to CONTRACT_CLOSED even though its validity window is still open —
* blocking further bookings and shipment requests, including inside an open
* booking window. Never throws: a status hiccup must not undo the booking
* that was just created.
*/
private async maybeCompleteContract(contract: Contract): Promise<void> {
try {
// ONE_TIME contracts are governed by the single-active-booking slot (and
// are promoted to GENERAL on split), so only GENERAL completes by cap.
if (contract.contractKind !== 'GENERAL') return;
if (!['CONTRACT_ACTIVE', 'FULLY_EXECUTED'].includes(contract.status)) return;
const capacity = await this.computeCapacity(contract);
if (capacity.length === 0) return; // uncapped — completes only by expiry
// 0.001 tolerance absorbs bulk-ton float rounding (split weights round to
// 3 decimals); container caps are integers and unaffected.
const exhausted = capacity.every(
(c) => c.remaining != null && c.remaining <= 0.001,
);
if (!exhausted) return;
await this.contractsRepository.update(contract.id, {
status: 'CONTRACT_CLOSED',
} as never);
this.logger.log(
`Contract ${contract.reference} quantity cap fully booked — completed; no further bookings within validity.`,
);
} catch (err) {
this.logger.error(
`Could not evaluate completion for contract ${contract.id}: ${
err instanceof Error ? err.message : String(err)
}`,
);
}
}
/**
* Quantities already booked under a contract that still hold capacity. Excludes
* bookings that never shipped (CANCELLED / REJECTED / EXPIRED).

View File

@@ -350,6 +350,17 @@ export class ContractTransitionService {
const updated = await this.contractsService.findById(contractId);
if (allDone) {
this.notifier.approved(updated);
// Final approval step also generates the contract document from the
// template matching the contract's direction/freight pair. Best-effort:
// a rendering hiccup must not roll back the approval — the document can
// still be generated manually or lazily on view/download.
try {
return await this.generateContract(contractId);
} catch (err) {
this.logger.warn(
`Auto contract generation after final approval failed for ${updated.reference}: ${err}`,
);
}
}
return updated;
}

View File

@@ -16,6 +16,7 @@ import { NotificationsModule } from '../notifications/notifications.module';
import { NotificationInboxModule } from '../notification-inbox/notification-inbox.module';
import { BookingsModule } from '../bookings/bookings.module';
import { TrainSchedulingModule } from '../train-scheduling/train-scheduling.module';
import { ContractTemplatesModule } from '../contract-templates/contract-templates.module';
import { ContractsController } from './contracts.controller';
import { ContractsService } from './contracts.service';
@@ -81,6 +82,9 @@ import { ContractDocumentViewModelBuilder } from '../../contracts/contract-docum
NotificationsModule,
NotificationInboxModule,
CompaniesModule,
// Provides the admin-editable contract document templates consumed by
// ContractDocumentViewModelBuilder when rendering contract PDFs.
ContractTemplatesModule,
// BookingsModule provides BookingsRepository/BookingPricingService used by the
// contract PDF builders (they read a Booking today — see docs/new-doc.md §3.3).
forwardRef(() => BookingsModule),

View File

@@ -265,10 +265,11 @@ export class ContractsService {
}
}
// Attach the company profile's onboarding / business-license documents to the
// contract by reference. The separate "Documents" intake step was removed —
// the profile documents are simply carried onto every contract automatically.
await this.attachProfileDocuments(contract.id, companyProfileId);
// Attach the company's onboarding documents (TIN, licenses, IDs) and the
// profile's business-license documents to the contract by reference. The
// separate "Documents" intake step was removed — the profile documents are
// simply carried onto every contract automatically.
await this.attachProfileDocuments(contract.id, companyId ?? null, companyProfileId);
return { contract: await this.findById(contract.id), warnings };
}
@@ -316,51 +317,95 @@ export class ContractsService {
}
/**
* Copy a company profile's stored business-license / onboarding documents onto
* a contract by reference (no byte re-upload). Codes are slugged from each
* document name so they group under "Profile documents" on the contract detail
* page. No-op when the contract has no profile or the profile has no documents.
* Copy the company's onboarding documents (TIN certificate, commercial /
* investment license, national ID, passport — resource "companies", coded by
* the upload-setting fileKey) and the company profile's business-license
* documents (resource "company_profiles") onto a contract by reference (no
* byte re-upload). Idempotent: codes already present on the contract — user
* uploads or an earlier carry — are never duplicated or overwritten, so it is
* safe to run on every create and update. No-op when there is nothing to copy.
*/
private async attachProfileDocuments(
contractId: string,
companyId: string | null,
companyProfileId: string | null,
): Promise<void> {
if (!companyProfileId) return;
// Business-license files are FileRecords (resource "company_profiles"); carry
// the live ones by reference. Staged/pending uploads are excluded by code.
const records = await this.filesService.findByResource(
companyProfileId,
'company_profiles',
if (!companyId && !companyProfileId) return;
const existingCodes = new Set(
(await this.filesService.findByResource(contractId, 'contracts')).map(
(r) => r.code,
),
);
const docs = records
.filter((r) => r.code === 'business_license')
.map((r) => ({
name: r.name,
url: r.url,
size: r.size,
mimeType: r.mimeType,
}));
const docs: Array<{
code: string;
name: string;
url: string;
size: number;
mimeType?: string;
}> = [];
if (companyId) {
// Company onboarding documents keep their fileKey codes (tin_certificate,
// commercial_license, …) so the portal can match them against the
// onboarding upload-setting fields. Re-uploads append rows, so keep only
// the newest record per code.
const companyRecords = await this.filesService.findByResource(
companyId,
'companies',
);
const latestByCode = new Map<string, (typeof companyRecords)[number]>();
for (const r of companyRecords) {
const prev = latestByCode.get(r.code);
if (!prev || r.createdAt > prev.createdAt) latestByCode.set(r.code, r);
}
for (const r of latestByCode.values()) {
if (existingCodes.has(r.code)) continue;
docs.push({
code: r.code,
name: r.name,
url: r.url,
size: r.size,
mimeType: r.mimeType,
});
}
}
if (companyProfileId) {
// Business-license files are FileRecords (resource "company_profiles");
// carry the live ones by reference. Staged/pending uploads are excluded by
// code. Codes are slugged from each document name so they group under
// "Profile documents" on the contract detail page.
const records = await this.filesService.findByResource(
companyProfileId,
'company_profiles',
);
const slug = (name: string) =>
name
.toLowerCase()
.replace(/\.[a-z0-9]+$/, '')
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '') || 'profile_document';
records
.filter((r) => r.code === 'business_license')
.forEach((r, i) => {
const code = `${slug(r.name)}_${i + 1}`;
if (existingCodes.has(code)) return;
docs.push({
code,
name: r.name,
url: r.url,
size: r.size,
mimeType: r.mimeType,
});
});
}
if (docs.length === 0) return;
const slug = (name: string) =>
name
.toLowerCase()
.replace(/\.[a-z0-9]+$/, '')
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '') || 'profile_document';
try {
await this.filesService.attachExistingFiles(
contractId,
'contracts',
docs.map((d, i) => ({
code: `${slug(d.name)}_${i + 1}`,
name: d.name,
url: d.url,
size: d.size,
mimeType: d.mimeType,
})),
);
await this.filesService.attachExistingFiles(contractId, 'contracts', docs);
} catch {
// Non-fatal — the contract is still valid without the carried documents.
}
@@ -481,6 +526,15 @@ export class ContractsService {
await this.filesService.uploadMany(id, 'contracts', files);
}
// Re-carry any company/profile document that is still missing from the
// contract (runs after the upload so fresh replacements keep their slot).
// Backfills contracts created before profile documents were carried over.
await this.attachProfileDocuments(
id,
existing.companyId ?? null,
existing.companyProfileId ?? null,
);
return { contract: await this.findById(id), warnings };
}

View File

@@ -0,0 +1,150 @@
# GPS Tracking (GT06) — Operations & Device Configuration
GT06 trackers speak a **raw TCP binary protocol**, not HTTP/HTTPS. This shapes
everything about how the service is deployed and how devices are pointed at it.
---
## 1. Why GPS needs its own dedicated TCP port
- **Not HTTP.** GT06 devices send binary frames
(`0x78 0x78 | len | protocol | payload | serial | CRC16 | 0x0D 0x0A`).
An HTTP server receiving these answers `400 Bad Request` and closes.
- **Dedicated port required.** A listening socket is keyed on `(IP, port)`; two
listeners on the same pair collide (`EADDRINUSE`). The REST API already owns
its port, so GPS traffic needs a separate one.
- **No hostname routing.** GT06 frames carry no `Host` header and no TLS SNI, so
L7 proxies (Nginx `http`, AWS ALB, Cloudflare proxy) cannot route them by
domain. Routing must happen at **Layer 4 (TCP)** by port.
- **DNS carries no port.** An A record maps a name to an IP only. The tracker
config must state the port explicitly (e.g. `gps.example.com:5023`).
### Operational requirements
| Item | Value |
| --- | --- |
| Protocol | Raw TCP (not HTTP, not TLS) |
| Default port | `5023` (configurable via `GT06_TCP_PORT`) |
| Listener bind | `0.0.0.0` inside the `freight-gps` container |
| Edge terminator | **L4** — AWS NLB or Nginx `stream {}`. **Not** ALB / Cloudflare proxy. |
---
## 2. Port configuration
`5023` is only this project's default — **not** a GT06 protocol requirement. The
listener binds whatever `GT06_TCP_PORT` says, as long as trackers are configured
with the same number.
Host and container ports are decoupled in `docker-compose.yaml`:
```yaml
freight-gps:
ports:
- "${GT06_TCP_PORT:-5023}:5023" # host is configurable; container fixed
environment:
GT06_TCP_PORT: "5023" # pinned inside the container
```
- The **container** always listens on `5023`.
- The **host/public** port is configurable (443, 5023, 9000, …) via the root
`.env`'s `GT06_TCP_PORT`.
- This split is required because the image runs as a **non-root** user
(`nestjs`, uid 1001), which cannot bind ports `<1024`. Docker (root) binds the
host port and forwards to `5023` inside.
- Running **outside Docker** (`pnpm dev:gps`, systemd), `GT06_TCP_PORT` is the
actual bind port, so `<1024` needs root or `CAP_NET_BIND_SERVICE`.
- **443 is allowed but risky:** GT06 stays raw TCP, not TLS. Middleboxes that
expect a TLS handshake on 443 may drop the connection.
---
## 3. Deployment topology
The GT06 listener runs as its own process (`dist/main.gps.js`, module
`GpsIngestModule`) — DB + GPS only, no HTTP server. It shares the `edr_freight`
DB with the API; the DB is the seam (ingester writes `gps_devices` /
`gps_positions`, API reads them).
```
freight-api HTTP :3001 GT06_TCP_PORT=0 (listener off, applies migrations)
freight-gps TCP :5023 DB_MIGRATIONS_RUN=false (owns the tracker socket)
```
`DB_MIGRATIONS_RUN=false` keeps the second process from racing migrations.
Horizontal scale: each tracker holds one long-lived TCP connection with
per-socket session state, so N `freight-gps` replicas can run behind an L4 LB —
each device sticks to one replica. `ensureDevice` is safe under concurrency
(unique IMEI).
---
## 4. Device configuration (GT06 side)
Config is done by **SMS to the tracker's SIM**. Commands below are the canonical
Concox/GT06 set — **verify against your unit's sheet**, syntax varies by firmware.
Default command password is usually `123456`.
Prep: data-enabled SIM, SMS on, **SIM PIN off**, know your carrier APN.
```
STATUS# # 1. sanity check — returns GSM/GPS/batt/GPRS
APN,<apn># # 2. carrier data APN (add ,user,pass if needed)
SERVER,1,gps.example.com,5023,0# # 3. point at server (1=domain). Port MUST match GT06_TCP_PORT
GPRSON,1# # 4. enable data
GPSON,1# # enable GPS
TIMER,10# # 5. upload interval, seconds (some use UPLOAD,10#)
RESET# # 6. reboot so it reconnects (many cache DNS until reboot)
```
Raw-IP variant of step 3: `SERVER,0,203.0.113.50,5023,0#`
Custom host port (e.g. 443): `SERVER,1,gps.example.com,443,0#`
### Verify from the server
```bash
docker compose logs -f freight-gps | grep -Ei "login|Auto-registering|ingester up"
nc -vz gps.example.com 5023
curl -H "Authorization: Bearer <token>" https://api.example.com/api/gps/positions/latest
```
First login packet **auto-registers** the IMEI (no manual step). `online:true`
only when `lastSeenAt` < 5 min (computed at read time).
### Link a tracker to a vehicle (optional)
Auto-register leaves `vehicleId` null. Attach it (needs `tracking.manage`):
```
PATCH /api/gps/devices/:id { "vehicleId": "<uuid>", "name": "Truck 03-ET" }
```
### Failure map
| Symptom | Cause |
| --- | --- |
| No SMS reply | SIM PIN on / no signal / wrong number |
| Replies but never connects | APN wrong, or `SERVER` port `GT06_TCP_PORT` |
| Connects then drops | server not ACKing, or middlebox on 443 expecting TLS |
| Registered but `online:false` | packets blocked by firewall open inbound TCP |
| Wrong location / `positioned:false` | no GPS fix yet open sky, cold start ~12 min |
---
## 5. Security
- GT06 authenticates with **IMEI only**, which is **spoofable**. Anyone who can
reach the port can inject fake positions.
- **Do not** expose the port to `0.0.0.0/0`. Restrict at the firewall / security
group to the SIM provider's **APN / IP range**.
- Trackers must use the same host+port as the server:
`SERVER,1,gps.example.com,<port>,0#`.
---
## 6. Edge (L4) termination
See [`infrastructure/nginx/gps-stream.conf`](../../../../../infrastructure/nginx/gps-stream.conf)
for an Nginx `stream {}` example, and the AWS NLB notes in the same file.
Reminder: **L4 only** an HTTP proxy cannot route GT06.

View File

@@ -34,3 +34,13 @@ export const DEFAULT_CONTAINER_WAGON_TARE_TONS = 22.4;
/** Default CW3 gondola tare for bulk bookings (T). */
export const DEFAULT_BULK_WAGON_TARE_TONS = 23.4;
/**
* Fallback rated payloads (T) matching the tare fallbacks above. A bulk booking's
* wagon count is its cargo divided by this, so a zero here would make the count
* infinite — callers must floor it at a positive number.
*/
export const DEFAULT_CONTAINER_WAGON_CAPACITY_TONS = 70;
/** Default CW3 gondola rated payload for bulk bookings (T). */
export const DEFAULT_BULK_WAGON_CAPACITY_TONS = 60;

View File

@@ -136,6 +136,7 @@ describe('BookingBatchService — PAID reconcile', () => {
expirePayable: jest.fn().mockResolvedValue(undefined),
} as never,
{ emitPhase: jest.fn() } as never,
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
);
});
@@ -563,6 +564,7 @@ describe('BookingBatchService — PAID reconcile', () => {
trainSchedulingService as never,
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
{ emitPhase: jest.fn() } as never,
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
undefined,
{ findOpenOffer: jest.fn() } as never,
);
@@ -585,6 +587,7 @@ describe('BookingBatchService — PAID reconcile', () => {
trainSchedulingService as never,
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
{ emitPhase: jest.fn() } as never,
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
undefined,
{ findOpenOffer: jest.fn() } as never,
);
@@ -615,6 +618,7 @@ describe('BookingBatchService — PAID reconcile', () => {
trainSchedulingService as never,
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
{ emitPhase: jest.fn() } as never,
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
undefined,
{ findOpenOffer: jest.fn() } as never,
);
@@ -731,3 +735,135 @@ describe('BookingBatchService — PAID reconcile', () => {
});
});
});
describe('BookingBatchService — wagonsFor', () => {
// wagonsFor is pure arithmetic over its two arguments and touches no injected
// dependency, so the service can be built with none.
const service = new BookingBatchService(
null as never,
null as never,
null as never,
null as never,
null as never,
null as never,
null as never,
null as never,
null as never,
null as never,
) as unknown as {
wagonsFor(booking: unknown, dims: unknown): number;
needFor(booking: unknown, dims: unknown): {
wagons: number;
weightTons: number;
lengthMeters: number;
};
};
// PW2 box wagon: 70T rated payload, 25.2T tare, 17.066m.
const dims = {
container: { lengthMeters: 13.966, tareWeightTons: 22.4, capacityTons: 70 },
bulk: { lengthMeters: 17.066, tareWeightTons: 25.2, capacityTons: 70 },
byWagonTypeId: new Map(),
};
const bulk = (cargoTons: number, over: Record<string, unknown> = {}) => ({
freightType: 'BULK',
cargoTotalWeightVgm: cargoTons,
bookingContainers: [],
...over,
});
it('sizes a bulk booking by cargo ÷ rated payload, not a flat 1 wagon', () => {
// 37 × 1400 fertilizer packages × 50kg = 2590T of cargo.
expect(service.wagonsFor(bulk(2590), dims)).toBe(37);
});
it('rounds a partial wagon up', () => {
expect(service.wagonsFor(bulk(70.1), dims)).toBe(2);
expect(service.wagonsFor(bulk(70), dims)).toBe(1);
});
it('still floors at one wagon when a bulk booking has no recorded cargo', () => {
expect(service.wagonsFor(bulk(0), dims)).toBe(1);
});
it('honours an explicit wagonsRequired override', () => {
expect(service.wagonsFor(bulk(2590, { wagonsRequired: 40 }), dims)).toBe(40);
});
it('ignores a stale undersized wagonsRequired: 700T of sugar rides 10 wagons, not 1', () => {
// Rows written while sumWagonsRequired hardcoded BULK to 1 are still in the
// DB; trusting them charged one tare for the whole consist (700 + 25.2
// instead of 700 + 10 × 25.2 gross).
expect(service.wagonsFor(bulk(700, { wagonsRequired: 1 }), dims)).toBe(10);
});
it('takes the binding axis for containers: weight can exceed TEU geometry', () => {
// Two 40ft units => 2 wagons by TEU geometry, but 210T needs 3 at 70T each.
const booking = {
freightType: 'CONTAINER',
cargoTotalWeightVgm: 210,
bookingContainers: [
{ quantity: 2, wagonsRequired: 2, containerType: { wagonsPerUnit: 1, sizeFt: 40 } },
],
};
expect(service.wagonsFor(booking, dims)).toBe(3);
});
it('keeps TEU geometry when it binds before weight', () => {
// Four 20ft units => 2 wagons by geometry; 40T of cargo needs only 1 by weight.
const booking = {
freightType: 'CONTAINER',
cargoTotalWeightVgm: 40,
bookingContainers: [
{ quantity: 4, wagonsRequired: 2, containerType: { wagonsPerUnit: 0.5, sizeFt: 20 } },
],
};
expect(service.wagonsFor(booking, dims)).toBe(2);
});
describe('per-booking wagon type (cargo/container type FK)', () => {
// The booking's cargo type rides PW2 (25.2T tare / 70T), but the
// representative bulk fallback is a CW3-ish 23.4T tare. Measuring the
// booking on the fallback under-charged its gross (2100 + 30 × 23.4 =
// 2802 instead of 2856), so the fill loop admitted sets that allocation's
// real-consist check later rejected — after the customer had paid.
const dimsWithTypes = {
container: { lengthMeters: 13.966, tareWeightTons: 22.4, capacityTons: 70 },
bulk: { lengthMeters: 17.066, tareWeightTons: 23.4, capacityTons: 70 },
byWagonTypeId: new Map([
['pw2-id', { lengthMeters: 17.066, tareWeightTons: 25.2, capacityTons: 70 }],
]),
};
it('charges a bulk booking the tare of ITS wagon type, not the representative', () => {
const booking = bulk(2100, { cargoType: { wagonTypeId: 'pw2-id' } });
const need = service.needFor(booking, dimsWithTypes);
expect(need.wagons).toBe(30);
expect(need.weightTons).toBe(2856); // 2100 + 30 × 25.2 — matches allocation
});
it('falls back to the representative dims when no wagon type is configured', () => {
const need = service.needFor(bulk(2100), dimsWithTypes);
expect(need.weightTons).toBe(2802); // 2100 + 30 × 23.4 (legacy behavior)
});
it('resolves a container booking through its container type', () => {
const booking = {
freightType: 'CONTAINER',
cargoTotalWeightVgm: 140,
bookingContainers: [
{
quantity: 2,
wagonsRequired: 2,
containerType: { wagonsPerUnit: 1, sizeFt: 40, wagonTypeId: 'pw2-id' },
},
],
};
const need = service.needFor(booking, dimsWithTypes);
expect(need.wagons).toBe(2);
expect(need.weightTons).toBe(190.4); // 140 + 2 × 25.2
expect(need.lengthMeters).toBeCloseTo(34.132, 3); // 2 × 17.066, not NW5's 13.966
});
});
});

View File

@@ -1,6 +1,8 @@
import {
BadRequestException,
ConflictException,
forwardRef,
Inject,
Injectable,
Logger,
NotFoundException,
@@ -9,10 +11,19 @@ import {
} from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { SchedulerRegistry } from '@nestjs/schedule';
import { DataSource, In } from 'typeorm';
import {
Between,
DataSource,
FindOptionsWhere,
ILike,
In,
LessThanOrEqual,
MoreThanOrEqual,
} from 'typeorm';
import { Booking } from '../bookings/entities/booking.entity';
import { BookingsRepository } from '../bookings/bookings.repository';
import { BookingPricingService } from '../bookings/booking-pricing.service';
import { Locomotive } from '../locomotives/entities/locomotive.entity';
import { formatRouteLabel } from '../routes/entities/route.entity';
import { RouteMilestone } from '../routes/entities/route-milestone.entity';
@@ -24,13 +35,19 @@ import { TrainSchedulingGlobalRules } from './entities/train-scheduling-global-r
import { BookingNotifierService } from './booking-notifier.service';
import { TrainSchedulingService } from './train-scheduling.service';
import { eatDay, groupBookingsIntoBoardWindows } from './batch-window.util';
import {
BATCH_BOARD_STATUSES,
BatchBoardQueryDto,
} from './dto/batch-board-query.dto';
import { Freight, TrainScheduleStatus as TrainScheduleStatusEnum } from "@edr/types";
import { BillingService } from "../billing/billing.service";
import {
DEFAULT_BULK_WAGON_CAPACITY_TONS,
DEFAULT_BULK_WAGON_LENGTH_METERS,
DEFAULT_BULK_WAGON_TARE_TONS,
DEFAULT_CONTAINER_WAGON_CAPACITY_TONS,
DEFAULT_CONTAINER_WAGON_LENGTH_METERS,
DEFAULT_CONTAINER_WAGON_TARE_TONS,
DEFAULT_WAGONS_PER_BOOKING,
@@ -38,8 +55,8 @@ import {
import {
WagonTypeDimensions,
bookingGrossWeightTons,
bookingTrainLengthMeters,
deriveTrainCapacityFromLocomotive,
sizePartialOfferWagons,
trainHardCaps,
wagonTypeDimensionsFromEntity,
} from './train-capacity.util';
@@ -55,11 +72,18 @@ import {
Capacity,
CorridorBudget,
CorridorLeg,
OverageTolerance,
stopYardsFor,
} from './corridor-capacity.util';
export type { Capacity } from './corridor-capacity.util';
/**
* A train's fill limits: the base caps the corridor budget spends from, plus
* the locomotive overage tolerance spendable only on whole-booking admission.
*/
type TrainLimits = { base: Capacity; tolerance: OverageTolerance };
/** A day-level pool key: all trains on this route departing on this EAT day. */
interface RouteDayGroup {
originYardId: string;
@@ -68,13 +92,20 @@ interface RouteDayGroup {
day: string;
}
/** One wagon type's footprint: its length on the train, the tare it adds to the
* locomotive's gross load, and the payload it carries. */
type PerWagonDims = { lengthMeters: number; tareWeightTons: number; capacityTons: number };
/**
* Per-freight-type wagon dimensions used to size a booking's capacity draw:
* its length on the train and the tare it adds to the locomotive's gross load.
* Wagon dimensions used to size a booking's capacity draw. `byWagonTypeId` holds
* every wagon type so a booking is measured on the type its cargo/container type
* actually rides (the same FK resolution allocation uses); `container`/`bulk` are
* representative fallbacks for bookings whose type has no wagon type configured.
*/
type WagonDims = {
container: { lengthMeters: number; tareWeightTons: number };
bulk: { lengthMeters: number; tareWeightTons: number };
container: PerWagonDims;
bulk: PerWagonDims;
byWagonTypeId: Map<string, PerWagonDims>;
};
export type BatchBoardBookingState =
@@ -139,6 +170,8 @@ export interface BatchWindowGroup {
export interface BatchBoardScheduleDetail {
scheduleId: string;
/** Human-facing schedule reference (S-YYYY-NNNNN). */
scheduleReference: string | null;
trainNumber: string | null;
routeName: string | null;
origin: string | null;
@@ -163,11 +196,14 @@ export interface BatchBoardScheduleDetail {
export interface BatchBoardSchedule {
scheduleId: string;
/** Human-facing schedule reference (S-YYYY-NNNNN). */
scheduleReference: string | null;
trainNumber: string | null;
routeName: string | null;
origin: string | null;
destination: string | null;
scheduleDate: string | null;
createdAt: string | null;
status: string;
bookingWindowStatus: string;
direction: string | null;
@@ -206,6 +242,16 @@ export interface BatchBoardSchedule {
bookings: BatchBoardBooking[];
}
/** Paginated batch-board list. `items` (not `data`) — the API response wrapper
* already uses `data`, and the frontend's unwrap() strips one `data` level. */
export interface BatchBoardListResponse {
items: BatchBoardSchedule[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}
/**
* Demand-batching engine: every 3h (EAT) it ranks each OPEN schedule's ready pool
* by priority, greedily fills the train to capacity (skipping bookings that don't fit),
@@ -237,6 +283,8 @@ export class BookingBatchService implements OnModuleInit {
private readonly trainSchedulingService: TrainSchedulingService,
private readonly billing: BillingService,
private readonly bookingWindowGateway: BookingWindowGateway,
@Inject(forwardRef(() => BookingPricingService))
private readonly pricingService: BookingPricingService,
@Optional() private readonly milestoneService?: ClearanceMilestoneService,
@Optional() private readonly splitService?: BookingSplitService,
@@ -433,7 +481,7 @@ export class BookingBatchService implements OnModuleInit {
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(
booking.trainScheduleId,
);
if (schedule && (await this.remainingWagons(schedule)) <= 0) {
if (schedule && (await this.isTrainFull(schedule))) {
await this.setWindow(booking.trainScheduleId, "FULL");
}
@@ -563,7 +611,14 @@ export class BookingBatchService implements OnModuleInit {
const partner = await this.dataSource
.getRepository(Booking)
.findOne({ where: { id: partnerId }, relations: { company: true, bookingContainers: true } });
.findOne({
where: { id: partnerId },
relations: {
company: true,
bookingContainers: { containerType: true },
cargoType: true,
},
});
// Partner not yet accepted → this booking is now FULLY_EXECUTED and simply
// waits; the partner's later accept will reserve the pair.
if (!partner || partner.status !== 'FULLY_EXECUTED') {
@@ -584,7 +639,7 @@ export class BookingBatchService implements OnModuleInit {
this.armSettle(scheduleId);
const schedule =
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
if (schedule && (await this.remainingWagons(schedule)) <= 0) {
if (schedule && (await this.isTrainFull(schedule))) {
await this.setWindow(scheduleId, 'FULL');
}
}
@@ -625,12 +680,70 @@ export class BookingBatchService implements OnModuleInit {
// ---- monitoring board -----------------------------------------------------
/**
* Read model for the batch monitoring page: every still-relevant schedule (not arrived/
* cancelled) with its locomotive, capacity usage and its bookings grouped by lifecycle
* state (allocated / awaiting payment / paid-waiting / pending contract / expired).
* Read model for the batch monitoring page: every import schedule — including
* dispatched, arrived and cancelled history — with its locomotive, capacity
* usage and its bookings grouped by lifecycle state (allocated / awaiting
* payment / paid-waiting / pending contract / expired). Paginated and
* filterable; per-schedule booking summaries are only computed for the
* requested page.
*/
async getBatchBoard(): Promise<BatchBoardSchedule[]> {
const schedules = await this.trainSchedulesRepository.findAll({
async getBatchBoard(
query: BatchBoardQueryDto = {},
): Promise<BatchBoardListResponse> {
const page = query.page ?? 1;
const pageSize = query.pageSize ?? 12;
// Status filter: any subset of the lifecycle. Omitted = all statuses, so
// arrived / cancelled / dispatched schedules stay visible as history.
const allowedStatuses = new Set<string>(BATCH_BOARD_STATUSES);
const statuses = (query.statuses ?? "")
.split(",")
.map((v) => v.trim().toUpperCase())
.filter((v) => allowedStatuses.has(v));
const dateRange = (from?: string, to?: string) => {
const f = from ? new Date(from) : null;
const t = to ? new Date(to) : null;
if (f && t) return Between(f, t);
if (f) return MoreThanOrEqual(f);
if (t) return LessThanOrEqual(t);
return undefined;
};
// Batch board is IMPORT-only: export is FCFS with no batch/priority calc,
// and domestic/legacy schedules run the legacy fill, not the window batch.
const base: FindOptionsWhere<TrainSchedule> = { direction: "IMPORT" };
if (statuses.length) base.status = In(statuses) as never;
if (query.bookingWindowStatus) {
base.bookingWindowStatus = query.bookingWindowStatus;
}
const departure = dateRange(query.departureFrom, query.departureTo);
if (departure) base.scheduledDepartureDate = departure as never;
const created = dateRange(query.createdFrom, query.createdTo);
if (created) base.createdAt = created as never;
// Search fans out across every human-recognizable label. Each OR variant
// repeats the base filters so the search never widens them.
const term = query.search?.trim();
let where: FindOptionsWhere<TrainSchedule> | FindOptionsWhere<TrainSchedule>[] =
base;
if (term) {
const like = ILike(`%${term}%`);
where = [
{ ...base, trainNumber: like as never },
{ ...base, originStation: { label: like } },
{ ...base, destinationStation: { label: like } },
{ ...base, route: { originYard: { label: like } } },
{ ...base, route: { destinationYard: { label: like } } },
{ ...base, trainSet: { locomotive: { code: like } } },
] as FindOptionsWhere<TrainSchedule>[];
}
const sortBy = query.sortBy ?? "createdAt";
const sortOrder = query.sortOrder ?? "DESC";
const [schedules, total] = await this.trainSchedulesRepository.findAndCount({
where,
relations: {
trainSet: { locomotive: true },
originStation: true,
@@ -638,7 +751,9 @@ export class BookingBatchService implements OnModuleInit {
// Yards supply the route's display name for `routeName` below.
route: { originYard: true, destinationYard: true },
},
order: { scheduledDepartureDate: "ASC" },
order: { [sortBy]: sortOrder } as never,
skip: (page - 1) * pageSize,
take: pageSize,
});
const wagonDims = await this.loadWagonDims();
@@ -647,11 +762,6 @@ export class BookingBatchService implements OnModuleInit {
const board: BatchBoardSchedule[] = [];
for (const s of schedules) {
if (s.status === "ARRIVED" || s.status === "CANCELLED") continue;
// Batch board is IMPORT-only: export is FCFS with no batch/priority calc,
// and domestic/legacy schedules run the legacy fill, not the window batch.
if (s.direction !== "IMPORT") continue;
const links = await linkRepo.find({ where: { trainScheduleId: s.id } });
const linkedIds = new Set(links.map((l) => l.bookingId));
const bookings = await this.bookingsRepository.findAllBySchedule(s.id);
@@ -679,7 +789,14 @@ export class BookingBatchService implements OnModuleInit {
board.push(this.buildScheduleSummary(s, items, rules));
}
return board;
return {
items: board,
total,
page,
pageSize,
totalPages: Math.max(1, Math.ceil(total / pageSize)),
};
}
/** Schedule-level batch board with EAT 3h windows grouped by fullyExecutedAt. */
@@ -690,9 +807,8 @@ export class BookingBatchService implements OnModuleInit {
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
if (!s)
throw new NotFoundException(`Train schedule ${scheduleId} not found`);
if (s.status === "ARRIVED" || s.status === "CANCELLED") {
throw new BadRequestException("Schedule is no longer active");
}
// Arrived / cancelled schedules stay viewable — the board is also the
// historical record of what each train carried.
// Batch board is IMPORT-only (export is FCFS, no batch/priority calc).
if (s.direction !== "IMPORT") {
throw new BadRequestException(
@@ -867,6 +983,7 @@ export class BookingBatchService implements OnModuleInit {
return {
scheduleId: s.id,
scheduleReference: s.reference ?? null,
trainNumber: s.trainNumber ?? null,
routeName: s.route ? formatRouteLabel(s.route) : null,
origin: s.originStation?.label ?? s.originStation?.code ?? null,
@@ -988,6 +1105,7 @@ export class BookingBatchService implements OnModuleInit {
return {
scheduleId: s.id,
scheduleReference: s.reference ?? null,
trainNumber: s.trainNumber ?? null,
routeName: s.route ? formatRouteLabel(s.route) : null,
origin: s.originStation?.label ?? s.originStation?.code ?? null,
@@ -996,6 +1114,7 @@ export class BookingBatchService implements OnModuleInit {
scheduleDate: s.scheduledDepartureDate
? s.scheduledDepartureDate.toISOString()
: null,
createdAt: s.createdAt ? s.createdAt.toISOString() : null,
status: s.status,
bookingWindowStatus: s.bookingWindowStatus,
direction: s.direction ?? null,
@@ -1089,12 +1208,17 @@ export class BookingBatchService implements OnModuleInit {
const limits = await this.capacityLimits(locomotive, rules);
await this.syncScheduleMaxWagons(schedule, locomotive, rules);
const budget = await this.remainingBudget(schedule, limits, wagonDims);
if (budget.maxRemaining().wagons <= 0) {
const minPerWagon = this.minPerWagonNeed(wagonDims);
if (budget.isExhausted(minPerWagon)) {
await this.setWindow(scheduleId, "FULL");
return 0;
}
const pool = await this.bookingsRepository.findBatchPool(scheduleId);
// Same bulk re-score as fillRouteDayInternal — the legacy per-schedule fill
// must rank bulk bookings by their wagon-derived priority too.
await this.recomputeBulkPriorities(pool, wagonDims);
this.resortPoolByPriority(pool);
const units = this.groupConsolidatedPool(pool);
let armed = false;
let reservedThisPass = 0;
@@ -1181,7 +1305,7 @@ export class BookingBatchService implements OnModuleInit {
this.logger.log(
`[fillSchedule ${scheduleId}] reserved ${reservedThisPass}/${units.length} unit(s) this pass`,
);
if (budget.maxRemaining().wagons <= 0) await this.setWindow(scheduleId, "FULL");
if (budget.isExhausted(minPerWagon)) await this.setWindow(scheduleId, "FULL");
if (armed) this.armSettle(scheduleId);
void this.triggerWagonAllocation(scheduleId);
return commercialReserved;
@@ -1312,6 +1436,10 @@ export class BookingBatchService implements OnModuleInit {
corridorYards,
day,
);
// BULK bookings only get their real (wagon-derived) priority score now, at
// batch time — stamp it and re-rank before the fill consumes the pool.
await this.recomputeBulkPriorities(pool, wagonDims);
this.resortPoolByPriority(pool);
// Consolidated partners collapse into one atomic unit (both-or-neither); a
// consolidated booking whose partner isn't ready this cycle is skipped.
const units = this.groupConsolidatedPool(pool);
@@ -1425,8 +1553,9 @@ export class BookingBatchService implements OnModuleInit {
`[fillRouteDay ${originYardId}->${destinationYardId} ${day}] reserved ${reservedThisPass}/${units.length} unit(s) this pass`,
);
const minPerWagon = this.minPerWagonNeed(wagonDims);
for (const t of trains) {
if (t.budget.maxRemaining().wagons <= 0) await this.setWindow(t.id, "FULL");
if (t.budget.isExhausted(minPerWagon)) await this.setWindow(t.id, "FULL");
if (t.armed) this.armSettle(t.id);
void this.triggerWagonAllocation(t.id);
}
@@ -1502,12 +1631,28 @@ export class BookingBatchService implements OnModuleInit {
if (await this.splitService.findOpenOffer(booking.id)) return null;
const wagonDims = await this.loadWagonDims();
const bulkCapacityTons = await this.loadBulkWagonCapacityTons();
// The wagon-slot axis alone under-constrains the offer. On a weight- or
// length-limited train (slots to spare, but e.g. only 798T of pull weight
// left) sizing by slots either produced an offer the fits() check below
// rejected, or — when the free slots exceeded the booking's own wagon
// count — sizeOffer refused outright, so a bulk booking on a weight-bound
// train was never offered a split at all. Size across all three axes,
// measured on the booking's REAL wagon type — the same one allocation
// validates against. Bulk splits ride FULL wagons only: the offer never
// part-loads its last wagon.
const perWagon = this.dimsFor(booking, wagonDims);
const partial = sizePartialOfferWagons(budget, need.wagons, perWagon, {
fullWagonsOnly: booking.freightType === "BULK",
});
if (!partial) return null;
const sized = await this.splitService.sizeOffer(
booking,
budget.wagons,
partial.wagons,
need.wagons,
bulkCapacityTons,
perWagon.capacityTons,
partial.maxCargoTons,
);
if (!sized) return null;
@@ -1516,13 +1661,9 @@ export class BookingBatchService implements OnModuleInit {
weightTons: bookingGrossWeightTons(
sized.offeredWeightTons,
sized.offeredWagons,
this.tareFor(booking.freightType, wagonDims),
),
lengthMeters: bookingTrainLengthMeters(
booking.freightType,
sized.offeredWagons,
this.lengthsOf(wagonDims),
perWagon.tareWeightTons,
),
lengthMeters: sized.offeredWagons * perWagon.lengthMeters,
};
if (!this.fits(offeredNeed, budget)) return null;
@@ -1540,14 +1681,6 @@ export class BookingBatchService implements OnModuleInit {
return offeredNeed;
}
private async loadBulkWagonCapacityTons(): Promise<number> {
const cw3 = await this.dataSource
.getRepository(WagonType)
.findOne({ where: { code: "CW3" } });
const capacity = cw3 ? wagonTypeDimensionsFromEntity(cw3).capacityTons : 60;
return capacity > 0 ? capacity : 60;
}
/**
* Settle a schedule's reserved bookings. `expireUnpaidUnknownDeadline` decides
* how to treat a reservation with no deadline (durable path: leave it; timeout
@@ -1743,7 +1876,7 @@ export class BookingBatchService implements OnModuleInit {
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(
booking.trainScheduleId,
);
if (schedule && (await this.remainingWagons(schedule)) <= 0) {
if (schedule && (await this.isTrainFull(schedule))) {
await this.setWindow(booking.trainScheduleId, "FULL");
}
void this.triggerWagonAllocation(booking.trainScheduleId!);
@@ -1917,8 +2050,9 @@ export class BookingBatchService implements OnModuleInit {
"PREPAID",
);
await this.notifier.payNow(booking, deadline);
const reservedWagons = this.wagonsFor(booking, await this.loadWagonDims());
this.logger.log(
`[BATCH] RESERVED ${booking.reference} (${this.wagonsFor(booking)}w, ` +
`[BATCH] RESERVED ${booking.reference} (${reservedWagons}w, ` +
`priority ${booking.priorityScore ?? 0}) on schedule ${scheduleId}` +
`pay by ${deadline.toISOString()}`,
);
@@ -2235,12 +2369,23 @@ export class BookingBatchService implements OnModuleInit {
const containers = (b: Booking): number =>
(b.bookingContainers ?? []).reduce((sum, c) => sum + Number(c.quantity ?? 0), 0);
const totalContainers = containers(primary) + containers(partner);
const sharedWagons =
totalContainers > 0
? Math.ceil(totalContainers / MAX_TEU_SLOTS_PER_WAGON)
: this.wagonsFor(primary) + this.wagonsFor(partner);
const cargoTons =
Number(primary.cargoTotalWeightVgm ?? 0) + Number(partner.cargoTotalWeightVgm ?? 0);
// Consolidation shares TEU slots, never rated payload: the pair still needs
// enough wagons to carry its combined cargo, so the weight axis bounds the
// shared count exactly as it bounds an individual booking's. A pair shares
// wagons, so the primary's wagon type stands for both partners.
const dims = this.dimsFor(primary, wagonDims);
const capacityTons = dims.capacityTons;
const byWeight =
cargoTons > 0 && capacityTons > 0 ? Math.ceil(cargoTons / capacityTons) : 0;
const byLength =
totalContainers > 0
? Math.ceil(totalContainers / MAX_TEU_SLOTS_PER_WAGON)
: this.wagonsFor(primary, wagonDims) + this.wagonsFor(partner, wagonDims);
const sharedWagons = Math.max(byLength, byWeight);
return {
wagons: sharedWagons,
// Consolidation saves tare as well as slots: the pair rides `sharedWagons`
@@ -2248,43 +2393,95 @@ export class BookingBatchService implements OnModuleInit {
weightTons: bookingGrossWeightTons(
cargoTons,
sharedWagons,
this.tareFor(primary.freightType, wagonDims),
),
lengthMeters: bookingTrainLengthMeters(
primary.freightType,
sharedWagons,
this.lengthsOf(wagonDims),
dims.tareWeightTons,
),
lengthMeters: sharedWagons * dims.lengthMeters,
};
}
/** Per-wagon tare for the wagon type this freight rides on. */
private tareFor(freightType: string | null | undefined, wagonDims: WagonDims): number {
return freightType === 'BULK'
? wagonDims.bulk.tareWeightTons
: wagonDims.container.tareWeightTons;
}
private lengthsOf(wagonDims: WagonDims): { container: number; bulk: number } {
return {
container: wagonDims.container.lengthMeters,
bulk: wagonDims.bulk.lengthMeters,
};
}
private wagonsFor(booking: Booking): number {
if (booking.wagonsRequired && booking.wagonsRequired > 0) {
return Math.ceil(booking.wagonsRequired);
/**
* Stamp real priority scores on the pool's BULK bookings before the batch
* ranks it. Submit-time scoring runs with totalWagons = 0 for bulk (a bulk
* booking has no container lines to carry a wagon count), so every
* wagon-range priority config missed and bulk import bookings entered the
* batch at score 0 — they were never prioritized. Their wagon footprint is
* derivable from tonnage vs. live wagon capacity (wagonsFor), so the score
* is computed here — when doc review closes and the batch runs — and
* persisted so the priority board shows the same ranking. The pool arrives
* SQL-ordered by the old scores; the caller must re-sort after this.
*/
private async recomputeBulkPriorities(
pool: Booking[],
wagonDims: WagonDims,
): Promise<void> {
for (const booking of pool) {
if (booking.freightType !== 'BULK') continue;
try {
const wagons = this.wagonsFor(booking, wagonDims);
const score = await this.pricingService.computeSubmitPriorityScore(
booking,
wagons,
);
if (Number(booking.priorityScore ?? 0) === score) continue;
await this.dataSource
.getRepository(Booking)
.update(booking.id, { priorityScore: score });
booking.priorityScore = score;
} catch (err) {
// A failed recompute keeps the stored score — never blocks the batch.
this.logger.warn(
`Bulk priority recompute failed for ${booking.reference ?? booking.id}: ` +
`${(err as Error).message}`,
);
}
}
// booking.wagonsRequired is NULL for most rows (only set on certain
// scheduling paths). Derive from the container lines, TEU-aware: two 20ft
// share one wagon (wagonsPerUnit = 0.5). The old fallback summed raw
// container QUANTITY, so 20×20ft counted as 20 wagons instead of 10 and
// wrongly filled the train.
const fromContainers = containerWagonsForLines(
booking.bookingContainers ?? [],
}
/** Restore the batch pool ordering (mirrors findBatchPool's ORDER BY) after scores changed. */
private resortPoolByPriority(pool: Booking[]): void {
pool.sort(
(a, b) =>
Number(b.isGovernment) - Number(a.isGovernment) ||
Number(b.priorityScore ?? 0) - Number(a.priorityScore ?? 0) ||
(a.fullyExecutedAt?.getTime() ?? Infinity) -
(b.fullyExecutedAt?.getTime() ?? Infinity) ||
a.createdAt.getTime() - b.createdAt.getTime(),
);
return Math.max(DEFAULT_WAGONS_PER_BOOKING, fromContainers);
}
/**
* Wagons a booking occupies. Two axes bind independently and the booking needs
* enough wagons to satisfy BOTH, so the count is the larger of:
*
* weight — ceil(cargoTons / wagonType.capacityTons), the rated payload
* length — TEU geometry, two 20ft to a wagon (container bookings only)
*
* The weight axis was missing entirely. A BULK booking carries no container
* lines, so `containerWagonsForLines` returned 0 and every bulk booking
* collapsed to a single wagon no matter its tonnage — a 2590T fertilizer
* booking counted as 1 wagon, and `needFor` then charged 1 tare instead of 37.
* That under-reported the board and let the fill loop overbook the train.
*/
private wagonsFor(booking: Booking, wagonDims: WagonDims): number {
// Stored wagonsRequired is a candidate, never an early return: rows written
// while sumWagonsRequired hardcoded BULK to 1 wagon are still in the DB, and
// trusting them charged one tare for a whole bulk consist (a 700T booking on
// 70T wagons read 700 + 1 tare instead of 700 + 10 tares).
const stored =
booking.wagonsRequired && booking.wagonsRequired > 0
? Math.ceil(booking.wagonsRequired)
: 0;
// TEU-aware: two 20ft share one wagon (wagonsPerUnit = 0.5). The old fallback
// summed raw container QUANTITY, so 20×20ft counted as 20 wagons, not 10.
const byLength = containerWagonsForLines(booking.bookingContainers ?? []);
const capacityTons = this.dimsFor(booking, wagonDims).capacityTons;
const cargoTons = Number(booking.cargoTotalWeightVgm ?? 0);
const byWeight =
cargoTons > 0 && capacityTons > 0 ? Math.ceil(cargoTons / capacityTons) : 0;
return Math.max(DEFAULT_WAGONS_PER_BOOKING, stored, byLength, byWeight);
}
/**
@@ -2296,19 +2493,16 @@ export class BookingBatchService implements OnModuleInit {
* 37-wagon box-wagon train read 2590T when it really weighed 3522T.
*/
private needFor(booking: Booking, wagonDims: WagonDims): Capacity {
const wagons = this.wagonsFor(booking);
const wagons = this.wagonsFor(booking, wagonDims);
const dims = this.dimsFor(booking, wagonDims);
return {
wagons,
weightTons: bookingGrossWeightTons(
Number(booking.cargoTotalWeightVgm ?? 0),
wagons,
this.tareFor(booking.freightType, wagonDims),
),
lengthMeters: bookingTrainLengthMeters(
booking.freightType,
wagons,
this.lengthsOf(wagonDims),
dims.tareWeightTons,
),
lengthMeters: wagons * dims.lengthMeters,
};
}
@@ -2321,14 +2515,16 @@ export class BookingBatchService implements OnModuleInit {
}
/**
* Hard caps for a schedule's train: gross pull weight, train length, and the
* Caps for a schedule's train: gross pull weight, train length, and the
* length-derived wagon slot count (never a fixed 53). Bookings spend against
* these via {@link needFor}, whose weight axis is gross.
* `base` via {@link needFor}, whose weight axis is gross. The locomotive's
* overage tolerance is returned separately — the corridor budget spends it
* only to admit a booking whole, never to size a split.
*/
private async capacityLimits(
locomotive: Locomotive,
rules: TrainSchedulingGlobalRules | null,
): Promise<Capacity> {
): Promise<TrainLimits> {
const wagonTypes = await this.loadWagonTypeDimensions();
const derived = deriveTrainCapacityFromLocomotive(
{
@@ -2348,9 +2544,15 @@ export class BookingBatchService implements OnModuleInit {
},
);
return {
wagons: derived.maxWagonSlots,
weightTons: derived.maxWeightTons,
lengthMeters: derived.maxLengthMeters,
base: {
wagons: derived.maxWagonSlots,
weightTons: derived.baseWeightTons,
lengthMeters: derived.baseLengthMeters,
},
tolerance: {
weightTons: derived.toleranceTons,
lengthMeters: derived.toleranceMeters,
},
};
}
@@ -2361,11 +2563,11 @@ export class BookingBatchService implements OnModuleInit {
rules: TrainSchedulingGlobalRules | null,
): Promise<void> {
const limits = await this.capacityLimits(locomotive, rules);
if ((schedule.maxWagons ?? 0) !== limits.wagons) {
if ((schedule.maxWagons ?? 0) !== limits.base.wagons) {
await this.dataSource
.getRepository(TrainSchedule)
.update(schedule.id, { maxWagons: limits.wagons });
schedule.maxWagons = limits.wagons;
.update(schedule.id, { maxWagons: limits.base.wagons });
schedule.maxWagons = limits.base.wagons;
}
}
@@ -2392,25 +2594,64 @@ export class BookingBatchService implements OnModuleInit {
];
}
/** Representative wagon per freight type: NW5 flat for containers, CW3 gondola for bulk. */
/**
* Every wagon type keyed by id (drives per-booking dims via the cargo/container
* type's wagon_type_id FK), plus representative fallbacks per freight type
* (NW5 flat for containers, CW3 gondola for bulk) for bookings whose type has
* no wagon type configured yet.
*/
private async loadWagonDims(): Promise<WagonDims> {
const types = await this.dataSource.getRepository(WagonType).find({
where: [{ code: "NW5" }, { code: "CW3" }],
});
const types = await this.dataSource.getRepository(WagonType).find();
const byCode = new Map(
types.map((t) => [t.code, wagonTypeDimensionsFromEntity(t)]),
);
const byWagonTypeId = new Map(
types.map((t) => [t.id, wagonTypeDimensionsFromEntity(t)]),
);
const nw5 = byCode.get("NW5");
const cw3 = byCode.get("CW3");
// capacityTons divides a bulk booking's cargo, so a 0 or missing rated payload
// must fall back rather than yield an infinite wagon count.
const payload = (value: number | undefined, fallback: number): number =>
value && value > 0 ? value : fallback;
return {
container: {
lengthMeters: nw5?.lengthMeters ?? DEFAULT_CONTAINER_WAGON_LENGTH_METERS,
tareWeightTons: nw5?.tareWeightTons ?? DEFAULT_CONTAINER_WAGON_TARE_TONS,
capacityTons: payload(nw5?.capacityTons, DEFAULT_CONTAINER_WAGON_CAPACITY_TONS),
},
bulk: {
lengthMeters: cw3?.lengthMeters ?? DEFAULT_BULK_WAGON_LENGTH_METERS,
tareWeightTons: cw3?.tareWeightTons ?? DEFAULT_BULK_WAGON_TARE_TONS,
capacityTons: payload(cw3?.capacityTons, DEFAULT_BULK_WAGON_CAPACITY_TONS),
},
byWagonTypeId,
};
}
/**
* Dimensions of the wagon type THIS booking rides: bulk resolves through its
* cargo type's wagon_type_id, container through the first container line's
* type — the same FK resolution `resolveWagonType` applies when the paid
* booking is allocated. Board/fill math measured on a representative wagon
* while allocation validated the real one let a selected batch flunk the
* post-payment gross-weight check; sharing the resolution closes that gap.
* Falls back to the representative dims when the FK or relation is absent.
*/
private dimsFor(booking: Booking, wagonDims: WagonDims): PerWagonDims {
const fallback =
booking.freightType === "BULK" ? wagonDims.bulk : wagonDims.container;
const wagonTypeId =
booking.freightType === "BULK"
? booking.cargoType?.wagonTypeId
: (booking.bookingContainers ?? [])
.map((line) => line.containerType?.wagonTypeId)
.find((id): id is string => Boolean(id));
const dims = wagonTypeId ? wagonDims.byWagonTypeId.get(wagonTypeId) : undefined;
if (!dims) return fallback;
return {
...dims,
capacityTons: dims.capacityTons > 0 ? dims.capacityTons : fallback.capacityTons,
};
}
@@ -2446,11 +2687,11 @@ export class BookingBatchService implements OnModuleInit {
*/
private async remainingBudget(
schedule: TrainSchedule,
limits: Capacity,
limits: TrainLimits,
wagonDims: WagonDims,
): Promise<CorridorBudget> {
const stops = await this.stopsForSchedule(schedule);
const budget = new CorridorBudget(stops, limits);
const budget = new CorridorBudget(stops, limits.base, limits.tolerance);
const allocated = (schedule.scheduleBookings ?? [])
.map((sb) => sb.booking)
.filter((b): b is Booking => Boolean(b));
@@ -2468,16 +2709,21 @@ export class BookingBatchService implements OnModuleInit {
/**
* Wagon slots still boardable somewhere on the corridor (most-open edge).
* ≤ 0 means no leg can take another booking — the train-wide FULL signal.
* ≤ 0 means no leg can take another booking. Slot axis ONLY — the train-wide
* FULL signal is {@link isTrainFull}, which also closes weight/length-bound
* trains that still show free slots.
*/
private async remainingWagons(schedule: TrainSchedule): Promise<number> {
const wagonDims = await this.loadWagonDims();
const budget = await this.remainingBudget(
schedule,
{
wagons: schedule.maxWagons ?? 0,
weightTons: Number.POSITIVE_INFINITY,
lengthMeters: Number.POSITIVE_INFINITY,
base: {
wagons: schedule.maxWagons ?? 0,
weightTons: Number.POSITIVE_INFINITY,
lengthMeters: Number.POSITIVE_INFINITY,
},
tolerance: { weightTons: 0, lengthMeters: 0 },
},
wagonDims,
);
@@ -2530,12 +2776,52 @@ export class BookingBatchService implements OnModuleInit {
);
}
/** No wagon slots left for allocated + reserved bookings. */
/**
* FULL on ANY capacity axis: out of wagon slots, or out of pull weight /
* train length for even one more loaded wagon. The old slot-only check let
* a weight-bound train (PW2: weight binds at 37 wagons = 3522.4T of
* 3500+90T, slots bind at 44) cycle its booking window forever instead of
* finalizing — 7 phantom slots kept it "not full" while nothing could board.
*/
async isScheduleFull(scheduleId: string): Promise<boolean> {
const schedule =
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
if (!schedule) return false;
return (await this.remainingWagons(schedule)) <= 0;
return this.isTrainFull(schedule);
}
/** See {@link isScheduleFull} — same check for callers that already hold the full graph. */
private async isTrainFull(schedule: TrainSchedule): Promise<boolean> {
if ((await this.remainingWagons(schedule)) <= 0) return true;
const locomotive = schedule.trainSet?.locomotive;
if (!locomotive) return false; // no weight/length limits to bind against
const rules = await this.loadGlobalRules();
const wagonDims = await this.loadWagonDims();
const limits = await this.capacityLimits(locomotive, rules);
const budget = await this.remainingBudget(schedule, limits, wagonDims);
return budget.isExhausted(this.minPerWagonNeed(wagonDims));
}
/**
* Smallest gross weight / shortest length one more wagon could add: the
* lightest wagon type at its rated payload. Feeds CorridorBudget.isExhausted,
* so FULL is only declared when not even this wagon fits anywhere.
*/
private minPerWagonNeed(wagonDims: WagonDims): {
grossWeightTons: number;
lengthMeters: number;
} {
const all = [
wagonDims.container,
wagonDims.bulk,
...wagonDims.byWagonTypeId.values(),
];
return {
grossWeightTons: Math.min(
...all.map((d) => d.tareWeightTons + d.capacityTons),
),
lengthMeters: Math.min(...all.map((d) => d.lengthMeters)),
};
}
/**
@@ -2556,7 +2842,10 @@ export class BookingBatchService implements OnModuleInit {
const schedule =
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
if (!schedule || schedule.bookingWindowStatus !== "FULL") return;
if ((await this.remainingWagons(schedule)) <= 0) return;
// Symmetric with isScheduleFull: a weight/length-bound FULL is not stale
// just because slots remain — clearing it here would reopen a train
// nothing can board.
if (await this.isTrainFull(schedule)) return;
const customerWindowOpen =
schedule.windowPhase == null || schedule.windowPhase === "OPEN";

View File

@@ -28,6 +28,9 @@ import { TrainCheckpointEvent } from './entities/train-checkpoint-event.entity';
* unload at its destination yard (IN_TRANSIT → ARRIVED for import/export,
* → COMPLETED for intercity), possibly long before the train's final arrival.
* Both are gated on the train's latest recorded checkpoint being at that yard.
* Unload also fires automatically: recording a checkpoint at a yard auto-
* unloads every booking destined there (autoUnloadAtYard), so the manual
* unload endpoint remains only a fallback.
*
* Unloading also settles the physical wagons: each wagon that alights with the
* booking is released at that yard and the move is written to the
@@ -198,6 +201,47 @@ export class BookingJourneyService {
};
}
/**
* Auto-unload on checkpoint: every IN_TRANSIT booking on this schedule whose
* destination is the yard the train just reached alights automatically, so
* the customer's booking flips to ARRIVED (COMPLETED for intercity) the
* moment the train is recorded at their yard — no separate operator unload.
* Runs through the same per-booking unload path (wagon settle + ledger +
* milestones); one booking's failure is logged and never blocks the
* checkpoint or the other bookings. Returns the unloaded booking ids.
*/
async autoUnloadAtYard(
scheduleId: string,
yardId: string,
userId?: string | null,
): Promise<string[]> {
const bookings = await this.dataSource
.getRepository(Booking)
.createQueryBuilder('booking')
.innerJoin(
'freight.train_schedule_bookings',
'tsb',
'tsb.booking_id = booking.id AND tsb.train_schedule_id = :scheduleId AND tsb.deleted_at IS NULL',
{ scheduleId },
)
.where('booking.destination_yard_id = :yardId', { yardId })
.andWhere(`booking.status = 'IN_TRANSIT'`)
.getMany();
const unloaded: string[] = [];
for (const booking of bookings) {
try {
await this.unloadBooking(scheduleId, booking.id, userId);
unloaded.push(booking.id);
} catch (err) {
this.logger.warn(
`Auto-unload failed for booking ${booking.id} at yard ${yardId}: ${(err as Error).message}`,
);
}
}
return unloaded;
}
/**
* Bulk fallback at the train's FINAL arrival: any booking destined for the
* final yard that operators didn't unload individually gets its per-booking

View File

@@ -36,6 +36,9 @@ export interface SizedOffer {
* rows, so reducing the lines releases it automatically) and can be rebooked in
* any later window within contract validity. A ONE_TIME contract is promoted to
* GENERAL on split (see applySplit) so its remainder is actually rebookable.
* Once the remainder is rebooked and the cap hits zero, ContractBookingService
* completes the contract (CONTRACT_CLOSED): no further bookings or shipment
* requests, even while validity and a booking window are still open.
*/
@Injectable()
export class BookingSplitService {
@@ -55,12 +58,17 @@ export class BookingSplitService {
* Size the largest part of the booking that fits `freeWagons`, priced via an
* in-memory clone. Returns null when nothing meaningful fits (no whole
* container unit / no bulk tonnage, or pricing failed).
*
* `maxOfferedWeightTons` caps the offered CARGO tonnage (bulk only) — on a
* weight-limited train the wagons' own tare eats into the locomotive's
* remaining pull weight, so the caller passes the room left after tare.
*/
async sizeOffer(
booking: Booking,
freeWagons: number,
totalWagons: number,
bulkWagonCapacityTons: number,
maxOfferedWeightTons?: number,
): Promise<SizedOffer | null> {
if (freeWagons < 1 || freeWagons >= totalWagons) return null;
@@ -110,10 +118,15 @@ export class BookingSplitService {
if (!offeredLines.length || offeredWagons <= 0) return null;
clone.bookingContainers = clonedContainers;
} else {
// Bulk: split by weight — the offered part is what freeWagons can carry.
// Bulk: split by weight — the offered part is what freeWagons can carry,
// further capped by the caller's weight room when the pull limit binds.
const totalWeight = Number(booking.cargoTotalWeightVgm ?? 0);
if (totalWeight <= 0 || bulkWagonCapacityTons <= 0) return null;
offeredWeightTons = Math.min(totalWeight, freeWagons * bulkWagonCapacityTons);
offeredWeightTons = Math.min(
totalWeight,
freeWagons * bulkWagonCapacityTons,
maxOfferedWeightTons ?? Number.POSITIVE_INFINITY,
);
if (offeredWeightTons <= 0) return null;
offeredWagons = Math.min(
freeWagons,

View File

@@ -0,0 +1,120 @@
import { Capacity, CorridorBudget } from './corridor-capacity.util';
import { sizePartialOfferWagons } from './train-capacity.util';
describe('corridor-capacity.util — overage tolerance', () => {
const pw2 = { lengthMeters: 17.066, capacityTons: 70, tareWeightTons: 25.2 };
const stops = ['yard-a', 'yard-b'];
const base: Capacity = { wagons: 44, weightTons: 3500, lengthMeters: 760 };
const tolerance = { weightTons: 90, lengthMeters: 0 };
const need = (weightTons: number, wagons = 1, lengthMeters = 17): Capacity => ({
wagons,
weightTons,
lengthMeters,
});
const budgetAt = (usedWeightTons: number): CorridorBudget => {
const budget = new CorridorBudget(stops, base, tolerance);
budget.subtract(need(usedWeightTons, 10, 170), budget.fullLeg());
return budget;
};
it('admits a whole booking that overflows the base cap by less than the tolerance', () => {
// 3500T train, 90T tolerance, 3560T committed: a 25T booking still boards
// entire (3585 ≤ 3590).
const budget = budgetAt(3560);
expect(budget.fits(need(25), budget.fullLeg())).toBe(true);
});
it('rejects a whole booking that overflows past the tolerance — no partial admission', () => {
// Same train at 3560T: a 210T booking would need 3770 > 3590 — skipped.
const budget = budgetAt(3560);
expect(budget.fits(need(210), budget.fullLeg())).toBe(false);
});
it('caps stacked overage admissions at base + tolerance', () => {
// Small units may keep boarding inside the overage zone, but never past it.
const budget = budgetAt(3560);
budget.subtract(need(25), budget.fullLeg()); // now 3585 committed
expect(budget.fits(need(5), budget.fullLeg())).toBe(true); // 3590 exactly
expect(budget.fits(need(6), budget.fullLeg())).toBe(false); // 3591 > 3590
});
it('excludes the tolerance from remainingFor, so split room never reaches into it', () => {
const budget = budgetAt(3400);
expect(budget.remainingFor(budget.fullLeg()).weightTons).toBe(100);
// Once a whole-unit admission spends the tolerance, base room goes negative.
const over = budgetAt(3560);
expect(over.remainingFor(over.fullLeg()).weightTons).toBe(-60);
});
it('yields no split offer once the base cap is spent — tolerance is whole-bookings-only', () => {
// The batch engine sizes splits from remainingFor; at/over base capacity
// that room cannot carry even one part-loaded wagon, so no offer opens.
const over = budgetAt(3560);
const room = over.remainingFor(over.fullLeg());
expect(sizePartialOfferWagons(room, 15, pw2)).toBeNull();
});
it('still offers a split while committed weight is under the base cap', () => {
// 744T of base room left: the boundary booking is offered the part that
// fits up to 3500, not up to 3590.
const budget = budgetAt(2756);
const room = budget.remainingFor(budget.fullLeg());
expect(sizePartialOfferWagons(room, 15, pw2)).toEqual({
wagons: 8,
maxCargoTons: 542.4,
});
});
it('leaves fits() strict when no tolerance is configured', () => {
const strict = new CorridorBudget(stops, base);
strict.subtract(need(3500, 10, 170), strict.fullLeg());
expect(strict.fits(need(1), strict.fullLeg())).toBe(false);
});
describe('isExhausted — train-wide FULL across all axes', () => {
// Lightest wagon at rated payload: PW2 25.2T tare + 70T = 95.2T gross.
const perWagon = {
grossWeightTons: pw2.tareWeightTons + pw2.capacityTons,
lengthMeters: pw2.lengthMeters,
};
it('reports FULL when weight binds first, with wagon slots still free', () => {
// 37 loaded PW2 wagons = 3522.4T of 3500+90T. 7 length-derived slots
// remain, but wagon 38 would need 95.2T against 67.6T of room — the
// schedule must finalize and its window must disappear.
const budget = new CorridorBudget(stops, base, tolerance);
budget.subtract(need(3522.4, 37, 631.442), budget.fullLeg());
expect(budget.maxRemaining().wagons).toBeGreaterThan(0); // slot check alone says "not full"
expect(budget.isExhausted(perWagon)).toBe(true);
});
it('is not FULL while one more loaded wagon still fits within base + tolerance', () => {
const budget = budgetAt(3300); // 200T base room + 90T tolerance ≥ 95.2T
expect(budget.isExhausted(perWagon)).toBe(false);
});
it('reports FULL when wagon slots run out regardless of weight room', () => {
const budget = new CorridorBudget(stops, base, tolerance);
budget.subtract(need(1000, 44, 700), budget.fullLeg());
expect(budget.isExhausted(perWagon)).toBe(true);
});
it('reports FULL when length room cannot take one more wagon', () => {
const budget = new CorridorBudget(stops, base, tolerance);
budget.subtract(need(1000, 30, 750), budget.fullLeg()); // 10m left < 17.066m
expect(budget.isExhausted(perWagon)).toBe(true);
});
it('only counts an edge as open when EVERY axis has room on that same edge', () => {
// Three stops → two edges. Edge 0 has weight but no slots; edge 1 has
// slots but no weight. Neither can board a wagon, so the train is FULL
// even though the per-axis maxima both look open.
const budget = new CorridorBudget(['a', 'b', 'c'], base, tolerance);
budget.subtract(need(0, 44, 0), { fromEdge: 0, toEdge: 1 });
budget.subtract(need(3522.4, 0, 0), { fromEdge: 1, toEdge: 2 });
expect(budget.isExhausted(perWagon)).toBe(true);
});
});
});

View File

@@ -63,18 +63,40 @@ export function stopYardsFor(
return [originStationId, destinationStationId];
}
/** Per-edge capacity budget along a schedule's stop list. */
/** Overage a locomotive may absorb beyond its base caps. */
export interface OverageTolerance {
weightTons: number;
lengthMeters: number;
}
/**
* Per-edge capacity budget along a schedule's stop list.
*
* `initial` must be the BASE caps (locomotive floored by rule caps, WITHOUT the
* overage tolerance). The tolerance is passed separately and is spendable only
* by admitting a unit WHOLE via {@link fits} — e.g. base 3500T + 90T tolerance,
* 3560T already committed: a 25T booking still boards entire (3585 ≤ 3590), a
* 210T booking does not. {@link remainingFor} deliberately excludes the
* tolerance (and goes negative once it is consumed), so split/partial offers
* sized from it can only fill up to the base cap and never spend the tolerance.
*/
export class CorridorBudget {
private readonly edges: Capacity[];
private readonly stopIndex: Map<string, number>;
private readonly tolerance: OverageTolerance;
constructor(
readonly stops: string[],
initial: Capacity,
tolerance?: Partial<OverageTolerance> | null,
) {
const edgeCount = Math.max(1, stops.length - 1);
this.edges = Array.from({ length: edgeCount }, () => ({ ...initial }));
this.stopIndex = new Map(stops.map((yardId, i) => [yardId, i]));
this.tolerance = {
weightTons: tolerance?.weightTons ?? 0,
lengthMeters: tolerance?.lengthMeters ?? 0,
};
}
/** The leg between two stops, or null when they aren't on this corridor in order. */
@@ -99,7 +121,12 @@ export class CorridorBudget {
return this.legOf(originYardId, destinationYardId) ?? this.fullLeg();
}
/** Remaining capacity usable by this leg = min across its edges. */
/**
* Remaining BASE capacity usable by this leg = min across its edges. Excludes
* the overage tolerance and goes negative once a whole-unit admission has
* spent it — sizing a split from this can therefore never reach into the
* tolerance, and yields nothing at all once the base cap is exhausted.
*/
remainingFor(leg: CorridorLeg): Capacity {
let min = { ...this.edges[leg.fromEdge] };
for (let i = leg.fromEdge + 1; i < leg.toEdge; i++) {
@@ -113,8 +140,20 @@ export class CorridorBudget {
return min;
}
/**
* Whether a unit fits WHOLE on this leg. This is the only place the overage
* tolerance may be spent: the unit boards entirely or not at all, so weight
* and length may dip into the tolerance. Admission keeps the invariant
* `remaining ≥ -tolerance` on every edge, i.e. the train never exceeds
* base + tolerance no matter how many small units board in the overage zone.
*/
fits(need: Capacity, leg: CorridorLeg): boolean {
return capacityFits(need, this.remainingFor(leg));
const remaining = this.remainingFor(leg);
return (
need.wagons <= remaining.wagons &&
need.weightTons <= remaining.weightTons + this.tolerance.weightTons &&
need.lengthMeters <= remaining.lengthMeters + this.tolerance.lengthMeters
);
}
subtract(need: Capacity, leg: CorridorLeg): void {
@@ -129,6 +168,25 @@ export class CorridorBudget {
}
}
/**
* Train-wide FULL across ALL capacity axes: true when no edge can board even
* one more loaded wagon. `perWagon` is the smallest gross weight and length
* a future wagon could add (lightest wagon type at rated payload); weight and
* length may dip into the overage tolerance, mirroring {@link fits}. Checked
* per edge — an edge with slots free but no pull weight is just as closed as
* one with no slots. A slot-only check misses weight-bound trains: PW2 at
* 37 × 95.2T = 3522.4T of 3500+90T has 7 length-derived slots free but no
* weight room for wagon 38, and its window must read FULL.
*/
isExhausted(perWagon: { grossWeightTons: number; lengthMeters: number }): boolean {
return this.edges.every(
(e) =>
e.wagons <= 0 ||
e.weightTons + this.tolerance.weightTons < perWagon.grossWeightTons ||
e.lengthMeters + this.tolerance.lengthMeters < perWagon.lengthMeters,
);
}
/**
* The most open edge — when even this has no wagon slots left, nothing can
* board anywhere and the schedule's window is genuinely FULL. (A train can be

View File

@@ -51,7 +51,7 @@ export class AssignBookingsDto {
@IsUUID('4', { each: true })
bookingIds!: string[];
@ApiPropertyOptional({ description: 'Bypass soft hold and overweight warnings' })
@ApiPropertyOptional({ description: 'Suppress soft hold and overweight warnings' })
@IsOptional()
@IsBoolean()
forceAssign?: boolean;

View File

@@ -0,0 +1,99 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsIn,
IsInt,
IsISO8601,
IsOptional,
IsString,
Max,
MaxLength,
Min,
} from 'class-validator';
export const BATCH_BOARD_STATUSES = [
'DRAFT',
'SCHEDULED',
'DISPATCHED',
'ARRIVED',
'CANCELLED',
] as const;
export const BATCH_BOARD_SORT_FIELDS = [
'createdAt',
'scheduledDepartureDate',
'trainNumber',
'status',
] as const;
export type BatchBoardSortField = (typeof BATCH_BOARD_SORT_FIELDS)[number];
/** Filters for the batch monitoring board list (import schedules, all statuses). */
export class BatchBoardQueryDto {
@ApiPropertyOptional({ default: 1, minimum: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number;
@ApiPropertyOptional({ default: 12, minimum: 1, maximum: 100 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(100)
pageSize?: number;
@ApiPropertyOptional({
description:
'Comma-separated schedule statuses (DRAFT,SCHEDULED,DISPATCHED,ARRIVED,CANCELLED). Omit for all.',
example: 'DISPATCHED,ARRIVED',
})
@IsOptional()
@IsString()
statuses?: string;
@ApiPropertyOptional({ enum: ['OPEN', 'FULL', 'CLOSED'] })
@IsOptional()
@IsIn(['OPEN', 'FULL', 'CLOSED'])
bookingWindowStatus?: 'OPEN' | 'FULL' | 'CLOSED';
@ApiPropertyOptional({
description:
'Case-insensitive match on train number, route yards, stations, or locomotive code.',
})
@IsOptional()
@IsString()
@MaxLength(120)
search?: string;
@ApiPropertyOptional({ description: 'Departure date lower bound (ISO 8601).' })
@IsOptional()
@IsISO8601()
departureFrom?: string;
@ApiPropertyOptional({ description: 'Departure date upper bound (ISO 8601).' })
@IsOptional()
@IsISO8601()
departureTo?: string;
@ApiPropertyOptional({ description: 'Created-at lower bound (ISO 8601).' })
@IsOptional()
@IsISO8601()
createdFrom?: string;
@ApiPropertyOptional({ description: 'Created-at upper bound (ISO 8601).' })
@IsOptional()
@IsISO8601()
createdTo?: string;
@ApiPropertyOptional({ enum: BATCH_BOARD_SORT_FIELDS, default: 'createdAt' })
@IsOptional()
@IsIn(BATCH_BOARD_SORT_FIELDS as unknown as string[])
sortBy?: BatchBoardSortField;
@ApiPropertyOptional({ enum: ['ASC', 'DESC'], default: 'DESC' })
@IsOptional()
@IsIn(['ASC', 'DESC'])
sortOrder?: 'ASC' | 'DESC';
}

View File

@@ -107,7 +107,13 @@ export class IntercityService {
for (const bookingId of bookingIds) {
const booking = await this.dataSource
.getRepository(Booking)
.findOne({ where: { id: bookingId }, relations: { bookingContainers: true } });
.findOne({
where: { id: bookingId },
relations: {
bookingContainers: { containerType: true },
cargoType: true,
},
});
if (!booking) {
rejected.push({ bookingId, reason: 'Booking not found' });
continue;
@@ -205,6 +211,8 @@ export class IntercityService {
.createQueryBuilder('booking')
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.leftJoinAndSelect('booking.originYard', 'originYard')
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
.where(`booking.trade_direction = 'DOMESTIC'`)
@@ -230,6 +238,8 @@ export class IntercityService {
.createQueryBuilder('booking')
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoinAndSelect('booking.cargoType', 'cargoType')
.leftJoinAndSelect('booking.originYard', 'originYard')
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
.where(`booking.trade_direction = 'DOMESTIC'`)

View File

@@ -6,6 +6,7 @@ import {
deriveTrainCapacityFromLocomotive,
grossWagonWeightTons,
minLocomotiveLimits,
sizePartialOfferWagons,
} from './train-capacity.util';
describe('train-capacity.util', () => {
@@ -73,6 +74,24 @@ describe('train-capacity.util', () => {
expect(derived.maxWeightTons).toBe(3590);
});
it('reports the base caps and tolerance separately so filling can budget on base', () => {
const derived = deriveTrainCapacityFromLocomotive(
{
maxPullWeightTons: 3500,
maxTrainLengthMeters: 760,
overageToleranceTons: 90,
overageToleranceMeters: 20,
},
[pw2],
);
expect(derived.baseWeightTons).toBe(3500);
expect(derived.baseLengthMeters).toBe(760);
expect(derived.toleranceTons).toBe(90);
expect(derived.toleranceMeters).toBe(20);
expect(derived.baseWeightTons + derived.toleranceTons).toBe(derived.maxWeightTons);
expect(derived.baseLengthMeters + derived.toleranceMeters).toBe(derived.maxLengthMeters);
});
it('ignores overage tolerance when unset (strict cap)', () => {
const derived = deriveTrainCapacityFromLocomotive(
{ maxPullWeightTons: 3500, maxTrainLengthMeters: 760 },
@@ -185,4 +204,96 @@ describe('train-capacity.util', () => {
expect(limits?.maxPullWeightTons).toBe(3500);
expect(limits?.overageToleranceTons).toBe(20);
});
describe('sizePartialOfferWagons', () => {
it('sizes a bulk split by the WEIGHT axis when the pull limit binds, not wagon slots', () => {
// The 3500T-train scenario: two 1000T bookings boarded gross (each 15 PW2
// wagons: 1000 + 378 tare = 1378), leaving 744T of pull weight but plenty
// of slots/length. The boundary 1000T booking (15 wagons) must be offered
// the largest part 744T can carry: 8 wagons whose tare is 201.6T, hauling
// 542.4T of cargo — gross exactly 744.
const offer = sizePartialOfferWagons(
{ wagons: 40, weightTons: 744, lengthMeters: 500 },
15,
pw2,
);
expect(offer).toEqual({ wagons: 8, maxCargoTons: 542.4 });
});
it('still sizes by wagon slots when they bind first (legacy behavior)', () => {
const offer = sizePartialOfferWagons(
{ wagons: 3, weightTons: 100000, lengthMeters: 100000 },
15,
pw2,
);
expect(offer?.wagons).toBe(3);
});
it('sizes by the LENGTH axis when it binds first', () => {
// 60m of train left → 3 PW2 (17.066m) fit, the 4th does not.
const offer = sizePartialOfferWagons(
{ wagons: 40, weightTons: 100000, lengthMeters: 60 },
15,
pw2,
);
expect(offer?.wagons).toBe(3);
});
it('never offers all of the booking — a split is a strict subset', () => {
const offer = sizePartialOfferWagons(
{ wagons: 40, weightTons: 100000, lengthMeters: 100000 },
15,
pw2,
);
expect(offer?.wagons).toBe(14);
});
it('returns null when not even one part-loaded wagon fits the weight room', () => {
expect(
sizePartialOfferWagons({ wagons: 5, weightTons: 20, lengthMeters: 500 }, 15, pw2),
).toBeNull();
});
describe('fullWagonsOnly (bulk)', () => {
it('offers only whole full wagons — each costs capacity + tare of gross room', () => {
// 704T of pull weight left. A full PW2 wagon is 70 + 25.2 = 95.2T gross,
// so 7 fit (666.4T) and the 8th (761.6T) does not. Cargo is exactly
// 7 × 70 = 490T — the last wagon is never part-loaded into the leftover.
const offer = sizePartialOfferWagons(
{ wagons: 40, weightTons: 704, lengthMeters: 500 },
9,
pw2,
{ fullWagonsOnly: true },
);
expect(offer).toEqual({ wagons: 7, maxCargoTons: 490 });
});
it('never squeezes a part-loaded wagon into leftover weight room', () => {
// Same 744T room as the part-load scenario above: the scan would pick
// 8 wagons hauling 542.4T (last wagon at 52.4/70). Full-wagon sizing
// stops at 7 fully loaded wagons.
const offer = sizePartialOfferWagons(
{ wagons: 40, weightTons: 744, lengthMeters: 500 },
15,
pw2,
{ fullWagonsOnly: true },
);
expect(offer).toEqual({ wagons: 7, maxCargoTons: 490 });
});
it('returns null when the room cannot take even one FULL wagon', () => {
// 67.6T left (3590 cap 3522.4 boarded): a part-loaded wagon would fit
// (25.2 tare + 42.4 cargo) but a full one (95.2 gross) does not — the
// booking must be skipped entirely, not trimmed onto the train.
expect(
sizePartialOfferWagons(
{ wagons: 40, weightTons: 67.6, lengthMeters: 500 },
3,
pw2,
{ fullWagonsOnly: true },
),
).toBeNull();
});
});
});
});

View File

@@ -52,6 +52,12 @@ export type DerivedTrainCapacity = {
maxLengthMeters: number;
/** Length-derived slot count. Weight is enforced separately against real cargo. */
maxWagonSlots: number;
/** Caps WITHOUT the overage tolerance — what batch filling budgets against. */
baseWeightTons: number;
baseLengthMeters: number;
/** Overage spendable only by admitting a booking whole, never by a split. */
toleranceTons: number;
toleranceMeters: number;
};
/** What a consist currently uses, and what is left on each axis. */
@@ -88,28 +94,48 @@ export function grossWagonWeightTons(slot: Pick<ConsistSlot, 'tareWeightTons' |
/**
* Hard caps for a train: the locomotive's own limits, floored by the global rule
* caps, then widened by the locomotive's overage tolerance.
*
* `base*` are the caps BEFORE the tolerance is added. The tolerance is not
* general-purpose headroom: batch filling budgets against the base caps and may
* spend the tolerance only to admit a booking WHOLE (never to size a split), so
* both figures are returned. `base + tolerance === max` always holds, including
* the fallback path.
*/
export function trainHardCaps(
locomotive: LocomotiveLimits,
ruleCaps?: { maxTrainWeightTons?: number; maxTrainLengthMeters?: number },
): { maxWeightTons: number; maxLengthMeters: number } {
): {
maxWeightTons: number;
maxLengthMeters: number;
baseWeightTons: number;
baseLengthMeters: number;
toleranceTons: number;
toleranceMeters: number;
} {
const overageTons = num(locomotive.overageToleranceTons);
const overageMeters = num(locomotive.overageToleranceMeters);
const weight =
Math.min(
num(locomotive.maxPullWeightTons, Infinity) || Infinity,
ruleCaps?.maxTrainWeightTons ?? Infinity,
) + overageTons;
const length =
Math.min(
num(locomotive.maxTrainLengthMeters, Infinity) || Infinity,
ruleCaps?.maxTrainLengthMeters ?? Infinity,
) + overageMeters;
const baseWeight = Math.min(
num(locomotive.maxPullWeightTons, Infinity) || Infinity,
ruleCaps?.maxTrainWeightTons ?? Infinity,
);
const baseLength = Math.min(
num(locomotive.maxTrainLengthMeters, Infinity) || Infinity,
ruleCaps?.maxTrainLengthMeters ?? Infinity,
);
const baseWeightTons = Number.isFinite(baseWeight) ? baseWeight : MAX_FALLBACK_WEIGHT;
const baseLengthMeters = Number.isFinite(baseLength) ? baseLength : MAX_FALLBACK_LENGTH;
const toleranceTons = Number.isFinite(baseWeight) ? overageTons : 0;
const toleranceMeters = Number.isFinite(baseLength) ? overageMeters : 0;
return {
maxWeightTons: Number.isFinite(weight) ? weight : MAX_FALLBACK_WEIGHT,
maxLengthMeters: Number.isFinite(length) ? length : MAX_FALLBACK_LENGTH,
maxWeightTons: baseWeightTons + toleranceTons,
maxLengthMeters: baseLengthMeters + toleranceMeters,
baseWeightTons,
baseLengthMeters,
toleranceTons,
toleranceMeters,
};
}
@@ -129,7 +155,7 @@ export function deriveTrainCapacityFromLocomotive(
wagonTypes: WagonTypeDimensions[],
ruleCaps?: { maxTrainWeightTons?: number; maxTrainLengthMeters?: number },
): DerivedTrainCapacity {
const { maxWeightTons, maxLengthMeters } = trainHardCaps(locomotive, ruleCaps);
const caps = trainHardCaps(locomotive, ruleCaps);
const lengths = wagonTypes
.map((w) => num(w.lengthMeters))
@@ -137,9 +163,9 @@ export function deriveTrainCapacityFromLocomotive(
const minLength = lengths.length ? Math.min(...lengths) : DEFAULT_WAGON_LENGTH_M;
const maxWagonSlots =
minLength > 0 ? Math.max(0, Math.floor(maxLengthMeters / minLength)) : 0;
minLength > 0 ? Math.max(0, Math.floor(caps.maxLengthMeters / minLength)) : 0;
return { maxWeightTons, maxLengthMeters, maxWagonSlots };
return { ...caps, maxWagonSlots };
}
/**
@@ -256,6 +282,58 @@ export function bookingGrossWeightTons(
return round3(num(cargoTons) + wagonCount * num(tarePerWagonTons));
}
/**
* Size a partial (split-on-payment) offer against the room left on a train,
* across ALL THREE capacity axes — not just wagon slots. Each wagon adds
* `capacityTons` of payload headroom but its own tare spends the same weight
* room the cargo needs, so on a weight-limited train more wagons is not always
* more cargo. Scans wagon counts (the last wagon may run part-loaded) and
* returns the count that maximizes the cargo carried, with the cargo cap the
* caller should apply. Null when not even one part-loaded wagon fits. The
* offer is a strict subset of the booking: never all `bookingWagons`.
*
* `fullWagonsOnly` (bulk): every offered wagon rides at its full rated payload,
* so each wagon costs `capacityTons + tareWeightTons` of gross weight room and
* the offer is the largest whole-wagon count whose gross fits — never a
* part-loaded last wagon squeezed into leftover pull weight.
*/
export function sizePartialOfferWagons(
room: { wagons: number; weightTons: number; lengthMeters: number },
bookingWagons: number,
perWagon: { capacityTons: number; tareWeightTons: number; lengthMeters: number },
opts?: { fullWagonsOnly?: boolean },
): { wagons: number; maxCargoTons: number } | null {
const maxByLength =
perWagon.lengthMeters > 0
? Math.floor(room.lengthMeters / perWagon.lengthMeters)
: room.wagons;
const ceiling = Math.min(room.wagons, maxByLength, bookingWagons - 1);
if (opts?.fullWagonsOnly) {
const grossPerWagon = perWagon.capacityTons + perWagon.tareWeightTons;
const maxByWeight =
grossPerWagon > 0 ? Math.floor(room.weightTons / grossPerWagon) : 0;
const wagons = Math.min(ceiling, maxByWeight);
if (wagons < 1) return null;
return { wagons, maxCargoTons: round3(wagons * perWagon.capacityTons) };
}
let wagons = 0;
let bestCargoTons = 0;
for (let w = 1; w <= ceiling; w += 1) {
const cargoAt = Math.min(
w * perWagon.capacityTons,
room.weightTons - w * perWagon.tareWeightTons,
);
if (cargoAt > bestCargoTons) {
bestCargoTons = cargoAt;
wagons = w;
}
}
if (wagons < 1) return null;
return { wagons, maxCargoTons: round3(room.weightTons - wagons * perWagon.tareWeightTons) };
}
export function wagonTypeDimensionsFromEntity(wt: {
lengthMeters?: number | string | null;
capacityTons?: number | string | null;

View File

@@ -39,6 +39,7 @@ import {
UploadImportDjiboutiDocumentDto,
} from "./dto/import-djibouti-operation.dto";
import { AvailableLocomotivesQueryDto } from "./dto/available-locomotives-query.dto";
import { BatchBoardQueryDto } from "./dto/batch-board-query.dto";
import { BookableSchedulesQueryDto } from "./dto/bookable-schedules-query.dto";
import { AvailableDaysQueryDto } from "./dto/available-days-query.dto";
import { AvailableDaysForCargoQueryDto } from "./dto/available-days-for-cargo-query.dto";
@@ -124,10 +125,11 @@ export class TrainSchedulingController {
@Get("batch-board")
@TrainSchedulingView()
@ApiOperation({
summary: "Batch monitoring board: schedules with bookings grouped by state",
summary:
"Batch monitoring board: paginated import schedules (all statuses) with bookings grouped by state",
})
getBatchBoard() {
return this.bookingBatchService.getBatchBoard();
getBatchBoard(@Query() query: BatchBoardQueryDto) {
return this.bookingBatchService.getBatchBoard(query);
}
@Get("batch-board/:scheduleId")

View File

@@ -72,7 +72,7 @@ const makeBooking = (
wagonsRequired,
vgmPerUnitTons: weight / quantity,
isOverweight: false,
containerType: { code: containerCode, label: containerCode },
containerType: { code: containerCode, label: containerCode, wagonTypeId: nw5.id },
},
],
...extra,
@@ -282,7 +282,7 @@ describe('TrainSchedulingService', () => {
expect(result.warnings[0]).toContain('soft hold window');
});
it('flags the overweight booking as invalid', async () => {
it('warns on the overweight booking but still allows scheduling', async () => {
const bookings = [
makeBooking('b6', 'BKG-CONT-006', 3600, 80, '40FT', 80, undefined, undefined, undefined, {
bookingContainers: [
@@ -293,7 +293,7 @@ describe('TrainSchedulingService', () => {
wagonsRequired: 80,
vgmPerUnitTons: 45,
isOverweight: true,
containerType: { code: '40FT', label: '40FT' },
containerType: { code: '40FT', label: '40FT', wagonTypeId: nw5.id },
},
],
}),
@@ -311,8 +311,8 @@ describe('TrainSchedulingService', () => {
destinationStationId: 'yard-destination',
});
expect(result.valid).toBe(false);
expect(result.violations.some((v) => v.includes('overweight'))).toBe(true);
expect(result.violations.some((v) => v.includes('overweight'))).toBe(false);
expect(result.warnings.some((w) => w.includes('overweight'))).toBe(true);
});
it('allows preview when bookings are already on the target schedule', async () => {

View File

@@ -1073,12 +1073,17 @@ export class TrainSchedulingService {
containerPlacements ?? [],
);
// The link above puts these bookings on the train: they are SCHEDULED, not
// ELIGIBLE. Leaving them ELIGIBLE re-offers an allocated booking to the next
// batch fill, which unlinks it and frees its wagons on the next window cycle.
const scheduledAt = new Date();
for (const booking of bookings) {
await this.bookingsRepository.updateSchedulingFields(
booking.id,
{
schedulingStatus: SchedulingStatus.Eligible,
wagonsRequired: sumWagonsRequired(booking),
schedulingStatus: SchedulingStatus.Scheduled,
scheduledAt,
wagonsRequired: sumWagonsRequired(booking, wagonPlan),
},
manager,
);
@@ -2509,6 +2514,12 @@ export class TrainSchedulingService {
if (dto.sequenceNo === finalSeq) {
await this.arriveSchedule(scheduleId);
} else {
// Mid-corridor auto-unload: bookings destined for this yard alight the
// moment the train is recorded here — the yard operator no longer has to
// unload each one by hand. The final station is covered by
// arriveSchedule's bulk fallback above.
await this.bookingJourneyService.autoUnloadAtYard(scheduleId, station.yardId);
}
return this.getScheduleCheckpoints(scheduleId);
@@ -2802,10 +2813,14 @@ export class TrainSchedulingService {
`Booking ${booking.reference} is within the soft hold window (expires ${booking.holdExpiresAt?.toISOString()})`,
);
}
// Overweight is the soft threshold (maxVgmTons): the customer already
// paid the overweight surcharge at booking. The hard ceiling
// (maxCapacityTons) blocks booking creation, so anything reaching
// scheduling is shippable — warn the planner, never block allocation.
const overweightLines = (booking.bookingContainers ?? []).filter((c) => c.isOverweight);
if (overweightLines.length) {
violations.push(
`Booking ${booking.reference} has overweight container lines; use forceAssign to override`,
warnings.push(
`Booking ${booking.reference} has ${overweightLines.length} overweight container line(s); overweight surcharge applied`,
);
}
}
@@ -4509,6 +4524,11 @@ export class TrainSchedulingService {
capacityTons: roundTons(Number(wagon.capacityTons)),
lengthMeters: roundTons(Number(wagon.lengthMeters)),
assignedWeightTons: roundTons(Number(wagon.assignedWeightTons)),
// Empty-wagon weight — the pull limit hauls tare + cargo, so the
// frontend needs it to show the gross train weight.
tareWeightTons: wagon.wagonType
? roundTons(Number(wagon.wagonType.tareWeightTons))
: null,
status: wagon.status,
physicalWagonId: wagon.physicalWagonId ?? null,
physicalWagonNumber: wagon.physicalWagon?.wagonNumber ?? null,

View File

@@ -82,6 +82,29 @@ describe('wagon-plan.util', () => {
expect(plan).toHaveLength(2);
});
it('counts a bulk booking\'s wagons from the plan, not a flat 1', () => {
// 700T of sugar on 60T CW3 gondolas = 12 wagons; the stored wagonsRequired
// must carry all of them so gross weight charges 12 tares downstream.
const booking = {
id: 'bulk-700',
reference: 'bulk-700',
freightType: 'BULK',
cargoTotalWeightVgm: 700,
bookingContainers: [],
} as unknown as Booking;
const plan = buildBulkWagonPlan([booking], cw3);
expect(plan).toHaveLength(12);
expect(sumWagonsRequired(booking, plan)).toBe(12);
// Without a plan the pre-plan fallback still applies.
expect(sumWagonsRequired(booking)).toBe(1);
});
it('counts container wagons from the plan TEU packing', () => {
const booking = makeContainerBooking('c-plan', [{ quantity: 6, wagonsRequired: 3 }]);
const plan = buildContainerWagonPlan([booking], nw5);
expect(sumWagonsRequired(booking, plan)).toBe(3);
});
it('6×20ft containers = 3 wagon slots (2 per wagon)', () => {
// 20ft containers have wagonsPerUnit = 0.5, so 6 * 0.5 = 3 wagons
const booking = makeContainerBooking('b6x20', [{ quantity: 6, wagonsRequired: 3 }]);

View File

@@ -436,7 +436,21 @@ export function expandContainerItems(
return items;
}
export function sumWagonsRequired(booking: Booking): number {
/**
* Wagons a booking actually occupies. Prefer counting the built wagon plan's
* slots that carry one of the booking's allocations — for BULK that is its
* tonnage spread over real wagons (a 700T booking on 70T wagons rides 10
* wagons, and downstream gross-weight math charges 10 tares, not 1). Without
* a plan there is no capacity to divide by, so fall back to the pre-plan
* estimates: 1 for bulk, the lines' stored counts for containers.
*/
export function sumWagonsRequired(booking: Booking, wagonPlan?: WagonPlanSlot[]): number {
const occupiedSlots = (wagonPlan ?? []).filter((slot) =>
slot.allocations.some((allocation) => allocation.bookingId === booking.id),
).length;
if (occupiedSlots > 0) {
return occupiedSlots;
}
if (booking.freightType === 'BULK') {
return 1;
}

View File

@@ -1,5 +1,5 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsNumber, IsOptional, IsString, Min } from 'class-validator';
import { IsBoolean, IsDateString, IsNumber, IsOptional, IsString, Min } from 'class-validator';
/** Records a DO / release order being sent to the customer for import pickup. */
export class ReleaseOrderDto {
@@ -90,4 +90,13 @@ export class ReleaseOrderDto {
@IsOptional()
@IsDateString()
gateOutTime?: string;
@ApiPropertyOptional({
description:
'Container bookings only: the operator chose not to weigh this truck. ' +
'Tare/gross become optional and the container weight match is skipped. Bulk always weighs.',
})
@IsOptional()
@IsBoolean()
weighingSkipped?: boolean;
}

View File

@@ -36,7 +36,9 @@ export const WAREHOUSE_INVENTORY_TRANSITIONS: Record<WarehouseInventoryStatus, W
RECEIVED: ['STORED', 'READY_FOR_PICKUP'],
// Reserve is retired from the operator flow — a stored export item advances
// straight to loading prep. RESERVED kept for any in-flight/legacy items.
STORED: ['RESERVED', 'READY_FOR_LOADING'],
// READY_FOR_PICKUP is the way back out for an IMPORT item that was parked in
// storage from READY_FOR_PICKUP; without it, Store is a one-way door.
STORED: ['RESERVED', 'READY_FOR_LOADING', 'READY_FOR_PICKUP'],
RESERVED: ['READY_FOR_LOADING'],
READY_FOR_LOADING: ['LOADED'],
LOADED: ['DISPATCHED'],

View File

@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { NotificationAudience, NotificationType } from '@edr/types';
import { DataSource, EntityManager, IsNull } from 'typeorm';
@@ -150,6 +151,37 @@ export class HandoverService {
);
}
/**
* Reminder loop: until a self-haul handover is signed, re-send the sign
* notification (in-app + SMS + email) every 5 minutes. One reminder per
* booking per tick, newest unsigned handover's reference. Stops the moment
* signForBooking() stamps signed_at.
*
* NB: runs in every API instance — keep a single instance in dev or the
* customer is reminded once per instance per tick.
*/
@Cron(CronExpression.EVERY_5_MINUTES, { name: 'handover-sign-reminder' })
async remindUnsignedHandovers(): Promise<void> {
try {
const rows: Array<{ bookingId: string; reference: string }> = await this.dataSource.query(
`SELECT DISTINCT ON (booking_id)
booking_id AS "bookingId", reference
FROM freight.booking_handovers
WHERE signed_at IS NULL
AND deleted_at IS NULL
AND mile_type = 'SELF_HAUL'
ORDER BY booking_id, generated_at DESC`,
);
if (!rows.length) return;
this.logger.log(`Handover sign reminder: ${rows.length} booking(s) still unsigned`);
for (const row of rows) {
await this.notifySignNeeded(row.bookingId, row.reference);
}
} catch (err) {
this.logger.warn(`Handover sign reminder tick failed: ${(err as Error).message}`);
}
}
/** Sign all unsigned handovers on a booking (self-haul: before the truck leaves). */
async signForBooking(bookingId: string, userId?: string | null): Promise<void> {
await this.dataSource

View File

@@ -207,6 +207,7 @@ export interface EligibleBookingRow {
customerTin: string | null;
customerPhone: string | null;
containerNumber: string | null;
sealNumbers: string | null;
containerQuantity: number | null;
containerPackagingType: string | null;
cargoDescription: string | null;
@@ -774,7 +775,8 @@ export class WarehouseInventoryService {
company.name AS "customer",
company.tin AS "customerTin",
COALESCE(company.contact_person_phone, company.phone, company.general_manager_phone, company.etrade_phone) AS "customerPhone",
bc.container_numbers AS "containerNumber",
COALESCE(bcu.unit_numbers, bc.container_numbers) AS "containerNumber",
bcu.seal_numbers AS "sealNumbers",
bc.container_quantity AS "containerQuantity",
bc.container_packaging_type AS "containerPackagingType",
(NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NOT NULL
@@ -831,6 +833,14 @@ export class WarehouseInventoryService {
LEFT JOIN freight.container_types container_type ON container_type.id = booking_container.container_type_id
WHERE booking_container.booking_id = b.id AND booking_container.deleted_at IS NULL
) bc ON true
LEFT JOIN LATERAL (
SELECT string_agg(NULLIF(unit.container_number, ''), ', ' ORDER BY unit.container_number) AS unit_numbers,
string_agg(DISTINCT NULLIF(unit.seal_number, ''), ', ') AS seal_numbers
FROM freight.booking_container_units unit
JOIN freight.booking_container line
ON line.id = unit.booking_container_id AND line.deleted_at IS NULL
WHERE line.booking_id = b.id AND unit.deleted_at IS NULL
) bcu ON true
LEFT JOIN LATERAL (
SELECT first_mile.id, first_mile.status, first_mile.vehicle_id
FROM freight.first_mile first_mile
@@ -881,11 +891,18 @@ export class WarehouseInventoryService {
}> = [];
await this.dataSource.transaction(async (manager) => {
await this.validateLocation(manager, {
const { warehouse, yard, zone } = await this.validateLocation(manager, {
warehouseId: dto.warehouseId,
yardId: dto.yardId,
zoneId: dto.zoneId,
});
// The receive location is whatever the operator selected above — never a
// hand-typed string. Stamp it on the truck entrance for the GRN/notes.
if (dto.truckEntrance && !dto.truckEntrance.warehouseCodeLocation) {
dto.truckEntrance.warehouseCodeLocation = [warehouse.code, yard.code, zone.code]
.filter(Boolean)
.join(' / ');
}
for (const bookingId of dto.bookingIds) {
const skip = (reason: string) => {
@@ -2357,6 +2374,27 @@ export class WarehouseInventoryService {
});
}
/**
* Self-haul = the customer's own truck collects the goods: either a truck
* assigned via the portal (customer_truck_assigned_at), or a walk-in truck
* registered at the gate on a booking with no EDR last-mile leg. EDR
* last-mile bookings are never self-haul.
*/
private async isSelfHaulBooking(bookingId: string, manager?: EntityManager): Promise<boolean> {
const runner = manager ?? this.dataSource;
const [row]: Array<{ ok: number }> = await runner.query(
`SELECT 1 AS ok
FROM freight.bookings b
LEFT JOIN freight.service_types st ON st.id = b.service_type_id
WHERE b.id = $1 AND b.deleted_at IS NULL
AND (b.customer_truck_assigned_at IS NOT NULL
OR (NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NULL
AND COALESCE(st.includes_last_mile, false) = false))`,
[bookingId],
);
return Boolean(row);
}
/** Record a DO / release order sent to the customer. Item stays READY_FOR_PICKUP. */
async release(id: string, dto: ReleaseOrderDto): Promise<WarehouseInventory> {
const item = await this.findById(id);
@@ -2366,19 +2404,17 @@ export class WarehouseInventoryService {
);
}
const isTruckLeaving = dto.grossWeight !== undefined && Boolean(dto.gateOutTime);
// Leaving = gate-out captured, with either a weighed gross or an explicit
// container weighing skip (bulk always weighs).
const isTruckLeaving =
Boolean(dto.gateOutTime) && (dto.grossWeight !== undefined || dto.weighingSkipped === true);
if (isTruckLeaving) {
await this.invoices.assertClearanceAllowed(id);
if (item.bookingId) {
const [truckInfo]: Array<{ customerTruckAssignedAt: string | null }> =
await this.dataSource.query(
`SELECT customer_truck_assigned_at AS "customerTruckAssignedAt"
FROM freight.bookings
WHERE id = $1 AND deleted_at IS NULL`,
[item.bookingId],
);
const usesCustomerTruck = Boolean(truckInfo?.customerTruckAssignedAt);
// Self-haul = customer collects: a truck assigned via the portal, OR a
// walk-in truck registered at the gate on a booking with no EDR last mile.
const usesCustomerTruck = await this.isSelfHaulBooking(item.bookingId);
// Self-haul: the handover must be signed before the exit paper is issued.
// Prefer the structured handover record; fall back to the legacy note.
const handoverSigned =
@@ -2392,7 +2428,8 @@ export class WarehouseInventoryService {
// Authoritative weight match: the truck's net (gross tare) must equal the
// total VGM cargo weight of the containers selected as loaded on it.
if (dto.containerNumber && dto.grossWeight != null && dto.tareWeight != null) {
// Skipped when the operator chose not to weigh (containers only).
if (!dto.weighingSkipped && dto.containerNumber && dto.grossWeight != null && dto.tareWeight != null) {
const selected = dto.containerNumber
.split(/[,;\n]+/)
.map((n) => n.trim())
@@ -2462,13 +2499,10 @@ export class WarehouseInventoryService {
[item.bookingId],
);
// Self-haul: generate the per-booking handover on first truck arrival
// (idempotent). It must be signed before the truck leaves.
const [selfHaul]: Array<{ ok: number }> = await manager.query(
`SELECT 1 AS ok FROM freight.bookings
WHERE id = $1 AND customer_truck_assigned_at IS NOT NULL AND deleted_at IS NULL`,
[item.bookingId],
);
if (selfHaul) {
// (idempotent) and notify the customer to sign it. Covers BOTH portal-
// assigned trucks and walk-in trucks registered manually at the gate
// (no portal assignment, no EDR last mile). Must be signed before leaving.
if (await this.isSelfHaulBooking(item.bookingId, manager)) {
await this.handover.ensureForArrivedTruck(item.bookingId, {}, manager);
}
}
@@ -4453,14 +4487,17 @@ export class WarehouseInventoryService {
if (!dto.driverName?.trim()) {
throw new BadRequestException('Driver name is required for exit inspection');
}
if (dto.tareWeight === undefined) {
// Container bookings may skip the weighbridge entirely (weighingSkipped);
// bulk always weighs.
const weighingSkipped = dto.weighingSkipped === true;
if (dto.tareWeight === undefined && !weighingSkipped) {
throw new BadRequestException('Tare weight is required for truck arrival');
}
const tareWeight = Number(dto.tareWeight);
const tareWeight = dto.tareWeight === undefined ? null : Number(dto.tareWeight);
const grossWeight = dto.grossWeight === undefined ? null : Number(dto.grossWeight);
const computedNetWeight =
grossWeight == null ? null : Number((grossWeight - tareWeight).toFixed(3));
grossWeight == null || tareWeight == null ? null : Number((grossWeight - tareWeight).toFixed(3));
const submittedNetWeight =
dto.netWeight === undefined || computedNetWeight == null ? computedNetWeight : Number(dto.netWeight);
@@ -4472,7 +4509,11 @@ export class WarehouseInventoryService {
throw new BadRequestException('Weight mismatch: net weight must equal gross weight minus tare weight.');
}
}
if ((dto.grossWeight !== undefined || dto.gateOutTime || dto.netWeight !== undefined) && grossWeight == null) {
if (
!weighingSkipped &&
(dto.grossWeight !== undefined || dto.gateOutTime || dto.netWeight !== undefined) &&
grossWeight == null
) {
throw new BadRequestException('Gross weight is required for truck exit');
}
@@ -4488,7 +4529,8 @@ export class WarehouseInventoryService {
dto.truckType?.trim() ? `Truck Type: ${dto.truckType.trim()}` : null,
dto.containerNumber?.trim() ? `Container Number: ${dto.containerNumber.trim()}` : null,
dto.gateInTime ? `Gate In Time: ${dto.gateInTime}` : null,
`Tare Weight: ${tareWeight} t`,
weighingSkipped ? 'Weighing: SKIPPED' : null,
tareWeight == null ? null : `Tare Weight: ${tareWeight} t`,
grossWeight == null ? null : `Gross Weight: ${grossWeight} t`,
computedNetWeight == null ? null : `Net Weight: ${computedNetWeight} t`,
dto.gateOutTime ? `Gate Out Time: ${dto.gateOutTime}` : null,
@@ -4512,6 +4554,8 @@ export class WarehouseInventoryService {
containerNumber: this.extractExitInspectionLine(inspection, 'Container Number') || dto.containerNumber,
gateInTime: this.extractExitInspectionLine(inspection, 'Gate In Time') || dto.gateInTime,
tareWeight: this.extractExitInspectionNumber(inspection, 'Tare Weight') ?? dto.tareWeight,
// The weigh/skip decision is made at arrival and sticks for the exit.
weighingSkipped: dto.weighingSkipped || /^Weighing:\s*SKIPPED/im.test(inspection) || undefined,
};
}