implement booking flow

This commit is contained in:
marshal
2026-06-04 15:16:27 +03:00
parent a5578ce714
commit 125ee18308
89 changed files with 6190 additions and 1724 deletions

View File

@@ -0,0 +1,57 @@
import { Injectable, Logger } from '@nestjs/common';
@Injectable()
export class ContractPdfService {
private readonly logger = new Logger(ContractPdfService.name);
async htmlToPdfBuffer(html: string): Promise<Buffer> {
try {
const puppeteer = await import('puppeteer');
const browser = await puppeteer.default.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'load' });
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
});
return Buffer.from(pdf);
} finally {
await browser.close();
}
} catch (err) {
this.logger.warn(
`Puppeteer PDF failed, falling back to minimal PDF stub: ${err}`,
);
return this.fallbackPdfBuffer(html);
}
}
/** Minimal valid PDF when Chromium is unavailable. */
private fallbackPdfBuffer(html: string): Buffer {
const text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').slice(0, 2000);
const escaped = text.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
const stream = `BT /F1 10 Tf 50 750 Td (${escaped}) Tj ET`;
const len = stream.length;
const pdf = `%PDF-1.4
1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj
2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj
3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>endobj
4 0 obj<< /Length ${len} >>stream
${stream}
endstream endobj
5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj
xref
0 6
0000000000 65535 f
trailer<< /Size 6 /Root 1 0 R >>
startxref
0
%%EOF`;
return Buffer.from(pdf, 'utf-8');
}
}

View File

@@ -0,0 +1,70 @@
import { Injectable } from '@nestjs/common';
import { BookingPricingService } from '../modules/bookings/booking-pricing.service';
import { Booking } from '../modules/bookings/entities/booking.entity';
import { PriceLineItemDto } from '../modules/bookings/dto/generate-price-response.dto';
export interface PricingScheduleRow {
label: string;
description: string;
amount: number;
currency: string;
}
export interface PricingSchedule {
lineItems: PricingScheduleRow[];
surcharges: PricingScheduleRow[];
totalAmount: number;
currency: string;
equipmentReturn?: string;
originLabel: string;
destinationLabel: string;
containerLines: Array<{
label: string;
quantity: number;
vgmPerUnitTons: number;
}>;
}
@Injectable()
export class ContractPricingScheduleBuilder {
constructor(private readonly pricingService: BookingPricingService) {}
async build(booking: Booking): Promise<PricingSchedule> {
const { lineItems, totalAmount, currency } =
await this.pricingService.computeContractLineItems(booking);
const isSurcharge = (l: PriceLineItemDto) =>
l.code.includes('SURCHARGE') || l.description.toLowerCase().includes('surcharge');
const baseLines = lineItems.filter((l) => !isSurcharge(l));
const surchargeLines = lineItems.filter(isSurcharge);
return {
lineItems: baseLines.map((l) => ({
label: l.code,
description: l.description,
amount: l.amount,
currency: l.currency,
})),
surcharges: surchargeLines.map((l) => ({
label: l.code,
description: l.description,
amount: l.amount,
currency: l.currency,
})),
totalAmount,
currency,
equipmentReturn: booking.equipmentReturn ?? undefined,
originLabel: booking.originYard?.label ?? booking.originYard?.code ?? '—',
destinationLabel:
booking.destinationYard?.label ?? booking.destinationYard?.code ?? '—',
containerLines: (booking.bookingContainers ?? []).map((c) => ({
label:
c.containerType?.label ?? c.containerType?.code ?? c.containerTypeId,
quantity: c.quantity,
vgmPerUnitTons: Number(c.vgmPerUnitTons),
})),
};
}
}

View File

@@ -0,0 +1,51 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import Handlebars from 'handlebars';
import { ContractViewModel } from './contract-view-model.builder';
@Injectable()
export class ContractRendererService implements OnModuleInit {
private readonly templatesDir = path.join(__dirname, 'templates');
private readonly compiled = new Map<string, Handlebars.TemplateDelegate>();
onModuleInit(): void {
Handlebars.registerHelper('eq', (a: unknown, b: unknown) => a === b);
const partialsDir = path.join(this.templatesDir, '_partials');
if (fs.existsSync(partialsDir)) {
for (const file of fs.readdirSync(partialsDir)) {
if (!file.endsWith('.hbs')) continue;
const name = file.replace(/\.hbs$/, '');
const content = fs.readFileSync(path.join(partialsDir, file), 'utf-8');
Handlebars.registerPartial(name, content);
}
}
}
render(view: ContractViewModel): string {
const fileName =
view.template.templateFile ?? 'generic.hbs';
const template = this.getCompiled(fileName);
return template({
...view,
paymentArticle: view.pricing.currency === 'ETB' ? 'ETB' : 'USD',
});
}
private getCompiled(fileName: string): Handlebars.TemplateDelegate {
const cached = this.compiled.get(fileName);
if (cached) return cached;
const filePath = path.join(this.templatesDir, fileName);
const fallbackPath = path.join(this.templatesDir, 'generic.hbs');
const source = fs.existsSync(filePath)
? fs.readFileSync(filePath, 'utf-8')
: fs.readFileSync(fallbackPath, 'utf-8');
const compiled = Handlebars.compile(source);
this.compiled.set(fileName, compiled);
return compiled;
}
}

View File

@@ -0,0 +1,98 @@
export interface ContractTemplateMeta {
key: string;
title: string;
directionLabel: string;
freightLabel: string;
currency: string;
serviceScope: 'TRANSPORT_ONLY' | 'FORWARDING';
/** Optional dedicated .hbs file; otherwise uses generic.hbs */
templateFile?: string;
whereas: string;
article1Objective: string;
}
const DIRECTION_LABELS: Record<string, string> = {
IMP: 'Import',
EXP: 'Export',
DOM: 'Domestic',
};
const FREIGHT_LABELS: Record<string, string> = {
CON: 'Container',
BULK: 'Bulk',
};
function buildMeta(
dir: string,
freight: string,
currency: string,
service: 'TRANSPORT_ONLY' | 'FORWARDING',
templateFile?: string,
): ContractTemplateMeta {
const key = `${dir}_${freight}_${currency}_${service}`;
const dirLabel = DIRECTION_LABELS[dir] ?? dir;
const freightLabel = FREIGHT_LABELS[freight] ?? freight;
const serviceLabel =
service === 'FORWARDING' ? 'Rail and Forwarding' : 'Transport Only';
const corridor =
dir === 'IMP'
? 'from SGTD railway freight station at Djibouti to Ethiopian dry ports and return of empty containers as applicable'
: dir === 'EXP'
? 'from Ethiopian dry ports to SGTD and related export corridors'
: 'between designated Ethiopian rail terminals';
return {
key,
title: `${dirLabel} ${freightLabel} Transport Service by Railway (${serviceLabel})`,
directionLabel: dirLabel,
freightLabel,
currency,
serviceScope: service,
templateFile,
whereas: `The Client has requested transportation of ${freightLabel.toLowerCase()} cargo ${corridor} using the Addis AbabaDjibouti Railway line. The Service Provider has agreed to provide services per this contract.`,
article1Objective: `To provide railway transportation services for ${freightLabel.toLowerCase()} cargo on the agreed corridor (${serviceLabel}).`,
};
}
const DIRECTIONS = ['IMP', 'EXP', 'DOM'] as const;
const FREIGHTS = ['CON', 'BULK'] as const;
const CURRENCIES = ['ETB', 'USD'] as const;
const SERVICES = ['TRANSPORT_ONLY', 'FORWARDING'] as const;
/** Full template matrix (24 keys). */
export const CONTRACT_TEMPLATE_REGISTRY: Record<string, ContractTemplateMeta> =
{};
for (const dir of DIRECTIONS) {
for (const freight of FREIGHTS) {
for (const currency of CURRENCIES) {
for (const service of SERVICES) {
const dedicated =
dir === 'IMP' &&
freight === 'CON' &&
currency === 'ETB' &&
service === 'TRANSPORT_ONLY'
? 'IMP_CON_ETB_TRANSPORT_ONLY.hbs'
: undefined;
const meta = buildMeta(dir, freight, currency, service, dedicated);
CONTRACT_TEMPLATE_REGISTRY[meta.key] = meta;
}
}
}
}
export function getTemplateMeta(key: string): ContractTemplateMeta {
return (
CONTRACT_TEMPLATE_REGISTRY[key] ?? {
key,
title: 'Freight Contract Agreement',
directionLabel: 'Freight',
freightLabel: 'Cargo',
currency: 'USD',
serviceScope: 'TRANSPORT_ONLY',
whereas: 'The parties agree to railway freight services as described in the schedule below.',
article1Objective: 'To provide railway transportation services per the agreed schedule.',
}
);
}

View File

@@ -0,0 +1,43 @@
import { Injectable } from '@nestjs/common';
import { Booking } from '../modules/bookings/entities/booking.entity';
import { ServiceType } from '../modules/rule-engine/entities/service-type.entity';
import { CargoType } from '../modules/rule-engine/entities/cargo-type.entity';
@Injectable()
export class ContractTemplateResolver {
resolve(booking: Booking): string {
const dir =
booking.tradeDirection === 'IMPORT'
? 'IMP'
: booking.tradeDirection === 'EXPORT'
? 'EXP'
: 'DOM';
let freight = booking.freightType === 'BULK' ? 'BULK' : 'CON';
const cargoCode = (booking.cargoType as CargoType | undefined)?.code ?? '';
if (cargoCode.startsWith('BREAK_BULK')) {
freight = 'BULK';
}
const currency = booking.paymentCurrency === 'ETB' ? 'ETB' : 'USD';
const service = this.resolveServiceScope(booking.serviceType);
return `${dir}_${freight}_${currency}_${service}`;
}
private resolveServiceScope(
serviceType?: ServiceType | null,
): 'TRANSPORT_ONLY' | 'FORWARDING' {
if (!serviceType) return 'TRANSPORT_ONLY';
const code = (serviceType.code ?? '').toUpperCase();
if (
serviceType.includesFirstMile ||
serviceType.includesLastMile ||
code.includes('FORWARD')
) {
return 'FORWARDING';
}
return 'TRANSPORT_ONLY';
}
}

View File

@@ -0,0 +1,118 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { BookingsRepository } from '../modules/bookings/bookings.repository';
import { Booking } from '../modules/bookings/entities/booking.entity';
import {
BookingContractSignature,
ContractSignerRole,
} from '../modules/bookings/entities/booking-contract-signature.entity';
import { ContractPricingScheduleBuilder, PricingSchedule } from './contract-pricing-schedule.builder';
import { ContractTemplateResolver } from './contract-template.resolver';
import { ContractTemplateMeta, getTemplateMeta } from './contract-template.registry';
export interface ContractSignatureView {
role: ContractSignerRole;
signerDisplayName: string;
signedAt: string;
signatureImageUrl?: string | null;
}
export interface ContractViewModel {
bookingId: string;
reference: string;
status: string;
templateKey: string;
template: ContractTemplateMeta;
contractDate: string;
contractYear: number;
client: {
companyName: string;
companyAddress: string;
companyLocation: string;
phone: string;
email: string;
tinNumber: string;
};
pricing: PricingSchedule;
signatures: ContractSignatureView[];
canSignCustomer: boolean;
canSignStaff: boolean;
hasContractDocument: boolean;
hasCustomerSignature: boolean;
hasStaffSignature: boolean;
}
@Injectable()
export class ContractViewModelBuilder {
constructor(
private readonly bookingsRepository: BookingsRepository,
private readonly templateResolver: ContractTemplateResolver,
private readonly pricingBuilder: ContractPricingScheduleBuilder,
) {}
async build(bookingId: string): Promise<{ booking: Booking; view: ContractViewModel }> {
const booking = await this.bookingsRepository.findByIdWithFiles(bookingId);
if (!booking) {
throw new NotFoundException(`Booking ${bookingId} not found`);
}
const templateKey =
booking.contractTemplateKey ?? this.templateResolver.resolve(booking);
const template = getTemplateMeta(templateKey);
const pricing = await this.pricingBuilder.build(booking);
const signatures = await this.loadSignatures(bookingId);
const hasCustomer = signatures.some((s) => s.role === 'CUSTOMER');
const hasStaff = signatures.some((s) => s.role === 'STAFF');
const hasContractFile = Boolean(
booking.files?.some((f) => f.code === 'contract'),
);
const view: ContractViewModel = {
bookingId: booking.id,
reference: booking.reference,
status: booking.status,
templateKey,
template,
contractDate: new Date().toLocaleDateString('en-GB', {
day: 'numeric',
month: 'long',
year: 'numeric',
}),
contractYear: new Date().getFullYear(),
client: {
companyName: booking.customer?.companyName ?? 'Client',
companyAddress: booking.customer?.companyAddress ?? '—',
companyLocation: booking.customer?.companyLocation ?? '—',
phone: booking.customer?.companyPhone ?? booking.customer?.phone ?? '—',
email: booking.customer?.companyEmail ?? booking.customer?.email ?? '—',
tinNumber: booking.customer?.tinNumber ?? '—',
},
pricing,
signatures,
canSignCustomer:
booking.status === 'CONTRACT_READY' && !hasCustomer,
canSignStaff:
booking.status === 'SIGNED_CUSTOMER' && hasCustomer && !hasStaff,
hasContractDocument: hasContractFile,
hasCustomerSignature: hasCustomer,
hasStaffSignature: hasStaff,
};
return { booking, view };
}
private async loadSignatures(bookingId: string): Promise<ContractSignatureView[]> {
const rows = await this.bookingsRepository.findContractSignatures(bookingId);
return rows.map((s) => this.toSignatureView(s));
}
toSignatureView(row: BookingContractSignature): ContractSignatureView {
return {
role: row.signerRole,
signerDisplayName: row.signerDisplayName,
signedAt: row.signedAt.toISOString(),
signatureImageUrl: row.signatureFile?.url ?? null,
};
}
}

View File

@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Import Container Transport — {{reference}}</title>
{{> styles}}
</head>
<body>
<div class="cover">
<h1>Contract Agreement</h1>
<h1>Import Container Transport Service by Railway</h1>
<p class="meta"><strong>Contract Ref No:</strong> {{reference}}</p>
<p class="meta"><strong>Year:</strong> {{contractYear}}</p>
</div>
<p>This Contract Agreement is made on <strong>{{contractDate}}</strong>.</p>
<p><strong>Between</strong> Ethio-Djibouti Standard Gauge Railway Share Company (EDR), Addis Ababa (“Service Provider”), and <strong>{{client.companyName}}</strong> at {{client.companyAddress}}, {{client.companyLocation}} (“Client”). Phone {{client.phone}} / {{client.email}}. TIN {{client.tinNumber}}.</p>
<h2>Whereas</h2>
<p>{{template.whereas}}</p>
<p>Now therefore, the parties agree as follows:</p>
<div class="article">
<h2>Article 1: Objective and Scope of Services</h2>
<p><strong>Objective:</strong> To provide railway transportation for 40ft and/or 20ft full containers from SGTD to Dire Dawa, Modjo dry port and/or Galaan Multipurpose port (GMP), and empty container return from those terminals to SGTD.</p>
<p><strong>Scope:</strong> (1) Railway transport service; (2) Cargo handling at Galaan Multipurpose port (GMP) where applicable.</p>
</div>
<div class="article">
<h2>Article 2: Obligations of the Client (summary)</h2>
<ol>
<li>Provide shipment instructions to EDR for container movements on the agreed corridor.</li>
<li>Meet minimum container supply per terminal (Modjo, Dire Dawa, GMP) as per EDR operational rules.</li>
<li>Submit required documents to Djibouti Nagad station at least 24 hours before loading.</li>
<li>Pay 100% transportation fees in advance per train set in {{paymentArticle}}.</li>
<li>Notify EDR 48 hours in advance for hazardous or valuable cargo.</li>
</ol>
</div>
<div class="article">
<h2>Article 3: Obligations of the Service Provider (summary)</h2>
<ol>
<li>Assign voyage per operational schedule and notify train schedule 48 hours in advance.</li>
<li>Provide safe transportation and deliver within agreed timelines when documents are complete.</li>
<li>Return empty containers from Dire Dawa, Modjo and GMP to SGTD within seven (7) calendar days of receipt.</li>
<li>Maintain cargo liability insurance per wagon.</li>
</ol>
</div>
{{> article5_pricing}}
<div class="article">
<h2>Article 4: Force Majeure</h2>
<p>Neither party is liable for delays due to force majeure interpreted under the Ethiopian Civil Code.</p>
</div>
<div class="article">
<h2>Article 6: Contract Documents</h2>
<ol>
<li>Amendments (if any)</li>
<li>This Contract Agreement</li>
<li>Final Minutes of Negotiation (if any)</li>
</ol>
</div>
{{> signatures_block}}
</body>
</html>

View File

@@ -0,0 +1,47 @@
<h2>Article 5: Contract Price and Terms of Payment</h2>
<div class="article">
<h3>Contract Price</h3>
<p><strong>Corridor:</strong> {{pricing.originLabel}}{{pricing.destinationLabel}}</p>
{{#if pricing.equipmentReturn}}
<p><strong>Equipment return:</strong> {{pricing.equipmentReturn}}</p>
{{/if}}
{{#if pricing.containerLines.length}}
<table class="schedule">
<thead>
<tr><th>Container type</th><th>Quantity</th><th>VGM / unit (t)</th></tr>
</thead>
<tbody>
{{#each pricing.containerLines}}
<tr><td>{{label}}</td><td>{{quantity}}</td><td>{{vgmPerUnitTons}}</td></tr>
{{/each}}
</tbody>
</table>
{{/if}}
<table class="schedule">
<thead>
<tr><th>Item</th><th>Description</th><th>Amount</th></tr>
</thead>
<tbody>
{{#each pricing.lineItems}}
<tr>
<td>{{label}}</td>
<td>{{description}}</td>
<td>{{currency}} {{amount}}</td>
</tr>
{{/each}}
{{#each pricing.surcharges}}
<tr>
<td>{{label}}</td>
<td>{{description}}</td>
<td>{{currency}} {{amount}}</td>
</tr>
{{/each}}
<tr>
<td colspan="2"><strong>Total contract value</strong></td>
<td><strong>{{pricing.currency}} {{pricing.totalAmount}}</strong></td>
</tr>
</tbody>
</table>
<h3>Terms of payment</h3>
<p>All payments shall be made in accordance with EDR policy in <strong>{{paymentArticle}}</strong>, unless otherwise agreed in writing.</p>
</div>

View File

@@ -0,0 +1,30 @@
<div class="signatures">
<div class="sig-block">
<p><strong>Service Provider (EDR)</strong></p>
{{#if hasStaffSignature}}
{{#each signatures}}
{{#if (eq role "STAFF")}}
{{#if signatureImageUrl}}<img src="{{signatureImageUrl}}" alt="Staff signature" />{{/if}}
<p>{{signerDisplayName}}</p>
<p class="sig-line">Signed: {{signedAt}}</p>
{{/if}}
{{/each}}
{{else}}
<p class="sig-line">Authorized representative (pending)</p>
{{/if}}
</div>
<div class="sig-block">
<p><strong>Client — {{client.companyName}}</strong></p>
{{#if hasCustomerSignature}}
{{#each signatures}}
{{#if (eq role "CUSTOMER")}}
{{#if signatureImageUrl}}<img src="{{signatureImageUrl}}" alt="Customer signature" />{{/if}}
<p>{{signerDisplayName}}</p>
<p class="sig-line">Signed: {{signedAt}}</p>
{{/if}}
{{/each}}
{{else}}
<p class="sig-line">Client representative (pending)</p>
{{/if}}
</div>
</div>

View File

@@ -0,0 +1,22 @@
<style>
* { box-sizing: border-box; }
body { font-family: 'Times New Roman', Times, serif; font-size: 11pt; line-height: 1.45; color: #111; margin: 0; padding: 24px; }
h1 { text-align: center; font-size: 14pt; text-transform: uppercase; margin: 0 0 8px; }
h2 { font-size: 12pt; margin: 20px 0 8px; text-transform: uppercase; }
h3 { font-size: 11pt; margin: 14px 0 6px; }
.cover { text-align: center; margin-bottom: 32px; border-bottom: 2px solid #1e3a5f; padding-bottom: 24px; }
.meta { margin: 12px 0; }
.meta strong { display: inline-block; min-width: 140px; }
.article { margin-bottom: 16px; }
.article ol { padding-left: 20px; }
.article li { margin-bottom: 6px; }
table.schedule { width: 100%; border-collapse: collapse; margin: 12px 0; font-size: 10pt; }
table.schedule th, table.schedule td { border: 1px solid #333; padding: 6px 8px; text-align: left; }
table.schedule th { background: #f0f4f8; }
.signatures { display: flex; gap: 40px; margin-top: 40px; page-break-inside: avoid; }
.sig-block { flex: 1; }
.sig-block img { max-height: 64px; max-width: 200px; display: block; margin: 8px 0; }
.sig-line { border-top: 1px solid #000; margin-top: 48px; padding-top: 4px; font-size: 10pt; }
.pending-banner { background: #fff8e6; border: 1px solid #e6c200; padding: 8px 12px; margin-bottom: 16px; font-size: 10pt; }
@media print { body { padding: 0; } }
</style>

View File

@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{{template.title}}{{reference}}</title>
{{> styles}}
</head>
<body>
<div class="cover">
<h1>Contract Agreement</h1>
<h1>{{template.title}}</h1>
<p class="meta"><strong>Contract Ref No:</strong> {{reference}}</p>
<p class="meta"><strong>Year:</strong> {{contractYear}}</p>
</div>
<p>This Contract Agreement is made on <strong>{{contractDate}}</strong>.</p>
<p><strong>Between</strong> Ethio-Djibouti Standard Gauge Railway Share Company (EDR) (“Service Provider”) and <strong>{{client.companyName}}</strong> (“Client”) at {{client.companyAddress}}, {{client.companyLocation}}. Phone: {{client.phone}}. Email: {{client.email}}. TIN: {{client.tinNumber}}.</p>
<h2>Whereas</h2>
<p>{{template.whereas}}</p>
<p>Now therefore, the parties agree as follows:</p>
<div class="article">
<h2>Article 1: Objective and Scope</h2>
<p>{{template.article1Objective}}</p>
</div>
{{> article5_pricing}}
<div class="article">
<h2>Article 4: Force Majeure</h2>
<p>Neither party shall be liable for delays caused by force majeure beyond reasonable control, interpreted per the Ethiopian Civil Code.</p>
</div>
<div class="article">
<h2>Article 6: Contract Documents</h2>
<p>This agreement, amendments (if any), and negotiated minutes constitute the contract.</p>
</div>
{{> signatures_block}}
</body>
</html>