From 125ee18308506561b1c12291386cc575a03a2f24 Mon Sep 17 00:00:00 2001 From: marshal Date: Thu, 4 Jun 2026 15:16:27 +0300 Subject: [PATCH] implement booking flow --- apps/edr-freight-api/nest-cli.json | 5 +- apps/edr-freight-api/package.json | 2 + .../src/common/resolve-auth-user-id.ts | 12 + .../src/contracts/contract-pdf.service.ts | 57 + .../contract-pricing-schedule.builder.ts | 70 ++ .../contracts/contract-renderer.service.ts | 51 + .../contracts/contract-template.registry.ts | 98 ++ .../contracts/contract-template.resolver.ts | 43 + .../contracts/contract-view-model.builder.ts | 118 +++ .../templates/IMP_CON_ETB_TRANSPORT_ONLY.hbs | 68 ++ .../templates/_partials/article5_pricing.hbs | 47 + .../templates/_partials/signatures_block.hbs | 30 + .../contracts/templates/_partials/styles.hbs | 22 + .../src/contracts/templates/generic.hbs | 42 + .../1749300000000-AddBookingFreightType.ts | 71 ++ .../1749400000000-AddContractSignatures.ts | 45 + .../bookings/booking-contract.service.ts | 210 +++- .../modules/bookings/booking-freight.util.ts | 43 + .../bookings/booking-pricing.service.ts | 99 +- .../bookings/booking-transition.service.ts | 25 +- .../modules/bookings/bookings.controller.ts | 120 ++- .../src/modules/bookings/bookings.module.ts | 12 + .../modules/bookings/bookings.repository.ts | 41 +- .../src/modules/bookings/bookings.service.ts | 147 ++- .../modules/bookings/dto/contract-view.dto.ts | 50 + .../bookings/dto/create-booking.dto.ts | 31 +- .../bookings/dto/filter-booking.dto.ts | 12 +- .../bookings/dto/request-changes.dto.ts | 36 +- .../modules/bookings/dto/sign-contract.dto.ts | 23 + .../bookings/dto/update-booking.dto.ts | 11 +- .../validators/booking-freight.validator.ts | 60 ++ .../booking-contract-signature.entity.ts | 44 + .../bookings/entities/booking.entity.ts | 19 +- .../src/modules/files/files.repository.ts | 8 + .../src/modules/files/files.service.ts | 7 + .../controllers/rates.controller.ts | 26 +- .../rule-engine/dto/create-rate.dto.ts | 10 - .../rule-engine/rule-engine.service.ts | 42 +- .../rule-engine/services/rates.service.ts | 11 +- .../services/surcharge-types.service.ts | 1 + apps/edr-freight-web/backoffice/src/App.tsx | 32 +- .../components/bookings/ApprovalStepsCard.tsx | 116 +++ .../bookings/BookingActionsMenu.tsx | 233 +++++ .../bookings/BookingActionsToolbar.tsx | 168 +++ .../bookings/BookingConfirmDialog.tsx | 134 +++ .../bookings/BookingPricingSummary.tsx | 86 ++ .../bookings/BookingPriorityBadge.tsx | 21 + .../components/bookings/BookingStatGrid.tsx | 56 + .../bookings/BookingStatusBadge.tsx | 21 + .../components/bookings/BookingStatusTabs.tsx | 91 ++ .../components/bookings/BookingTableEmpty.tsx | 44 + .../bookings/BookingWorkflowStepper.tsx | 124 +++ .../bookings/ContractSignaturePad.tsx | 107 ++ .../components/bookings/booking-ui.styles.ts | 32 + .../bookings/useBookingActionDialog.ts | 132 +++ .../ruleEngine/ruleEngineFormat.tsx | 40 + .../backoffice/src/constants/QUERY_KEYS.ts | 50 + .../src/constants/TANSTACK_QUEY_KEY.ts | 25 - .../backoffice/src/constants/URLS.ts | 30 +- .../bookings/booking-actions.config.ts | 268 +++++ .../bookings/booking-status.config.ts | 260 +++++ .../features/bookings/mapBookingListRow.ts | 34 + .../src/hooks/bookings/useBookings.ts | 178 ++++ .../src/hooks/rule-engine/useRuleEngine.ts | 152 +-- .../backoffice/src/hooks/useBookings.ts | 53 +- .../backoffice/src/lib/queryClient.ts | 12 + apps/edr-freight-web/backoffice/src/main.tsx | 5 +- .../pages/bookings/BookingContractPage.tsx | 218 ++++ .../bookings/BookingRequestDetailPage.tsx | 985 +++++++----------- .../pages/bookings/BookingRequestsPage.tsx | 624 +++++------ .../pages/bookings/booking-requests.mock.ts | 182 +--- .../src/pages/bookings/bookings.mock.ts | 9 + .../ruleEngine/RuleEngineResourcePage.tsx | 131 +-- .../src/pages/ruleEngine/config/resources.ts | 46 +- .../backoffice/src/services/api.ts | 135 ++- .../src/services/bookings.service.ts | 179 +++- .../services/ruleEngine/ruleEngine.service.ts | 8 +- .../backoffice/src/types/booking.ts | 126 +++ .../backoffice/src/types/rule-engine/index.ts | 4 - .../backoffice/src/utils/endpoint.ts | 12 +- .../backoffice/src/utils/queryInvalidation.ts | 56 + apps/edr-freight-web/portal/src/App.tsx | 2 + .../bookings/ContractSignaturePad.tsx | 105 ++ .../portal/src/constants/URLS.ts | 4 + .../pages/bookings/BookingContractPage.tsx | 165 +++ .../src/pages/bookings/BookingDetailPage.tsx | 21 + .../portal/src/services/bookings.service.ts | 48 + packages/types/src/freight/index.ts | 12 +- pnpm-lock.yaml | 469 +++++++++ 89 files changed, 6190 insertions(+), 1724 deletions(-) create mode 100644 apps/edr-freight-api/src/common/resolve-auth-user-id.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-pdf.service.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-pricing-schedule.builder.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-renderer.service.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-template.registry.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-template.resolver.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-view-model.builder.ts create mode 100644 apps/edr-freight-api/src/contracts/templates/IMP_CON_ETB_TRANSPORT_ONLY.hbs create mode 100644 apps/edr-freight-api/src/contracts/templates/_partials/article5_pricing.hbs create mode 100644 apps/edr-freight-api/src/contracts/templates/_partials/signatures_block.hbs create mode 100644 apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs create mode 100644 apps/edr-freight-api/src/contracts/templates/generic.hbs create mode 100644 apps/edr-freight-api/src/migrations/1749300000000-AddBookingFreightType.ts create mode 100644 apps/edr-freight-api/src/migrations/1749400000000-AddContractSignatures.ts create mode 100644 apps/edr-freight-api/src/modules/bookings/booking-freight.util.ts create mode 100644 apps/edr-freight-api/src/modules/bookings/dto/contract-view.dto.ts create mode 100644 apps/edr-freight-api/src/modules/bookings/dto/sign-contract.dto.ts create mode 100644 apps/edr-freight-api/src/modules/bookings/dto/validators/booking-freight.validator.ts create mode 100644 apps/edr-freight-api/src/modules/bookings/entities/booking-contract-signature.entity.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/ApprovalStepsCard.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsMenu.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsToolbar.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingConfirmDialog.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingPricingSummary.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingPriorityBadge.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingStatGrid.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingStatusBadge.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingStatusTabs.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingTableEmpty.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/BookingWorkflowStepper.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/ContractSignaturePad.tsx create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/booking-ui.styles.ts create mode 100644 apps/edr-freight-web/backoffice/src/components/bookings/useBookingActionDialog.ts create mode 100644 apps/edr-freight-web/backoffice/src/constants/QUERY_KEYS.ts delete mode 100644 apps/edr-freight-web/backoffice/src/constants/TANSTACK_QUEY_KEY.ts create mode 100644 apps/edr-freight-web/backoffice/src/features/bookings/booking-actions.config.ts create mode 100644 apps/edr-freight-web/backoffice/src/features/bookings/booking-status.config.ts create mode 100644 apps/edr-freight-web/backoffice/src/features/bookings/mapBookingListRow.ts create mode 100644 apps/edr-freight-web/backoffice/src/hooks/bookings/useBookings.ts create mode 100644 apps/edr-freight-web/backoffice/src/lib/queryClient.ts create mode 100644 apps/edr-freight-web/backoffice/src/pages/bookings/BookingContractPage.tsx create mode 100644 apps/edr-freight-web/backoffice/src/pages/bookings/bookings.mock.ts create mode 100644 apps/edr-freight-web/backoffice/src/types/booking.ts create mode 100644 apps/edr-freight-web/backoffice/src/utils/queryInvalidation.ts create mode 100644 apps/edr-freight-web/portal/src/components/bookings/ContractSignaturePad.tsx create mode 100644 apps/edr-freight-web/portal/src/pages/bookings/BookingContractPage.tsx diff --git a/apps/edr-freight-api/nest-cli.json b/apps/edr-freight-api/nest-cli.json index 6c524a8a1..f4a3b488d 100644 --- a/apps/edr-freight-api/nest-cli.json +++ b/apps/edr-freight-api/nest-cli.json @@ -4,7 +4,10 @@ "sourceRoot": "src", "compilerOptions": { "deleteOutDir": true, - "assets": [{ "include": "migrations/**/*", "outDir": "dist" }], + "assets": [ + { "include": "migrations/**/*", "outDir": "dist" }, + { "include": "contracts/templates/**/*", "watchAssets": true } + ], "watchAssets": true } } diff --git a/apps/edr-freight-api/package.json b/apps/edr-freight-api/package.json index 5114e20da..7e85ffe21 100644 --- a/apps/edr-freight-api/package.json +++ b/apps/edr-freight-api/package.json @@ -31,7 +31,9 @@ "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "dotenv": "^17.4.2", + "handlebars": "^4.7.9", "minio": "7.1.3", + "puppeteer": "^24.2.0", "pg": "^8.13.0", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", diff --git a/apps/edr-freight-api/src/common/resolve-auth-user-id.ts b/apps/edr-freight-api/src/common/resolve-auth-user-id.ts new file mode 100644 index 000000000..cab29b671 --- /dev/null +++ b/apps/edr-freight-api/src/common/resolve-auth-user-id.ts @@ -0,0 +1,12 @@ +import { UnauthorizedException } from '@nestjs/common'; + +export type AuthUserPayload = { id?: string; sub?: string } | null | undefined; + +/** Resolve IAM user id from JWT payload attached by JwtGuard. */ +export function resolveAuthUserId(user: AuthUserPayload): string { + const id = user?.id ?? user?.sub; + if (!id) { + throw new UnauthorizedException('Authentication required'); + } + return id; +} diff --git a/apps/edr-freight-api/src/contracts/contract-pdf.service.ts b/apps/edr-freight-api/src/contracts/contract-pdf.service.ts new file mode 100644 index 000000000..399559fb2 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-pdf.service.ts @@ -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 { + 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'); + } +} diff --git a/apps/edr-freight-api/src/contracts/contract-pricing-schedule.builder.ts b/apps/edr-freight-api/src/contracts/contract-pricing-schedule.builder.ts new file mode 100644 index 000000000..f9dc0b7aa --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-pricing-schedule.builder.ts @@ -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 { + 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), + })), + }; + } +} diff --git a/apps/edr-freight-api/src/contracts/contract-renderer.service.ts b/apps/edr-freight-api/src/contracts/contract-renderer.service.ts new file mode 100644 index 000000000..dd539df25 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-renderer.service.ts @@ -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(); + + 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; + } +} diff --git a/apps/edr-freight-api/src/contracts/contract-template.registry.ts b/apps/edr-freight-api/src/contracts/contract-template.registry.ts new file mode 100644 index 000000000..aacf6a0a3 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-template.registry.ts @@ -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 = { + IMP: 'Import', + EXP: 'Export', + DOM: 'Domestic', +}; + +const FREIGHT_LABELS: Record = { + 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 Ababa–Djibouti 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 = + {}; + +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.', + } + ); +} diff --git a/apps/edr-freight-api/src/contracts/contract-template.resolver.ts b/apps/edr-freight-api/src/contracts/contract-template.resolver.ts new file mode 100644 index 000000000..daa48a4e7 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-template.resolver.ts @@ -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'; + } +} diff --git a/apps/edr-freight-api/src/contracts/contract-view-model.builder.ts b/apps/edr-freight-api/src/contracts/contract-view-model.builder.ts new file mode 100644 index 000000000..36c0328c8 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-view-model.builder.ts @@ -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 { + 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, + }; + } +} diff --git a/apps/edr-freight-api/src/contracts/templates/IMP_CON_ETB_TRANSPORT_ONLY.hbs b/apps/edr-freight-api/src/contracts/templates/IMP_CON_ETB_TRANSPORT_ONLY.hbs new file mode 100644 index 000000000..90b6dba93 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/IMP_CON_ETB_TRANSPORT_ONLY.hbs @@ -0,0 +1,68 @@ + + + + + Import Container Transport — {{reference}} + {{> styles}} + + +
+

Contract Agreement

+

Import Container Transport Service by Railway

+

Contract Ref No: {{reference}}

+

Year: {{contractYear}}

+
+ +

This Contract Agreement is made on {{contractDate}}.

+

Between Ethio-Djibouti Standard Gauge Railway Share Company (EDR), Addis Ababa (“Service Provider”), and {{client.companyName}} at {{client.companyAddress}}, {{client.companyLocation}} (“Client”). Phone {{client.phone}} / {{client.email}}. TIN {{client.tinNumber}}.

+ +

Whereas

+

{{template.whereas}}

+

Now therefore, the parties agree as follows:

+ +
+

Article 1: Objective and Scope of Services

+

Objective: 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.

+

Scope: (1) Railway transport service; (2) Cargo handling at Galaan Multipurpose port (GMP) where applicable.

+
+ +
+

Article 2: Obligations of the Client (summary)

+
    +
  1. Provide shipment instructions to EDR for container movements on the agreed corridor.
  2. +
  3. Meet minimum container supply per terminal (Modjo, Dire Dawa, GMP) as per EDR operational rules.
  4. +
  5. Submit required documents to Djibouti Nagad station at least 24 hours before loading.
  6. +
  7. Pay 100% transportation fees in advance per train set in {{paymentArticle}}.
  8. +
  9. Notify EDR 48 hours in advance for hazardous or valuable cargo.
  10. +
+
+ +
+

Article 3: Obligations of the Service Provider (summary)

+
    +
  1. Assign voyage per operational schedule and notify train schedule 48 hours in advance.
  2. +
  3. Provide safe transportation and deliver within agreed timelines when documents are complete.
  4. +
  5. Return empty containers from Dire Dawa, Modjo and GMP to SGTD within seven (7) calendar days of receipt.
  6. +
  7. Maintain cargo liability insurance per wagon.
  8. +
+
+ + {{> article5_pricing}} + +
+

Article 4: Force Majeure

+

Neither party is liable for delays due to force majeure interpreted under the Ethiopian Civil Code.

+
+ +
+

Article 6: Contract Documents

+
    +
  1. Amendments (if any)
  2. +
  3. This Contract Agreement
  4. +
  5. Final Minutes of Negotiation (if any)
  6. +
+
+ + {{> signatures_block}} + + diff --git a/apps/edr-freight-api/src/contracts/templates/_partials/article5_pricing.hbs b/apps/edr-freight-api/src/contracts/templates/_partials/article5_pricing.hbs new file mode 100644 index 000000000..d56c8b8a6 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/_partials/article5_pricing.hbs @@ -0,0 +1,47 @@ +

Article 5: Contract Price and Terms of Payment

+
+

Contract Price

+

Corridor: {{pricing.originLabel}} → {{pricing.destinationLabel}}

+ {{#if pricing.equipmentReturn}} +

Equipment return: {{pricing.equipmentReturn}}

+ {{/if}} + {{#if pricing.containerLines.length}} + + + + + + {{#each pricing.containerLines}} + + {{/each}} + +
Container typeQuantityVGM / unit (t)
{{label}}{{quantity}}{{vgmPerUnitTons}}
+ {{/if}} + + + + + + {{#each pricing.lineItems}} + + + + + + {{/each}} + {{#each pricing.surcharges}} + + + + + + {{/each}} + + + + + +
ItemDescriptionAmount
{{label}}{{description}}{{currency}} {{amount}}
{{label}}{{description}}{{currency}} {{amount}}
Total contract value{{pricing.currency}} {{pricing.totalAmount}}
+

Terms of payment

+

All payments shall be made in accordance with EDR policy in {{paymentArticle}}, unless otherwise agreed in writing.

+
diff --git a/apps/edr-freight-api/src/contracts/templates/_partials/signatures_block.hbs b/apps/edr-freight-api/src/contracts/templates/_partials/signatures_block.hbs new file mode 100644 index 000000000..ed5b7048d --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/_partials/signatures_block.hbs @@ -0,0 +1,30 @@ +
+
+

Service Provider (EDR)

+ {{#if hasStaffSignature}} + {{#each signatures}} + {{#if (eq role "STAFF")}} + {{#if signatureImageUrl}}Staff signature{{/if}} +

{{signerDisplayName}}

+

Signed: {{signedAt}}

+ {{/if}} + {{/each}} + {{else}} +

Authorized representative (pending)

+ {{/if}} +
+
+

Client — {{client.companyName}}

+ {{#if hasCustomerSignature}} + {{#each signatures}} + {{#if (eq role "CUSTOMER")}} + {{#if signatureImageUrl}}Customer signature{{/if}} +

{{signerDisplayName}}

+

Signed: {{signedAt}}

+ {{/if}} + {{/each}} + {{else}} +

Client representative (pending)

+ {{/if}} +
+
diff --git a/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs b/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs new file mode 100644 index 000000000..601768185 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs @@ -0,0 +1,22 @@ + diff --git a/apps/edr-freight-api/src/contracts/templates/generic.hbs b/apps/edr-freight-api/src/contracts/templates/generic.hbs new file mode 100644 index 000000000..23a35cb88 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/generic.hbs @@ -0,0 +1,42 @@ + + + + + {{template.title}} — {{reference}} + {{> styles}} + + +
+

Contract Agreement

+

{{template.title}}

+

Contract Ref No: {{reference}}

+

Year: {{contractYear}}

+
+ +

This Contract Agreement is made on {{contractDate}}.

+

Between Ethio-Djibouti Standard Gauge Railway Share Company (EDR) (“Service Provider”) and {{client.companyName}} (“Client”) at {{client.companyAddress}}, {{client.companyLocation}}. Phone: {{client.phone}}. Email: {{client.email}}. TIN: {{client.tinNumber}}.

+ +

Whereas

+

{{template.whereas}}

+

Now therefore, the parties agree as follows:

+ +
+

Article 1: Objective and Scope

+

{{template.article1Objective}}

+
+ + {{> article5_pricing}} + +
+

Article 4: Force Majeure

+

Neither party shall be liable for delays caused by force majeure beyond reasonable control, interpreted per the Ethiopian Civil Code.

+
+ +
+

Article 6: Contract Documents

+

This agreement, amendments (if any), and negotiated minutes constitute the contract.

+
+ + {{> signatures_block}} + + diff --git a/apps/edr-freight-api/src/migrations/1749300000000-AddBookingFreightType.ts b/apps/edr-freight-api/src/migrations/1749300000000-AddBookingFreightType.ts new file mode 100644 index 000000000..795d93fc3 --- /dev/null +++ b/apps/edr-freight-api/src/migrations/1749300000000-AddBookingFreightType.ts @@ -0,0 +1,71 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddBookingFreightType1749300000000 implements MigrationInterface { + name = 'AddBookingFreightType1749300000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE freight.bookings + ADD COLUMN IF NOT EXISTS freight_type VARCHAR(20); + `); + + await queryRunner.query(` + UPDATE freight.bookings b + SET freight_type = 'CONTAINER' + WHERE EXISTS ( + SELECT 1 FROM freight.booking_container bc WHERE bc.booking_id = b.id + ); + `); + + await queryRunner.query(` + UPDATE freight.bookings b + SET freight_type = 'BULK' + WHERE freight_type IS NULL + AND b.cargo_type_id IS NOT NULL + AND EXISTS ( + SELECT 1 FROM freight.cargo_types ct + WHERE ct.id = b.cargo_type_id AND ct.requires_director_approval = true + ); + `); + + await queryRunner.query(` + UPDATE freight.bookings + SET freight_type = 'CONTAINER' + WHERE freight_type IS NULL; + `); + + await queryRunner.query(` + ALTER TABLE freight.bookings + ALTER COLUMN cargo_type_id DROP NOT NULL; + `); + + await queryRunner.query(` + ALTER TABLE freight.bookings + ALTER COLUMN freight_type SET NOT NULL; + `); + + await queryRunner.query(` + ALTER TABLE freight.bookings + ADD CONSTRAINT chk_bookings_freight_type + CHECK (freight_type IN ('CONTAINER', 'BULK')); + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE freight.bookings DROP CONSTRAINT IF EXISTS chk_bookings_freight_type; + `); + await queryRunner.query(` + ALTER TABLE freight.bookings DROP COLUMN IF EXISTS freight_type; + `); + await queryRunner.query(` + UPDATE freight.bookings SET cargo_type_id = ( + SELECT id FROM freight.cargo_types LIMIT 1 + ) WHERE cargo_type_id IS NULL; + `); + await queryRunner.query(` + ALTER TABLE freight.bookings + ALTER COLUMN cargo_type_id SET NOT NULL; + `); + } +} diff --git a/apps/edr-freight-api/src/migrations/1749400000000-AddContractSignatures.ts b/apps/edr-freight-api/src/migrations/1749400000000-AddContractSignatures.ts new file mode 100644 index 000000000..8126b91ca --- /dev/null +++ b/apps/edr-freight-api/src/migrations/1749400000000-AddContractSignatures.ts @@ -0,0 +1,45 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddContractSignatures1749400000000 implements MigrationInterface { + name = 'AddContractSignatures1749400000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE freight.bookings + ADD COLUMN IF NOT EXISTS contract_template_key VARCHAR(80), + ADD COLUMN IF NOT EXISTS contract_generated_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS pricing_breakdown JSONB; + `); + + await queryRunner.query(` + CREATE TABLE IF NOT EXISTS freight.booking_contract_signatures ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + booking_id UUID NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE, + signer_role VARCHAR(20) NOT NULL, + signer_user_id UUID, + signer_display_name VARCHAR(200) NOT NULL, + signed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + signature_file_id UUID REFERENCES freight.files(id) ON DELETE SET NULL, + consent_text TEXT, + ip_address VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ, + CONSTRAINT uq_booking_contract_signatures_role + UNIQUE (booking_id, signer_role) + ); + CREATE INDEX IF NOT EXISTS idx_booking_contract_signatures_booking_id + ON freight.booking_contract_signatures(booking_id); + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_contract_signatures;`); + await queryRunner.query(` + ALTER TABLE freight.bookings + DROP COLUMN IF EXISTS pricing_breakdown, + DROP COLUMN IF EXISTS contract_generated_at, + DROP COLUMN IF EXISTS contract_template_key; + `); + } +} diff --git a/apps/edr-freight-api/src/modules/bookings/booking-contract.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-contract.service.ts index 65c317eaf..4eadff0fc 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-contract.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-contract.service.ts @@ -1,16 +1,34 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; import { Readable } from 'stream'; +import { ContractPdfService } from '../../contracts/contract-pdf.service'; +import { ContractRendererService } from '../../contracts/contract-renderer.service'; +import { getTemplateMeta } from '../../contracts/contract-template.registry'; +import { ContractTemplateResolver } from '../../contracts/contract-template.resolver'; +import { ContractViewModelBuilder } from '../../contracts/contract-view-model.builder'; +import { MinioService } from '../minio/minio.service'; import { FilesService } from '../files/files.service'; import { BookingsRepository } from './bookings.repository'; import { Booking } from './entities/booking.entity'; import { assertBookingStatus } from './booking-status.util'; +import { ContractViewDto } from './dto/contract-view.dto'; +import { SignContractDto } from './dto/sign-contract.dto'; +import { ContractSignerRole } from './entities/booking-contract-signature.entity'; @Injectable() export class BookingContractService { constructor( private readonly bookingsRepository: BookingsRepository, private readonly filesService: FilesService, + private readonly minioService: MinioService, + private readonly templateResolver: ContractTemplateResolver, + private readonly viewModelBuilder: ContractViewModelBuilder, + private readonly renderer: ContractRendererService, + private readonly pdfService: ContractPdfService, ) {} buildContractSummary(booking: Booking): string { @@ -22,7 +40,7 @@ export class BookingContractService { : booking.tradeDirection; const cargo = booking.cargoType; - const isBulk = cargo?.requiresDirectorApproval; + const isBulk = booking.freightType === 'BULK'; let cargoLabel: string; if (isBulk) { @@ -36,7 +54,7 @@ export class BookingContractService { cargoLabel = lines.length > 0 ? `Container (${lines.join(', ')})` - : `Container (${cargo?.cargoTypeName ?? 'Standard'})`; + : 'Container (Standard)'; } return `Operation: ${direction} | Cargo Type: ${cargoLabel}`; @@ -48,25 +66,117 @@ export class BookingContractService { return { summary }; } + async getContractView(bookingId: string): Promise { + const { view } = await this.viewModelBuilder.build(bookingId); + await this.enrichSignatureUrls(view.signatures); + const html = this.renderer.render(view); + return { + bookingId: view.bookingId, + reference: view.reference, + status: view.status, + templateKey: view.templateKey, + title: view.template.title, + html, + canSignCustomer: view.canSignCustomer, + canSignStaff: view.canSignStaff, + hasContractDocument: view.hasContractDocument, + signatures: view.signatures, + pricingSchedule: view.pricing as unknown as Record, + }; + } + async generateContract(bookingId: string): Promise { const booking = await this.requireBooking(bookingId); assertBookingStatus(booking, ['APPROVED']); - const summary = this.buildContractSummary(booking); - const body = [ - 'FREIGHT CONTRACT (STUB)', - `Reference: ${booking.reference}`, - summary, - `Total: ${booking.totalAmount} ${booking.paymentCurrency}`, - `Trade: ${booking.tradeDirection}`, - ].join('\n'); + const templateKey = this.templateResolver.resolve(booking); + const { view } = await this.viewModelBuilder.build(bookingId); + view.templateKey = templateKey; + view.template = getTemplateMeta(templateKey); + + const html = this.renderer.render(view); + const pdfBuffer = await this.pdfService.htmlToPdfBuffer(html); + const summary = this.buildContractSummary(booking); - const buffer = Buffer.from(body, 'utf-8'); const file: Express.Multer.File = { fieldname: 'contract', - originalname: `contract-${booking.reference}.txt`, + originalname: `contract-${booking.reference}.pdf`, encoding: '7bit', - mimetype: 'text/plain', + mimetype: 'application/pdf', + size: pdfBuffer.length, + buffer: pdfBuffer, + stream: Readable.from(pdfBuffer), + destination: '', + filename: '', + path: '', + }; + + await this.filesService.upsertByCode({ + resourceId: bookingId, + resource: 'bookings', + code: 'contract', + file, + }); + + const now = new Date(); + const updated = await this.bookingsRepository.update(bookingId, { + status: 'CONTRACT_READY', + contractSummary: summary, + contractTemplateKey: templateKey, + contractGeneratedAt: now, + } as never); + return updated!; + } + + async streamContract(bookingId: string) { + try { + const record = await this.filesService.findByCode( + bookingId, + 'bookings', + 'contract', + ); + return this.filesService.streamById(record.id); + } catch { + throw new NotFoundException( + 'Contract document not found. Generate the contract first.', + ); + } + } + + async signContract( + bookingId: string, + dto: SignContractDto, + options: { signerUserId?: string; ipAddress?: string }, + ): Promise { + const booking = await this.requireBooking(bookingId); + const role = dto.role as ContractSignerRole; + + if (role === 'CUSTOMER') { + assertBookingStatus(booking, ['CONTRACT_READY']); + const existing = await this.bookingsRepository.findContractSignature( + bookingId, + 'CUSTOMER', + ); + if (existing) { + throw new BadRequestException('Customer has already signed this contract'); + } + } else { + assertBookingStatus(booking, ['SIGNED_CUSTOMER']); + const existing = await this.bookingsRepository.findContractSignature( + bookingId, + 'STAFF', + ); + if (existing) { + throw new BadRequestException('Staff has already signed this contract'); + } + } + + const buffer = this.decodeSignatureImage(dto.signatureImageBase64); + const sigFile: Express.Multer.File = { + fieldname: `signature_${role.toLowerCase()}`, + originalname: `signature-${role.toLowerCase()}-${booking.reference}.png`, + encoding: '7bit', + mimetype: 'image/png', size: buffer.length, buffer, stream: Readable.from(buffer), @@ -75,27 +185,71 @@ export class BookingContractService { path: '', }; - await this.filesService.upload({ + const fileRecord = await this.filesService.upsertByCode({ resourceId: bookingId, resource: 'bookings', - code: 'contract', - file, + code: role === 'CUSTOMER' ? 'signature_customer' : 'signature_staff', + file: sigFile, }); - const updated = await this.bookingsRepository.update(bookingId, { - status: 'CONTRACT_READY', - contractSummary: summary, - } as never); + const now = new Date(); + await this.bookingsRepository.saveContractSignature({ + bookingId, + signerRole: role, + signerUserId: options.signerUserId ?? null, + signerDisplayName: dto.signerDisplayName, + signedAt: now, + signatureFileId: fileRecord.id, + consentText: dto.consentText ?? null, + ipAddress: options.ipAddress ?? null, + }); + + const updates: Record = {}; + + if (role === 'CUSTOMER') { + updates.status = 'SIGNED_CUSTOMER'; + updates.customerSignedAt = now; + } else { + updates.status = 'FULLY_EXECUTED'; + updates.fullyExecutedAt = now; + updates.marketingApprovedAt = now; + updates.marketingApprovedById = options.signerUserId ?? null; + updates.lockedAt = now; + } + + const updated = await this.bookingsRepository.update(bookingId, updates as never); return updated!; } - async streamContract(bookingId: string) { - const record = await this.filesService.findByCode( - bookingId, - 'bookings', - 'contract', - ); - return this.filesService.streamById(record.id); + async getSignatures(bookingId: string) { + const rows = await this.bookingsRepository.findContractSignatures(bookingId); + const views = rows.map((r) => this.viewModelBuilder.toSignatureView(r)); + await this.enrichSignatureUrls(views); + return { signatures: views }; + } + + private async enrichSignatureUrls( + signatures: Array<{ signatureImageUrl?: string | null }>, + ): Promise { + for (const sig of signatures) { + if (!sig.signatureImageUrl) continue; + try { + const objectName = this.extractObjectName(sig.signatureImageUrl); + sig.signatureImageUrl = await this.minioService.getSignedUrl(objectName, 3600); + } catch { + /* keep original url */ + } + } + } + + private extractObjectName(url: string): string { + const parts = url.split('/'); + return parts.slice(4).join('/'); + } + + private decodeSignatureImage(base64: string): Buffer { + const raw = base64.includes(',') ? base64.split(',')[1]! : base64; + return Buffer.from(raw, 'base64'); } private async requireBooking(id: string): Promise { diff --git a/apps/edr-freight-api/src/modules/bookings/booking-freight.util.ts b/apps/edr-freight-api/src/modules/bookings/booking-freight.util.ts new file mode 100644 index 000000000..cf4561c7b --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/booking-freight.util.ts @@ -0,0 +1,43 @@ +import { BadRequestException } from '@nestjs/common'; + +import { FREIGHT_TYPES, FreightType } from './entities/booking.entity'; +import { BookingFreightShapeInput } from './dto/validators/booking-freight.validator'; + +/** Normalize and validate booking freight shape (used on create and after update merge). */ +export function assertFreightShape(input: BookingFreightShapeInput): void { + if (!input.freightType || !FREIGHT_TYPES.includes(input.freightType as FreightType)) { + throw new BadRequestException( + `freightType is required and must be one of: ${FREIGHT_TYPES.join(', ')}`, + ); + } + + const containers = input.containers ?? []; + const hasContainers = containers.length > 0; + const hasCargoType = Boolean(input.cargoTypeId); + + if (input.freightType === 'BULK') { + if (hasContainers) { + throw new BadRequestException( + 'BULK freight cannot include container lines; use cargoTypeId only', + ); + } + if (!hasCargoType) { + throw new BadRequestException('cargoTypeId is required for BULK freight'); + } + return; + } + + if (hasCargoType) { + throw new BadRequestException('cargoTypeId is not allowed for CONTAINER freight'); + } + if (!hasContainers) { + throw new BadRequestException( + 'CONTAINER freight requires at least one container line with containerTypeId', + ); + } + for (const line of containers) { + if (!line.containerTypeId) { + throw new BadRequestException('Each container line must include containerTypeId'); + } + } +} diff --git a/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts index 621fb58e9..4e47456e0 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts @@ -1,14 +1,8 @@ -import { Inject, Injectable, NotFoundException } from '@nestjs/common'; +import { Injectable, NotFoundException } from '@nestjs/common'; import { ContainerTypesService } from '../rule-engine/services/container-types.service'; -import { - IRatesRepository, - RATES_REPOSITORY, -} from '../rule-engine/interfaces/rates.repository.interface'; -import { - IServiceTypesRepository, - SERVICE_TYPES_REPOSITORY, -} from '../rule-engine/interfaces/service-types.repository.interface'; +import { RatesService } from '../rule-engine/services/rates.service'; +import { ServiceTypesService } from '../rule-engine/services/service-types.service'; import { Rate } from '../rule-engine/entities/rate.entity'; import { AppliedCargoModifier, @@ -26,10 +20,8 @@ export class BookingPricingService { private readonly bookingsRepository: BookingsRepository, private readonly ruleEngineService: RuleEngineService, private readonly containerTypesService: ContainerTypesService, - @Inject(RATES_REPOSITORY) - private readonly ratesRepo: IRatesRepository, - @Inject(SERVICE_TYPES_REPOSITORY) - private readonly serviceTypesRepo: IServiceTypesRepository, + private readonly ratesService: RatesService, + private readonly serviceTypesService: ServiceTypesService, ) {} async generatePrice(bookingId: string): Promise { @@ -37,6 +29,7 @@ export class BookingPricingService { assertBookingStatus(booking, ['DRAFT']); const evalInput = await this.buildEvalInputForBooking(booking); + console.log('evalInput----', evalInput); const ruleResult = await this.ruleEngineService.evaluate(evalInput); this.ruleEngineService.assertNoHardBlocks(ruleResult); @@ -65,6 +58,12 @@ export class BookingPricingService { await this.bookingsRepository.update(bookingId, { totalAmount: total, priorityScore: ruleResult.priorityScore, + pricingBreakdown: { + lineItems, + totalAmount: total, + currency: booking.paymentCurrency, + generatedAt: new Date().toISOString(), + }, } as never); return { @@ -92,7 +91,8 @@ export class BookingPricingService { }), ); return { - cargoTypeId: booking.cargoTypeId, + freightType: booking.freightType as 'CONTAINER' | 'BULK', + cargoTypeId: booking.cargoTypeId ?? null, serviceTypeId: booking.serviceTypeId, paymentCurrency: booking.paymentCurrency, tradeDirection: booking.tradeDirection, @@ -109,13 +109,71 @@ export class BookingPricingService { return booking; } + /** Line items for contract schedule (uses stored breakdown or recomputes). */ + async computeContractLineItems(booking: Booking): Promise<{ + lineItems: PriceLineItemDto[]; + totalAmount: number; + currency: string; + }> { + const stored = booking.pricingBreakdown as { + lineItems?: PriceLineItemDto[]; + totalAmount?: number; + currency?: string; + } | null; + + if (stored?.lineItems?.length) { + return { + lineItems: stored.lineItems, + totalAmount: Number(stored.totalAmount ?? booking.totalAmount), + currency: stored.currency ?? booking.paymentCurrency, + }; + } + + const evalInput = await this.buildEvalInputForBooking(booking); + const ruleResult = await this.ruleEngineService.evaluate(evalInput); + const lineItems: PriceLineItemDto[] = []; + let total = 0; + + const baseLines = await this.computeBaseRailLines(booking, evalInput); + for (const line of baseLines) { + lineItems.push(line); + total += line.amount; + } + + for (const mod of ruleResult.appliedModifiers) { + lineItems.push({ + code: mod.surchargeTypeCode, + description: `Surcharge: ${mod.surchargeTypeCode}`, + amount: mod.calculatedAmount, + currency: mod.currency, + }); + total += mod.calculatedAmount; + } + + if (lineItems.length === 0) { + total = Number(booking.totalAmount); + lineItems.push({ + code: 'TOTAL', + description: 'Contract total', + amount: total, + currency: booking.paymentCurrency, + }); + } + + return { + lineItems, + totalAmount: total || Number(booking.totalAmount), + currency: booking.paymentCurrency, + }; + } + /** Recompute priority on submit (USD + service tier). */ async computeSubmitPriorityScore(booking: Booking): Promise { const evalInput = await this.buildEvalInputForBooking(booking); const ruleResult = await this.ruleEngineService.evaluate(evalInput); let score = ruleResult.priorityScore; - const serviceType = await this.serviceTypesRepo.findById(booking.serviceTypeId); + const serviceType = await this.serviceTypesService.findById(booking.serviceTypeId); if (booking.paymentCurrency === 'USD' && serviceType) { const code = (serviceType.code ?? '').toUpperCase(); const hasForwarding = @@ -136,10 +194,10 @@ export class BookingPricingService { booking: Booking, evalInput: BookingEvaluationInput, ): Promise { - const liveRates = await this.ratesRepo.findLiveRates(); + const liveRates = await this.ratesService.findLiveRates(); const currency = booking.paymentCurrency; - const isBulk = booking.cargoType?.requiresDirectorApproval ?? false; - + const isBulk = booking.freightType === 'BULK'; +console.log('liveRates----', liveRates); const rateType = booking.tradeDirection === 'IMPORT' ? isBulk @@ -151,11 +209,16 @@ export class BookingPricingService { : 'CONTAINER_EXPORT' : 'INTERCITY_CONTAINER'; + + console.log('rateType----', rateType); + const lines: PriceLineItemDto[] = []; const wagonCount = await this.bookingsRepository.calculateWagonCount(booking.id); for (const container of evalInput.containers) { + console.log('container----', container); const rate = this.pickRate(liveRates, rateType, container.containerTypeId, currency); + console.log('rate----', rate); if (!rate) continue; const amount = this.amountForRate(rate, container.quantity, wagonCount); diff --git a/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts index d40d6590b..ad76fa7a3 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts @@ -42,7 +42,7 @@ export class BookingTransitionService { async requestChanges( bookingId: string, note: string, - actorId?: string, + actorId: string, ): Promise { const booking = await this.bookingsService.findById(bookingId); assertBookingStatus(booking, ['SUBMITTED']); @@ -60,19 +60,19 @@ export class BookingTransitionService { return this.bookingsService.findById(updated!.id); } - async acceptIntake(bookingId: string, actorId?: string): Promise { + async acceptIntake(bookingId: string, actorId: string): Promise { const booking = await this.bookingsService.findById(bookingId); assertBookingStatus(booking, ['SUBMITTED']); - await this.ruleEngineService.instantiateApprovalSteps( - bookingId, - booking.cargoTypeId, - ); + await this.ruleEngineService.instantiateApprovalSteps(bookingId, { + freightType: booking.freightType as 'CONTAINER' | 'BULK', + cargoTypeId: booking.cargoTypeId, + }); const updated = await this.bookingsRepository.update(bookingId, { status: 'PENDING_APPROVAL', - approvedByStaffId: actorId ?? booking.approvedByStaffId, - approvedByStaffAt: actorId ? new Date() : booking.approvedByStaffAt, + approvedByStaffId: actorId, + approvedByStaffAt: new Date(), } as never); return this.bookingsService.findById(updated!.id); } @@ -80,7 +80,7 @@ export class BookingTransitionService { async staffReject( bookingId: string, reason: string, - actorId?: string, + actorId: string, ): Promise { const booking = await this.bookingsService.findById(bookingId); assertBookingStatus(booking, ['SUBMITTED', 'PENDING_APPROVAL']); @@ -211,17 +211,14 @@ export class BookingTransitionService { return this.bookingsService.findById(updated!.id); } - async marketingApprove( - bookingId: string, - actorId?: string, - ): Promise { + async marketingApprove(bookingId: string, actorId: string): Promise { const booking = await this.bookingsService.findById(bookingId); assertBookingStatus(booking, ['SIGNED_CUSTOMER']); const updated = await this.bookingsRepository.update(bookingId, { status: 'FULLY_EXECUTED', fullyExecutedAt: new Date(), - marketingApprovedById: actorId ?? null, + marketingApprovedById: actorId, marketingApprovedAt: new Date(), lockedAt: new Date(), } as never); diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts b/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts index c8572dd76..03c5cfde4 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts @@ -14,8 +14,11 @@ import { Res, StreamableFile, UploadedFiles, + UseGuards, UseInterceptors, } from '@nestjs/common'; +import { CurrentUser } from '@edr/api-common'; +import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; import { AnyFilesInterceptor } from '@nestjs/platform-express'; import { ApiBearerAuth, @@ -41,12 +44,16 @@ import { ApproveStepDto, CancelBookingDto, RejectStepDto, - MarketingApproveDto, RequestChangesDto, - StaffAcceptDto, StaffRejectDto, } from './dto/request-changes.dto'; +import { ContractViewDto } from './dto/contract-view.dto'; +import { SignContractDto } from './dto/sign-contract.dto'; import { UpdateBookingDto } from './dto/update-booking.dto'; +import { + type AuthUserPayload, + resolveAuthUserId, +} from '../../common/resolve-auth-user-id'; @ApiTags('bookings') @Controller('bookings') @@ -155,96 +162,146 @@ export class BookingsController { } @Post(':id/staff/request-changes') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Staff return booking for customer updates' }) async requestChanges( @Param('id', ParseUUIDPipe) id: string, @Body() dto: RequestChangesDto, + @CurrentUser() user: AuthUserPayload, ) { const booking = await this.transitionService.requestChanges( id, dto.note, - dto.actorId, + resolveAuthUserId(user), ); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/staff/accept') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Staff accept intake → start approval chain' }) async acceptIntake( @Param('id', ParseUUIDPipe) id: string, - @Body() dto: StaffAcceptDto, + @CurrentUser() user: AuthUserPayload, ) { - const booking = await this.transitionService.acceptIntake(id, dto.actorId); + const booking = await this.transitionService.acceptIntake( + id, + resolveAuthUserId(user), + ); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/staff/reject') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Staff final reject' }) async staffReject( @Param('id', ParseUUIDPipe) id: string, @Body() dto: StaffRejectDto, + @CurrentUser() user: AuthUserPayload, ) { const booking = await this.transitionService.staffReject( id, dto.reason, - dto.actorId, + resolveAuthUserId(user), ); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/approval-steps/:stepId/approve') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Approve one approval step in sequence' }) async approveStep( @Param('id', ParseUUIDPipe) id: string, @Param('stepId', ParseUUIDPipe) stepId: string, @Body() dto: ApproveStepDto, + @CurrentUser() user: AuthUserPayload, ) { const booking = await this.transitionService.approveStep( id, stepId, - dto.actorId, + resolveAuthUserId(user), dto.requiredRole, ); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/approval-steps/:stepId/reject') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Reject at approval step' }) async rejectStep( @Param('id', ParseUUIDPipe) id: string, @Param('stepId', ParseUUIDPipe) stepId: string, @Body() dto: RejectStepDto, + @CurrentUser() user: AuthUserPayload, ) { const booking = await this.transitionService.rejectStep( id, stepId, - dto.actorId, + resolveAuthUserId(user), dto.reason, ); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/contract/generate') - @ApiOperation({ summary: 'Generate contract document' }) + @UseGuards(JwtGuard) + @ApiOperation({ summary: 'Generate contract PDF from template' }) async generateContract(@Param('id', ParseUUIDPipe) id: string) { const booking = await this.contractService.generateContract(id); return this.transitionService.enrichBookingResponse(booking); } - @Get(':id/contract') - @ApiOperation({ summary: 'Download contract file' }) - async downloadContract( + @Get(':id/contract/view') + @ApiOkResponse({ type: ContractViewDto }) + @ApiOperation({ summary: 'Contract HTML view for portal and backoffice' }) + getContractView(@Param('id', ParseUUIDPipe) id: string) { + return this.contractService.getContractView(id); + } + + @Get(':id/contract/document') + @ApiOperation({ summary: 'Download contract PDF' }) + async downloadContractDocument( @Param('id', ParseUUIDPipe) id: string, @Res({ passthrough: true }) res: Response, ) { const { stream, record } = await this.contractService.streamContract(id); res.set({ - 'Content-Type': record.mimeType ?? 'application/octet-stream', + 'Content-Type': record.mimeType ?? 'application/pdf', 'Content-Disposition': `attachment; filename="${record.name}"`, }); return new StreamableFile(stream); } + @Get(':id/contract') + @ApiOperation({ summary: 'Download contract file (alias)' }) + async downloadContract( + @Param('id', ParseUUIDPipe) id: string, + @Res({ passthrough: true }) res: Response, + ) { + return this.downloadContractDocument(id, res); + } + + @Post(':id/contract/sign') + @ApiOperation({ summary: 'Apply digital signature (customer or staff)' }) + async signContract( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: SignContractDto, + @Request() req: { user?: { id?: string; sub?: string }; ip?: string }, + ) { + const userId = req.user?.id ?? req.user?.sub; + const booking = await this.contractService.signContract(id, dto, { + signerUserId: userId, + ipAddress: req.ip, + }); + return this.transitionService.enrichBookingResponse(booking); + } + + @Get(':id/contract/signatures') + @ApiOperation({ summary: 'List contract signatures' }) + getContractSignatures(@Param('id', ParseUUIDPipe) id: string) { + return this.contractService.getSignatures(id); + } + @Get(':id/summary') @ApiOperation({ summary: 'Contract summary string for dashboard' }) getSummary(@Param('id', ParseUUIDPipe) id: string) { @@ -252,22 +309,41 @@ export class BookingsController { } @Post(':id/customer/sign') - @ApiOperation({ summary: 'Customer digital signature' }) - async customerSign(@Param('id', ParseUUIDPipe) id: string) { - const booking = await this.transitionService.customerSign(id); + @ApiOperation({ + summary: 'Customer digital signature (deprecated — use POST contract/sign)', + }) + async customerSign( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: SignContractDto, + @Request() req: { user?: { id?: string; sub?: string }; ip?: string }, + ) { + const payload: SignContractDto = { ...dto, role: 'CUSTOMER' }; + const booking = await this.contractService.signContract(id, payload, { + signerUserId: req.user?.id ?? req.user?.sub, + ipAddress: req.ip, + }); return this.transitionService.enrichBookingResponse(booking); } @Post(':id/marketing/approve') - @ApiOperation({ summary: 'Marketing verify and fully execute' }) + @UseGuards(JwtGuard) + @ApiOperation({ + summary: 'Staff contract signature and fully execute (use contract/sign STAFF preferred)', + }) async marketingApprove( @Param('id', ParseUUIDPipe) id: string, - @Body() dto: MarketingApproveDto, + @Body() dto: SignContractDto, + @CurrentUser() user: AuthUserPayload, + @Request() req: { ip?: string }, ) { - const booking = await this.transitionService.marketingApprove( - id, - dto.actorId, - ); + const payload: SignContractDto = { + ...dto, + role: 'STAFF', + }; + const booking = await this.contractService.signContract(id, payload, { + signerUserId: resolveAuthUserId(user), + ipAddress: req.ip, + }); return this.transitionService.enrichBookingResponse(booking); } diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.module.ts b/apps/edr-freight-api/src/modules/bookings/bookings.module.ts index f3b3a9360..1f96176ba 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.module.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.module.ts @@ -19,8 +19,14 @@ import { BookingApprovalStep } from './entities/booking-approval-step.entity'; import { BookingCargoModifier } from './entities/booking-cargo-modifier.entity'; import { BookingContainer } from './entities/booking-container.entity'; import { BookingRateSnapshot } from './entities/booking-rate-snapshot.entity'; +import { BookingContractSignature } from './entities/booking-contract-signature.entity'; import { BookingReviewNote } from './entities/booking-review-note.entity'; import { Booking } from './entities/booking.entity'; +import { ContractPdfService } from '../../contracts/contract-pdf.service'; +import { ContractPricingScheduleBuilder } from '../../contracts/contract-pricing-schedule.builder'; +import { ContractRendererService } from '../../contracts/contract-renderer.service'; +import { ContractTemplateResolver } from '../../contracts/contract-template.resolver'; +import { ContractViewModelBuilder } from '../../contracts/contract-view-model.builder'; @Module({ imports: [ @@ -31,6 +37,7 @@ import { Booking } from './entities/booking.entity'; BookingApprovalStep, BookingRateSnapshot, BookingReviewNote, + BookingContractSignature, ]), FilesModule, MinioModule, @@ -47,6 +54,11 @@ import { Booking } from './entities/booking.entity'; BookingTransitionService, BookingContractService, BookingPaymentService, + ContractTemplateResolver, + ContractViewModelBuilder, + ContractPricingScheduleBuilder, + ContractRendererService, + ContractPdfService, ], exports: [BookingsService], }) diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts b/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts index 3a6155f3b..04c8a2fb7 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts @@ -10,6 +10,10 @@ import { BookingContainer } from './entities/booking-container.entity'; import { BookingRateSnapshot } from './entities/booking-rate-snapshot.entity'; import { BookingReviewNote, ReviewNoteType } from './entities/booking-review-note.entity'; import { Booking } from './entities/booking.entity'; +import { + BookingContractSignature, + ContractSignerRole, +} from './entities/booking-contract-signature.entity'; import { FileRecord } from '../files/entities/file.entity'; import { ContainerWeightResult } from '../rule-engine/rule-engine.service'; @@ -353,7 +357,7 @@ export class BookingsRepository extends BaseRepository { .where('booking.status IN (:...statuses)', { statuses }); if (options.excludeBulk) { - qb.andWhere('cargo.requires_director_approval = false'); + qb.andWhere("booking.freight_type = 'CONTAINER'"); } const sortField = @@ -380,4 +384,39 @@ export class BookingsRepository extends BaseRepository { order: options.order, }); } + + findContractSignatures(bookingId: string): Promise { + return this.dataSource.getRepository(BookingContractSignature).find({ + where: { bookingId }, + relations: ['signatureFile'], + order: { signedAt: 'ASC' }, + }); + } + + findContractSignature( + bookingId: string, + role: ContractSignerRole, + ): Promise { + return this.dataSource.getRepository(BookingContractSignature).findOne({ + where: { bookingId, signerRole: role }, + relations: ['signatureFile'], + }); + } + + async saveContractSignature( + data: Partial, + ): Promise { + const repo = this.dataSource.getRepository(BookingContractSignature); + const existing = await repo.findOne({ + where: { + bookingId: data.bookingId!, + signerRole: data.signerRole!, + }, + }); + if (existing) { + Object.assign(existing, data); + return repo.save(existing); + } + return repo.save(repo.create(data)); + } } diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.service.ts b/apps/edr-freight-api/src/modules/bookings/bookings.service.ts index 1039e60c1..f4351a1e6 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.service.ts @@ -16,10 +16,11 @@ import { } from '../rule-engine/rule-engine.service'; import { BookingsRepository } from './bookings.repository'; import { ConsolidationService } from './consolidation.service'; +import { assertFreightShape } from './booking-freight.util'; import { CreateBookingContainerDto, CreateBookingDto } from './dto/create-booking.dto'; import { FilterBookingDto } from './dto/filter-booking.dto'; import { UpdateBookingDto } from './dto/update-booking.dto'; -import { CUSTOMER_EDITABLE_STATUSES } from './entities/booking.entity'; +import { CUSTOMER_EDITABLE_STATUSES, FreightType } from './entities/booking.entity'; import { Booking } from './entities/booking.entity'; import { FileRecord } from '../files/entities/file.entity'; @@ -42,22 +43,23 @@ export class BookingsService { return `BK-${year}-${String(count + 1).padStart(6, '0')}`; } - /** Build evaluation input from DTO containers. */ - private async buildEvalInput( - dto: Pick< - CreateBookingDto, - | 'cargoTypeId' - | 'serviceTypeId' - | 'paymentCurrency' - | 'tradeDirection' - | 'isHazardous' - | 'allowConsolidation' - | 'shippingLineId' - | 'containers' - >, - ): Promise { + /** Build evaluation input from booking freight shape. */ + private async buildEvalInput(dto: { + freightType: FreightType; + cargoTypeId?: string | null; + serviceTypeId: string; + paymentCurrency: string; + tradeDirection: string; + isHazardous?: boolean; + allowConsolidation?: boolean; + shippingLineId?: string | null; + containers: CreateBookingContainerDto[]; + }): Promise { + const containerLines = + dto.freightType === 'CONTAINER' ? dto.containers : []; + const containers = await Promise.all( - dto.containers.map(async (c) => { + containerLines.map(async (c) => { const ct = await this.containerTypesService.findById(c.containerTypeId); const totalVgmTons = c.quantity * c.vgmPerUnitTons; return { @@ -69,13 +71,16 @@ export class BookingsService { }; }), ); + return { - cargoTypeId: dto.cargoTypeId, + freightType: dto.freightType, + cargoTypeId: dto.cargoTypeId ?? null, serviceTypeId: dto.serviceTypeId, paymentCurrency: dto.paymentCurrency, tradeDirection: dto.tradeDirection, isHazardous: dto.isHazardous ?? false, - allowConsolidation: dto.allowConsolidation, + allowConsolidation: + dto.freightType === 'CONTAINER' ? dto.allowConsolidation : false, shippingLineId: dto.shippingLineId, containers, }; @@ -161,12 +166,29 @@ export class BookingsService { } const reference = dto.reference || (await this.generateReference()); - const allowConsolidation = await this.resolveConsolidation( - dto.containers, - dto.allowConsolidation, - ); + const containers = dto.containers ?? []; + assertFreightShape({ + freightType: dto.freightType, + cargoTypeId: dto.cargoTypeId, + containers, + }); - const evalInput = await this.buildEvalInput({ ...dto, allowConsolidation }); + const allowConsolidation = + dto.freightType === 'CONTAINER' + ? await this.resolveConsolidation(containers, dto.allowConsolidation) + : false; + + const evalInput = await this.buildEvalInput({ + freightType: dto.freightType as FreightType, + cargoTypeId: dto.freightType === 'BULK' ? dto.cargoTypeId : null, + serviceTypeId: dto.serviceTypeId, + paymentCurrency: dto.paymentCurrency, + tradeDirection: dto.tradeDirection, + isHazardous: dto.isHazardous, + allowConsolidation, + shippingLineId: dto.shippingLineId, + containers, + }); const ruleResult = await this.ruleEngineService.evaluate(evalInput); this.ruleEngineService.assertNoHardBlocks(ruleResult); @@ -185,7 +207,8 @@ export class BookingsService { originYardId: dto.originYardId, destinationYardId: dto.destinationYardId, tradeDirection: dto.tradeDirection, - cargoTypeId: dto.cargoTypeId, + freightType: dto.freightType, + cargoTypeId: dto.freightType === 'BULK' ? dto.cargoTypeId! : null, cargoFreeText: dto.cargoFreeText, shippingLineId: dto.shippingLineId, cargoTotalWeightVgm: dto.cargoTotalWeightVgm, @@ -203,18 +226,19 @@ export class BookingsService { paymentStatus: 'PENDING', }); - await this.bookingsRepository.createContainers( - booking.id, - dto.containers.map((c, i) => ({ - containerTypeId: c.containerTypeId, - quantity: c.quantity, - vgmPerUnitTons: c.vgmPerUnitTons, - weightResult: ruleResult.containerWeightResults[i], - })), - ); - - const wagonCount = await this.bookingsRepository.calculateWagonCount(booking.id); - warnings.push(`Estimated wagons required: ${wagonCount}`); + if (dto.freightType === 'CONTAINER') { + await this.bookingsRepository.createContainers( + booking.id, + containers.map((c, i) => ({ + containerTypeId: c.containerTypeId, + quantity: c.quantity, + vgmPerUnitTons: c.vgmPerUnitTons, + weightResult: ruleResult.containerWeightResults[i], + })), + ); + const wagonCount = await this.bookingsRepository.calculateWagonCount(booking.id); + warnings.push(`Estimated wagons required: ${wagonCount}`); + } if (files.length > 0) { try { @@ -249,19 +273,44 @@ export class BookingsService { } const warnings: string[] = []; - const containers = dto.containers ?? existing.bookingContainers?.map((bc) => ({ - containerTypeId: bc.containerTypeId, - quantity: bc.quantity, - vgmPerUnitTons: Number(bc.vgmPerUnitTons), - })) ?? []; + const freightType = (dto.freightType ?? existing.freightType) as FreightType; + let containers = + dto.containers ?? + existing.bookingContainers?.map((bc) => ({ + containerTypeId: bc.containerTypeId, + quantity: bc.quantity, + vgmPerUnitTons: Number(bc.vgmPerUnitTons), + })) ?? + []; - const allowConsolidation = await this.resolveConsolidation( - containers, - dto.allowConsolidation ?? existing.allowConsolidation, - ); + let cargoTypeId = + dto.cargoTypeId !== undefined ? dto.cargoTypeId : existing.cargoTypeId; + + if (freightType === 'BULK') { + containers = []; + if (dto.containers !== undefined) { + await this.bookingsRepository.deleteContainers(id); + } + } else { + cargoTypeId = null; + if (dto.cargoTypeId !== undefined && dto.cargoTypeId !== null) { + throw new BadRequestException('cargoTypeId is not allowed for CONTAINER freight'); + } + } + + assertFreightShape({ freightType, cargoTypeId, containers }); + + const allowConsolidation = + freightType === 'CONTAINER' + ? await this.resolveConsolidation( + containers, + dto.allowConsolidation ?? existing.allowConsolidation, + ) + : false; const evalInput = await this.buildEvalInput({ - cargoTypeId: dto.cargoTypeId ?? existing.cargoTypeId, + freightType, + cargoTypeId, serviceTypeId: dto.serviceTypeId ?? existing.serviceTypeId, paymentCurrency: dto.paymentCurrency ?? existing.paymentCurrency, tradeDirection: dto.tradeDirection ?? existing.tradeDirection, @@ -277,6 +326,8 @@ export class BookingsService { const updates: Record = { ...dto, + freightType, + cargoTypeId: freightType === 'BULK' ? cargoTypeId : null, allowConsolidation, priorityScore: ruleResult.priorityScore, }; @@ -287,7 +338,7 @@ export class BookingsService { await this.bookingsRepository.update(id, updates); - if (dto.containers) { + if (freightType === 'CONTAINER' && dto.containers) { await this.bookingsRepository.deleteContainers(id); await this.bookingsRepository.createContainers( id, @@ -328,6 +379,7 @@ export class BookingsService { if (filter.contractType) where.contractType = filter.contractType; if (filter.serviceTypeId) where.serviceTypeId = filter.serviceTypeId; if (filter.cargoTypeId) where.cargoTypeId = filter.cargoTypeId; + if (filter.freightType) where.freightType = filter.freightType; if (filter.tradeDirection) where.tradeDirection = filter.tradeDirection; if (filter.paymentCurrency) where.paymentCurrency = filter.paymentCurrency; if (filter.allowConsolidation !== undefined) { @@ -347,6 +399,7 @@ export class BookingsService { skip: (page - 1) * pageSize, take: pageSize, order: { [sortField]: sortDir }, + relations: ['customer', 'originYard', 'destinationYard', 'serviceType'], }); return { items, total }; } diff --git a/apps/edr-freight-api/src/modules/bookings/dto/contract-view.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/contract-view.dto.ts new file mode 100644 index 000000000..4af9e535d --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/dto/contract-view.dto.ts @@ -0,0 +1,50 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +export class ContractSignatureDto { + @ApiProperty({ enum: ['CUSTOMER', 'STAFF'] }) + role!: string; + + @ApiProperty() + signerDisplayName!: string; + + @ApiProperty() + signedAt!: string; + + @ApiPropertyOptional() + signatureImageUrl?: string | null; +} + +export class ContractViewDto { + @ApiProperty() + bookingId!: string; + + @ApiProperty() + reference!: string; + + @ApiProperty() + status!: string; + + @ApiProperty() + templateKey!: string; + + @ApiProperty() + title!: string; + + @ApiProperty({ description: 'Full HTML document for in-browser display' }) + html!: string; + + @ApiProperty() + canSignCustomer!: boolean; + + @ApiProperty() + canSignStaff!: boolean; + + @ApiProperty() + hasContractDocument!: boolean; + + @ApiProperty({ type: [ContractSignatureDto] }) + signatures!: ContractSignatureDto[]; + + @ApiPropertyOptional() + pricingSchedule?: Record; +} diff --git a/apps/edr-freight-api/src/modules/bookings/dto/create-booking.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/create-booking.dto.ts index 0d61752f4..30cfd9fab 100644 --- a/apps/edr-freight-api/src/modules/bookings/dto/create-booking.dto.ts +++ b/apps/edr-freight-api/src/modules/bookings/dto/create-booking.dto.ts @@ -1,6 +1,7 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { Transform, Type } from 'class-transformer'; import { + ArrayMinSize, IsArray, IsBoolean, IsDateString, @@ -11,9 +12,12 @@ import { IsString, IsUUID, Min, + Validate, + ValidateIf, ValidateNested, } from 'class-validator'; -import { BOOKING_STATUSES } from '../entities/booking.entity'; +import { BOOKING_STATUSES, FREIGHT_TYPES } from '../entities/booking.entity'; +import { BookingFreightShapeConstraint } from './validators/booking-freight.validator'; const CONTRACT_TYPES = ['NEW', 'RENEWAL'] as const; const EQUIPMENT_RETURNS = ['WITH_RETURN', 'WITHOUT_RETURN', 'NA'] as const; @@ -24,6 +28,7 @@ export { BOOKING_STATUSES, CONTRACT_TYPES, EQUIPMENT_RETURNS, + FREIGHT_TYPES, TRADE_DIRECTIONS, PAYMENT_CURRENCIES, }; @@ -47,6 +52,9 @@ export class CreateBookingContainerDto { } export class CreateBookingDto { + /** Class-level freight shape check (not a request field). */ + @Validate(BookingFreightShapeConstraint) + freightShapeValidation?: boolean; @ApiPropertyOptional({ description: 'Unique booking reference (auto-generated if omitted)' }) @IsOptional() @IsString() @@ -107,9 +115,17 @@ export class CreateBookingDto { @IsIn([...TRADE_DIRECTIONS]) tradeDirection!: string; - @ApiProperty({ format: 'uuid', description: 'FK to cargo_types.id' }) + @ApiProperty({ enum: FREIGHT_TYPES, description: 'CONTAINER or BULK (mutually exclusive cargo shape)' }) + @IsIn([...FREIGHT_TYPES]) + freightType!: string; + + @ApiPropertyOptional({ + format: 'uuid', + description: 'Required for BULK; must be omitted for CONTAINER', + }) + @ValidateIf((o) => o.freightType === 'BULK') @IsUUID() - cargoTypeId!: string; + cargoTypeId?: string; @ApiPropertyOptional({ maxLength: 200 }) @IsOptional() @@ -157,11 +173,16 @@ export class CreateBookingDto { @IsString() financialTerms?: string; - @ApiProperty({ type: [CreateBookingContainerDto] }) + @ApiPropertyOptional({ + type: [CreateBookingContainerDto], + description: 'Required for CONTAINER (min 1 line); must be empty for BULK', + }) + @ValidateIf((o) => o.freightType === 'CONTAINER') @IsArray() + @ArrayMinSize(1) @ValidateNested({ each: true }) @Type(() => CreateBookingContainerDto) - containers!: CreateBookingContainerDto[]; + containers?: CreateBookingContainerDto[]; @ApiPropertyOptional({ default: false }) @IsOptional() diff --git a/apps/edr-freight-api/src/modules/bookings/dto/filter-booking.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/filter-booking.dto.ts index 912064905..cdf4a6b18 100644 --- a/apps/edr-freight-api/src/modules/bookings/dto/filter-booking.dto.ts +++ b/apps/edr-freight-api/src/modules/bookings/dto/filter-booking.dto.ts @@ -1,7 +1,12 @@ import { ApiPropertyOptional } from '@nestjs/swagger'; import { Transform } from 'class-transformer'; import { IsIn, IsOptional, IsUUID } from 'class-validator'; -import { BOOKING_STATUSES, PAYMENT_CURRENCIES, TRADE_DIRECTIONS } from './create-booking.dto'; +import { + BOOKING_STATUSES, + FREIGHT_TYPES, + PAYMENT_CURRENCIES, + TRADE_DIRECTIONS, +} from './create-booking.dto'; export class FilterBookingDto { @ApiPropertyOptional({ enum: BOOKING_STATUSES }) @@ -28,6 +33,11 @@ export class FilterBookingDto { @IsUUID() cargoTypeId?: string; + @ApiPropertyOptional({ enum: FREIGHT_TYPES }) + @IsOptional() + @IsIn([...FREIGHT_TYPES]) + freightType?: string; + @ApiPropertyOptional({ enum: TRADE_DIRECTIONS }) @IsOptional() @IsIn([...TRADE_DIRECTIONS]) diff --git a/apps/edr-freight-api/src/modules/bookings/dto/request-changes.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/request-changes.dto.ts index 8e77b51fc..6f716388c 100644 --- a/apps/edr-freight-api/src/modules/bookings/dto/request-changes.dto.ts +++ b/apps/edr-freight-api/src/modules/bookings/dto/request-changes.dto.ts @@ -1,30 +1,11 @@ -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { IsOptional, IsString, IsUUID, MinLength } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MinLength } from 'class-validator'; export class RequestChangesDto { @ApiProperty({ description: 'Staff note explaining what the customer must fix' }) @IsString() @MinLength(1) note!: string; - - @ApiPropertyOptional({ format: 'uuid' }) - @IsOptional() - @IsUUID() - actorId?: string; -} - -export class StaffAcceptDto { - @ApiPropertyOptional({ format: 'uuid' }) - @IsOptional() - @IsUUID() - actorId?: string; -} - -export class MarketingApproveDto { - @ApiPropertyOptional({ format: 'uuid' }) - @IsOptional() - @IsUUID() - actorId?: string; } export class StaffRejectDto { @@ -32,28 +13,15 @@ export class StaffRejectDto { @IsString() @MinLength(1) reason!: string; - - @ApiPropertyOptional({ format: 'uuid' }) - @IsOptional() - @IsUUID() - actorId?: string; } export class ApproveStepDto { - @ApiProperty({ format: 'uuid' }) - @IsUUID() - actorId!: string; - @ApiProperty({ description: 'LINE_STAFF | DIRECTOR | CEO' }) @IsString() requiredRole!: string; } export class RejectStepDto { - @ApiProperty({ format: 'uuid' }) - @IsUUID() - actorId!: string; - @ApiProperty() @IsString() @MinLength(1) diff --git a/apps/edr-freight-api/src/modules/bookings/dto/sign-contract.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/sign-contract.dto.ts new file mode 100644 index 000000000..0b176ebd5 --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/dto/sign-contract.dto.ts @@ -0,0 +1,23 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { IsIn, IsOptional, IsString, MinLength } from 'class-validator'; + +export class SignContractDto { + @ApiProperty({ enum: ['CUSTOMER', 'STAFF'] }) + @IsIn(['CUSTOMER', 'STAFF']) + role!: 'CUSTOMER' | 'STAFF'; + + @ApiProperty({ description: 'PNG signature image as base64 (with or without data URL prefix)' }) + @IsString() + @MinLength(20) + signatureImageBase64!: string; + + @ApiProperty() + @IsString() + @MinLength(1) + signerDisplayName!: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + consentText?: string; +} diff --git a/apps/edr-freight-api/src/modules/bookings/dto/update-booking.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/update-booking.dto.ts index 2b97debc6..328e71180 100644 --- a/apps/edr-freight-api/src/modules/bookings/dto/update-booking.dto.ts +++ b/apps/edr-freight-api/src/modules/bookings/dto/update-booking.dto.ts @@ -1,5 +1,10 @@ -import { PartialType } from "@nestjs/mapped-types"; +import { PartialType } from '@nestjs/mapped-types'; +import { Validate } from 'class-validator'; -import { CreateBookingDto } from "./create-booking.dto"; +import { CreateBookingDto } from './create-booking.dto'; +import { BookingFreightShapeConstraint } from './validators/booking-freight.validator'; -export class UpdateBookingDto extends PartialType(CreateBookingDto) {} +export class UpdateBookingDto extends PartialType(CreateBookingDto) { + @Validate(BookingFreightShapeConstraint) + freightShapeValidation?: boolean; +} diff --git a/apps/edr-freight-api/src/modules/bookings/dto/validators/booking-freight.validator.ts b/apps/edr-freight-api/src/modules/bookings/dto/validators/booking-freight.validator.ts new file mode 100644 index 000000000..1365158b1 --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/dto/validators/booking-freight.validator.ts @@ -0,0 +1,60 @@ +import { + ValidationArguments, + ValidatorConstraint, + ValidatorConstraintInterface, +} from 'class-validator'; + +import { FREIGHT_TYPES, FreightType } from '../../entities/booking.entity'; + +export interface BookingFreightShapeInput { + freightType?: string; + cargoTypeId?: string | null; + containers?: Array<{ containerTypeId?: string }> | null; +} + +@ValidatorConstraint({ name: 'BookingFreightShape', async: false }) +export class BookingFreightShapeConstraint implements ValidatorConstraintInterface { + validate(_value: unknown, args: ValidationArguments): boolean { + const dto = args.object as BookingFreightShapeInput; + if (!dto.freightType || !FREIGHT_TYPES.includes(dto.freightType as FreightType)) { + return true; + } + + const containers = dto.containers ?? []; + const hasContainers = containers.length > 0; + const hasCargoType = + dto.cargoTypeId !== undefined && + dto.cargoTypeId !== null && + String(dto.cargoTypeId).trim() !== ''; + + if (dto.freightType === 'BULK') { + if (hasContainers) return false; + if (!hasCargoType) return false; + return true; + } + + if (dto.freightType === 'CONTAINER') { + if (hasCargoType) return false; + if (!hasContainers) return false; + return containers.every( + (c) => + c.containerTypeId !== undefined && + c.containerTypeId !== null && + String(c.containerTypeId).trim() !== '', + ); + } + + return true; + } + + defaultMessage(args: ValidationArguments): string { + const dto = args.object as BookingFreightShapeInput; + if (dto.freightType === 'BULK') { + return 'BULK freight requires cargoTypeId and must not include container lines'; + } + if (dto.freightType === 'CONTAINER') { + return 'CONTAINER freight requires at least one container line with containerTypeId and must not include cargoTypeId'; + } + return 'Invalid freight type shape'; + } +} diff --git a/apps/edr-freight-api/src/modules/bookings/entities/booking-contract-signature.entity.ts b/apps/edr-freight-api/src/modules/bookings/entities/booking-contract-signature.entity.ts new file mode 100644 index 000000000..6370c97c2 --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/entities/booking-contract-signature.entity.ts @@ -0,0 +1,44 @@ +import { BaseEntity } from '@edr/api-common'; +import { Column, Entity, Index, JoinColumn, ManyToOne, Unique } from 'typeorm'; +import { FileRecord } from '../../files/entities/file.entity'; +import { Booking } from './booking.entity'; + +export const CONTRACT_SIGNER_ROLES = ['CUSTOMER', 'STAFF'] as const; +export type ContractSignerRole = (typeof CONTRACT_SIGNER_ROLES)[number]; + +@Entity({ schema: 'freight', name: 'booking_contract_signatures' }) +@Unique(['bookingId', 'signerRole']) +@Index(['bookingId']) +export class BookingContractSignature extends BaseEntity { + @Column({ name: 'booking_id', type: 'uuid' }) + bookingId!: string; + + @ManyToOne(() => Booking, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'booking_id' }) + booking?: Booking; + + @Column({ name: 'signer_role', type: 'varchar', length: 20 }) + signerRole!: ContractSignerRole; + + @Column({ name: 'signer_user_id', type: 'uuid', nullable: true }) + signerUserId?: string | null; + + @Column({ name: 'signer_display_name', type: 'varchar', length: 200 }) + signerDisplayName!: string; + + @Column({ name: 'signed_at', type: 'timestamptz' }) + signedAt!: Date; + + @Column({ name: 'signature_file_id', type: 'uuid', nullable: true }) + signatureFileId?: string | null; + + @ManyToOne(() => FileRecord, { nullable: true }) + @JoinColumn({ name: 'signature_file_id' }) + signatureFile?: FileRecord | null; + + @Column({ name: 'consent_text', type: 'text', nullable: true }) + consentText?: string | null; + + @Column({ name: 'ip_address', type: 'varchar', length: 64, nullable: true }) + ipAddress?: string | null; +} diff --git a/apps/edr-freight-api/src/modules/bookings/entities/booking.entity.ts b/apps/edr-freight-api/src/modules/bookings/entities/booking.entity.ts index 6a4140006..eaec84e82 100644 --- a/apps/edr-freight-api/src/modules/bookings/entities/booking.entity.ts +++ b/apps/edr-freight-api/src/modules/bookings/entities/booking.entity.ts @@ -46,6 +46,9 @@ export const PAYMENT_STATUSES = [ export type PaymentStatus = (typeof PAYMENT_STATUSES)[number]; +export const FREIGHT_TYPES = ['CONTAINER', 'BULK'] as const; +export type FreightType = (typeof FREIGHT_TYPES)[number]; + /** Statuses where the customer may edit booking fields. */ export const CUSTOMER_EDITABLE_STATUSES: BookingStatus[] = [ 'DRAFT', @@ -126,8 +129,11 @@ export class Booking extends BaseEntity { @Column({ name: 'trade_direction', type: 'varchar', length: 10 }) tradeDirection!: string; - @Column({ name: 'cargo_type_id', type: 'uuid' }) - cargoTypeId!: string; + @Column({ name: 'freight_type', type: 'varchar', length: 20 }) + freightType!: string; + + @Column({ name: 'cargo_type_id', type: 'uuid', nullable: true }) + cargoTypeId?: string | null; @ManyToOne(() => CargoType) @JoinColumn({ name: 'cargo_type_id' }) @@ -200,6 +206,15 @@ export class Booking extends BaseEntity { @Column({ name: 'contract_summary', type: 'text', nullable: true }) contractSummary?: string | null; + @Column({ name: 'contract_template_key', type: 'varchar', length: 80, nullable: true }) + contractTemplateKey?: string | null; + + @Column({ name: 'contract_generated_at', type: 'timestamptz', nullable: true }) + contractGeneratedAt?: Date | null; + + @Column({ name: 'pricing_breakdown', type: 'jsonb', nullable: true }) + pricingBreakdown?: Record | null; + @Column({ name: 'locked_at', type: 'timestamptz', nullable: true }) lockedAt?: Date | null; diff --git a/apps/edr-freight-api/src/modules/files/files.repository.ts b/apps/edr-freight-api/src/modules/files/files.repository.ts index 2ec2b94a2..ea4bfd19e 100644 --- a/apps/edr-freight-api/src/modules/files/files.repository.ts +++ b/apps/edr-freight-api/src/modules/files/files.repository.ts @@ -25,4 +25,12 @@ export class FilesRepository extends BaseRepository { ): Promise { return this.repository.findOne({ where: { resourceId, resource, code } }); } + + async deleteByCode( + resourceId: string, + resource: string, + code: string, + ): Promise { + await this.repository.delete({ resourceId, resource, code }); + } } diff --git a/apps/edr-freight-api/src/modules/files/files.service.ts b/apps/edr-freight-api/src/modules/files/files.service.ts index e08fce72b..1f0076986 100644 --- a/apps/edr-freight-api/src/modules/files/files.service.ts +++ b/apps/edr-freight-api/src/modules/files/files.service.ts @@ -35,6 +35,13 @@ export class FilesService { }); } + /** Replace existing file row for the same resource + code (e.g. contract PDF). */ + async upsertByCode(input: CreateFileInput): Promise { + const { resourceId, resource, code } = input; + await this.filesRepository.deleteByCode(resourceId, resource, code); + return this.upload(input); + } + async uploadMany( resourceId: string, resource: string, diff --git a/apps/edr-freight-api/src/modules/rule-engine/controllers/rates.controller.ts b/apps/edr-freight-api/src/modules/rule-engine/controllers/rates.controller.ts index 02408e53d..0ff7ef543 100644 --- a/apps/edr-freight-api/src/modules/rule-engine/controllers/rates.controller.ts +++ b/apps/edr-freight-api/src/modules/rule-engine/controllers/rates.controller.ts @@ -1,9 +1,15 @@ import { Body, Controller, Delete, Get, HttpCode, HttpStatus, - Param, ParseUUIDPipe, Patch, Post, Query, + Param, ParseUUIDPipe, Patch, Post, Query, UseGuards, } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { ApproveRateDto, CreateRateDto } from '../dto/create-rate.dto'; +import { CurrentUser } from '@edr/api-common'; +import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; +import { CreateRateDto } from '../dto/create-rate.dto'; +import { + type AuthUserPayload, + resolveAuthUserId, +} from '../../../common/resolve-auth-user-id'; import { UpdateRateDto } from '../dto/update-rate.dto'; import { RatesService } from '../services/rates.service'; @@ -38,9 +44,13 @@ export class RatesController { } @Post() + @UseGuards(JwtGuard) @ApiOperation({ summary: 'Create a rate (DRAFT)' }) - create(@Body() dto: CreateRateDto) { - return this.service.create(dto); + create( + @Body() dto: CreateRateDto, + @CurrentUser() user: AuthUserPayload, + ) { + return this.service.create(dto, resolveAuthUserId(user)); } @Patch(':id') @@ -56,9 +66,13 @@ export class RatesController { } @Post(':id/approve') + @UseGuards(JwtGuard) @ApiOperation({ summary: 'CEO approves a rate' }) - approve(@Param('id', ParseUUIDPipe) id: string, @Body() dto: ApproveRateDto) { - return this.service.approve(id, dto); + approve( + @Param('id', ParseUUIDPipe) id: string, + @CurrentUser() user: AuthUserPayload, + ) { + return this.service.approve(id, resolveAuthUserId(user)); } @Delete(':id') diff --git a/apps/edr-freight-api/src/modules/rule-engine/dto/create-rate.dto.ts b/apps/edr-freight-api/src/modules/rule-engine/dto/create-rate.dto.ts index fe9084395..2f73780d9 100644 --- a/apps/edr-freight-api/src/modules/rule-engine/dto/create-rate.dto.ts +++ b/apps/edr-freight-api/src/modules/rule-engine/dto/create-rate.dto.ts @@ -35,10 +35,6 @@ export class CreateRateDto { @IsIn([...RATE_UNITS]) rateUnit!: string; - @ApiProperty({ description: 'ID of the staff member (Director) proposing this rate' }) - @IsUUID() - proposedByStaffId!: string; - @ApiProperty({ description: 'Date from which this rate is effective (ISO date)', example: '2025-01-01' }) @IsDateString() effectiveFrom!: string; @@ -49,12 +45,6 @@ export class CreateRateDto { effectiveTo?: string; } -export class ApproveRateDto { - @ApiProperty({ description: 'ID of the CEO approving this rate' }) - @IsUUID() - approvedByCeoId!: string; -} - export class SubmitRateForApprovalDto { @ApiPropertyOptional({ description: 'Optional note for the approval request', maxLength: 500 }) @IsOptional() diff --git a/apps/edr-freight-api/src/modules/rule-engine/rule-engine.service.ts b/apps/edr-freight-api/src/modules/rule-engine/rule-engine.service.ts index 5fc27ecbd..452bee90b 100644 --- a/apps/edr-freight-api/src/modules/rule-engine/rule-engine.service.ts +++ b/apps/edr-freight-api/src/modules/rule-engine/rule-engine.service.ts @@ -47,7 +47,8 @@ export interface BookingContainerEvalInput { } export interface BookingEvaluationInput { - cargoTypeId: string; + cargoTypeId?: string | null; + freightType?: 'CONTAINER' | 'BULK'; serviceTypeId: string; paymentCurrency: string; tradeDirection: string; @@ -115,13 +116,19 @@ export class RuleEngineService { let priorityScore = 0; let requiresDirectorApproval = false; - const cargoType = await this.cargoTypesRepo.findById(input.cargoTypeId); - if (!cargoType) { - hardBlocked.push(`Cargo type ${input.cargoTypeId} not found`); - } else if (cargoType.requiresDirectorApproval) { + if (input.freightType === 'BULK') { requiresDirectorApproval = true; } + if (input.cargoTypeId) { + const cargoType = await this.cargoTypesRepo.findById(input.cargoTypeId); + if (!cargoType) { + hardBlocked.push(`Cargo type ${input.cargoTypeId} not found`); + } else if (cargoType.requiresDirectorApproval) { + requiresDirectorApproval = true; + } + } + for (const container of input.containers) { const rules = await this.weightLimitRulesRepo.findActiveByContainerTypeId( container.containerTypeId, @@ -232,16 +239,29 @@ export class RuleEngineService { } /** - * Instantiate booking_approval_step rows from approval_rules for a cargo type. + * Instantiate booking_approval_step rows from approval_rules by freight type. */ - async instantiateApprovalSteps(bookingId: string, cargoTypeId: string): Promise { - const cargoType = await this.cargoTypesRepo.findById(cargoTypeId); - if (!cargoType) { - throw new BadRequestException(`Cargo type ${cargoTypeId} not found`); + async instantiateApprovalSteps( + bookingId: string, + options: { + freightType: 'CONTAINER' | 'BULK'; + cargoTypeId?: string | null; + }, + ): Promise { + let requiresDirectorApproval = options.freightType === 'BULK'; + + if (options.cargoTypeId) { + const cargoType = await this.cargoTypesRepo.findById(options.cargoTypeId); + if (!cargoType) { + throw new BadRequestException(`Cargo type ${options.cargoTypeId} not found`); + } + if (cargoType.requiresDirectorApproval) { + requiresDirectorApproval = true; + } } const chain = await this.approvalRulesRepo.findChainForCargo( - cargoType.requiresDirectorApproval, + requiresDirectorApproval, ); const stepRepo = this.dataSource.getRepository(BookingApprovalStep); diff --git a/apps/edr-freight-api/src/modules/rule-engine/services/rates.service.ts b/apps/edr-freight-api/src/modules/rule-engine/services/rates.service.ts index 656802e3f..0202ef44a 100644 --- a/apps/edr-freight-api/src/modules/rule-engine/services/rates.service.ts +++ b/apps/edr-freight-api/src/modules/rule-engine/services/rates.service.ts @@ -1,5 +1,5 @@ import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common'; -import { ApproveRateDto, CreateRateDto } from '../dto/create-rate.dto'; +import { CreateRateDto } from '../dto/create-rate.dto'; import { UpdateRateDto } from '../dto/update-rate.dto'; import { Rate } from '../entities/rate.entity'; import { IRatesRepository, RATES_REPOSITORY } from '../interfaces/rates.repository.interface'; @@ -46,7 +46,7 @@ export class RatesService { } /** Create a rate in DRAFT status. */ - async create(dto: CreateRateDto): Promise { + async create(dto: CreateRateDto, proposedByStaffId: string): Promise { return this.repository.create({ rateType: dto.rateType as Rate['rateType'], containerTypeId: dto.containerTypeId, @@ -55,7 +55,7 @@ export class RatesService { rateValue: dto.rateValue, rateUnit: dto.rateUnit as Rate['rateUnit'], status: 'DRAFT', - proposedByStaffId: dto.proposedByStaffId, + proposedByStaffId, effectiveFrom: new Date(dto.effectiveFrom), effectiveTo: dto.effectiveTo ? new Date(dto.effectiveTo) : undefined, }); @@ -74,7 +74,6 @@ export class RatesService { if (dto.currency) updates.currency = dto.currency; if (dto.rateValue !== undefined) updates.rateValue = dto.rateValue; if (dto.rateUnit) updates.rateUnit = dto.rateUnit as Rate['rateUnit']; - if (dto.proposedByStaffId) updates.proposedByStaffId = dto.proposedByStaffId; if (dto.effectiveFrom) updates.effectiveFrom = new Date(dto.effectiveFrom); if (dto.effectiveTo) updates.effectiveTo = new Date(dto.effectiveTo); const updated = await this.repository.update(id, updates); @@ -93,14 +92,14 @@ export class RatesService { } /** CEO approves a rate — moves to LIVE. */ - async approve(id: string, dto: ApproveRateDto): Promise { + async approve(id: string, approverUserId: string): Promise { const rate = await this.findById(id); if (rate.status !== 'PENDING_APPROVAL') { throw new BadRequestException('Only PENDING_APPROVAL rates can be approved'); } const updated = await this.repository.update(id, { status: 'LIVE', - approvedByCeoId: dto.approvedByCeoId, + approvedByCeoId: approverUserId, approvedAt: new Date(), }); return updated!; diff --git a/apps/edr-freight-api/src/modules/rule-engine/services/surcharge-types.service.ts b/apps/edr-freight-api/src/modules/rule-engine/services/surcharge-types.service.ts index 98e5b1642..387e26ba9 100644 --- a/apps/edr-freight-api/src/modules/rule-engine/services/surcharge-types.service.ts +++ b/apps/edr-freight-api/src/modules/rule-engine/services/surcharge-types.service.ts @@ -28,6 +28,7 @@ export class SurchargeTypesService { const [data, total] = await this.repository.findAndCount({ where, + relations: { rate: true }, order: { label: 'ASC' }, skip: (page - 1) * pageSize, take: pageSize, diff --git a/apps/edr-freight-web/backoffice/src/App.tsx b/apps/edr-freight-web/backoffice/src/App.tsx index 7cc6a9935..884fde00b 100644 --- a/apps/edr-freight-web/backoffice/src/App.tsx +++ b/apps/edr-freight-web/backoffice/src/App.tsx @@ -1,5 +1,4 @@ import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { Boxes, FileText, @@ -14,6 +13,7 @@ import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@ import LoadingScreen from "./components/LoadingScreen"; import { useAuth } from "./auth/useAuth"; import LoginPage from "./pages/auth/LoginPage"; +import BookingContractPage from "./pages/bookings/BookingContractPage"; import BookingRequestDetailPage from "./pages/bookings/BookingRequestDetailPage"; import BookingRequestsPage from "./pages/bookings/BookingRequestsPage"; import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page"; @@ -31,16 +31,6 @@ import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirec import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage"; import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources"; -const queryClient = new QueryClient({ - defaultOptions: { - queries: { - retry: 1, - refetchOnWindowFocus: false, - staleTime: 5 * 60 * 1000, - }, - }, -}); - const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [ { title: "Main menu", @@ -188,18 +178,15 @@ const App = () => { if (!user) { return ( - - - } /> - } /> - - + + } /> + } /> + ); } return ( - - + } /> } /> @@ -208,6 +195,10 @@ const App = () => { } /> } /> + } + /> } /> } /> @@ -251,8 +242,7 @@ const App = () => { } /> - - + ); }; diff --git a/apps/edr-freight-web/backoffice/src/components/bookings/ApprovalStepsCard.tsx b/apps/edr-freight-web/backoffice/src/components/bookings/ApprovalStepsCard.tsx new file mode 100644 index 000000000..64cca7db3 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/bookings/ApprovalStepsCard.tsx @@ -0,0 +1,116 @@ +import { useMemo } from "react"; +import { ShieldCheck } from "lucide-react"; + +import type { BookingApprovalStep, BookingDetail } from "@/types/booking"; +import { getNextPendingApprovalStep } from "@/features/bookings/booking-actions.config"; +import { Badge } from "@edr/ui-common"; +import { cn } from "@/lib/utils"; + +interface ApprovalStepsCardProps { + booking: BookingDetail; +} + +/** Read-only approval chain visualization; actions live in BookingActionsToolbar. */ +export function ApprovalStepsCard({ booking }: ApprovalStepsCardProps) { + const steps = useMemo( + () => + [...(booking.approvalSteps ?? [])].sort( + (a, b) => a.stepOrder - b.stepOrder, + ), + [booking.approvalSteps], + ); + + const nextPending = getNextPendingApprovalStep(steps); + + return ( +
+
+
+ +
+
+

+ Approval chain +

+

+ Next:{" "} + {nextPending + ? `${nextPending.requiredRole} · step ${nextPending.stepOrder}` + : steps.length + ? "All steps complete" + : "Accept submission to begin"} +

+
+
+ +
+ {steps.length === 0 ? ( +

+ Use Accept for approval{" "} + in staff actions to instantiate steps. +

+ ) : ( +
    + {steps.map((step) => ( + + ))} +
+ )} +
+
+ ); +} + +function StepRow({ + step, + isNext, +}: { + step: BookingApprovalStep; + isNext: boolean; +}) { + const statusStyles = + step.status === "APPROVED" + ? "bg-emerald-500/15 text-emerald-800 dark:text-emerald-300" + : step.status === "REJECTED" + ? "bg-red-500/15 text-red-800 dark:text-red-300" + : isNext + ? "bg-amber-500/15 text-amber-800 dark:text-amber-300" + : "bg-muted text-muted-foreground"; + + return ( +
  • +
    + + {step.stepOrder} + +
    +

    + {step.requiredRole} +

    + {step.remarks && ( +

    + {step.remarks} +

    + )} +
    +
    + + {step.status} + +
  • + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsMenu.tsx b/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsMenu.tsx new file mode 100644 index 000000000..29b4e9b19 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsMenu.tsx @@ -0,0 +1,233 @@ +import { useNavigate } from "react-router-dom"; +import { + ChevronRight, + ExternalLink, + Loader2, + MoreHorizontal, + Upload, +} from "lucide-react"; + +import { BookingConfirmDialog } from "./BookingConfirmDialog"; +import { useBookingActionDialog } from "./useBookingActionDialog"; +import { + listRowHasActions, + type BookingActionContext, +} from "@/features/bookings/booking-actions.config"; +import type { BookingListRow } from "@/types/booking"; +import { cn } from "@/lib/utils"; +import { + Button, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@edr/ui-common"; + +interface BookingActionsMenuProps { + row: BookingListRow; + /** Compact table cell vs. larger detail toolbar */ + variant?: "table" | "toolbar"; + className?: string; +} + +export function BookingActionsMenu({ + row, + variant = "table", + className, +}: BookingActionsMenuProps) { + const navigate = useNavigate(); + const context: BookingActionContext = { + status: row.status, + paymentCurrency: row.paymentCurrency, + reference: row.reference, + }; + + const flow = useBookingActionDialog(row.id, context); + const { actions, pendingAction, mutations } = flow; + + const goToContract = () => + navigate(`/dashboard/booking-requests/${row.id}/contract`); + + const showUsdPaymentHint = + row.status === "FULLY_EXECUTED" && row.paymentCurrency === "USD"; + const hasMenu = listRowHasActions(row) || showUsdPaymentHint; + + const primary = actions.find((a) => a.primary) ?? actions[0]; + + if (!hasMenu && variant === "table") { + return ( + + ); + } + + return ( + <> +
    e.stopPropagation()} + onKeyDown={(e) => e.stopPropagation()} + > + {variant === "table" && primary && ( + + )} + + {variant === "toolbar" && actions.length > 0 ? ( +
    + {actions.map((action) => { + const Icon = action.icon; + return ( + + ); + })} +
    + ) : ( + + + + + + + {row.reference} + + + {actions.map((action) => { + const Icon = action.icon; + return ( + + action.id === "viewContract" + ? goToContract() + : flow.openAction(action) + } + > + + {action.label} + + ); + })} + {showUsdPaymentHint && ( + + navigate(`/dashboard/booking-requests/${row.id}`) + } + > + + Upload payment proof… + + )} + {(actions.length > 0 || showUsdPaymentHint) && ( + + )} + + navigate(`/dashboard/booking-requests/${row.id}`) + } + > + + Open full details + + + + )} +
    + + + + Loading approval steps… +

    + ) : pendingAction?.id === "approve" && + !flow.mergedContext.approvalSteps?.length ? ( +

    + No pending approval step found. Accept the submission on the detail + page first. +

    + ) : null + } + /> + + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsToolbar.tsx b/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsToolbar.tsx new file mode 100644 index 000000000..8c0b123d5 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/bookings/BookingActionsToolbar.tsx @@ -0,0 +1,168 @@ +import { useRef } from "react"; +import { Download, Upload, Zap } from "lucide-react"; + +import type { BookingDetail } from "@/types/booking"; +import { BookingActionsMenu } from "./BookingActionsMenu"; +import { bookingSurface } from "./booking-ui.styles"; +import { toBookingListRow } from "@/features/bookings/mapBookingListRow"; +import type { useBookingMutations } from "@/hooks/bookings/useBookings"; +import { Button } from "@edr/ui-common"; + +type Mutations = ReturnType; + +interface BookingActionsToolbarProps { + booking: BookingDetail; + mutations: Mutations; +} + +/** Detail-page actions: primary toolbar + payment uploads + downloads. */ +export function BookingActionsToolbar({ + booking, + mutations, +}: BookingActionsToolbarProps) { + const fileRef = useRef(null); + const row = toBookingListRow(booking); + const { status, paymentCurrency } = booking; + const pending = mutations.isPending; + + const downloadBlob = async (fn: () => Promise, filename: string) => { + const blob = await fn(); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = filename; + a.click(); + URL.revokeObjectURL(url); + }; + + if ( + status === "REJECTED" || + status === "CANCELLED" || + status === "COMPLETED" + ) { + return null; + } + + if (status === "CHANGES_REQUESTED") { + return ( + + {booking.latestChangeRequestNote && ( +

    + {booking.latestChangeRequestNote} +

    + )} +
    + ); + } + + if (["DRAFT", "PENDING_CONSOLIDATION", "CONSOLIDATED"].includes(status)) { + return ( + + ); + } + + return ( +
    + + + + + {status === "FULLY_EXECUTED" && paymentCurrency === "USD" && ( + + { + const file = e.target.files?.[0]; + if (file) mutations.submitPaymentProof.mutate(file); + }} + /> +
    + + +
    +
    + )} + + {status === "CONTRACT_READY" && ( + + + + )} +
    + ); +} + +function PanelShell({ + title, + description, + children, + muted, +}: { + title: string; + description: string; + children: React.ReactNode; + muted?: boolean; +}) { + return ( +
    +
    +
    + +
    +
    +

    {title}

    +

    {description}

    +
    +
    +
    {children}
    +
    + ); +} diff --git a/apps/edr-freight-web/backoffice/src/components/bookings/BookingConfirmDialog.tsx b/apps/edr-freight-web/backoffice/src/components/bookings/BookingConfirmDialog.tsx new file mode 100644 index 000000000..183995a65 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/bookings/BookingConfirmDialog.tsx @@ -0,0 +1,134 @@ +import { Loader2 } from "lucide-react"; + +import type { BookingActionDef } from "@/features/bookings/booking-actions.config"; +import { cn } from "@/lib/utils"; +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + Textarea, +} from "@edr/ui-common"; + +interface BookingConfirmDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + action: BookingActionDef | null; + reference?: string; + inputValue: string; + onInputChange: (value: string) => void; + onConfirm: () => void; + isPending: boolean; + confirmDisabled?: boolean; + extra?: React.ReactNode; +} + +export function BookingConfirmDialog({ + open, + onOpenChange, + action, + reference, + inputValue, + onInputChange, + onConfirm, + isPending, + confirmDisabled = false, + extra, +}: BookingConfirmDialogProps) { + if (!action || !action.confirmTitle) return null; + + const Icon = action.icon; + const needsInput = Boolean(action.input); + const inputMissing = needsInput && !inputValue.trim(); + const isDestructive = action.variant === "destructive"; + + return ( + + +
    + +
    +
    + +
    +
    + + {action.confirmTitle} + + {reference && ( +

    + {reference} +

    + )} +
    +
    + + {action.confirmDescription} + +
    +
    + +
    + {needsInput && ( +
    + +