From 3443b7964464eec69a0ddd4a7dfd1ee7712bd432 Mon Sep 17 00:00:00 2001 From: Marshal Date: Thu, 9 Jul 2026 21:13:07 +0000 Subject: [PATCH] make a contrat template --- apps/edr-freight-api/src/app.module.ts | 2 + .../src/contracts/contract-article.util.ts | 63 ++ .../contract-document-view-model.builder.ts | 30 +- .../contract-dynamic-template.spec.ts | 151 +++ .../contracts/contract-renderer.service.ts | 36 + .../contracts/contract-view-model.builder.ts | 16 + .../templates/_partials/dynamic_articles.hbs | 23 + .../contracts/templates/_partials/styles.hbs | 227 ++++- .../src/contracts/templates/edr-dynamic.hbs | 184 ++++ .../2090000000000-CreateContractTemplates.ts | 58 ++ .../contract-templates.controller.ts | 97 ++ .../contract-templates.module.ts | 21 + .../contract-templates.repository.ts | 31 + .../contract-templates.service.spec.ts | 66 ++ .../contract-templates.service.ts | 276 ++++++ .../dto/contract-template.dto.ts | 134 +++ .../entities/contract-template.entity.ts | 77 ++ .../contracts/contract-transition.service.ts | 11 + .../src/modules/contracts/contracts.module.ts | 4 + .../seed/data/contract-template-defaults.ts | 873 ++++++++++++++++++ apps/edr-freight-web/backoffice/src/App.tsx | 25 + .../useContractTemplates.ts | 98 ++ .../ContractTemplateEditorPage.tsx | 468 ++++++++++ .../ContractTemplatesPage.tsx | 152 +++ .../TemplatePreviewModal.tsx | 49 + .../services/contract-templates.service.ts | 112 +++ 26 files changed, 3243 insertions(+), 41 deletions(-) create mode 100644 apps/edr-freight-api/src/contracts/contract-article.util.ts create mode 100644 apps/edr-freight-api/src/contracts/contract-dynamic-template.spec.ts create mode 100644 apps/edr-freight-api/src/contracts/templates/_partials/dynamic_articles.hbs create mode 100644 apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs create mode 100644 apps/edr-freight-api/src/migrations/2090000000000-CreateContractTemplates.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/contract-templates.module.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/contract-templates.repository.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.spec.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/dto/contract-template.dto.ts create mode 100644 apps/edr-freight-api/src/modules/contract-templates/entities/contract-template.entity.ts create mode 100644 apps/edr-freight-api/src/seed/data/contract-template-defaults.ts create mode 100644 apps/edr-freight-web/backoffice/src/hooks/contract-templates/useContractTemplates.ts create mode 100644 apps/edr-freight-web/backoffice/src/pages/contract_templates/ContractTemplateEditorPage.tsx create mode 100644 apps/edr-freight-web/backoffice/src/pages/contract_templates/ContractTemplatesPage.tsx create mode 100644 apps/edr-freight-web/backoffice/src/pages/contract_templates/TemplatePreviewModal.tsx create mode 100644 apps/edr-freight-web/backoffice/src/services/contract-templates.service.ts diff --git a/apps/edr-freight-api/src/app.module.ts b/apps/edr-freight-api/src/app.module.ts index 9561a7b73..afb214137 100644 --- a/apps/edr-freight-api/src/app.module.ts +++ b/apps/edr-freight-api/src/app.module.ts @@ -41,6 +41,7 @@ import { NotificationsModule } from "./modules/notifications/notifications.modul import { NotificationInboxModule } from "./modules/notification-inbox/notification-inbox.module"; import { FileUploadSettingsModule } from "./modules/file-upload-settings/file-upload-settings.module"; import { DropdownSettingsModule } from "./modules/dropdown-settings/dropdown-settings.module"; +import { ContractTemplatesModule } from "./modules/contract-templates/contract-templates.module"; import { OtpModule } from "./modules/otp/otp.module"; import { RuleEngineModule } from "./modules/rule-engine/rule-engine.module"; import { BackofficeModule } from "./modules/backoffice/backoffice.module"; @@ -158,6 +159,7 @@ import { LoggerMiddleware } from "./logger.middleware"; NotificationInboxModule, FileUploadSettingsModule, DropdownSettingsModule, + ContractTemplatesModule, OtpModule, RuleEngineModule, BackofficeModule, diff --git a/apps/edr-freight-api/src/contracts/contract-article.util.ts b/apps/edr-freight-api/src/contracts/contract-article.util.ts new file mode 100644 index 000000000..5f0c86a6c --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-article.util.ts @@ -0,0 +1,63 @@ +import Handlebars from 'handlebars'; + +/** One numbered clause of a dynamic article, with optional nested bullets. */ +export interface RenderedClause { + text: string; + bullets: string[]; +} + +/** A dynamic article ready for the Handlebars template. */ +export interface RenderedArticle { + number: number; + title: string; + /** Set (instead of clauses) when the body is a single plain paragraph. */ + paragraph?: string; + clauses: RenderedClause[]; +} + +/** + * Parse a template article body into clauses. Format: one clause per line; + * lines prefixed with "- " become bullets nested under the preceding clause. + * A body that reduces to a single clause without bullets renders as a plain + * paragraph rather than a numbered list of one. + */ +export function parseArticleBody(body: string): Pick { + const lines = (body ?? '') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + const clauses: RenderedClause[] = []; + for (const line of lines) { + if (line.startsWith('- ')) { + const bullet = line.slice(2).trim(); + if (clauses.length === 0) { + clauses.push({ text: bullet, bullets: [] }); + } else { + clauses[clauses.length - 1].bullets.push(bullet); + } + } else { + clauses.push({ text: line, bullets: [] }); + } + } + + if (clauses.length === 1 && clauses[0].bullets.length === 0) { + return { paragraph: clauses[0].text, clauses: [] }; + } + return { clauses }; +} + +/** + * Interpolate Handlebars placeholders ({{client.companyName}}, {{contractDate}}, + * …) inside admin-authored template text against the contract view model. + * Malformed placeholders must never break document generation — fall back to + * the raw text. + */ +export function interpolateTemplateText(text: string, context: unknown): string { + if (!text || !text.includes('{{')) return text ?? ''; + try { + return Handlebars.compile(text)(context); + } catch { + return text; + } +} diff --git a/apps/edr-freight-api/src/contracts/contract-document-view-model.builder.ts b/apps/edr-freight-api/src/contracts/contract-document-view-model.builder.ts index 05061ed9a..559415fd8 100644 --- a/apps/edr-freight-api/src/contracts/contract-document-view-model.builder.ts +++ b/apps/edr-freight-api/src/contracts/contract-document-view-model.builder.ts @@ -8,6 +8,7 @@ import { ContractSignerRole, } from '../modules/contracts/entities/contract-signature.entity'; import { ContractPricingBreakdown } from '../modules/contracts/contract-pricing.service'; +import { ContractTemplatesService } from '../modules/contract-templates/contract-templates.service'; import { ContractTemplateResolver } from './contract-template.resolver'; import { getTemplateMeta } from './contract-template.registry'; import { ContractViewModel } from './contract-view-model.builder'; @@ -74,6 +75,7 @@ export class ContractDocumentViewModelBuilder { constructor( private readonly contractsRepository: ContractsRepository, private readonly templateResolver: ContractTemplateResolver, + private readonly contractTemplates: ContractTemplatesService, ) {} async build( @@ -86,7 +88,32 @@ export class ContractDocumentViewModelBuilder { const templateKey = contract.contractTemplateKey ?? this.templateResolver.resolve(this.toResolverInput(contract)); - const template = getTemplateMeta(templateKey); + let template = getTemplateMeta(templateKey); + + // Prefer the admin-editable DB template matching the contract's + // direction/freight pair; fall back to the code-defined generic layout + // when none is active. + const dynamicSource = await this.contractTemplates.findActiveForContract( + contract.tradeDirection, + contract.freightType, + ); + const dynamicTemplate = dynamicSource + ? { + code: dynamicSource.code, + name: dynamicSource.name, + documentTitle: dynamicSource.documentTitle, + whereasClauses: dynamicSource.whereasClauses ?? [], + articles: dynamicSource.articles ?? [], + } + : undefined; + if (dynamicTemplate) { + template = { + ...template, + title: dynamicTemplate.name, + templateFile: 'edr-dynamic.hbs', + }; + } + const pricing = this.buildPricing(contract); const signatures = await this.loadSignatures(contractId); @@ -139,6 +166,7 @@ export class ContractDocumentViewModelBuilder { hasContractDocument: hasContractFile, hasCustomerSignature: hasCustomer, hasStaffSignature: hasStaff, + dynamicTemplate, }; return { contract, view }; diff --git a/apps/edr-freight-api/src/contracts/contract-dynamic-template.spec.ts b/apps/edr-freight-api/src/contracts/contract-dynamic-template.spec.ts new file mode 100644 index 000000000..032030243 --- /dev/null +++ b/apps/edr-freight-api/src/contracts/contract-dynamic-template.spec.ts @@ -0,0 +1,151 @@ +import { parseArticleBody, interpolateTemplateText } from './contract-article.util'; +import { ContractRendererService } from './contract-renderer.service'; +import { getTemplateMeta } from './contract-template.registry'; +import type { ContractViewModel } from './contract-view-model.builder'; + +describe('parseArticleBody', () => { + it('numbers each non-empty line as a clause', () => { + const parsed = parseArticleBody('First clause.\nSecond clause.\n\nThird clause.'); + expect(parsed.paragraph).toBeUndefined(); + expect(parsed.clauses.map((c) => c.text)).toEqual([ + 'First clause.', + 'Second clause.', + 'Third clause.', + ]); + }); + + it('nests "- " lines as bullets under the previous clause', () => { + const parsed = parseArticleBody('Rates are:\n- USD 10 per ton\n- USD 20 per wagon\nPayment in advance.'); + expect(parsed.clauses).toHaveLength(2); + expect(parsed.clauses[0].bullets).toEqual(['USD 10 per ton', 'USD 20 per wagon']); + expect(parsed.clauses[1].text).toBe('Payment in advance.'); + }); + + it('renders a single bare line as a paragraph', () => { + const parsed = parseArticleBody('This Agreement becomes effective when signed.'); + expect(parsed.paragraph).toBe('This Agreement becomes effective when signed.'); + expect(parsed.clauses).toEqual([]); + }); +}); + +describe('interpolateTemplateText', () => { + it('fills placeholders from the view model', () => { + expect( + interpolateTemplateText('Valid until August 31, {{contractYear}}.', { + contractYear: 2026, + }), + ).toBe('Valid until August 31, 2026.'); + }); + + it('falls back to raw text on malformed placeholders', () => { + expect(interpolateTemplateText('Broken {{#if}} tag', {})).toBe('Broken {{#if}} tag'); + }); +}); + +describe('dynamic template rendering (edr-dynamic.hbs)', () => { + const renderer = new ContractRendererService(); + renderer.onModuleInit(); + + function dynamicView(): ContractViewModel { + const meta = getTemplateMeta('IMP_BULK_USD_FORWARDING'); + return { + bookingId: 'test-id', + reference: 'EDR/CT/2026/0042', + status: 'CONTRACT_READY', + templateKey: 'IMP_BULK_USD_FORWARDING', + template: { ...meta, title: 'Bulk Import Contract', templateFile: 'edr-dynamic.hbs' }, + contractDate: '1 January 2026', + contractYear: 2026, + client: { + companyName: 'Abyssinia Trading PLC', + companyAddress: 'Bole Sub-city, Addis Ababa', + companyLocation: 'Ethiopia', + phone: '+251900000000', + email: 'test@example.com', + tinNumber: '1234567890', + vatNumber: 'VAT-001', + fanNumber: 'FAN-001', + businessLicense: 'BL-001', + }, + provider: { + name: 'Ethio-Djibouti Standard Gauge Railway Share Company', + address: 'Nifas Silk Lafto Sub City, Addis Ababa, Ethiopia', + phone: '+251 11 872 0000', + email: 'info@edr.gov.et', + tinNumber: '—', + }, + schedule: { + originLabel: 'Nagad', + destinationLabel: 'Galaan Multipurpose Port', + tradeDirection: 'IMPORT', + freightType: 'BULK', + serviceType: 'Rail + clearance', + scheduledDate: '—', + contractType: 'GENERAL', + cargoDescription: 'Steel billets', + totalWeightVgm: '—', + equipmentReturn: '—', + hazardousLabel: 'No', + firstMilePickupAddress: '—', + lastMileDeliveryAddress: '—', + }, + pricing: { + displayMode: 'UNIT_RATES', + unitRates: [ + { label: 'Rail transport', unitPrice: 59.4, unit: 'ton', currency: 'USD' }, + ], + currency: 'USD', + equipmentReturn: '—', + originLabel: 'Nagad', + destinationLabel: 'Galaan Multipurpose Port', + } as unknown as ContractViewModel['pricing'], + signatures: [], + canSignCustomer: false, + canSignStaff: false, + hasContractDocument: false, + hasCustomerSignature: false, + hasStaffSignature: false, + dynamicTemplate: { + code: 'IMPORT_BULK', + name: 'Bulk Import Contract', + documentTitle: 'Bulk Cargo Transportation and Customs Clearance Services', + whereasClauses: ['The Client has agreed to engage the Service Provider.'], + articles: [ + { + id: 'objective', + title: 'Objective of the Services', + body: 'Integrated logistics services including:\n- Rail transport to GMP\n- Customs clearance', + order: 1, + }, + { + id: 'duration', + title: 'Duration', + body: 'Valid until August 31, {{contractYear}}.', + order: 2, + }, + ], + }, + }; + } + + it('renders numbered dynamic articles with bullets and interpolation', () => { + const html = renderer.render(dynamicView()); + expect(html).toContain('Bulk Cargo Transportation and Customs Clearance Services'); + expect(html).toContain('Article 1'); + expect(html).toContain('Objective of the Services'); + expect(html).toContain('Rail transport to GMP'); + expect(html).toContain('Valid until August 31, 2026.'); + expect(html).toContain('Abyssinia Trading PLC'); + expect(html).toContain('Annex A — Commercial Schedule'); + // Greenish theme marker from styles.hbs + expect(html).toContain('#1b9e7a'); + }); + + it('keeps the generic layout when no dynamic template is attached', () => { + const view = dynamicView(); + delete view.dynamicTemplate; + view.template = getTemplateMeta('IMP_BULK_USD_FORWARDING'); + const html = renderer.render(view); + expect(html).toContain('Article 5: Contract Price'); + }); +}); diff --git a/apps/edr-freight-api/src/contracts/contract-renderer.service.ts b/apps/edr-freight-api/src/contracts/contract-renderer.service.ts index dd539df25..7b3301c87 100644 --- a/apps/edr-freight-api/src/contracts/contract-renderer.service.ts +++ b/apps/edr-freight-api/src/contracts/contract-renderer.service.ts @@ -3,6 +3,11 @@ import * as fs from 'fs'; import * as path from 'path'; import Handlebars from 'handlebars'; +import { + interpolateTemplateText, + parseArticleBody, + RenderedArticle, +} from './contract-article.util'; import { ContractViewModel } from './contract-view-model.builder'; @Injectable() @@ -31,9 +36,40 @@ export class ContractRendererService implements OnModuleInit { return template({ ...view, paymentArticle: view.pricing.currency === 'ETB' ? 'ETB' : 'USD', + ...this.buildDynamicSections(view), }); } + /** + * Turn the DB-backed dynamic template (when present) into render-ready data: + * interpolate placeholders against the view model, then parse each article + * body into numbered clauses with nested bullets. + */ + private buildDynamicSections(view: ContractViewModel): { + dynamicDocumentTitle?: string; + dynamicWhereas?: string[]; + dynamicArticles?: RenderedArticle[]; + } { + const dyn = view.dynamicTemplate; + if (!dyn || dyn.articles.length === 0) return {}; + + const articles = [...dyn.articles] + .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) + .map((article, index) => ({ + number: index + 1, + title: interpolateTemplateText(article.title, view), + ...parseArticleBody(interpolateTemplateText(article.body, view)), + })); + + return { + dynamicDocumentTitle: interpolateTemplateText(dyn.documentTitle, view), + dynamicWhereas: dyn.whereasClauses.map((clause) => + interpolateTemplateText(clause, view), + ), + dynamicArticles: articles, + }; + } + private getCompiled(fileName: string): Handlebars.TemplateDelegate { const cached = this.compiled.get(fileName); if (cached) return cached; 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 index 41a2f3b44..d90b8e709 100644 --- a/apps/edr-freight-api/src/contracts/contract-view-model.builder.ts +++ b/apps/edr-freight-api/src/contracts/contract-view-model.builder.ts @@ -17,6 +17,21 @@ export interface ContractSignatureView { signatureImageUrl?: string | null; } +/** + * DB-backed contract template (freight.contract_templates) attached to the + * view model when an active template matches the contract's direction/freight + * pair. The renderer turns its articles into numbered clauses and switches to + * the dedicated edr-dynamic.hbs layout; absent, the legacy generic layout with + * code-defined clause packs is used. + */ +export interface ContractDynamicTemplateView { + code: string; + name: string; + documentTitle: string; + whereasClauses: string[]; + articles: Array<{ id: string; title: string; body: string; order: number }>; +} + export interface ContractViewModel { bookingId: string; reference: string; @@ -65,6 +80,7 @@ export interface ContractViewModel { hasContractDocument: boolean; hasCustomerSignature: boolean; hasStaffSignature: boolean; + dynamicTemplate?: ContractDynamicTemplateView; } @Injectable() diff --git a/apps/edr-freight-api/src/contracts/templates/_partials/dynamic_articles.hbs b/apps/edr-freight-api/src/contracts/templates/_partials/dynamic_articles.hbs new file mode 100644 index 000000000..717fbde8f --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/_partials/dynamic_articles.hbs @@ -0,0 +1,23 @@ +{{#each dynamicArticles}} +
+

Article {{number}}{{title}}

+ {{#if paragraph}} +

{{paragraph}}

+ {{else}} +
    + {{#each clauses}} +
  1. + {{text}} + {{#if bullets.length}} +
      + {{#each bullets}} +
    • {{this}}
    • + {{/each}} +
    + {{/if}} +
  2. + {{/each}} +
+ {{/if}} +
+{{/each}} diff --git a/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs b/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs index 43a5495ec..0207ff9fb 100644 --- a/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs +++ b/apps/edr-freight-api/src/contracts/templates/_partials/styles.hbs @@ -4,11 +4,11 @@ body { margin: 0; - background: #f5f7fb; - color: #111827; + background: #f3f8f5; + color: #16241d; font-family: "Times New Roman", Times, serif; font-size: 10.5pt; - line-height: 1.48; + line-height: 1.5; } .contract { @@ -21,25 +21,28 @@ h1, h2, h3, p { margin-top: 0; } h1 { - color: #0f2742; - font-size: 18pt; - line-height: 1.25; + color: #0a3d2e; + font-size: 17pt; + letter-spacing: 0.02em; + line-height: 1.3; margin-bottom: 10px; text-align: center; text-transform: uppercase; } h2 { - border-bottom: 1.5px solid #1e3a5f; - color: #1e3a5f; - font-size: 12pt; - letter-spacing: 0.03em; - margin: 18px 0 10px; + border-bottom: 1.5px solid #1b9e7a; + color: #0e5b45; + font-family: Arial, sans-serif; + font-size: 11.5pt; + letter-spacing: 0.04em; + margin: 20px 0 10px; padding-bottom: 5px; text-transform: uppercase; } h3 { - color: #0f2742; - font-size: 10.8pt; + color: #0a3d2e; + font-family: Arial, sans-serif; + font-size: 10.5pt; margin: 12px 0 6px; } p { margin-bottom: 8px; } @@ -52,16 +55,17 @@ page-break-inside: avoid; } + /* ── Brand header ─────────────────────────────────────────────────────── */ .brand-row { align-items: center; - border-bottom: 3px solid #1e3a5f; + border-bottom: 3px double #1b9e7a; display: flex; gap: 14px; padding-bottom: 14px; } .logo-mark { align-items: center; - background: #1e3a5f; + background: linear-gradient(135deg, #0e5b45 0%, #1b9e7a 100%); border-radius: 8px; color: #fff; display: flex; @@ -74,7 +78,7 @@ width: 72px; } .kicker { - color: #1e3a5f; + color: #0e5b45; font-family: Arial, sans-serif; font-size: 10pt; font-weight: 700; @@ -83,36 +87,74 @@ text-transform: uppercase; } .muted { - color: #6b7280; + color: #5c6f66; font-family: Arial, sans-serif; font-size: 9pt; margin: 0; } + .muted-note { + color: #5c6f66; + font-size: 9.5pt; + } + /* ── Cover page ───────────────────────────────────────────────────────── */ .cover { + display: flex; + flex-direction: column; min-height: 255mm; position: relative; } .cover-title { - margin: 54mm 0 34mm; + margin: 34mm 0 22mm; text-align: center; } + .cover-rule { + background: #1b9e7a; + height: 2px; + margin: 14px auto; + width: 46mm; + } .document-label { - color: #6b7280; + color: #1b9e7a; font-family: Arial, sans-serif; - font-size: 10pt; + font-size: 11pt; font-weight: 700; - letter-spacing: 0.12em; - margin-bottom: 10px; + letter-spacing: 0.18em; + margin-bottom: 6px; text-transform: uppercase; } + .cover-for, + .cover-between { + color: #5c6f66; + font-family: Arial, sans-serif; + font-size: 9.5pt; + font-style: italic; + margin: 10px 0 6px; + } + .cover-party { + color: #0a3d2e; + font-family: Arial, sans-serif; + font-size: 12pt; + font-weight: 700; + margin: 4px 0; + } .summary-line { - color: #374151; + color: #38493f; font-family: Arial, sans-serif; font-size: 9.5pt; margin-top: 12px; } + .cover-year { + color: #0e5b45; + font-family: Arial, sans-serif; + font-size: 13pt; + font-weight: 700; + letter-spacing: 0.1em; + margin-top: auto; + text-align: right; + } + /* ── Tables ───────────────────────────────────────────────────────────── */ table { border-collapse: collapse; width: 100%; @@ -129,7 +171,7 @@ .details-table td, .schedule th, .schedule td { - border: 1px solid #cbd5e1; + border: 1px solid #c9e4d9; padding: 7px 8px; text-align: left; vertical-align: top; @@ -137,35 +179,46 @@ .meta-grid th, .details-table th, .schedule th { - background: #eef4fb; - color: #1e3a5f; + background: #e9f6f0; + color: #0e5b45; font-family: Arial, sans-serif; font-size: 8.5pt; text-transform: uppercase; } - .schedule tbody tr:nth-child(even) td { background: #f8fafc; } + .schedule tbody tr:nth-child(even) td { background: #f5faf8; } .total-row td { - background: #e8f0f8 !important; - color: #0f2742; + background: #ddf2e9 !important; + color: #0a3d2e; font-weight: 700; } + /* ── Parties ──────────────────────────────────────────────────────────── */ .lead { - color: #374151; + color: #38493f; font-size: 10.5pt; } + .between-label { + color: #0e5b45; + font-family: Arial, sans-serif; + font-size: 9.5pt; + font-weight: 700; + letter-spacing: 0.08em; + margin: 10px 0 4px; + text-transform: uppercase; + } .party-grid { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; + margin-top: 12px; } .party-card { - border: 1px solid #cbd5e1; + border: 1px solid #c9e4d9; border-radius: 8px; padding: 12px; } .party-card h3 { - background: #1e3a5f; + background: #0e5b45; border-radius: 5px; color: #fff; font-family: Arial, sans-serif; @@ -175,7 +228,7 @@ text-transform: uppercase; } .party-name { - color: #0f2742; + color: #0a3d2e; font-weight: 700; margin-bottom: 8px; } @@ -185,7 +238,7 @@ margin: 0; } dt { - color: #475569; + color: #47594f; font-family: Arial, sans-serif; font-size: 8.5pt; font-weight: 700; @@ -196,6 +249,81 @@ padding: 2px 0; } + /* ── Recitals ─────────────────────────────────────────────────────────── */ + .whereas-label { + color: #0e5b45; + font-family: Arial, sans-serif; + font-size: 9pt; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; + } + .now-therefore { + color: #0a3d2e; + font-weight: 700; + margin-top: 10px; + } + + /* ── Dynamic articles ─────────────────────────────────────────────────── */ + .article-heading { + align-items: baseline; + display: flex; + gap: 10px; + } + .article-no { + color: #1b9e7a; + font-family: Arial, sans-serif; + font-size: 9.5pt; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; + white-space: nowrap; + } + .article-name { color: #0e5b45; } + .article-paragraph { margin: 4px 0 0; } + ol.clauses { + counter-reset: clause; + list-style: none; + margin: 6px 0 0; + padding-left: 0; + } + ol.clauses > li { + counter-increment: clause; + margin-bottom: 6px; + padding-left: 24px; + position: relative; + text-align: justify; + } + ol.clauses > li::before { + color: #0e5b45; + content: counter(clause) "."; + font-family: Arial, sans-serif; + font-size: 9.5pt; + font-weight: 700; + left: 0; + position: absolute; + top: 1px; + } + ul.clause-bullets { + margin: 5px 0 2px; + padding-left: 16px; + } + ul.clause-bullets > li { + list-style: none; + margin-bottom: 3px; + padding-left: 12px; + position: relative; + } + ul.clause-bullets > li::before { + color: #1b9e7a; + content: "▪"; + font-size: 8pt; + left: 0; + position: absolute; + top: 1px; + } + + /* ── Signatures ───────────────────────────────────────────────────────── */ .signatures { display: grid; gap: 18px; @@ -204,13 +332,13 @@ page-break-inside: avoid; } .sig-block { - border: 1.5px solid #1e3a5f; + border: 1.5px solid #1b9e7a; border-radius: 8px; min-height: 96mm; padding: 12px; } .sig-title { - color: #1e3a5f; + color: #0e5b45; font-family: Arial, sans-serif; font-size: 9pt; font-weight: 700; @@ -219,7 +347,7 @@ } .sig-image-box { align-items: center; - border: 1px dashed #94a3b8; + border: 1px dashed #7fbfa9; display: flex; height: 28mm; justify-content: center; @@ -231,21 +359,40 @@ max-width: 70mm; } .sig-placeholder { - color: #94a3b8; + color: #7fbfa9; font-family: Arial, sans-serif; font-size: 8.5pt; } .sig-line { - border-top: 1px solid #111827; + border-top: 1px solid #16241d; margin-top: 16px; padding-top: 5px; } .sig-meta { - color: #475569; + color: #47594f; font-size: 9pt; margin: 4px 0; } + /* ── Witnesses ────────────────────────────────────────────────────────── */ + .witnesses { margin-top: 20px; } + .witness-table { + font-size: 9.5pt; + margin-top: 6px; + } + .witness-table th, + .witness-table td { + border-bottom: 1px solid #c9e4d9; + padding: 9px 8px; + text-align: left; + } + .witness-table th { + color: #0e5b45; + font-family: Arial, sans-serif; + font-size: 8.5pt; + text-transform: uppercase; + } + @media print { body { background: #fff; } .contract { diff --git a/apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs b/apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs new file mode 100644 index 000000000..4ba35ea3b --- /dev/null +++ b/apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs @@ -0,0 +1,184 @@ + + + + + {{dynamicDocumentTitle}} — {{reference}} + {{> styles}} + + +
+ + {{!-- ─────────────────────────── Cover page ─────────────────────────── --}} +
+
+
EDR
+
+

Ethio-Djibouti Standard Gauge Railway Share Company

+

Freight Transport Services

+
+
+ +
+

Contract Agreement

+
+

for

+

{{dynamicDocumentTitle}}

+

between

+

Ethio-Djibouti Standard Gauge Railway Share Company

+

and

+

{{client.companyName}}

+
+
+ + + + + + + + + + + + + + +
Contract Ref No.{{reference}}Contract Date{{contractDate}}
Trade Direction{{schedule.tradeDirection}}Freight Type{{schedule.freightType}}
+ +

{{contractYear}}

+
+ + {{!-- ──────────────────────────── Preamble ──────────────────────────── --}} +
+

Parties to the Agreement

+

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

+

Between

+

+ Ethio-Djibouti Standard Gauge Railway Share Company (EDR), a share company + incorporated under the laws of the Federal Democratic Republic of Ethiopia (FDRE), having its + principal place of business at {{provider.address}} (hereinafter referred to as the + "Service Provider"); +

+

And

+

+ {{client.companyName}}, an organization incorporated under the laws of the + Federal Democratic Republic of Ethiopia (FDRE), having its principal place of business at + {{client.companyAddress}} (hereinafter referred to as the "Client"). +

+ +
+
+

Service Provider

+

{{provider.name}}

+
+
Address
{{provider.address}}
+
Phone
{{provider.phone}}
+
Email
{{provider.email}}
+
TIN
{{provider.tinNumber}}
+
+
+
+

Client

+

{{client.companyName}}

+
+
Address
{{client.companyAddress}}
+
Location
{{client.companyLocation}}
+
Phone
{{client.phone}}
+
Email
{{client.email}}
+
TIN
{{client.tinNumber}}
+
VAT
{{client.vatNumber}}
+
Business license
{{client.businessLicense}}
+
+
+
+
+ + {{#if dynamicWhereas.length}} +
+

Recitals

+ {{#each dynamicWhereas}} +

Whereas {{this}}

+ {{/each}} +

Now, therefore, the parties agree as follows:

+
+ {{/if}} + + {{!-- ──────────────────────── Dynamic articles ──────────────────────── --}} + {{> dynamic_articles}} + + {{!-- ─────────────────── Commercial schedule (annex) ─────────────────── --}} +
+

Annex A — Commercial Schedule

+ + + + + + + + + + + + + + + + + + + + + +
Route{{schedule.originLabel}} → {{schedule.destinationLabel}}Service type{{schedule.serviceType}}
Cargo{{schedule.cargoDescription}}Hazardous cargo{{schedule.hazardousLabel}}
Equipment return{{schedule.equipmentReturn}}Payment currency{{paymentArticle}}
+ + {{#if pricing.unitRates.length}} +

Agreed Unit Rates

+

+ The rates below are the frozen unit prices applicable to this contract. Quantities and resulting + totals are determined per shipment at booking time. +

+ + + + + + {{#each pricing.unitRates}} + + + + + {{/each}} + +
ItemUnit price
{{label}}{{currency}} {{unitPrice}} / {{unit}}
+ {{/if}} +
+ + {{!-- ────────────────────────── Signatures ───────────────────────────── --}} +
+

Execution

+

+ In witness whereof, the parties hereto have caused this contract to be signed in their respective + names as of the day and year first above written. The signatories confirm that they are fully + authorized to sign and execute this Contract Agreement. +

+ {{> signatures_block}} + +
+

Witnesses

+ + + + + + + + +
NameSignatureDate
1.
2.
+
+
+
+ + diff --git a/apps/edr-freight-api/src/migrations/2090000000000-CreateContractTemplates.ts b/apps/edr-freight-api/src/migrations/2090000000000-CreateContractTemplates.ts new file mode 100644 index 000000000..a553319cc --- /dev/null +++ b/apps/edr-freight-api/src/migrations/2090000000000-CreateContractTemplates.ts @@ -0,0 +1,58 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +import { CONTRACT_TEMPLATE_DEFAULTS } from '../seed/data/contract-template-defaults'; + +/** + * Creates freight.contract_templates — the six editable contract document + * templates (direction × freight type) whose dynamic articles drive the + * generated contract PDF — and seeds them from the EDR reference contract + * documents. Seeding is idempotent (ON CONFLICT (code) DO NOTHING) so admin + * edits are never overwritten by redeploys. + */ +export class CreateContractTemplates2090000000000 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE IF NOT EXISTS freight.contract_templates ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + code VARCHAR(40) NOT NULL, + name VARCHAR(200) NOT NULL, + description TEXT, + document_title VARCHAR(300) NOT NULL, + whereas_clauses JSONB NOT NULL DEFAULT '[]', + articles JSONB NOT NULL DEFAULT '[]', + is_active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + deleted_at TIMESTAMPTZ, + CONSTRAINT uq_contract_templates_code UNIQUE (code) + ); + `); + + for (const seed of CONTRACT_TEMPLATE_DEFAULTS) { + const articles = seed.articles.map((article, index) => ({ + ...article, + order: index + 1, + })); + await queryRunner.query( + ` + INSERT INTO freight.contract_templates + (code, name, description, document_title, whereas_clauses, articles) + VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb) + ON CONFLICT (code) DO NOTHING; + `, + [ + seed.code, + seed.name, + seed.description, + seed.documentTitle, + JSON.stringify(seed.whereasClauses), + JSON.stringify(articles), + ], + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE IF EXISTS freight.contract_templates;`); + } +} diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts new file mode 100644 index 000000000..8cf1c5671 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts @@ -0,0 +1,97 @@ +import { + Body, + Controller, + Delete, + Get, + Param, + Patch, + Post, + Put, +} from "@nestjs/common"; +import { ApiOperation, ApiTags } from "@nestjs/swagger"; + +import { FreightAdmin } from "../../common/booking-guards"; +import { ContractTemplatesService } from "./contract-templates.service"; +import { + CreateArticleDto, + PreviewContractTemplateDto, + ReplaceArticlesDto, + UpdateArticleDto, + UpdateContractTemplateDto, +} from "./dto/contract-template.dto"; + +@ApiTags("contract-templates") +@Controller("contract-templates") +export class ContractTemplatesController { + constructor(private readonly service: ContractTemplatesService) {} + + // Reads stay open to authenticated staff (the backoffice Templates tab); + // writes are admin-guarded like other freight configuration resources. + + @Get() + @ApiOperation({ summary: "List the six contract document templates" }) + list() { + return this.service.list(); + } + + @Get(":code") + @ApiOperation({ summary: "Get one contract template by code" }) + getByCode(@Param("code") code: string) { + return this.service.getByCode(code); + } + + @Patch(":code") + @FreightAdmin() + @ApiOperation({ summary: "Update template metadata (name, title, recitals, active flag)" }) + update(@Param("code") code: string, @Body() dto: UpdateContractTemplateDto) { + return this.service.update(code, dto); + } + + @Post(":code/preview") + @ApiOperation({ + summary: "Render an HTML preview of the template against mock contract data", + }) + preview( + @Param("code") code: string, + @Body() dto: PreviewContractTemplateDto, + ) { + return this.service.preview(code, dto); + } + + /* ------------------------- article routes ------------------------- */ + + @Put(":code/articles") + @FreightAdmin() + @ApiOperation({ summary: "Replace the full ordered article list (used for reorder)" }) + replaceArticles(@Param("code") code: string, @Body() dto: ReplaceArticlesDto) { + return this.service.replaceArticles(code, dto.articles); + } + + @Post(":code/articles") + @FreightAdmin() + @ApiOperation({ summary: "Add an article to the template" }) + addArticle(@Param("code") code: string, @Body() dto: CreateArticleDto) { + return this.service.addArticle(code, dto); + } + + @Patch(":code/articles/:articleId") + @FreightAdmin() + @ApiOperation({ summary: "Update an article's title or body" }) + updateArticle( + @Param("code") code: string, + @Param("articleId") articleId: string, + @Body() dto: UpdateArticleDto, + ) { + return this.service.updateArticle(code, articleId, dto); + } + + @Delete(":code/articles/:articleId") + @FreightAdmin() + @ApiOperation({ summary: "Remove an article from the template" }) + removeArticle( + @Param("code") code: string, + @Param("articleId") articleId: string, + ) { + return this.service.removeArticle(code, articleId); + } +} diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.module.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.module.ts new file mode 100644 index 000000000..d2a658ca8 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.module.ts @@ -0,0 +1,21 @@ +import { Module } from "@nestjs/common"; +import { TypeOrmModule } from "@nestjs/typeorm"; + +import { ContractRendererService } from "../../contracts/contract-renderer.service"; +import { ContractTemplatesController } from "./contract-templates.controller"; +import { ContractTemplatesRepository } from "./contract-templates.repository"; +import { ContractTemplatesService } from "./contract-templates.service"; +import { ContractTemplate } from "./entities/contract-template.entity"; + +@Module({ + imports: [TypeOrmModule.forFeature([ContractTemplate])], + controllers: [ContractTemplatesController], + providers: [ + ContractTemplatesRepository, + ContractTemplatesService, + // Stateless Handlebars renderer reused from src/contracts for previews. + ContractRendererService, + ], + exports: [ContractTemplatesService], +}) +export class ContractTemplatesModule {} diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.repository.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.repository.ts new file mode 100644 index 000000000..2f4fb0117 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.repository.ts @@ -0,0 +1,31 @@ +import { BaseRepository } from "@edr/api-common"; +import { Injectable } from "@nestjs/common"; +import { InjectRepository } from "@nestjs/typeorm"; +import { Repository } from "typeorm"; + +import { + ContractTemplate, + ContractTemplateCode, +} from "./entities/contract-template.entity"; + +@Injectable() +export class ContractTemplatesRepository extends BaseRepository { + constructor( + @InjectRepository(ContractTemplate) + repository: Repository, + ) { + super(repository); + } + + findByCode(code: ContractTemplateCode): Promise { + return this.repository.findOne({ where: { code } }); + } + + override findAll(): Promise { + return this.repository.find({ order: { code: "ASC" } }); + } + + async saveTemplate(template: ContractTemplate): Promise { + return this.repository.save(template); + } +} diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.spec.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.spec.ts new file mode 100644 index 000000000..0478db102 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.spec.ts @@ -0,0 +1,66 @@ +import { ContractRendererService } from "../../contracts/contract-renderer.service"; +import { CONTRACT_TEMPLATE_DEFAULTS } from "../../seed/data/contract-template-defaults"; +import { ContractTemplatesService } from "./contract-templates.service"; +import { ContractTemplatesRepository } from "./contract-templates.repository"; +import { + ContractTemplate, + contractTemplateCodeFor, +} from "./entities/contract-template.entity"; + +function seededTemplate(code: string): ContractTemplate { + const seed = CONTRACT_TEMPLATE_DEFAULTS.find((t) => t.code === code)!; + return { + id: "00000000-0000-0000-0000-000000000001", + code: seed.code, + name: seed.name, + description: seed.description, + documentTitle: seed.documentTitle, + whereasClauses: seed.whereasClauses, + articles: seed.articles.map((article, index) => ({ ...article, order: index + 1 })), + isActive: true, + createdAt: new Date(), + updatedAt: new Date(), + deletedAt: null, + } as ContractTemplate; +} + +describe("contractTemplateCodeFor", () => { + it("maps every direction/freight pair to one of the six codes", () => { + expect(contractTemplateCodeFor("IMPORT", "BULK")).toBe("IMPORT_BULK"); + expect(contractTemplateCodeFor("EXPORT", "CONTAINER")).toBe("EXPORT_CONTAINER"); + expect(contractTemplateCodeFor("DOMESTIC", "CONTAINER")).toBe("INTERCITY_CONTAINER"); + expect(contractTemplateCodeFor("DOMESTIC", "BULK")).toBe("INTERCITY_BULK"); + expect(contractTemplateCodeFor(null, null)).toBe("INTERCITY_CONTAINER"); + }); +}); + +describe("ContractTemplatesService.preview", () => { + const renderer = new ContractRendererService(); + renderer.onModuleInit(); + + const repository = { + findByCode: jest.fn((code: string) => Promise.resolve(seededTemplate(code))), + } as unknown as ContractTemplatesRepository; + + const service = new ContractTemplatesService(repository, renderer); + + it.each(CONTRACT_TEMPLATE_DEFAULTS.map((t) => [t.code] as const))( + "renders a complete mock preview for %s", + async (code) => { + const { html } = await service.preview(code); + expect(html).toContain("Article 1"); + expect(html).toContain("Article 13"); + expect(html).toContain("Abyssinia Trading PLC"); + expect(html).toContain("Annex A — Commercial Schedule"); + // No unrendered handlebars placeholders may leak into the document. + expect(html).not.toContain("{{"); + // Greenish theme applied. + expect(html).toContain("#1b9e7a"); + }, + ); + + it("interpolates {{contractYear}} inside seeded article bodies", async () => { + const { html } = await service.preview("IMPORT_BULK"); + expect(html).toContain(`August 31, ${new Date().getFullYear()}`); + }); +}); diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.ts new file mode 100644 index 000000000..d2aea9bc7 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.service.ts @@ -0,0 +1,276 @@ +import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common"; +import { randomUUID } from "node:crypto"; + +import { ContractRendererService } from "../../contracts/contract-renderer.service"; +import { getTemplateMeta } from "../../contracts/contract-template.registry"; +import { + ContractDynamicTemplateView, + ContractViewModel, +} from "../../contracts/contract-view-model.builder"; +import { ContractTemplatesRepository } from "./contract-templates.repository"; +import { + CreateArticleDto, + PreviewContractTemplateDto, + ReplaceArticleDto, + UpdateArticleDto, + UpdateContractTemplateDto, +} from "./dto/contract-template.dto"; +import { + CONTRACT_TEMPLATE_CODES, + ContractTemplate, + ContractTemplateArticle, + ContractTemplateCode, + contractTemplateCodeFor, +} from "./entities/contract-template.entity"; + +/** Registry keys used to derive labels for the mock preview per template code. */ +const PREVIEW_TEMPLATE_KEYS: Record = { + IMPORT_BULK: "IMP_BULK_USD_FORWARDING", + EXPORT_BULK: "EXP_BULK_USD_TRANSPORT_ONLY", + INTERCITY_BULK: "DOM_BULK_USD_TRANSPORT_ONLY", + IMPORT_CONTAINER: "IMP_CON_USD_TRANSPORT_ONLY", + EXPORT_CONTAINER: "EXP_CON_USD_FORWARDING", + INTERCITY_CONTAINER: "DOM_CON_USD_TRANSPORT_ONLY", +}; + +@Injectable() +export class ContractTemplatesService { + constructor( + private readonly repository: ContractTemplatesRepository, + private readonly renderer: ContractRendererService, + ) {} + + async list(): Promise { + const templates = await this.repository.findAll(); + const rank = new Map(CONTRACT_TEMPLATE_CODES.map((code, i) => [code, i] as const)); + return templates.sort( + (a, b) => (rank.get(a.code) ?? 99) - (rank.get(b.code) ?? 99), + ); + } + + async getByCode(code: string): Promise { + const template = await this.repository.findByCode(this.assertCode(code)); + if (!template) { + throw new NotFoundException(`Contract template ${code} not found`); + } + return template; + } + + /** + * The active template used when generating a contract document for the given + * direction/freight pair; null when missing or deactivated (the renderer then + * falls back to the built-in generic layout). + */ + async findActiveForContract( + tradeDirection?: string | null, + freightType?: string | null, + ): Promise { + const code = contractTemplateCodeFor(tradeDirection, freightType); + const template = await this.repository.findByCode(code); + return template?.isActive ? template : null; + } + + async update(code: string, dto: UpdateContractTemplateDto): Promise { + const template = await this.getByCode(code); + if (dto.name !== undefined) template.name = dto.name; + if (dto.description !== undefined) template.description = dto.description; + if (dto.documentTitle !== undefined) template.documentTitle = dto.documentTitle; + if (dto.whereasClauses !== undefined) template.whereasClauses = dto.whereasClauses; + if (dto.isActive !== undefined) template.isActive = dto.isActive; + return this.repository.saveTemplate(template); + } + + async addArticle(code: string, dto: CreateArticleDto): Promise { + const template = await this.getByCode(code); + const articles = this.sorted(template.articles); + const article: ContractTemplateArticle = { + id: randomUUID(), + title: dto.title, + body: dto.body, + order: 0, + }; + const index = + dto.position && dto.position <= articles.length ? dto.position - 1 : articles.length; + articles.splice(index, 0, article); + template.articles = this.renumber(articles); + return this.repository.saveTemplate(template); + } + + async updateArticle( + code: string, + articleId: string, + dto: UpdateArticleDto, + ): Promise { + const template = await this.getByCode(code); + const article = template.articles.find((item) => item.id === articleId); + if (!article) { + throw new NotFoundException(`Article ${articleId} not found on template ${code}`); + } + if (dto.title !== undefined) article.title = dto.title; + if (dto.body !== undefined) article.body = dto.body; + template.articles = this.renumber(this.sorted(template.articles)); + return this.repository.saveTemplate(template); + } + + async removeArticle(code: string, articleId: string): Promise { + const template = await this.getByCode(code); + const remaining = template.articles.filter((item) => item.id !== articleId); + if (remaining.length === template.articles.length) { + throw new NotFoundException(`Article ${articleId} not found on template ${code}`); + } + template.articles = this.renumber(this.sorted(remaining)); + return this.repository.saveTemplate(template); + } + + /** Replace the full ordered article list (also how the editor reorders). */ + async replaceArticles( + code: string, + articles: ReplaceArticleDto[], + ): Promise { + const template = await this.getByCode(code); + template.articles = this.renumber( + articles.map((item) => ({ + id: item.id ?? randomUUID(), + title: item.title, + body: item.body, + order: 0, + })), + ); + return this.repository.saveTemplate(template); + } + + /** + * Render the template against a representative mock contract so admins can + * see the final document without touching a real contract. Draft overrides + * allow previewing unsaved editor state. + */ + async preview( + code: string, + overrides?: PreviewContractTemplateDto, + ): Promise<{ html: string }> { + const template = await this.getByCode(code); + + const dynamicTemplate: ContractDynamicTemplateView = { + code: template.code, + name: overrides?.name ?? template.name, + documentTitle: overrides?.documentTitle ?? template.documentTitle, + whereasClauses: overrides?.whereasClauses ?? template.whereasClauses, + articles: overrides?.articles + ? overrides.articles.map((item, index) => ({ + id: item.id ?? randomUUID(), + title: item.title, + body: item.body, + order: index + 1, + })) + : this.sorted(template.articles), + }; + + const view = this.buildMockView(template.code, dynamicTemplate); + return { html: this.renderer.render(view) }; + } + + private buildMockView( + code: ContractTemplateCode, + dynamicTemplate: ContractDynamicTemplateView, + ): ContractViewModel { + const meta = getTemplateMeta(PREVIEW_TEMPLATE_KEYS[code]); + const isBulk = code.endsWith("_BULK"); + const now = new Date(); + + const unitRates = isBulk + ? [ + { label: "Rail transport — per metric ton", unitPrice: 59.4, unit: "ton", currency: "USD" }, + { label: "Origin handling and documentation", unitPrice: 18, unit: "ton", currency: "USD" }, + { label: "Lashing material (when provided by EDR)", unitPrice: 150, unit: "unit", currency: "USD" }, + ] + : [ + { label: "Rail transport — 40ft container", unitPrice: 1916, unit: "container", currency: "USD" }, + { label: "Rail transport — 2 × 20ft containers", unitPrice: 1944, unit: "container", currency: "USD" }, + { label: "Excess tonnage surcharge", unitPrice: 10, unit: "ton", currency: "USD" }, + ]; + + return { + bookingId: "00000000-0000-0000-0000-000000000000", + reference: "EDR/CT/2026/0042", + status: "CONTRACT_READY", + templateKey: PREVIEW_TEMPLATE_KEYS[code], + template: { ...meta, title: dynamicTemplate.name, templateFile: "edr-dynamic.hbs" }, + contractDate: now.toLocaleDateString("en-GB", { + day: "numeric", + month: "long", + year: "numeric", + }), + contractYear: now.getFullYear(), + client: { + companyName: "Abyssinia Trading PLC", + companyAddress: "Bole Sub-city, Woreda 03, H.No 1234, Addis Ababa", + companyLocation: "Ethiopia", + phone: "+251 91 123 4567", + email: "logistics@abyssiniatrading.et", + tinNumber: "0011223344", + vatNumber: "VAT-556677", + fanNumber: "FAN-889900", + businessLicense: "BL/AA/12/345678", + }, + provider: { + name: "Ethio-Djibouti Standard Gauge Railway Share Company", + address: "Nifas Silk Lafto Sub City, Addis Ababa, Ethiopia", + phone: "+251 11 872 0000", + email: "info@edr.gov.et", + tinNumber: "—", + }, + schedule: { + originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station", + destinationLabel: "Galaan Multipurpose Port (GMP)", + tradeDirection: code.startsWith("IMPORT") + ? "IMPORT" + : code.startsWith("EXPORT") + ? "EXPORT" + : "DOMESTIC", + freightType: isBulk ? "BULK" : "CONTAINER", + serviceType: "Rail transport and customs clearance", + scheduledDate: "—", + contractType: "GENERAL", + cargoDescription: isBulk ? "Steel billets — 2,800 MT" : "40ft containers — FMCG cargo", + totalWeightVgm: "—", + equipmentReturn: isBulk ? "—" : "With empty return", + hazardousLabel: "No", + firstMilePickupAddress: "—", + lastMileDeliveryAddress: "—", + }, + pricing: { + displayMode: "UNIT_RATES", + unitRates, + currency: "USD", + equipmentReturn: isBulk ? "—" : "With empty return", + originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station", + destinationLabel: "Galaan Multipurpose Port (GMP)", + } as unknown as ContractViewModel["pricing"], + signatures: [], + canSignCustomer: false, + canSignStaff: false, + hasContractDocument: false, + hasCustomerSignature: false, + hasStaffSignature: false, + dynamicTemplate, + }; + } + + private assertCode(code: string): ContractTemplateCode { + const upper = code?.toUpperCase() as ContractTemplateCode; + if (!CONTRACT_TEMPLATE_CODES.includes(upper)) { + throw new BadRequestException( + `Unknown contract template code "${code}". Valid codes: ${CONTRACT_TEMPLATE_CODES.join(", ")}`, + ); + } + return upper; + } + + private sorted(articles: ContractTemplateArticle[]): ContractTemplateArticle[] { + return [...(articles ?? [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)); + } + + private renumber(articles: ContractTemplateArticle[]): ContractTemplateArticle[] { + return articles.map((article, index) => ({ ...article, order: index + 1 })); + } +} diff --git a/apps/edr-freight-api/src/modules/contract-templates/dto/contract-template.dto.ts b/apps/edr-freight-api/src/modules/contract-templates/dto/contract-template.dto.ts new file mode 100644 index 000000000..0ea69f262 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/dto/contract-template.dto.ts @@ -0,0 +1,134 @@ +import { ApiPropertyOptional, ApiProperty } from "@nestjs/swagger"; +import { Type } from "class-transformer"; +import { + IsArray, + IsBoolean, + IsInt, + IsOptional, + IsString, + MaxLength, + Min, + MinLength, + ValidateNested, +} from "class-validator"; + +export class UpdateContractTemplateDto { + @ApiPropertyOptional({ description: "Display name of the template" }) + @IsOptional() + @IsString() + @MinLength(3) + @MaxLength(200) + name?: string; + + @ApiPropertyOptional({ description: "Short description shown on the template card" }) + @IsOptional() + @IsString() + description?: string; + + @ApiPropertyOptional({ description: "Cover-page service title of the generated document" }) + @IsOptional() + @IsString() + @MinLength(3) + @MaxLength(300) + documentTitle?: string; + + @ApiPropertyOptional({ description: "WHEREAS recitals", type: [String] }) + @IsOptional() + @IsArray() + @IsString({ each: true }) + whereasClauses?: string[]; + + @ApiPropertyOptional({ description: "Whether the template is used for generation" }) + @IsOptional() + @IsBoolean() + isActive?: boolean; +} + +export class CreateArticleDto { + @ApiProperty({ description: "Article heading (without the Article N prefix)" }) + @IsString() + @MinLength(2) + @MaxLength(200) + title!: string; + + @ApiProperty({ + description: + 'Article body. One clause per line; prefix a line with "- " to nest it as a bullet under the previous clause.', + }) + @IsString() + @MinLength(2) + body!: string; + + @ApiPropertyOptional({ description: "1-based position to insert at (appends when omitted)" }) + @IsOptional() + @IsInt() + @Min(1) + position?: number; +} + +export class UpdateArticleDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MinLength(2) + @MaxLength(200) + title?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MinLength(2) + body?: string; +} + +export class ReplaceArticleDto { + @ApiPropertyOptional({ description: "Existing article id (new id assigned when omitted)" }) + @IsOptional() + @IsString() + id?: string; + + @ApiProperty() + @IsString() + @MinLength(2) + @MaxLength(200) + title!: string; + + @ApiProperty() + @IsString() + @MinLength(2) + body!: string; +} + +export class ReplaceArticlesDto { + @ApiProperty({ type: [ReplaceArticleDto], description: "Full ordered article list" }) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ReplaceArticleDto) + articles!: ReplaceArticleDto[]; +} + +/** Optional draft overrides so the editor can preview unsaved changes. */ +export class PreviewContractTemplateDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + name?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsString() + documentTitle?: string; + + @ApiPropertyOptional({ type: [String] }) + @IsOptional() + @IsArray() + @IsString({ each: true }) + whereasClauses?: string[]; + + @ApiPropertyOptional({ type: [ReplaceArticleDto] }) + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ReplaceArticleDto) + articles?: ReplaceArticleDto[]; +} diff --git a/apps/edr-freight-api/src/modules/contract-templates/entities/contract-template.entity.ts b/apps/edr-freight-api/src/modules/contract-templates/entities/contract-template.entity.ts new file mode 100644 index 000000000..73729fbb6 --- /dev/null +++ b/apps/edr-freight-api/src/modules/contract-templates/entities/contract-template.entity.ts @@ -0,0 +1,77 @@ +import { BaseEntity } from "@edr/api-common"; +import { Column, Entity, Index } from "typeorm"; + +/** + * The six canonical contract document templates, one per + * (trade direction × freight type) combination. Contracts store DOMESTIC for + * intercity movements; the template layer labels those INTERCITY to match the + * commercial vocabulary used on the printed documents. + */ +export const CONTRACT_TEMPLATE_CODES = [ + "IMPORT_BULK", + "EXPORT_BULK", + "INTERCITY_BULK", + "IMPORT_CONTAINER", + "EXPORT_CONTAINER", + "INTERCITY_CONTAINER", +] as const; + +export type ContractTemplateCode = (typeof CONTRACT_TEMPLATE_CODES)[number]; + +/** + * One dynamic article on a contract template. `body` is plain multiline text: + * each non-empty line renders as a numbered clause; lines prefixed with "- " + * render as bullet points nested under the preceding clause. A single-line + * body renders as an unnumbered paragraph. Handlebars placeholders (e.g. + * {{client.companyName}}, {{contractDate}}, {{contractYear}}, {{reference}}) + * are interpolated against the contract view model at render time. + */ +export interface ContractTemplateArticle { + id: string; + title: string; + body: string; + order: number; +} + +/** Map a contract's stored direction/freight pair onto a template code. */ +export function contractTemplateCodeFor( + tradeDirection?: string | null, + freightType?: string | null, +): ContractTemplateCode { + const direction = + tradeDirection === "IMPORT" + ? "IMPORT" + : tradeDirection === "EXPORT" + ? "EXPORT" + : "INTERCITY"; + const freight = + (freightType ?? "").toUpperCase().includes("BULK") ? "BULK" : "CONTAINER"; + return `${direction}_${freight}` as ContractTemplateCode; +} + +@Entity({ schema: "freight", name: "contract_templates" }) +@Index(["code"], { unique: true }) +export class ContractTemplate extends BaseEntity { + @Column({ name: "code", type: "varchar", length: 40, unique: true }) + code!: ContractTemplateCode; + + @Column({ name: "name", type: "varchar", length: 200 }) + name!: string; + + @Column({ name: "description", type: "text", nullable: true }) + description?: string | null; + + /** Cover-page service line, e.g. "Steel Billet Transportation and Customs Clearance Services". */ + @Column({ name: "document_title", type: "varchar", length: 300 }) + documentTitle!: string; + + /** WHEREAS recitals rendered between the parties block and the articles. */ + @Column({ name: "whereas_clauses", type: "jsonb", default: () => "'[]'" }) + whereasClauses!: string[]; + + @Column({ name: "articles", type: "jsonb", default: () => "'[]'" }) + articles!: ContractTemplateArticle[]; + + @Column({ name: "is_active", type: "boolean", default: true }) + isActive!: boolean; +} diff --git a/apps/edr-freight-api/src/modules/contracts/contract-transition.service.ts b/apps/edr-freight-api/src/modules/contracts/contract-transition.service.ts index e25c10054..e109d40a1 100644 --- a/apps/edr-freight-api/src/modules/contracts/contract-transition.service.ts +++ b/apps/edr-freight-api/src/modules/contracts/contract-transition.service.ts @@ -350,6 +350,17 @@ export class ContractTransitionService { const updated = await this.contractsService.findById(contractId); if (allDone) { this.notifier.approved(updated); + // Final approval step also generates the contract document from the + // template matching the contract's direction/freight pair. Best-effort: + // a rendering hiccup must not roll back the approval — the document can + // still be generated manually or lazily on view/download. + try { + return await this.generateContract(contractId); + } catch (err) { + this.logger.warn( + `Auto contract generation after final approval failed for ${updated.reference}: ${err}`, + ); + } } return updated; } diff --git a/apps/edr-freight-api/src/modules/contracts/contracts.module.ts b/apps/edr-freight-api/src/modules/contracts/contracts.module.ts index 33a547a9f..96bdf22b1 100644 --- a/apps/edr-freight-api/src/modules/contracts/contracts.module.ts +++ b/apps/edr-freight-api/src/modules/contracts/contracts.module.ts @@ -16,6 +16,7 @@ import { NotificationsModule } from '../notifications/notifications.module'; import { NotificationInboxModule } from '../notification-inbox/notification-inbox.module'; import { BookingsModule } from '../bookings/bookings.module'; import { TrainSchedulingModule } from '../train-scheduling/train-scheduling.module'; +import { ContractTemplatesModule } from '../contract-templates/contract-templates.module'; import { ContractsController } from './contracts.controller'; import { ContractsService } from './contracts.service'; @@ -81,6 +82,9 @@ import { ContractDocumentViewModelBuilder } from '../../contracts/contract-docum NotificationsModule, NotificationInboxModule, CompaniesModule, + // Provides the admin-editable contract document templates consumed by + // ContractDocumentViewModelBuilder when rendering contract PDFs. + ContractTemplatesModule, // BookingsModule provides BookingsRepository/BookingPricingService used by the // contract PDF builders (they read a Booking today — see docs/new-doc.md §3.3). forwardRef(() => BookingsModule), diff --git a/apps/edr-freight-api/src/seed/data/contract-template-defaults.ts b/apps/edr-freight-api/src/seed/data/contract-template-defaults.ts new file mode 100644 index 000000000..6fba64010 --- /dev/null +++ b/apps/edr-freight-api/src/seed/data/contract-template-defaults.ts @@ -0,0 +1,873 @@ +import type { + ContractTemplateArticle, + ContractTemplateCode, +} from "../../modules/contract-templates/entities/contract-template.entity"; + +/** + * Default article packs for the six contract templates, transcribed from the + * signed EDR contract documents (test/contrat_docs). Article bodies use the + * dynamic-article text format: one clause per line, "- " prefix for bullets + * nested under the previous clause, single-line body = plain paragraph. + * Handlebars placeholders ({{client.companyName}}, {{contractDate}}, + * {{contractYear}}, {{reference}}) interpolate at render time. + */ +export interface ContractTemplateSeed { + code: ContractTemplateCode; + name: string; + description: string; + documentTitle: string; + whereasClauses: string[]; + articles: Array>; +} + +const a = (id: string, title: string, body: string): Omit => ({ + id, + title, + body: body.trim(), +}); + +/* ────────────────────────────── IMPORT / BULK ────────────────────────────── */ + +const IMPORT_BULK: ContractTemplateSeed = { + code: "IMPORT_BULK", + name: "Bulk Import Contract", + description: + "Import of bulk cargo (e.g. steel billets) from Djibouti (DMP/Nagad) to Galaan Multipurpose Port with customs clearance and optional last-mile delivery.", + documentTitle: "Bulk Cargo Transportation and Customs Clearance Services", + whereasClauses: [ + "The Client has agreed to engage the Service Provider for transportation and customs clearance services for bulk cargo, including first-mile transport to the railway station at Djibouti, loading at either DMP or Nagad Railway Station (Djibouti), port/rail terminal handling, loading onto the train, railway transport to Galaan Multipurpose Port (GMP) in Ethiopia, unloading at the destination port from train to load directly on truck, onward transportation to the Client's site (excluding truck loading at Djibouti and truck unloading at the Client destination where last-mile service is undertaken by the Service Provider), and all related documentation.", + "The Service Provider has agreed to provide the requested services in accordance with the terms and conditions of this Agreement.", + ], + articles: [ + a( + "objective", + "Objective of the Services", + `The objective of this contract is to provide the Client with integrated logistics services for the transportation of bulk cargo, including: +- First-mile transportation in Djibouti from the Client's designated cargo location to the selected railway station (DMP or Nagad). +- Port handling and loading onto railway wagons. +- Railway transport from DMP and/or Nagad Railway freight station (Djibouti) to Galaan Multipurpose Port. +- Customs clearance in Djibouti and Ethiopia. +- Unloading from train at the destination port to load directly on truck. +- Last-mile delivery by truck to the Client's delivery site where the last-mile service is undertaken by the Service Provider. +The truck loading at Djibouti and the truck unloading at the Client's delivery site shall be the responsibility of the Client.`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Provide written/email/electronic instructions specifying the cargo volume and the selected loading station (DMP or Nagad) for each shipment. +Prepare and submit all necessary documents and permits to enable smooth service execution. +Ensure cargo readiness in compliance with specifications (including weight, size, and contour restrictions). +Handle truck loading at Djibouti Free Zone/Old Port/DMP and any other designated cargo location at Djibouti, and truck unloading at the delivery site. +Ensure safety and proper securing of cargo during truck handling. +Submit all required documents necessary for customs clearance and cargo release within one (1) calendar day from the date of request or notification by the Service Provider. +Upon receipt of the wagon allocation list and train schedule from the Service Provider, ensure that the cargo is transferred to the designated loading freight station and made ready for loading within two (2) days prior to wagon arrival. Any delay beyond this period resulting from Client-related issues shall be subject to a charge of USD 56 per wagon per day, or part thereof, until the cargo is made available for loading. +Upon arrival of the train at Galaan Multipurpose Port (GMP), offload cargo from wagons within twenty-four (24) hours of train arrival. Where the Client undertakes last-mile transportation, the Client may arrange sufficient trucks at the time of train arrival to enable direct loading of cargo from wagons to trucks. +In the event the Client is unable to provide trucks for the collection of cargo within twenty-four (24) hours of train arrival, the Service Provider shall have the right to handle and reposition the cargo to any location it deems appropriate, and shall not be held responsible for any loss, shortage, or damage arising from such repositioning. +Any additional handling, re-handling, or repeated loading operations performed by the Service Provider shall be charged as double handling fees at a rate of USD 4 per ton, payable by the Client. +If stored, the full cargo must be collected from the Galaan Multipurpose Port compound within three (3) days from the time of train arrival at the port. +If the Client fails to collect the cargo within the specified period, the Client shall be liable to pay demurrage charges of USD 2 per day per ton, calculated based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date of payment. +Where the last-mile service is provided by the Service Provider, unload the cargo from the truck at the delivery site within the agreed time frame. +Designate authorized representatives (with valid power of attorney) for handover at origin and destination. +Settle demurrage payments within ten (10) calendar days from the date the Service Provider issues a claim. +Pay the Service Provider one hundred percent (100%) of the contract price in advance for each train set in accordance with the pricing article of this Agreement. +Contact the Service Provider to obtain confirmation prior to booking and proceeding with payment.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Provide first-mile transportation in Djibouti from the Client's designated location to the selected railway station (DMP or Nagad). +Carry out port handling and loading onto railway wagons. +Provide railway transportation from DMP/Nagad (Djibouti) railway freight station to Galaan Multipurpose Port. +Perform unloading at Galaan Multipurpose Port (GMP) to load directly on truck. +Perform customs clearance in Djibouti and Ethiopia, including border station procedures. +Prepare and submit all required transport documentation. +Provide cargo insurance coverage for each supplied wagon. +Notify the Client of train schedules, wagon numbers, and expected arrival times in advance.`, + ), + a( + "force-majeure", + "Force Majeure", + `Neither party shall be liable for delays or non-performance caused by force majeure events beyond their reasonable control. +Force majeure shall be interpreted in accordance with the Ethiopian Civil Code.`, + ), + a( + "liability", + "Liabilities Related to Damages and Losses", + `The Service Provider shall be fully responsible for any loss, shortage, or damage to cargo that occurs after it has been taken over until delivery to the Client's delivery site. +Compensation shall be based on the market value of the cargo, in accordance with applicable laws.`, + ), + a( + "pricing", + "Contract Price and Payment Terms", + `Rail transport to Galaan Multipurpose Port: USD 59.4 per metric ton. +Djibouti handling (first-mile, port handling and loading, and documentation): USD 18 (eighteen) per metric ton for cargo from the Free Zone; USD 20 (twenty) per metric ton for cargo from the Old Port or DMP. +Lashing materials shall be charged at USD 150 (one hundred fifty) per wagon and wood at USD 50 (fifty) per wagon when provided by the Service Provider; the provision continues until the cargo reaches and is fully unloaded at the designated destination station. +Each wagon shall be loaded up to a maximum of seventy (70) metric tons; for billing purposes one full wagon shall be deemed equivalent to this volume. +The price for last-mile delivery shall be determined once the cargo departs from the loading point and shall be communicated to the Client by official email upon the Client's request. +Payments shall be made 100% in advance in USD.`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents form part of this contract: +- This Contract Agreement. +- Any amendments made to this Agreement. +- Minutes of negotiation (if any).`, + ), + a( + "documentation", + "Documentation Requirements", + `The Service Provider shall deliver the following to the Client: +- Freight Carriage Acceptance Sheet of the Addis Ababa–Djibouti Railway. +- Notice of transportation and miscellaneous charges. +- Summary of payment request as per the agreed tariff, if required.`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider shall certify the taking over of goods in the Freight Carriage Acceptance Sheet. +This document shall serve as prima facie evidence of receipt of the cargo. +Upon delivery of the cargo to the Client, the Cargo Handover Out Voucher signed by both parties shall serve as evidence of cargo receipt.`, + ), + a( + "termination", + "Termination of Contract", + `This contract may be terminated: +- By mutual consent. +- Upon completion of the agreed contract period or cargo volume. +- For breach of fundamental provisions, with one-week prior written notice.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `This Agreement becomes effective on the date it is signed by both parties.`, + ), + a( + "duration", + "Duration", + `The contract is valid until August 31, {{contractYear}} from the date of effectiveness, extendable by mutual agreement.`, + ), + a( + "disputes", + "Settlement of Disputes", + `Disputes shall first be settled amicably. +If unresolved, disputes shall be referred to the competent Federal Court of Ethiopia in Addis Ababa. +The governing law shall be the laws of the Federal Democratic Republic of Ethiopia.`, + ), + ], +}; + +/* ────────────────────────────── EXPORT / BULK ────────────────────────────── */ + +const EXPORT_BULK: ContractTemplateSeed = { + code: "EXPORT_BULK", + name: "Bulk Export Contract", + description: + "Export of bulk cargo (e.g. livestock) by railway from Ethiopian loading stations to Nagad railway freight yard, Djibouti.", + documentTitle: "Bulk Cargo Transportation Service by Railway", + whereasClauses: [ + "The Client has agreed to deliver bulk cargo to the Service Provider for transport from the agreed Ethiopian loading station to Nagad railway freight yard using the Addis Ababa–Djibouti railway line.", + "The Service Provider has agreed to provide the service to transport the bulk cargo from the agreed loading station to Nagad railway freight yard.", + ], + articles: [ + a( + "objective", + "Objective of the Service", + `To undertake the railway transportation of bulk cargo from the agreed Ethiopian loading station to Nagad railway freight yard.`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Give written instruction to the Service Provider to transport a minimum of one wagon of cargo; the wagon request shall be made at least five (5) days in advance for each wagon. +Maintain detailed information incorporating type, weight, and destination of the cargo ready for shipment, and notify the Service Provider or its nominated agent by notice, email, or fax. +Prepare the necessary documents and facilities to make the cargo ready for transport. +Note the allowable transport period of the cargo: the maximum time range during which the goods maintain their condition without any problem. The allowable transport period must be at least two (2) days longer than the delivery period. +Ensure cargo is properly loaded and fastened in the wagons, provide the necessary lashing and barriers for loading as per the instruction of the departure station, and bear responsibility for the condition of the cargo during the transport period. +Supply the necessary provisions for the cargo for each wagon and assign a responsible person to travel with the train to check the status of the cargo during transport, where the nature of the cargo so requires. +Supply the minimum amount of cargo available for at least one wagon. +Execute loading, lashing, and preparing barriers on wagons at the loading station and provide the complete documents/bill to the Service Provider within one (1) calendar day. +For each extra calendar day used for loading cargo and completing documents at the loading station, pay the wagon-occupied fee per the pricing article; the fee shall be paid within ten (10) calendar days from the date the Service Provider claims it, failing which compensation is payable calculated on the basis of the Commercial Bank of Ethiopia interest rate for the delay period. +Be responsible for safety matters, and indemnify and hold the Service Provider harmless against all consequences resulting from accidents arising from or associated with the loading and unloading process. +Execute and cover the cost of loading and unloading of cargo at both the loading station and Nagad railway freight yard. +Follow up that the cargo is loaded and unloaded on time. +Delegate representatives at both ends to consign and receive cargo with signature and stamp. Representatives shall hold a duly signed and stamped power of attorney and shall produce their ID or passport when consigning or receiving the cargo. +Prepare the necessary facilities to take over the transported cargo at Nagad freight yard upon arrival by issuing handover documents. +Take the transported cargo out of the wagons at Nagad freight yard within one (1) calendar day starting from the day following the notice of arrival. +Pay the wagon-occupied fee per the pricing article for delays of more than one (1) calendar day at Nagad railway freight yard due to the fault of the Client in resolving customs or third-party claims or any other causes. +After the wagon list is submitted to the Client, if a wagon is not loaded due to the fault of the Client, pay 100% of the transportation price per wagon for each unloaded wagon. +Pay the Service Provider 100% of the contract price in advance for each wagon.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Provide the list and identification numbers of wagons with sequence and locomotives at least twenty-four (24) hours in advance to the Client, with any correction at least twelve (12) hours before arrival at destination. +Transport the cargo from the loading station to Nagad railway freight yard. +Provide safe transportation of the cargo throughout the transit. +Present customs clearance documents and mobilize the rolling stock as needed. +Provide the wagons assigned for the freight at the agreed place and time, and follow up that the cargo is loaded on time. +Transport and deliver the cargo taken over, in the condition received, within two (2) calendar days to Nagad railway freight yard. +Where a wagon carrying cargo stops due to accident or mechanical problem, promptly notify the nearby customs station, police office, and the Client. A wagon stopped in Ethiopia due to mechanical defect shall be maintained within four (4) calendar days; within Nagad (Djibouti) territory within twelve (12) calendar days. In case of accident where the problem cannot be solved within one (1) calendar day and the wagon is not operational, the Service Provider shall have the cargo carried and delivered by another wagon, and shall provide an accident or defect report issued by the local police office regarding the sustained damage. +Buy a cargo liability insurance policy for each supplied wagon. +Provide wagon cleaning service and charge the cleaning fee based on actual expenditure. +If the Client fails or refuses to receive the cargo beyond the allowable transport period, the Service Provider has the right to handle the cargo. +Neither party shall be liable for any indirect or consequential loss sustained by the other in connection with this Agreement.`, + ), + a( + "force-majeure", + "Force Majeure", + `The parties have no obligation to pay demurrage or any other compensation if they have failed to discharge their obligations due to force majeure. +Force majeure shall be deemed to exist when the contract is not performed due to any event beyond the reasonable control of a party which prevents that party from complying with its obligations under this Agreement, including but not limited to: +- Acts of God (such as, but not limited to, fires, explosions, earthquakes, drought, tidal waves, and floods). +- War, hostilities (whether war is declared or not), invasion, acts of foreign enemies, mobilization, requisition, or embargo. +- Rebellion, revolution, insurrection, military or usurped power, or civil war. +- Contamination by radioactivity from any nuclear fuel or nuclear waste. +- Riot, commotion, strikes, go-slows, lockouts, or disorder. +- Acts of terrorism. +A party wishing to claim protection in respect of a force majeure event shall, as soon as possible following the occurrence or commencement of the event, notify the other party of its nature and expected duration, and shall thereafter keep the other party informed until it is able to perform its obligations under this Agreement.`, + ), + a( + "pricing", + "Contract Price and Terms of Payment", + `The price of bulk cargo transportation from the loading station to Nagad shall be USD 696 (six hundred ninety-six) per wagon. +Payment for transport services shall be made in Birr based on the selling price of USD to Birr on the date of payment set by the Commercial Bank of Ethiopia. +If there is an increment or decrement of the USD exchange rate to Birr between the date of payment and the date the wagon/train number is provided to the Client, either the Client shall make the additional payment to the Service Provider or the Service Provider shall refund the difference from the initial payment to the Client. +The cost of loading at the loading station and unloading at Nagad shall be covered by the Client and is not part of this contract agreement. +The Client shall pay 100% of the contract price in advance. +The Client shall pay a demurrage fee for occupied wagons as follows: +- Wagons occupied between 1 and 3 days: USD 193 per wagon per day. +- Wagons occupied between 4 and 7 days: USD 290 per wagon per day. +- Wagons occupied 8 days and above: USD 590 per wagon per day. +Demurrage payment shall be made in Birr based on the selling price of USD to Birr set by the Commercial Bank of Ethiopia on the date of the demurrage occurrence.`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents shall constitute the contract between the Client and the Service Provider: +- Amendments made to this contract (if any). +- This Contract Agreement. +- Final minutes of negotiation (if any). +If there is any discrepancy between the documents, they shall be interpreted with priority in the order listed above.`, + ), + a( + "documentation", + "Documentation Requirements", + `The following documents shall be delivered to the Client upon request for settlement: +- Consignment Note (cargo handover document to the Client). +- Summary of payment request of the Service Provider prepared as per the agreed tariff.`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider must certify the taking over of the goods on the duplicates of the consignment note in an appropriate manner and return the duplicate to the Client. +A consignment note shall be prima facie evidence of the receipt of the goods by the Service Provider and of the kind, number, and weight of the goods.`, + ), + a( + "termination", + "Termination of Contract", + `The contract may be terminated: +- Upon mutual consent of the parties. +- Upon completion of the contract period. +- If either or both parties breach a fundamental provision of the contract, upon prior legal notice delivered by either party.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `The contract shall come into full force and effect on the date when all of the following are accomplished: +- The contract is signed by the Client and the Service Provider. +- The Service Provider has received the advance payment of 100% of the contract price for each train set of cargo.`, + ), + a( + "cargo-amount", + "Cargo Amount", + `The minimum cargo to be transported shall be one wagon.`, + ), + a( + "duration", + "Duration of Contract", + `The contract shall last for three (3) months starting from the date of contract signing, with possible extension upon mutual agreement.`, + ), + a( + "disputes", + "Settlement of Disputes", + `If a dispute arises between the parties, they shall exert efforts to settle their differences amicably. +If the parties fail to settle their disputes amicably, the case shall be taken to the competent Federal Court of law presiding in Addis Ababa. +The governing law shall be the laws of the Federal Democratic Republic of Ethiopia.`, + ), + ], +}; + +/* ──────────────────────────── INTERCITY / BULK ───────────────────────────── */ + +const INTERCITY_BULK: ContractTemplateSeed = { + code: "INTERCITY_BULK", + name: "Bulk Intercity Contract", + description: + "Domestic (intercity) bulk cargo transportation by railway between Ethiopian freight yards, e.g. Dire Dawa to Sebeta.", + documentTitle: "Bulk Cargo Transportation Service by Railway (Intercity)", + whereasClauses: [ + "The Client has requested the Service Provider to transport bulk cargo between the agreed Ethiopian railway freight yards using the Ethio–Djibouti Railway.", + "The Service Provider has accepted the Client's request to render the said transportation service.", + ], + articles: [ + a( + "objective", + "Objective of the Contract", + `The Service Provider shall undertake the railway transportation of bulk cargo from the agreed origin railway freight yard to the agreed destination railway freight yard.`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Provide written instructions to the Service Provider to transport a minimum of sixteen (16) wagons of cargo per consignment. +Prepare all necessary documents, including laboratory tests from the pertinent organ and off-taking contract where applicable, and the facilities required to sign the contract and make the cargo ready for transport. +Assign representatives at the origin yard and other stations, as required, to hand over the cargo to the Service Provider and handle transit clearance if required. +Transport the cargo to the designated loading points at the origin yard. +Be responsible for cargo handling: loading at the origin yard and unloading at the destination yard, in accordance with the standards set by the EDR operations and technical terms. +Make advance payment to the Service Provider for services in accordance with the payment terms and conditions of this contract. +Follow up to ensure that the cargo is loaded and unloaded on time. +Delegate representatives at the cargo destination to immediately receive the transported cargo. +Ensure representatives are duly authorized with a power of attorney, signed and stamped by the Client, and present valid identification (ID or passport) when consigning or receiving cargo. +Maintain detailed information including item, weight, and destination of the cargo, and communicate the same to the Service Provider or its nominated agent via written notice, email, or fax. +Prepare the necessary facilities to immediately take over the transported cargo at the destination upon arrival and provide sufficient trucks at the destination freight yard for unloading from railway wagons. +Upon arrival of the train/wagon at the unloading site, sign the train arrival confirmation sheet to acknowledge the arrival time. +Inspect the loaded wagons jointly with the Service Provider and EDR at the loading yard, and again with the customs agent (if required) and the Service Provider at the destination yard. +After receiving the cargo, sign the Freight Carriage Acceptance Sheet (copies II, III, and IV) immediately to confirm delivery. +Compensate the Service Provider or any third party for actual loss or damage caused to persons, property, or wagons during unloading where such damage is attributable to the Client's fault. +Each consignment (train) shall be granted three (3) hours of free time at the loading station and one (1) day at the unloading station. For each additional 3 hours of loading or parking the Client shall pay ETB 5,000 (five thousand) per wagon, and for each additional day of unloading ETB 5,000 (five thousand) per wagon per day. +Bear demurrage charges of ETB 5,000 (five thousand) per wagon per 3 hours for delays exceeding three (3) hours at any station resulting from the Client's failure to resolve customs or third-party claims. +Pay 100% of the transport price in advance. Any additional charges or fees shall be paid within ten (10) calendar days after submission of the Service Provider's payment request.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Provide the necessary train(s) to execute the transportation service under this contract, and furnish the Client with the list and identification numbers of wagons and locomotives at least 24 hours in advance, with corrections (if any) communicated at least 12 hours before the expected time of arrival at destination. +Provide pre-arrival notification including the train number to the discharging terminal and customs at least 24/12 hours before train arrival. +Transport the cargo from origin to destination within two (2) days from completion of loading (time counting starts upon completion of documentation and loading). +Provide safe transportation of the cargo throughout transit. +Deliver the cargo to the Client at the destination railway freight yard in the same condition as received. +Purchase a cargo liability insurance policy for each wagon transported.`, + ), + a( + "force-majeure", + "Force Majeure", + `Neither party shall be liable due to a force majeure event. +For the purposes of this contract, force majeure shall mean any unforeseeable event or circumstance beyond the reasonable control of the affected party which absolutely prevents the performance of the contract, including but not limited to natural disasters, war, civil commotion, strikes, government actions, epidemics, or interruption of railway operations due to accidents or infrastructure failure. +The affected party shall notify the other party in writing within a reasonable period not exceeding two (2) hours after the occurrence of the force majeure event, providing evidence and details of the impact on performance and the mitigating steps taken.`, + ), + a( + "liability", + "Liabilities Related to Damages and Losses", + `The Service Provider will be responsible for any loss, shortage, or damage occurring to the cargo it has received.`, + ), + a( + "pricing", + "Contract Price", + `The price for transporting cargo from the origin freight yard to the destination freight yard shall be USD 400 (four hundred) per wagon. +Each wagon shall be loaded with a maximum of 70 (seventy) metric tons. +Payment for transport services may be made in Ethiopian Birr, based on the Commercial Bank of Ethiopia's official selling exchange rate of USD to Birr on the date of payment. +If the exchange rate changes between the payment and the wagon assignment date, payment adjustments will be made accordingly. +The contract price shall include the cost of railway transportation from the origin freight yard to the destination freight yard. +Excluded cost: cargo handling (loading and unloading) is not included in the contract price and shall remain the sole responsibility of the Client.`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents shall constitute the contract between the Client and the Service Provider: +- Amendments made to this contract (if any). +- This Contract Agreement. +- Final minutes of negotiation (if any). +If there is any discrepancy between the documents, they shall be interpreted with priority in the order listed above.`, + ), + a( + "documentation", + "Documentation Requirements", + `The following documents shall be delivered to the Client by the Service Provider to collect and settle payment: +- Freight Carriage Acceptance Sheet of the Ethio-Djibouti Railway. +- Notice of collecting transportation and miscellaneous charges of the Ethio-Djibouti Railway (if any). +- Summary of payment request of the Service Provider prepared as per the agreed tariff. +- Railway Waybill.`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider must certify the taking over of the goods on copy III (kept by the consignee for future reference) of the Freight Carriage Acceptance Sheet of the Ethio-Djibouti Railway in an appropriate manner and provide it to the Client. +The Freight Carriage Acceptance Sheet shall be prima facie evidence of the receipt of the goods by the Service Provider and of the kind, number, and weight of the goods.`, + ), + a( + "termination", + "Termination of Contract", + `The contract may be terminated: +- Upon mutual consent of the parties. +- Upon completion of the contract period or amount of cargo, whichever comes first. +- If either or both parties breach a fundamental provision of the contract, upon one-week prior legal notice delivered by either party.`, + ), + a( + "duration", + "Duration of Contract", + `The contract duration shall be three (3) months from the date of effectiveness of the contract, with possible extension upon mutual agreement of the parties.`, + ), + a( + "disputes", + "Settlement of Disputes", + `If a dispute arises between the parties, they shall exert efforts to settle their differences amicably. +If the parties fail to settle their dispute amicably, the case shall be taken to the competent Federal Court of law presiding in Addis Ababa. +The governing law shall be the laws of the Federal Democratic Republic of Ethiopia.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `The contract shall come into full force and effect on the date when the contract is signed by the parties and witnesses.`, + ), + ], +}; + +/* ──────────────────────────── IMPORT / CONTAINER ─────────────────────────── */ + +const IMPORT_CONTAINER: ContractTemplateSeed = { + code: "IMPORT_CONTAINER", + name: "Container Import Contract", + description: + "Import container transport by railway from SGTD (Djibouti) to Dire Dawa, Modjo dry port, or Galaan Multipurpose Port, with empty-container return.", + documentTitle: "Import Container Transport Service by Railway", + whereasClauses: [ + "The Client has requested and agreed to the transportation of container cargo from SGTD railway freight station at Djibouti to Dire Dawa, Modjo dry port, and Galaan Multipurpose Port (GMP), and the return of empty containers from Dire Dawa, Modjo dry port, and Galaan Multipurpose Port (GMP) to SGTD railway freight station using the Addis Ababa–Djibouti railway line.", + "The Service Provider has agreed to transport the container cargo as per the terms of this contract.", + ], + articles: [ + a( + "objective", + "Objective and Scope of the Services", + `To provide railway transportation services 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 Dire Dawa, Modjo dry port, and Galaan Multipurpose Port (GMP) to SGTD. +The scope of the services comprises: +- Railway transport service. +- Cargo handling at Galaan Multipurpose Port (GMP).`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Give written/email/electronic shipment instructions to the Service Provider for transportation of container cargo from SGTD to Dire Dawa, Modjo dry port, and/or Galaan Multipurpose Port (GMP). +Prepare all necessary documents and facilities for shipment. +Ensure the following minimum supply of containers per shipment based on the loading terminal and destination: +- Minimum of twenty-five (25) 40ft containers or fifty (50) 20ft containers to Modjo dry port. +- Minimum of ten (10) 40ft containers or twenty (20) 20ft containers to Dire Dawa dry port. +- Minimum of one (1) 40ft container or two (2) TEU to Galaan Multipurpose Port (GMP). +One flat wagon must carry either one 40ft container or two 20ft containers. +If two 20ft containers are loaded on one flat wagon, their weight difference must not exceed 10 tons. +Ensure timely loading and unloading of cargo. +Assign representatives at both ends to oversee container handover and ensure the necessary arrangements for cargo reception at the destination upon arrival. +Maintain and provide detailed cargo information (type, weight, destination, etc.). +Be responsible for cargo handling, loading, and unloading of both empty and full containers at Modjo, Dire Dawa dry port, and SGTD. +Book wagons at least five (5) days in advance. +Ensure containers are ready one day before the planned loading date. +Submit all required documents to the Djibouti Nagad station at least 24 hours in advance before starting to load. Failure to submit the documents within the stipulated time shall result in the following demurrage charges, calculated as a percentage of the booked wagon price: +- Delay of up to twelve (12) hours: 20% of the booked wagon price. +- Delay exceeding twelve (12) hours but not more than one (1) day: 50% of the booked wagon price. +- Delay of more than one (1) day: 100% of the booked wagon price. +Collect the full container from Galaan Multipurpose Port (GMP) within three (3) calendar days from the day following the arrival notice. +If the Client fails to collect the container within the specified period, the Service Provider shall have the right to reposition the container to any location it deems appropriate; in such case, the Service Provider shall not be held responsible for any damage or loss arising from such repositioning. +If the Client fails to collect the container from Galaan Multipurpose Port within the specified period, the Client shall be liable to pay demurrage charges of 15 USD per day per 20ft container and 27 USD per day per 40ft container, calculated based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date of payment. +In the event the Client fails to collect the container(s) within the specified period, the Client shall be liable to pay double handling charges of 27 USD per 20ft container per handling or 40 USD per 40ft container per handling, calculated based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date of payment. +If empty containers cannot be offloaded from the train upon arrival at SGTD due to any Client-related issue, the Client shall be liable for the applicable penalty charges. +Penalty charges for delay at SGTD/Nagad upon train arrival: 20 USD per day per 20ft container; 33 USD per day per 40ft container. +Collect the containers within one day at Dire Dawa and Modjo dry port, or make the necessary payment to the dry port as per the standard of the dry port. +For returning empty containers, deliver to Dire Dawa dry port, Modjo dry port, or Galaan Multipurpose Port. +Once the empty containers are returned from the Client's premises and stored at Dire Dawa/Modjo dry port while awaiting train allocation for return to SGTD, any demurrage and/or storage charges incurred from the dry port thereafter shall not be the responsibility or liability of the Service Provider; the Client shall be solely responsible for settling such charges. +Provide clean empty containers that meet SGTD standards. If the port refuses to take over an empty container because of inside cleanliness problems, additional cleaning costs incurred due to non-compliance will be borne by the Client. +Ensure containers are structurally intact and meet weight distribution requirements. +Prohibited cargo: cargo covered with tarpaulin is not allowed due to safety risks. +Notify the Service Provider forty-eight (48) hours in advance before wagon booking if transporting hazardous or valuable goods. +If a booked wagon is not loaded due to Client-related issues, including but not limited to a damaged container, missing lock, unpaid demurrage, port system errors, or incomplete documentation and submission, the Client shall be charged 100% of the total price of the reserved wagon. +Refund requests before wagon booking require an official request, with a 3% administrative fee deducted. If the refund is due to the Service Provider, the Client shall receive a full refund. Refunds not requested and completed within six months shall be considered waived. +Pay 100% of the transportation fee in advance for each train set. +Settle additional penalties due to non-compliance within ten (10) days of invoice issuance. +Late payment incurs a penalty of an additional 10%.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Assign the necessary voyage based on the operational schedule and cargo demand, and notify the train schedule 48 hours in advance. +Provide a list of wagons/voyage or train number 24 hours in advance and update corrections 12 hours before arrival. +Provide safe transportation of the containers. +Deliver the cargo within two (2) days after train departure, provided that all required documents are submitted on time and no unforeseen circumstances or events occur. +Return empty containers from Dire Dawa, Modjo, and Galaan Multipurpose Port to SGTD within seven (7) calendar days of receipt. +In the event of export cargo operations, the Service Provider may prioritize the loading of export containers during the loading of empty containers and the unloading of import containers from the train at Galaan Multipurpose Port. +The Service Provider reserves the right to refuse the transportation of any cargo classified as dangerous goods. +If any operational, technical, or mechanical problem occurs throughout the transit, notify customs and arrange cargo transfer within 4 days if the incident occurs in Ethiopia, or within 6 days if it occurs in Djibouti. +Provide accident or defect reports if needed. +Buy cargo liability insurance for each wagon.`, + ), + a( + "force-majeure", + "Force Majeure", + `Neither party shall be liable for delays or non-performance caused by force majeure events beyond their reasonable control. +Force majeure shall be interpreted in accordance with the Ethiopian Civil Code.`, + ), + a( + "pricing", + "Contract Price and Terms of Payment", + `From SGTD to Dire Dawa dry port, the rate is USD 919 per one 40ft or USD 942 per two 20ft containers with empty return; USD 762 per one 40ft or USD 780 per two 20ft containers without empty return. +From SGTD to Modjo, the rate is USD 1,781 per one 40ft or USD 1,808 per two 20ft containers with empty return, and USD 1,507 per one 40ft or two 20ft containers without empty return. +From SGTD to Galaan Multipurpose Port, the rate is USD 1,916 per one 40ft or USD 1,944 per two 20ft containers with empty return, and USD 1,676 per one 40ft or USD 1,690 per two 20ft containers without empty return. +If cargo exceeds 40 tons per two 20ft containers of gross weight, additional charges apply proportionally. +Gross weight shall be the total sum of cargo, packing, and container tare weight. +Payment for any additional tonnage shall be made in advance before the container is loaded onto the wagon. +The price of loading and unloading and container handling at Modjo, Dire Dawa dry port, and SGTD container railway freight yard is not part of this contract; it is the Client's responsibility. +Additional costs (if applicable): +- Last-mile delivery service by truck from Galaan Multipurpose Port or Modjo to Addis Ababa or Modjo and surrounding areas shall incur an additional cost, fully covered by the Client. +- For clients utilizing EDR's last-mile logistics services, the applicable charges shall vary based on the cargo movement route. +- The charge for last-mile delivery from Galaan Multipurpose Port and Modjo dry port shall be communicated to the Client by the Service Provider after receiving the necessary details regarding the cargo destination, type, and weight. +All payments shall be made one hundred percent (100%) in advance in United States Dollars (USD).`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents constitute this contract: +- Amendments (if any). +- This Contract Agreement. +- Final minutes of negotiation (if any). +If there is any discrepancy between the documents, they shall be interpreted with priority in the order listed above.`, + ), + a( + "documentation", + "Documentation Requirements", + `Equipment Interchange Receipt of SGTD, Railway Waybill, Container Carriage Acceptance Sheet, and incidental charges (if any). +Payment summary as per the agreed contract price (if required).`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider must certify the taking over and handing over of the container cargo on the Freight Carriage Acceptance Sheet of EDR in an appropriate manner and provide it to the Client. +The Freight Carriage Acceptance Sheet shall be prima facie evidence of the receipt of the container cargo by the Service Provider and of the kind, number, and weight of the goods. +Upon delivery of the cargo to the Client, the Cargo Handover Out Voucher signed by both parties shall serve as evidence of cargo receipt.`, + ), + a( + "amendment", + "Amendment", + `This contract can be amended by mutual agreement. +Notwithstanding the above, the Service Provider may revise transport tariffs due to operational and regulatory changes by providing at least five (5) working days' prior written notice to the Client.`, + ), + a( + "termination", + "Termination of Contract", + `The contract may be terminated: +- By mutual agreement. +- Upon completion of the contract period or agreed cargo shipments. +- If either party breaches fundamental terms.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `The contract is valid once signed by both parties and witnesses.`, + ), + a( + "duration", + "Contract Period", + `Valid until August 31, {{contractYear}}, with a possible extension upon mutual agreement.`, + ), + a( + "disputes", + "Settlement of Disputes", + `Disputes shall be settled amicably. +If unresolved, disputes shall be taken to the Federal Court in Addis Ababa.`, + ), + ], +}; + +/* ──────────────────────────── EXPORT / CONTAINER ─────────────────────────── */ + +const EXPORT_CONTAINER: ContractTemplateSeed = { + code: "EXPORT_CONTAINER", + name: "Container Export Contract", + description: + "Export container transport, freight forwarding, and customs clearing from Galaan Multipurpose Port or Modjo dry port to SGTD container freight station (Djibouti).", + documentTitle: "Export Container Transport, Freight Forwarding and Customs Clearing Service", + whereasClauses: [ + "The parties have agreed on the following services: rail transport, customs clearance, transit work, freight forwarding, and handling of container cargo.", + ], + articles: [ + a( + "objective", + "Objective and Scope of the Services", + `Customs clearance (Ethiopia side): +- Processing of export declarations. +- Coordination with the Ethiopian Customs Authority for clearance. +- Ensuring compliance with all export regulations. +Rail transport: +- Transportation of containers from Galaan Multipurpose Port (GMP) or Modjo dry port to SGTD container freight station. +Djibouti transit and handling: +- Customs clearance in Djibouti. +- Coordination with Djibouti port and transit authorities. +- Freight forwarding and last-mile facilitation as required. +Excluded costs: +- Shore handling. +- Shifting of containers from SGTD to DMP or DMP to SGTD port.`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Give written/email instructions to the Service Provider for transportation of containers from Galaan Multipurpose Port (GMP) and/or Modjo to Djibouti. +Supply a minimum of two (2) 20ft containers (or an equivalent load to fill one flat wagon). +Submit all forwarding service booking requests at least seventy-two (72) hours prior to the scheduled train departure and no later than 7 days before the vessel cut-off time, whichever is applicable. +For clients requiring first-mile service, submit a first-mile service request notice no less than seventy-two (72) hours in advance. +Complete and submit accurate export documents as per the request of the Service Provider; payment must be submitted at least 36 hours before train departure. +Deliver all cargo to the designated loading port or freight station at least three (3) hours prior to the scheduled train loading time. +Failure to meet the stated deadlines may result in cancellation of the booking and transfer arrangements; any resulting delays, penalties, or additional costs shall be the sole responsibility of the Client. +If the Client fails to deliver the container, fails to provide the requested documents for completing export documents as instructed above, or cancels after wagon reservation, the Client shall pay USD 150.00 per wagon as a penalty, after notification. +Containers must have four (4) undamaged corners. +One flat wagon must carry either one 40ft container or two 20ft containers. +If two 20ft containers are loaded on one flat wagon, their weight difference must not exceed 10 tons. +The gross weight of the container must not exceed the standard loading capacity indicated on the container; the Client is responsible for ensuring full compliance with the maximum allowable load. +Prohibited cargo: cargo covered with tarpaulin is not allowed due to safety risks. +If the cargo to be transported is dangerous and/or valuable goods, notify the Service Provider 48 (forty-eight) hours before the wagon booking for further discussion and decision. +Refund requests before wagon booking require an official request, with a 3% administrative fee deducted. If the refund is due to the Service Provider, the Client shall receive a full refund. Refunds not requested and completed within six months shall be considered waived. +Any delay caused by missing or incorrect documents shall be the Client's responsibility. +100% of the transportation and customs clearance fee must be paid in advance.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Complete gate pass processing and submit to Nagad Station for each shipment within eighteen (18) hours after train departure. +The Service Provider reserves the right to refuse the transportation of any cargo classified as dangerous goods. +Maintain cargo liability insurance for railway transport; additional insurance for port handling or last-mile transport shall be the Client's responsibility. +The Service Provider is not liable for customs penalties or demurrage due to delays beyond its control. +Notify the Client immediately, in writing, of any delays, port issues, or customs holds. +The Service Provider shall not be liable for: +- Inherent defects of the cargo. +- Improper packing or loading conducted by the Client. +- Customs-related delays. +- Delays caused by force majeure events.`, + ), + a( + "force-majeure", + "Force Majeure", + `Neither party shall be liable for delays or non-performance caused by force majeure events beyond their reasonable control. +Force majeure shall be interpreted in accordance with the Ethiopian Civil Code.`, + ), + a( + "pricing", + "Pricing and Payment Terms", + `Railway transportation charges from GMP to SGTD: USD 819 (eight hundred nineteen) per 40ft container; USD 834 (eight hundred thirty-four) per two (2) 20ft containers. +Railway transportation charges from Modjo to SGTD: USD 725 (seven hundred twenty-five) per 40ft container; USD 725 (seven hundred twenty-five) per two (2) 20ft containers. +Where the total cargo weight exceeds fifty (50) metric tons per two (2) 20ft containers, an additional charge of USD 10 (ten) shall apply for each excess metric ton. +Freight forwarding and customs clearance charges from GMP to SGTD: USD 540 (five hundred forty) per 40ft container; USD 349 (three hundred forty-nine) per 20ft container. +Freight forwarding and customs clearance charges from Modjo to SGTD: USD 569 (five hundred sixty-nine) per 40ft container; USD 389 (three hundred eighty-nine) per 20ft container. +For consolidated containers containing more than one (1) shipping document, the first document shall be included under the agreed contract rate; any additional document within the same container shall be subject to an extra charge of USD 50 per document. +Payment must be supported by an official receipt before cargo departs from Galaan Multipurpose Port/Modjo. +If the Client uses PIL Shipping Line, any local charge incurred will be covered by the Client as per the invoice issued by the shipping line. +If storage or demurrage occurs due to Client-related issues (delay in document submission, payment delay, or any other Client-related reason), the Client shall pay the corresponding charges; charges apply per day after the free storage period, based on the invoice and SGTD tariff. +During export season, EDR may provide seasonal export support through the facilitation of empty containers. +Additional costs (if applicable): +- First-mile delivery service by truck within Addis Ababa or Modjo and surrounding areas, originating from warehouses or any other places designated by the Client, shall incur an additional cost fully covered by the Client. +- For clients utilizing EDR's first- or last-mile logistics services, the applicable charges shall vary based on the cargo movement route. +- The charge for first-mile delivery to Galaan Multipurpose Port and Modjo dry port shall be communicated to the Client by the Service Provider after receiving the necessary details regarding the cargo origin, type, and weight. +- For any vessel outbound charges, IMO charges, or other fees not included in the port handling payment, the Service Provider shall request the Client to settle the required amount based on the official receipt issued by the port or the shipping line. +Payment terms: +- All charges, including rail transport and customs clearance charges, remain 100% payable in advance. +- Payments shall be calculated based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date the wagon or train number is provided. +- If the exchange rate changes between the payment and the wagon assignment date, adjustments will be made accordingly. +- Any additional costs incurred due to customs issues or port delays shall be borne by the Client and paid based on actual costs, supported by official receipts, within 10 days. +- Late payment incurs a penalty of 10%.`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents shall constitute the contract between the Client and the Service Provider: +- Any amendments made to this contract (if applicable). +- This Contract Agreement. +- Final minutes of negotiation (if applicable). +In the event of any discrepancy between these documents, they shall be interpreted with priority in the order listed above.`, + ), + a( + "documentation", + "Documentation Requirements", + `Consignment Note (cargo handover document). +Payment summary prepared as per the agreed tariff, if required.`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider must certify the taking over and handing over of the container cargo on the Freight Carriage Acceptance Sheet of EDR in an appropriate manner and provide it to the Client. +The Freight Carriage Acceptance Sheet shall be prima facie evidence of the receipt of the container cargo by the Service Provider and of the kind, number, and weight of the goods. +Upon delivery of the cargo to the Client, the Cargo Handover Out Voucher signed by both parties shall serve as evidence of cargo receipt.`, + ), + a( + "amendment", + "Amendment", + `This contract can be amended by mutual agreement. +Notwithstanding the above, the Service Provider may revise transport tariffs due to operational and regulatory changes by providing at least five (5) working days' prior written notice to the Client.`, + ), + a( + "termination", + "Termination of Contract", + `The contract may be terminated: +- By mutual agreement. +- Upon completion of the contract period or agreed cargo shipments. +- If either party breaches fundamental terms. +If terminated for cause, the terminating party must issue a 15-day written notice specifying the breach and allow an opportunity to cure, if applicable.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `The contract is valid once signed by both parties and witnesses.`, + ), + a( + "duration", + "Contract Period", + `Valid until August 31, {{contractYear}}, with a possible extension upon mutual agreement.`, + ), + a( + "disputes", + "Settlement of Disputes", + `Disputes shall be settled amicably. +If amicable settlement fails, disputes shall be submitted to the Federal Court located in Addis Ababa. +The signatories confirm that they are fully authorized to sign and execute this Contract Agreement; the power of attorney of the signatories for the parties is enclosed with this contract agreement.`, + ), + ], +}; + +/* ─────────────────────────── INTERCITY / CONTAINER ───────────────────────── */ + +const INTERCITY_CONTAINER: ContractTemplateSeed = { + code: "INTERCITY_CONTAINER", + name: "Container Intercity Contract", + description: + "Domestic (intercity) container transport by railway between Ethiopian terminals — Galaan Multipurpose Port, Modjo dry port, and Dire Dawa — including empty repositioning.", + documentTitle: "Intercity Container Transport Service by Railway", + whereasClauses: [ + "The Client has requested and agreed to the transportation of container cargo between the agreed Ethiopian railway terminals (Galaan Multipurpose Port (GMP), Modjo dry port, and Dire Dawa), including the repositioning of empty containers between those terminals, using the Addis Ababa–Djibouti railway line within Ethiopia.", + "The Service Provider has agreed to transport the container cargo as per the terms of this contract.", + ], + articles: [ + a( + "objective", + "Objective and Scope of the Services", + `To provide domestic railway transportation services for 40ft and/or 20ft full containers between the agreed Ethiopian terminals (Galaan Multipurpose Port (GMP), Modjo dry port, and Dire Dawa), and the repositioning of empty containers between those terminals. +The scope of the services comprises: +- Railway transport service between the agreed origin and destination terminals. +- Cargo handling at Galaan Multipurpose Port (GMP).`, + ), + a( + "client-obligations", + "Obligations of the Client", + `Give written/email/electronic shipment instructions to the Service Provider for transportation of container cargo between the agreed terminals. +Prepare all necessary documents and facilities for shipment. +Ensure the minimum supply of containers per shipment agreed with the Service Provider for the selected loading terminal and destination. +One flat wagon must carry either one 40ft container or two 20ft containers. +If two 20ft containers are loaded on one flat wagon, their weight difference must not exceed 10 tons. +Ensure timely loading and unloading of cargo. +Assign representatives at both ends to oversee container handover and ensure the necessary arrangements for cargo reception at the destination upon arrival. +Maintain and provide detailed cargo information (type, weight, destination, etc.). +Be responsible for cargo handling, loading, and unloading of both empty and full containers at Modjo and Dire Dawa dry port. +Book wagons at least five (5) days in advance. +Ensure containers are ready one day before the planned loading date. +Collect the full container from Galaan Multipurpose Port (GMP) within three (3) calendar days from the day following the arrival notice. +If the Client fails to collect the container within the specified period, the Service Provider shall have the right to reposition the container to any location it deems appropriate; in such case, the Service Provider shall not be held responsible for any damage or loss arising from such repositioning. +If the Client fails to collect the container from Galaan Multipurpose Port within the specified period, the Client shall be liable to pay demurrage charges of 15 USD per day per 20ft container and 27 USD per day per 40ft container, calculated based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date of payment. +In the event the Client fails to collect the container(s) within the specified period, the Client shall be liable to pay double handling charges of 27 USD per 20ft container per handling or 40 USD per 40ft container per handling. +Collect the containers within one day at Dire Dawa and Modjo dry port, or make the necessary payment to the dry port as per the standard of the dry port. +Once empty containers are returned from the Client's premises and stored at a dry port while awaiting train allocation, any demurrage and/or storage charges incurred from the dry port thereafter shall be the sole responsibility of the Client. +Provide clean empty containers that meet the receiving terminal's standards; additional cleaning costs incurred due to non-compliance will be borne by the Client. +Ensure containers are structurally intact and meet weight distribution requirements. +Prohibited cargo: cargo covered with tarpaulin is not allowed due to safety risks. +Notify the Service Provider forty-eight (48) hours in advance before wagon booking if transporting hazardous or valuable goods. +If a booked wagon is not loaded due to Client-related issues, including but not limited to a damaged container, missing lock, unpaid demurrage, port system errors, or incomplete documentation and submission, the Client shall be charged 100% of the total price of the reserved wagon. +Refund requests before wagon booking require an official request, with a 3% administrative fee deducted. If the refund is due to the Service Provider, the Client shall receive a full refund. Refunds not requested and completed within six months shall be considered waived. +Pay 100% of the transportation fee in advance for each train set. +Settle additional penalties due to non-compliance within ten (10) days of invoice issuance. +Late payment incurs a penalty of an additional 10%.`, + ), + a( + "provider-obligations", + "Obligations of the Service Provider", + `Assign the necessary voyage based on the operational schedule and cargo demand, and notify the train schedule 48 hours in advance. +Provide a list of wagons/voyage or train number 24 hours in advance and update corrections 12 hours before arrival. +Provide safe transportation of the containers. +Deliver the cargo within two (2) days after train departure, provided that all required documents are submitted on time and no unforeseen circumstances or events occur. +In the event of export cargo operations, the Service Provider may prioritize the loading of export containers during the loading of empty containers and the unloading of containers from the train at Galaan Multipurpose Port. +The Service Provider reserves the right to refuse the transportation of any cargo classified as dangerous goods. +If any operational, technical, or mechanical problem occurs throughout the transit, notify the Client and the relevant authorities and arrange cargo transfer within four (4) days. +Provide accident or defect reports if needed. +Buy cargo liability insurance for each wagon.`, + ), + a( + "force-majeure", + "Force Majeure", + `Neither party shall be liable for delays or non-performance caused by force majeure events beyond their reasonable control. +Force majeure shall be interpreted in accordance with the Ethiopian Civil Code.`, + ), + a( + "pricing", + "Contract Price and Terms of Payment", + `The applicable rate per 40ft container or per two (2) 20ft containers for the agreed route shall be as per the prevailing EDR domestic container tariff, as set out in the commercial schedule of this contract. +If cargo exceeds 40 tons per two 20ft containers of gross weight, additional charges apply proportionally. +Gross weight shall be the total sum of cargo, packing, and container tare weight. +Payment for any additional tonnage shall be made in advance before the container is loaded onto the wagon. +The price of loading and unloading and container handling at Modjo and Dire Dawa dry port is not part of this contract; it is the Client's responsibility. +Additional costs (if applicable): +- Last-mile delivery service by truck from the destination terminal to the Client's premises shall incur an additional cost, fully covered by the Client. +- For clients utilizing EDR's last-mile logistics services, the applicable charges shall vary based on the cargo movement route and shall be communicated to the Client by the Service Provider after receiving the necessary details regarding the cargo destination, type, and weight. +All payments shall be made one hundred percent (100%) in advance. +Payment may be made in Ethiopian Birr based on the Commercial Bank of Ethiopia's daily selling exchange rate on the date the wagon or train number is provided; if the exchange rate changes between the payment and the wagon assignment date, adjustments will be made accordingly.`, + ), + a( + "contract-documents", + "Contract Documents", + `The following documents constitute this contract: +- Amendments (if any). +- This Contract Agreement. +- Final minutes of negotiation (if any). +If there is any discrepancy between the documents, they shall be interpreted with priority in the order listed above.`, + ), + a( + "documentation", + "Documentation Requirements", + `Equipment Interchange Receipt, Railway Waybill, Container Carriage Acceptance Sheet, and incidental charges (if any). +Payment summary as per the agreed contract price (if required).`, + ), + a( + "consignment-notes", + "Consignment Notes", + `The Service Provider must certify the taking over and handing over of the container cargo on the Freight Carriage Acceptance Sheet of EDR in an appropriate manner and provide it to the Client. +The Freight Carriage Acceptance Sheet shall be prima facie evidence of the receipt of the container cargo by the Service Provider and of the kind, number, and weight of the goods. +Upon delivery of the cargo to the Client, the Cargo Handover Out Voucher signed by both parties shall serve as evidence of cargo receipt.`, + ), + a( + "amendment", + "Amendment", + `This contract can be amended by mutual agreement. +Notwithstanding the above, the Service Provider may revise transport tariffs due to operational and regulatory changes by providing at least five (5) working days' prior written notice to the Client.`, + ), + a( + "termination", + "Termination of Contract", + `The contract may be terminated: +- By mutual agreement. +- Upon completion of the contract period or agreed cargo shipments. +- If either party breaches fundamental terms.`, + ), + a( + "effectiveness", + "Contract Effectiveness", + `The contract is valid once signed by both parties and witnesses.`, + ), + a( + "duration", + "Contract Period", + `Valid until August 31, {{contractYear}}, with a possible extension upon mutual agreement.`, + ), + a( + "disputes", + "Settlement of Disputes", + `Disputes shall be settled amicably. +If unresolved, disputes shall be taken to the Federal Court in Addis Ababa.`, + ), + ], +}; + +export const CONTRACT_TEMPLATE_DEFAULTS: ContractTemplateSeed[] = [ + IMPORT_BULK, + EXPORT_BULK, + INTERCITY_BULK, + IMPORT_CONTAINER, + EXPORT_CONTAINER, + INTERCITY_CONTAINER, +]; diff --git a/apps/edr-freight-web/backoffice/src/App.tsx b/apps/edr-freight-web/backoffice/src/App.tsx index 0bee03fc6..15c8cf19c 100644 --- a/apps/edr-freight-web/backoffice/src/App.tsx +++ b/apps/edr-freight-web/backoffice/src/App.tsx @@ -13,6 +13,7 @@ import { PackageOpen, Paperclip, Receipt, + ScrollText, Send, Settings, ShieldCheck, @@ -84,6 +85,8 @@ import UserManagementPage from "./pages/dashboard/user-management/UserManagement import UsersPage from "./pages/dashboard/user-management/UsersPage"; import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage"; import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage"; +import ContractTemplatesPage from "./pages/contract_templates/ContractTemplatesPage"; +import ContractTemplateEditorPage from "./pages/contract_templates/ContractTemplateEditorPage"; import FleetResourcePage from "./pages/fleet/FleetResourcePage"; import VehicleDetailPage from "./pages/fleet/VehicleDetailPage"; import DriverDetailPage from "./pages/fleet/DriverDetailPage"; @@ -461,6 +464,12 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [ icon: , permission: FREIGHT_PERMS.admin, }, + { + label: "Contract templates", + href: "/dashboard/contract-templates", + icon: , + permission: FREIGHT_PERMS.admin, + }, ], }, { @@ -1252,6 +1261,22 @@ const App = () => { } /> + + + + } + /> + + + + } + /> ["contract-templates", "list"] as const, + byCode: (code: string) => ["contract-templates", "detail", code] as const, + preview: (code: string) => ["contract-templates", "preview", code] as const, +}; + +export function useContractTemplates() { + return useQuery({ + queryKey: KEYS.list(), + queryFn: () => contractTemplatesService.list(), + }); +} + +export function useContractTemplate(code: string | undefined) { + return useQuery({ + queryKey: KEYS.byCode(code ?? ""), + queryFn: () => contractTemplatesService.getByCode(code as string), + enabled: Boolean(code), + }); +} + +/** Rendered mock-data HTML preview of the template's saved state. */ +export function useContractTemplatePreview(code: string | undefined, enabled = true) { + return useQuery({ + queryKey: KEYS.preview(code ?? ""), + queryFn: () => contractTemplatesService.preview(code as string), + enabled: Boolean(code) && enabled, + staleTime: 0, + }); +} + +function useTemplateMutation( + mutationFn: (vars: TVariables) => Promise, + successMessage: string, +) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn, + onSuccess: () => { + toast.success(successMessage); + void queryClient.invalidateQueries({ queryKey: KEYS.ROOT }); + }, + onError: (error: unknown) => { + const message = + (error as { response?: { data?: { message?: string } } })?.response?.data + ?.message ?? "Something went wrong"; + toast.error(Array.isArray(message) ? message.join(", ") : message); + }, + }); +} + +export function useUpdateContractTemplate(code: string) { + return useTemplateMutation( + (payload: UpdateContractTemplatePayload) => + contractTemplatesService.update(code, payload), + "Template updated", + ); +} + +export function useAddArticle(code: string) { + return useTemplateMutation( + (payload: ArticlePayload) => contractTemplatesService.addArticle(code, payload), + "Article added", + ); +} + +export function useUpdateArticle(code: string) { + return useTemplateMutation( + (vars: { articleId: string; payload: Partial }) => + contractTemplatesService.updateArticle(code, vars.articleId, vars.payload), + "Article updated", + ); +} + +export function useRemoveArticle(code: string) { + return useTemplateMutation( + (articleId: string) => contractTemplatesService.removeArticle(code, articleId), + "Article removed", + ); +} + +export function useReplaceArticles(code: string) { + return useTemplateMutation( + (articles: Array<{ id?: string; title: string; body: string }>) => + contractTemplatesService.replaceArticles(code, articles), + "Articles reordered", + ); +} diff --git a/apps/edr-freight-web/backoffice/src/pages/contract_templates/ContractTemplateEditorPage.tsx b/apps/edr-freight-web/backoffice/src/pages/contract_templates/ContractTemplateEditorPage.tsx new file mode 100644 index 000000000..0ad7ef301 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/pages/contract_templates/ContractTemplateEditorPage.tsx @@ -0,0 +1,468 @@ +import { useMemo, useState } from "react"; +import { useParams } from "react-router-dom"; +import { + ActionIcon, + Badge, + Button, + Card, + Center, + Group, + Loader, + Modal, + Paper, + Stack, + Switch, + Text, + Textarea, + TextInput, + Title, + Tooltip, +} from "@mantine/core"; +import { + ArrowDown, + ArrowUp, + Pencil, + Plus, + RefreshCw, + Settings2, + Trash2, +} from "lucide-react"; + +import { PageContainer, PageHeader } from "@/components/page"; +import { + useAddArticle, + useContractTemplate, + useContractTemplatePreview, + useRemoveArticle, + useReplaceArticles, + useUpdateArticle, + useUpdateContractTemplate, +} from "@/hooks/contract-templates/useContractTemplates"; +import type { ContractTemplateArticle } from "@/services/contract-templates.service"; + +const BODY_HINT = + 'One clause per line — clauses are numbered automatically. Prefix a line with "- " to nest it as a bullet under the previous clause. Placeholders like {{client.companyName}}, {{contractDate}}, {{contractYear}} and {{reference}} are filled from the contract.'; + +interface ArticleDraft { + id?: string; + title: string; + body: string; +} + +export default function ContractTemplateEditorPage() { + const { code } = useParams<{ code: string }>(); + const { data: template, isLoading } = useContractTemplate(code); + const preview = useContractTemplatePreview(code); + + const updateTemplate = useUpdateContractTemplate(code ?? ""); + const addArticle = useAddArticle(code ?? ""); + const updateArticle = useUpdateArticle(code ?? ""); + const removeArticle = useRemoveArticle(code ?? ""); + const replaceArticles = useReplaceArticles(code ?? ""); + + const [articleDraft, setArticleDraft] = useState(null); + const [deleteTarget, setDeleteTarget] = useState(null); + const [detailsOpen, setDetailsOpen] = useState(false); + + const sortedArticles = useMemo( + () => [...(template?.articles ?? [])].sort((a, b) => a.order - b.order), + [template], + ); + + const moveArticle = (index: number, delta: -1 | 1) => { + const next = [...sortedArticles]; + const target = index + delta; + if (target < 0 || target >= next.length) return; + [next[index], next[target]] = [next[target], next[index]]; + replaceArticles.mutate( + next.map(({ id, title, body }) => ({ id, title, body })), + ); + }; + + const saveArticle = () => { + if (!articleDraft) return; + if (articleDraft.id) { + updateArticle.mutate({ + articleId: articleDraft.id, + payload: { title: articleDraft.title, body: articleDraft.body }, + }); + } else { + addArticle.mutate({ title: articleDraft.title, body: articleDraft.body }); + } + setArticleDraft(null); + }; + + if (isLoading || !template) { + return ( + +
+ +
+
+ ); + } + + return ( + + + + {template.code.replaceAll("_", " · ")} + + {!template.isActive && ( + + Inactive + + )} + + } + action={ + + + updateTemplate.mutate({ isActive: event.currentTarget.checked }) + } + /> + + + + } + /> + +
+ {/* ── Article list ─────────────────────────────────────────────── */} + + {sortedArticles.map((article, index) => ( + + +
+ + Article {index + 1} + + {article.title} + + {article.body} + +
+ + + moveArticle(index, -1)} + > + + + + + moveArticle(index, 1)} + > + + + + + + setArticleDraft({ + id: article.id, + title: article.title, + body: article.body, + }) + } + > + + + + + setDeleteTarget(article)} + > + + + + +
+
+ ))} + {sortedArticles.length === 0 && ( + +
+ + No articles yet — add the first article to build this contract. + +
+
+ )} +
+ + {/* ── Live preview ─────────────────────────────────────────────── */} + + + + Document preview (mock data) + + + void preview.refetch()} + > + + + + + + {preview.isLoading ? ( +
+ +
+ ) : ( +