mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
Merge branch 'alpha' of github.com:Tria-plc/edr-platform into alpha
This commit is contained in:
42
.claude/skills/edr-db/SKILL.md
Normal file
42
.claude/skills/edr-db/SKILL.md
Normal file
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: edr-db
|
||||
description: Query, EXPLAIN-validate, and inspect the remote EDR freight dev database. Use whenever you need to check data, verify a raw SQL statement before shipping it, list a table's columns, check schema drift, or see which migrations are recorded. psql is NOT installed on this machine — this runner is the sanctioned path. Triggers - "check the db", "query edr_dev", "does column X exist", "validate this SQL", "is migration recorded", "seed check", diagnosing a 400/500 whose cause may be data or schema.
|
||||
---
|
||||
|
||||
# EDR dev-DB runner
|
||||
|
||||
One script, runs from anywhere in the repo (resolves `pg` from `apps/edr-freight-api`):
|
||||
|
||||
```bash
|
||||
node .claude/skills/edr-db/query.cjs "SELECT ... " # run SQL, console.table output
|
||||
node .claude/skills/edr-db/query.cjs explain "SELECT ..." # EXPLAIN-validate only (no rows touched)
|
||||
node .claude/skills/edr-db/query.cjs columns <table> # freight.<table> column list
|
||||
node .claude/skills/edr-db/query.cjs migrations [like] # public.migrations rows (newest first)
|
||||
node .claude/skills/edr-db/query.cjs drift <table> # bare column names, for diffing vs the entity
|
||||
```
|
||||
|
||||
Connection comes from `DB_HOST` / `DB_PORT` / `DB_USER` / `DB_PASSWORD` / `DB_NAME`,
|
||||
defaulting to the shared dev database (`edr_dev`).
|
||||
|
||||
## Rules that go with it
|
||||
|
||||
- **HARD RULE: every raw SQL statement you write into a service must pass
|
||||
`explain` here before you ship it.** A typo'd column is a runtime 500 the
|
||||
type-checker cannot catch.
|
||||
- Never assume a recorded migration applied — check `migrations <name>` **and**
|
||||
`columns <table>` together. Recorded-but-absent = schema drift; fix with a
|
||||
NEW repair migration (idempotent DDL, no-op `down()`), never by editing the
|
||||
recorded one.
|
||||
- Writes to dev data are fine for seeding/diagnosis but keep them idempotent
|
||||
(`WHERE NOT EXISTS` guards) — watch-mode API instances race `migrationsRun`,
|
||||
and non-idempotent statements have double-run here before.
|
||||
- Timestamps for new migrations: must be unique across `src/migrations/` AND
|
||||
higher than `SELECT max(timestamp) FROM public.migrations`.
|
||||
|
||||
## Diagnosing a pasted 400/500 (the recurring loop)
|
||||
|
||||
1. Find the route: grep the path segment in `apps/edr-freight-api/src/modules/*/**.controller.ts`.
|
||||
2. Read the service method — list its guard `throw`s. Most "bugs" are a guard
|
||||
working as designed (handover unsigned, fee unpaid, not PAID, wrong direction).
|
||||
3. Check the actual DB state for that record with this runner.
|
||||
4. Only then decide: guard doing its job (fix the UI affordance) vs real defect.
|
||||
88
.claude/skills/edr-db/query.cjs
Normal file
88
.claude/skills/edr-db/query.cjs
Normal file
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Dev-DB runner for the EDR freight database. psql is NOT installed on this
|
||||
* machine; this is the sanctioned way to query, EXPLAIN-validate, and inspect
|
||||
* the remote dev DB. Resolves `pg` from apps/edr-freight-api so it runs from
|
||||
* anywhere in the repo.
|
||||
*
|
||||
* node .claude/skills/edr-db/query.cjs "SELECT ... " run SQL (console.table)
|
||||
* node .claude/skills/edr-db/query.cjs explain "SELECT..." EXPLAIN-validate only
|
||||
* node .claude/skills/edr-db/query.cjs columns <table> list freight.<table> columns
|
||||
* node .claude/skills/edr-db/query.cjs migrations [like] public.migrations rows
|
||||
* node .claude/skills/edr-db/query.cjs drift <table> columns vs entity check helper
|
||||
*
|
||||
* Connection: DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME env vars, falling
|
||||
* back to the shared dev database.
|
||||
*/
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const repoRoot = path.resolve(__dirname, '..', '..', '..');
|
||||
const apiRequire = createRequire(
|
||||
path.join(repoRoot, 'apps', 'edr-freight-api', 'package.json'),
|
||||
);
|
||||
const { Client } = apiRequire('pg');
|
||||
|
||||
const cfg = {
|
||||
host: process.env.DB_HOST ?? '10.18.7.207',
|
||||
port: parseInt(process.env.DB_PORT ?? '5432', 10),
|
||||
user: process.env.DB_USER ?? 'postgres',
|
||||
password: process.env.DB_PASSWORD ?? 'dcba@1234',
|
||||
database: process.env.DB_NAME ?? 'edr_dev',
|
||||
};
|
||||
|
||||
const [, , first, ...rest] = process.argv;
|
||||
|
||||
async function main() {
|
||||
if (!first) {
|
||||
console.error('usage: query.cjs "<sql>" | explain "<sql>" | columns <table> | migrations [like] | drift <table>');
|
||||
process.exit(2);
|
||||
}
|
||||
const c = new Client(cfg);
|
||||
await c.connect();
|
||||
try {
|
||||
if (first === 'columns') {
|
||||
const r = await c.query(
|
||||
`SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema='freight' AND table_name=$1
|
||||
ORDER BY ordinal_position`,
|
||||
[rest[0]],
|
||||
);
|
||||
console.table(r.rows);
|
||||
} else if (first === 'migrations') {
|
||||
const like = rest[0] ? `%${rest[0]}%` : '%';
|
||||
const r = await c.query(
|
||||
`SELECT id, timestamp, name FROM public.migrations
|
||||
WHERE name ILIKE $1 ORDER BY id DESC LIMIT 40`,
|
||||
[like],
|
||||
);
|
||||
console.table(r.rows);
|
||||
} else if (first === 'drift') {
|
||||
// Quick drift signal: DB columns for the table. Compare by eye against
|
||||
// the entity's @Column names; a recorded-but-absent column = drift.
|
||||
const r = await c.query(
|
||||
`SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema='freight' AND table_name=$1 ORDER BY column_name`,
|
||||
[rest[0]],
|
||||
);
|
||||
console.log(r.rows.map((x) => x.column_name).join('\n'));
|
||||
} else if (first === 'explain') {
|
||||
await c.query('EXPLAIN ' + rest.join(' '));
|
||||
console.log('OK — statement is valid against', cfg.database);
|
||||
} else {
|
||||
const sql = [first, ...rest].join(' ');
|
||||
const started = Date.now();
|
||||
const r = await c.query(sql);
|
||||
if (Array.isArray(r.rows) && r.rows.length) console.table(r.rows);
|
||||
console.log(`${r.rowCount ?? 0} row(s), ${Date.now() - started}ms`);
|
||||
}
|
||||
} finally {
|
||||
await c.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('FAIL:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
40
.claude/skills/standup/SKILL.md
Normal file
40
.claude/skills/standup/SKILL.md
Normal file
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: standup
|
||||
description: Produce the work report Hagernesh asks for - "what have I done today", "tasks of yesterday and today", daily/period summaries for tickets or timesheets. Builds the answer from git history plus uncommitted work, never from memory alone.
|
||||
---
|
||||
|
||||
# Work report (standup / ticket summary)
|
||||
|
||||
Ground every line in git. Do not reconstruct from conversation memory — commits
|
||||
are the record.
|
||||
|
||||
## Gather
|
||||
|
||||
```bash
|
||||
# Commits in the window (adjust dates; author matches "Hagernesh")
|
||||
git log --since="YYYY-MM-DD 00:00" --until="YYYY-MM-DD 00:00" --author=Hagernesh \
|
||||
--pretty=format:"%h|%ad|%s" --date=short
|
||||
|
||||
# What each commit actually contains (subjects lie sometimes)
|
||||
git show --stat --pretty=format:"%s" <hash> | head -12
|
||||
|
||||
# In-flight work = part of "today" even if uncommitted
|
||||
git status --short
|
||||
git log origin/dev..HEAD --oneline # branch commits not yet in dev
|
||||
```
|
||||
|
||||
## Known pitfalls in this repo
|
||||
|
||||
- **Check subjects against contents.** Commit titles here sometimes mismatch the
|
||||
diff (e.g. a commit titled "unload export" that actually contained ISO
|
||||
container validation). Use `git show --stat` before reporting a title as fact.
|
||||
- A day with no commits usually still has uncommitted/in-flight work — report it
|
||||
as its own section with per-item status (done / uncommitted / blocked).
|
||||
- Merge commits from other authors are noise; filter with `--author`.
|
||||
|
||||
## Output format
|
||||
|
||||
One table per day: `# | Task (plain language, not the commit subject verbatim) |
|
||||
Commit / Status`. Follow with a short "carry-over / blocked" list naming what
|
||||
blocks each item. Keep it ticket-ready: no jargon that needs the repo open to
|
||||
decode.
|
||||
59
.claude/skills/verify/SKILL.md
Normal file
59
.claude/skills/verify/SKILL.md
Normal file
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: verify
|
||||
description: Project definition-of-done runner for the EDR platform. Use before calling any code change finished, before committing, and whenever asked "is it done / does it work". Runs the targeted checks that actually catch this repo's failure modes - type-check with turbo filters, @edr/types dist rebuild, raw-SQL EXPLAIN validation, migration safety, and honest test reporting.
|
||||
---
|
||||
|
||||
# Verify a change (EDR definition of done)
|
||||
|
||||
Run these in order. Report which you ran and what each said — never call
|
||||
unverified work done.
|
||||
|
||||
## 1. Type-check exactly what you touched
|
||||
|
||||
```bash
|
||||
pnpm turbo type-check --filter=@edr/freight-api --filter=@edr/freight-backoffice --filter=@edr/freight-portal
|
||||
```
|
||||
|
||||
Drop filters you didn't touch; whole-repo runs waste minutes. **If you edited
|
||||
`packages/types`, rebuild it FIRST** — consumers read its `dist/`, not `src/`:
|
||||
|
||||
```bash
|
||||
pnpm turbo build --filter=@edr/types
|
||||
```
|
||||
|
||||
## 2. Validate every raw SQL statement
|
||||
|
||||
Each new/edited `dataSource.query` / `manager.query` string must pass:
|
||||
|
||||
```bash
|
||||
node .claude/skills/edr-db/query.cjs explain "<the statement with dummy params>"
|
||||
```
|
||||
|
||||
## 3. Migration checklist (if you added one)
|
||||
|
||||
- Timestamp unique in `src/migrations/` **and** greater than
|
||||
`node .claude/skills/edr-db/query.cjs "SELECT max(timestamp) FROM public.migrations"`.
|
||||
- DDL idempotent (`IF NOT EXISTS`, guarded backfills).
|
||||
- Watch-mode reload does NOT run migrations — apply the SQL to the dev DB
|
||||
yourself or fully restart the API, then confirm with
|
||||
`query.cjs columns <table>`.
|
||||
|
||||
## 4. Tests — honest bar
|
||||
|
||||
`pnpm test` for `@edr/freight-api` is currently red on `dev`, so a green suite
|
||||
is not the bar. The bar: run the specs nearest what you touched and introduce
|
||||
**no new failure**. If you touched a service constructor, update its `.spec.ts`
|
||||
mocks (constructor-arity breaks are this repo's most common test regression).
|
||||
|
||||
## 5. Observe the behaviour
|
||||
|
||||
Compiling is not working. Hit the endpoint, drive the UI flow, or query the
|
||||
resulting rows. If you genuinely could not observe it, say so explicitly in the
|
||||
summary — do not imply it was seen working.
|
||||
|
||||
## 6. Before commit
|
||||
|
||||
- Conventional message (`fix(warehouses): …`). Git hooks do NOT run in this
|
||||
repo (husky shims exist but no user hooks) — nothing will catch it for you.
|
||||
- Lint the files you touched if in doubt: `pnpm turbo lint --filter=<pkg>`.
|
||||
- Do not commit or push unless the user asked.
|
||||
4
.github/workflows/deploy.yml
vendored
4
.github/workflows/deploy.yml
vendored
@@ -31,6 +31,7 @@ jobs:
|
||||
"freight-api"
|
||||
"freight-portal"
|
||||
"freight-backoffice"
|
||||
"gps-tracker"
|
||||
"passenger-api"
|
||||
"passenger-portal"
|
||||
"passenger-backoffice"
|
||||
@@ -71,6 +72,7 @@ jobs:
|
||||
echo "$CHANGED" | grep -q "^apps/edr-freight-api/" && SERVICES+=("freight-api")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-freight-web/portal/" && SERVICES+=("freight-portal")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-freight-web/backoffice/" && SERVICES+=("freight-backoffice")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-gps-tracker/" && SERVICES+=("gps-tracker")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-passenger-api/" && SERVICES+=("passenger-api")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-passenger-web/portal/" && SERVICES+=("passenger-portal")
|
||||
echo "$CHANGED" | grep -q "^apps/edr-passenger-web/backoffice/" && SERVICES+=("passenger-backoffice")
|
||||
@@ -109,7 +111,7 @@ jobs:
|
||||
- name: Resolve project and build env file
|
||||
run: |
|
||||
case "${{ matrix.service }}" in
|
||||
freight-api|freight-portal|freight-backoffice)
|
||||
freight-api|freight-portal|freight-backoffice|gps-tracker)
|
||||
echo "PROJECT=edr-freight" >> "$GITHUB_ENV"
|
||||
echo "BUILD_ENV_FILE=freight-web.build.env" >> "$GITHUB_ENV"
|
||||
;;
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -28,3 +28,4 @@ coverage/
|
||||
*~
|
||||
\#*\#
|
||||
.\#*
|
||||
docker-compose.override.yml
|
||||
|
||||
294
CLAUDE_NEW.md
Normal file
294
CLAUDE_NEW.md
Normal file
@@ -0,0 +1,294 @@
|
||||
# EDR Platform — Developer Guide
|
||||
|
||||
> This file is the contract. If something here contradicts the code, the code is the
|
||||
> truth and this file is a bug — fix it in the same PR.
|
||||
|
||||
## Overview
|
||||
|
||||
Monorepo for the Ethio Djibouti Railway (EDR) digital platform. Contains the Freight
|
||||
Management and Passenger Management applications, a payment microservice, plus shared
|
||||
types, NestJS utilities, and React component libraries.
|
||||
|
||||
The freight domain is the largest and most active area. Its core flow is:
|
||||
**booking → receive to warehouse → store → load onto train → dispatch → arrive → unload
|
||||
→ customer truck (self-haul) or EDR last mile → handover → exit paper → delivered.**
|
||||
Fees (storage, demurrage, double handling, truck detention) and allocation rules
|
||||
(warehouse/yard/zone) hang off the warehouse stage.
|
||||
|
||||
## Apps
|
||||
|
||||
| App | Package name | Purpose | Default port |
|
||||
| ------------------------------ | --------------------------- | -------------------------------------------------- | ------------ |
|
||||
| `edr-freight-api` | `@edr/freight-api` | NestJS API for freight management | 3001 |
|
||||
| `edr-freight-web/portal` | `@edr/freight-portal` | React frontend for freight customer/portal users | 5173 |
|
||||
| `edr-freight-web/backoffice` | `@edr/freight-backoffice` | React frontend for freight backoffice employees | 5183 |
|
||||
| `edr-passenger-api` | `@edr/passenger-api` | NestJS API for passenger management | 3002 |
|
||||
| `edr-payment-api` | `@edr/payment-api` | NestJS payment microservice (intents, webhooks) | 3003 |
|
||||
| `edr-passenger-web/portal` | `@edr/passenger-portal` | React frontend for passenger customer/portal users | 5174 |
|
||||
| `edr-passenger-web/backoffice` | `@edr/passenger-backoffice` | React frontend for passenger backoffice employees | 5184 |
|
||||
|
||||
`edr-freight-web` and `edr-passenger-web` are grouping folders, not workspace packages.
|
||||
Each holds a `portal/` and `backoffice/` sub-app, both independent pnpm workspace
|
||||
packages (see `pnpm-workspace.yaml`).
|
||||
|
||||
`apps/edr-landing/` exists on disk but has **no `package.json`** — it is not a workspace
|
||||
package and is not built, linted, or type-checked. Leave it alone unless asked.
|
||||
|
||||
## Packages
|
||||
|
||||
| Package | Purpose |
|
||||
| ---------------------- | ---------------------------------------------------------------------------------- |
|
||||
| `@edr/types` | Shared TypeScript interfaces and enums |
|
||||
| `@edr/api-common` | Shared NestJS decorators, filters, interceptors, pipes, BaseEntity, BaseRepository |
|
||||
| `@edr/ui-common` | Shared React components and theme |
|
||||
| `@edr/eslint-config` | Shared ESLint configurations (base/nestjs/react) |
|
||||
| `@edr/tsconfig` | Shared TypeScript configurations |
|
||||
| `@edr/prettier-config` | Shared Prettier configuration |
|
||||
|
||||
**`@edr/types` is consumed as its built `dist/`** (`main: ./dist/index.js`). Editing a
|
||||
type in `packages/types/src` changes nothing for consumers until you rebuild:
|
||||
|
||||
```bash
|
||||
pnpm turbo build --filter=@edr/types
|
||||
```
|
||||
|
||||
If a type-check fails on a field you just added to `@edr/types`, this is why.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Description |
|
||||
| --------------------------- | ---------------------------------------- |
|
||||
| `pnpm install` | Install all workspace dependencies |
|
||||
| `pnpm dev` | Run every app in dev mode |
|
||||
| `pnpm dev:freight` | Freight API + portal + backoffice |
|
||||
| `pnpm dev:freight:api` | Freight API only |
|
||||
| `pnpm dev:freight:portal` | Freight portal only |
|
||||
| `pnpm dev:freight:backoffice` | Freight backoffice only |
|
||||
| `pnpm dev:passenger` | Passenger API + web |
|
||||
| `pnpm dev:payment` | Payment API |
|
||||
| `pnpm build` | Build every package and app |
|
||||
| `pnpm test` | Run all tests (turbo) |
|
||||
| `pnpm lint` | Lint everything |
|
||||
| `pnpm type-check` | Type-check every package |
|
||||
| `pnpm format` | Format all files with Prettier |
|
||||
|
||||
Prefer targeted turbo filters over whole-repo runs — they are minutes faster:
|
||||
|
||||
```bash
|
||||
pnpm turbo type-check --filter=@edr/freight-api --filter=@edr/freight-backoffice
|
||||
```
|
||||
|
||||
`apps/edr-freight-api` also carries many `seed:*` scripts (demo bookings, wagons, trains,
|
||||
gate-pass scenarios). Read the script before running one; several write real rows.
|
||||
|
||||
## Environment & database
|
||||
|
||||
- Postgres is **external**. There is no postgres service in `docker-compose.yaml`, and
|
||||
no port `5433`/`5434` is published anywhere in the repo.
|
||||
- Freight API connection comes from `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`,
|
||||
`DB_NAME` (defaults: `localhost:5433`, `edr_freight`). Development points these at a
|
||||
remote database.
|
||||
- The connection sits behind a **connection pooler**. Do **not** pass
|
||||
`extra.options: '-c search_path=…'` — the pooler rejects it with
|
||||
`08P01 unsupported startup parameter in options: search_path`. `search_path` is applied
|
||||
per-connection in a pool `connect` handler instead. See
|
||||
`apps/edr-freight-api/src/config/database.config.ts` before touching connection options.
|
||||
- Each app owns its own database. **No cross-database joins**; cross-domain data flows
|
||||
through API calls or message queues.
|
||||
- `psql` is not installed on the dev machine. To query the database, write a short Node
|
||||
script using the `pg` client and run it from `apps/edr-freight-api` (where `pg` resolves).
|
||||
|
||||
## Hard rules
|
||||
|
||||
These are non-negotiable. Everything else is a strong default.
|
||||
|
||||
- **pnpm only.** Never run `npm install` or `yarn`.
|
||||
- **TypeScript strict mode** is on in every package and app. Do not weaken it, and do not
|
||||
reach for `any` to make an error go away.
|
||||
- **Never `synchronize: true`.** Not in production, not anywhere. It is currently `false`
|
||||
in every config and it has already corrupted this database twice (see *Migrations*).
|
||||
All schema changes go through TypeORM migrations.
|
||||
- **All entities** use UUID primary keys (`@PrimaryGeneratedColumn('uuid')`).
|
||||
- **All entities** extend `BaseEntity` from `@edr/api-common` — `createdAt`, `updatedAt`,
|
||||
`deletedAt` (soft delete).
|
||||
- **All columns** are `snake_case` in the database (`@Column({ name: 'snake_case' })`);
|
||||
TypeScript properties are `camelCase`.
|
||||
- **Controllers contain no business logic.** They validate, delegate, and shape the response.
|
||||
- **Conventional commits.** `fix(warehouses): …`, `feat(bookings): …`.
|
||||
- **Do not commit or push unless asked.** Propose the change; let the human decide when it lands.
|
||||
- **Do not break working behaviour to add new behaviour.** When a fix is risky, say so and
|
||||
offer the safe version.
|
||||
|
||||
## Architecture
|
||||
|
||||
### NestJS module shape
|
||||
|
||||
`module → controller → service → repository`, with `entities/` and `dto/` alongside.
|
||||
|
||||
### Data access — the real model
|
||||
|
||||
There are two sanctioned ways to read and write, and you must pick the right one:
|
||||
|
||||
1. **Entity CRUD → the custom repository class.** Extends `BaseRepository<Entity>` from
|
||||
`@edr/api-common`. Services inject the repository class, never `Repository<T>` directly.
|
||||
2. **Read projections, queue endpoints, cross-table reports → raw SQL** via
|
||||
`this.dataSource.query(...)` or `manager.query(...)` inside a transaction.
|
||||
|
||||
Raw SQL is normal here, not a smell — the warehouse and scheduling modules are built on it.
|
||||
It carries one obligation:
|
||||
|
||||
> **HARD RULE — validate every raw SQL statement against a real database before you ship it.**
|
||||
> A typo'd column name is a runtime 500 that no type-checker will catch. Run it through
|
||||
> `EXPLAIN` against the dev database. Column drift is real (see *Migrations*).
|
||||
|
||||
Writes inside a transaction use `manager.getRepository(Entity)`, not the injected repository,
|
||||
so they join the caller's transaction.
|
||||
|
||||
**Never do slow I/O inside a database transaction.** Queue the work and fan it out after
|
||||
commit. An SMS awaited inside a transaction once held capacity locks open for the whole
|
||||
gateway timeout. Any outbound HTTP call must set an explicit `timeout` — axios defaults to
|
||||
no timeout and will wait forever.
|
||||
|
||||
### Migrations
|
||||
|
||||
Migrations are the most dangerous surface in this repo. Two production-grade incidents have
|
||||
already come from it.
|
||||
|
||||
- `migrationsRun: true` — **migrations run automatically on API boot**, with
|
||||
`migrationsTransactionMode: 'each'`.
|
||||
- Consequences you must design for:
|
||||
- Running several `nest start --watch` instances races `migrationsRun`. A non-idempotent
|
||||
data migration can execute twice. Keep one instance.
|
||||
- A watch-mode hot reload does **not** re-run migrations. If you add a column that new
|
||||
code reads, apply it to the dev database yourself (idempotently) or fully restart.
|
||||
- **Give every migration a unique timestamp.** 34 timestamps are currently shared by two or
|
||||
more migrations. TypeORM orders by timestamp and breaks ties non-deterministically. Before
|
||||
adding one, check the filename prefix is unused *and* higher than the newest recorded row.
|
||||
- **Write idempotent DDL**: `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, and
|
||||
backfills guarded by `WHERE col IS NULL`.
|
||||
- **Never assume a recorded migration actually applied.** `AddGrnNumberToWarehouseInventory`
|
||||
was recorded in `migrations` while its column was absent — it had been dropped out of band.
|
||||
TypeORM will never re-run a recorded migration, so the fix is a *new repair migration*.
|
||||
- **A repair migration's `down()` should be a no-op.** Reverting a repair must not
|
||||
re-introduce the outage it fixed.
|
||||
|
||||
### Auth
|
||||
|
||||
Auth **is implemented in this repo.** Do not add TODO stubs, and do not write your own.
|
||||
|
||||
- `@CurrentUser()` (`@edr/api-common`) is a real `createParamDecorator`, not a metadata stub.
|
||||
- Route protection uses `@UseGuards(JwtGuard)` and `@UseGuards(PermissionGuard([...]))`.
|
||||
- Freight-domain checks use `hasFreightPermission(user, FREIGHT_PERMS.<area>.<action>)`.
|
||||
- Permissions are declared in `apps/edr-freight-api/src/seed/freight-permissions.registry.ts`.
|
||||
Add a permission there before referencing it.
|
||||
- IAM has its own migrations, run ahead of freight migrations from the same data source, and
|
||||
its own CLI scripts (`iam:migration:run`, `iam:seed:run`).
|
||||
|
||||
Ownership checks are separate from permission checks. A staff user passes
|
||||
`hasFreightPermission`; a customer must additionally pass an ownership assertion such as
|
||||
`assertCustomerCanAccessBooking`. Do not drop the ownership check because the permission check passed.
|
||||
|
||||
## Frontend conventions
|
||||
|
||||
- The web apps use **Mantine v9**. Its APIs differ from v6/v7 — check the installed version
|
||||
before copying a snippet.
|
||||
- `@edr/ui-common` holds shared components and theme; it is imported in ~94 files across the
|
||||
freight web apps. Prefer it over re-implementing a component.
|
||||
- **Blob downloads need the async error decoder.** A request with `responseType: 'blob'`
|
||||
delivers the JSON error body as a `Blob`, so the synchronous `extractErrorMessage` finds no
|
||||
`.message` and degrades to `"Request failed with status code 400"`. Use
|
||||
`await extractDownloadErrorMessage(error)` in every PDF/blob catch block. Mutation catches
|
||||
keep the synchronous version — their bodies are already parsed JSON.
|
||||
- Server-side guards must be reflected in the UI. If the API will reject the action, the
|
||||
button should be disabled, hidden, or explain the blocker — not fire and surface a 400.
|
||||
- Prefer disabling a control with a visible reason over silently hiding it.
|
||||
|
||||
## Notifications
|
||||
|
||||
In-app notifications resolve recipients from the company's **linked portal users**. If a
|
||||
company has none, `notify()` logs `0 recipients — skipped` and stores nothing, with no error.
|
||||
SMS and email still send, because they address the company's phone and email directly. Check
|
||||
this before debugging a "missing notification".
|
||||
|
||||
## PDF generation
|
||||
|
||||
Chromium is not installed in every environment. PDF paths must fall back to the hand-rolled
|
||||
generators (`styled-pdf.util.ts`, `buildFallbackPdf`, `buildTabularFallbackPdf`) rather than
|
||||
assume a headless browser exists.
|
||||
|
||||
## Adding a new module to a NestJS app
|
||||
|
||||
1. Create `modules/<feature>/` with `entities/`, `dto/`, and the four
|
||||
`<feature>.{module,controller,service,repository}.ts` files.
|
||||
2. The entity extends `BaseEntity` from `@edr/api-common`.
|
||||
3. The repository extends `BaseRepository<Entity>` from `@edr/api-common`.
|
||||
4. The service injects the repository class (not `Repository<T>` directly).
|
||||
5. The controller uses `@ApiTags()` + `@ApiOperation()` for Swagger, and guards the route.
|
||||
6. Register the module in the app's `app.module.ts`.
|
||||
|
||||
## Adding a new shared component to `@edr/ui-common`
|
||||
|
||||
1. Create `src/components/<Name>/<Name>.tsx` and `src/components/<Name>/index.ts`.
|
||||
2. Export from `src/index.ts`.
|
||||
3. Component is a functional component with a `ComponentNameProps` interface
|
||||
(named-exported alongside the default).
|
||||
|
||||
## Definition of done
|
||||
|
||||
A change is done when **all** of these hold. State explicitly which you ran.
|
||||
|
||||
1. **It type-checks.** `pnpm turbo type-check --filter=<each touched package>` passes.
|
||||
If you edited `packages/types`, you ran `pnpm turbo build --filter=@edr/types` first.
|
||||
2. **Raw SQL is verified.** Every new or edited SQL statement ran under `EXPLAIN` against the
|
||||
dev database without error.
|
||||
3. **Migrations are safe.** Unique timestamp, idempotent DDL, and — if the migration adds
|
||||
something the new code reads — applied to the dev database, since watch mode will not run it.
|
||||
4. **No new test failures.** `pnpm test` for `@edr/freight-api` is **currently red on `dev`**,
|
||||
so a fully green suite is not the bar. Run the specs covering what you touched and confirm
|
||||
you introduced no new failure.
|
||||
5. **Lint and format are clean** for the files you touched. Git hooks do **not** run these
|
||||
automatically (see below), so run them yourself.
|
||||
6. **The behaviour was actually observed**, not merely compiled — you drove the flow, hit the
|
||||
endpoint, or ran the query. If you could not, say so plainly.
|
||||
7. **Report honestly.** If a check was skipped, tests failed, or a fix is unverified, say it in
|
||||
the summary. Never describe unverified work as done.
|
||||
|
||||
### Hooks do not run
|
||||
|
||||
`commitlint.config.js` and a `lint-staged` config both exist, and husky's shims are installed
|
||||
at `.husky/_/`. But there are **no user hook scripts** (`.husky/pre-commit`,
|
||||
`.husky/commit-msg`), so husky's shim exits 0 and **neither lint-staged nor commitlint ever
|
||||
fire.** Nothing validates your commit message or formats your staged files. Run the checks by
|
||||
hand; do not assume the hook caught it.
|
||||
|
||||
## Known traps
|
||||
|
||||
| Trap | What happens | What to do |
|
||||
| --- | --- | --- |
|
||||
| Schema drift | A recorded migration's column is missing; queries and inserts 500 | Write a new repair migration; never edit the recorded one |
|
||||
| Duplicate migration timestamps | Non-deterministic ordering; a migration can be skipped | Pick a fresh, higher timestamp |
|
||||
| `@edr/types` not rebuilt | Consumers can't see your new field | `pnpm turbo build --filter=@edr/types` |
|
||||
| Slow I/O in a transaction | Locks held for the gateway timeout | Queue it; fan out after commit; always set an HTTP timeout |
|
||||
| Blob error bodies | Real 400 message replaced by "Request failed with status code 400" | `await extractDownloadErrorMessage(error)` |
|
||||
| Company with no portal user | In-app notification silently vanishes | Check portal users before debugging |
|
||||
| Watch-mode reload | New code, old schema → 500 | Apply the migration to the dev DB or restart fully |
|
||||
|
||||
## Project skills
|
||||
|
||||
Reusable workflows live in `.claude/skills/`. Use them instead of re-deriving the steps:
|
||||
|
||||
| Skill | Use for |
|
||||
| --- | --- |
|
||||
| `edr-db` | Query / `EXPLAIN`-validate / inspect the remote dev DB (`node .claude/skills/edr-db/query.cjs …`). psql is not installed — this is the sanctioned path. Also carries the 400/500 diagnosis loop. |
|
||||
| `verify` | The definition-of-done runner: targeted type-check, `@edr/types` rebuild, SQL validation, migration checklist, honest test bar. Run before calling anything finished. |
|
||||
| `standup` | "What did I do today / this week" reports for tickets, grounded in `git log` — including the check that commit subjects match their contents. |
|
||||
|
||||
## Working style
|
||||
|
||||
- **Verify before asserting.** Read the code or query the database. Do not infer behaviour
|
||||
from a filename.
|
||||
- **Investigate, then propose.** For anything risky or wide-reaching, present the plan and the
|
||||
trade-off before changing files.
|
||||
- **Small, reviewable commits**, one logical change each, conventional message.
|
||||
- **Branch from `dev`; PRs target `dev`.**
|
||||
- When a finding turns out to be wrong, say so and retract it. A rejected finding is a result.
|
||||
@@ -56,7 +56,7 @@
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@nestjs/websockets": "^11.1.27",
|
||||
"@tria-plc/api-common": "file:../../local-packages/tria-plc-api-common-1.4.3.tgz",
|
||||
"@tria-plc/iamapi-common": "file:../../local-packages/tria-plc-iamapi-common-0.7.7.tgz",
|
||||
"@tria-plc/iamapi-common": "file:../../local-packages/tria-plc-iamapi-common-0.7.9.tgz",
|
||||
"amqp-connection-manager": "^5.0.0",
|
||||
"amqplib": "^2.0.1",
|
||||
"axios": "^1.16.1",
|
||||
|
||||
@@ -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";
|
||||
@@ -68,6 +69,7 @@ import { MarshallingDemoTrainsSeeder } from "./seed/marshalling-demo-trains.seed
|
||||
import { FreightPermissionKeyMigrationSeeder } from "./seed/freight-permission-key-migration.seeder";
|
||||
import { DemoFreightDataSeeder } from "./seed/demo-freight-data.seeder";
|
||||
import { GovCompaniesSeeder } from "./seed/gov-companies.seeder";
|
||||
import { EdrTruckFleetSeeder } from "./seed/edr-truck-fleet.seeder";
|
||||
import { ApprovedFirstLastMileDemoBookingsSeeder } from "./seed/approved-first-lastmile-demo-bookings.seeder";
|
||||
import { PaidImportExportMileDemoSeeder } from "./seed/paid-import-export-mile-demo.seeder";
|
||||
//New Trains, Wagons, Container and Cargo management modules
|
||||
@@ -92,6 +94,7 @@ import { FirstMileModule } from "./modules/first-mile/first-mile.module";
|
||||
import { LastMileModule } from "./modules/last-mile/last-mile.module";
|
||||
import { InterchangeDocumentsModule } from "./modules/interchange-documents/interchange-documents.module";
|
||||
import { ImportOperationsModule } from "./modules/import-operations/import-operations.module";
|
||||
import { AiModule } from "./modules/ai/ai.module";
|
||||
import { LoggerMiddleware } from "./logger.middleware";
|
||||
|
||||
@Module({
|
||||
@@ -158,6 +161,7 @@ import { LoggerMiddleware } from "./logger.middleware";
|
||||
NotificationInboxModule,
|
||||
FileUploadSettingsModule,
|
||||
DropdownSettingsModule,
|
||||
ContractTemplatesModule,
|
||||
OtpModule,
|
||||
RuleEngineModule,
|
||||
BackofficeModule,
|
||||
@@ -186,6 +190,7 @@ import { LoggerMiddleware } from "./logger.middleware";
|
||||
ImportOperationsModule,
|
||||
VerifaydaModule,
|
||||
FleetHistoryModule,
|
||||
AiModule,
|
||||
],
|
||||
providers: [
|
||||
EdrOrgSeeder,
|
||||
@@ -197,6 +202,7 @@ import { LoggerMiddleware } from "./logger.middleware";
|
||||
FreightPermissionKeyMigrationSeeder,
|
||||
DemoFreightDataSeeder,
|
||||
GovCompaniesSeeder,
|
||||
EdrTruckFleetSeeder,
|
||||
IndodeFacilitySeeder,
|
||||
Batch14TestDataSeeder,
|
||||
Batch5TestDataSeeder,
|
||||
@@ -229,6 +235,7 @@ export class AppModule implements OnApplicationBootstrap {
|
||||
private readonly freightPermissionKeyMigrationSeeder: FreightPermissionKeyMigrationSeeder,
|
||||
private readonly demoFreightDataSeeder: DemoFreightDataSeeder,
|
||||
private readonly govCompaniesSeeder: GovCompaniesSeeder,
|
||||
private readonly edrTruckFleetSeeder: EdrTruckFleetSeeder,
|
||||
) { }
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
@@ -259,6 +266,7 @@ export class AppModule implements OnApplicationBootstrap {
|
||||
// Government entities (with importer/exporter profiles) that government
|
||||
// bookings bill to. Idempotent — keyed by fixed IDs.
|
||||
await this.govCompaniesSeeder.run();
|
||||
await this.edrTruckFleetSeeder.run();
|
||||
}
|
||||
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
|
||||
107
apps/edr-freight-api/src/contracts/contract-article.util.ts
Normal file
107
apps/edr-freight-api/src/contracts/contract-article.util.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import Handlebars from 'handlebars';
|
||||
|
||||
/** One numbered clause of a dynamic article, with optional nested bullets. */
|
||||
export interface RenderedClause {
|
||||
text: string;
|
||||
/** Computed outline number, e.g. "3" or "2.1.4". */
|
||||
number: string;
|
||||
/** Nesting level: 1 = clause, 2 = sub-clause (x.y), 3 = x.y.z, … */
|
||||
depth: number;
|
||||
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[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Leading outline token on a clause line: "1.", "2)", "1.1", "1.1.1." …
|
||||
* The token's segment count sets the clause depth; its digits are ignored —
|
||||
* numbering is recomputed sequentially so stale numbers self-heal.
|
||||
* A single-segment token requires its "."/")" ("10 tons…" is prose, "10. x"
|
||||
* is clause ten); multi-segment tokens ("1.1") may omit it. A token may also
|
||||
* end the line — that is an empty clause still being typed in the editor.
|
||||
*/
|
||||
const CLAUSE_NUMBER_RE = /^(?:(\d+(?:\.\d+)+)[.)]?|(\d+)[.)])(?:\s+|$)/;
|
||||
|
||||
/** Deepest supported sub-clause level (1.1.1.1.1.1). */
|
||||
const MAX_CLAUSE_DEPTH = 6;
|
||||
|
||||
/**
|
||||
* Parse a template article body into clauses. Format: one clause per line.
|
||||
* A leading outline number ("2. ", "2.1 ", "2.1.3 ") nests the line as a
|
||||
* sub-clause at that depth — the typed digits are stripped and renumbered
|
||||
* sequentially, so editing order never leaves stale numbers in the document.
|
||||
* Lines prefixed with "- " become bullets nested under the preceding clause.
|
||||
* A body that reduces to a single un-numbered clause without bullets renders
|
||||
* as a plain paragraph rather than a numbered list of one.
|
||||
*/
|
||||
export function parseArticleBody(body: string): Pick<RenderedArticle, 'paragraph' | 'clauses'> {
|
||||
const lines = (body ?? '')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
|
||||
const clauses: RenderedClause[] = [];
|
||||
// counters[i] = current number at depth i+1; truncated when a shallower
|
||||
// clause arrives so deeper numbering restarts at 1.
|
||||
const counters: number[] = [];
|
||||
let sawNumberToken = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('- ')) {
|
||||
const bullet = line.slice(2).trim();
|
||||
if (clauses.length === 0) {
|
||||
counters.splice(0, counters.length, 1);
|
||||
clauses.push({ text: bullet, number: '1', depth: 1, bullets: [] });
|
||||
} else {
|
||||
clauses[clauses.length - 1].bullets.push(bullet);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = CLAUSE_NUMBER_RE.exec(line);
|
||||
const token = match ? (match[1] ?? match[2]) : null;
|
||||
let depth = token ? Math.min(token.split('.').length, MAX_CLAUSE_DEPTH) : 1;
|
||||
// A sub-clause can only sit directly under an existing parent — "1.1.1"
|
||||
// typed as the first line clamps to whatever level is actually open.
|
||||
depth = Math.min(depth, counters.length + 1);
|
||||
if (match) sawNumberToken = true;
|
||||
|
||||
counters.splice(depth);
|
||||
while (counters.length < depth) counters.push(0);
|
||||
counters[depth - 1] += 1;
|
||||
|
||||
clauses.push({
|
||||
text: match ? line.slice(match[0].length).trim() : line,
|
||||
number: counters.slice(0, depth).join('.'),
|
||||
depth,
|
||||
bullets: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (clauses.length === 1 && clauses[0].bullets.length === 0 && !sawNumberToken) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
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([]);
|
||||
});
|
||||
|
||||
it('nests numbered sub-clauses by their outline token and renumbers sequentially', () => {
|
||||
const parsed = parseArticleBody(
|
||||
'1. Scope\n5.1 Rail transport\n1.1.1 Wagon supply\n2. Payment',
|
||||
);
|
||||
expect(parsed.clauses.map((c) => [c.number, c.depth, c.text])).toEqual([
|
||||
['1', 1, 'Scope'],
|
||||
['1.1', 2, 'Rail transport'],
|
||||
['1.1.1', 3, 'Wagon supply'],
|
||||
['2', 1, 'Payment'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('clamps a sub-clause with no open parent to the next available level', () => {
|
||||
const parsed = parseArticleBody('1.1.1 Orphan sub-clause\nSecond clause.');
|
||||
expect(parsed.clauses.map((c) => [c.number, c.depth])).toEqual([
|
||||
['1', 1],
|
||||
['2', 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves prose that merely starts with a number un-tokenized', () => {
|
||||
const parsed = parseArticleBody('10 tons is the minimum load.\nPayment in advance.');
|
||||
expect(parsed.clauses.map((c) => c.text)).toEqual([
|
||||
'10 tons is the minimum load.',
|
||||
'Payment in advance.',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps a single explicitly numbered line as a clause, not a paragraph', () => {
|
||||
const parsed = parseArticleBody('1. Only clause.');
|
||||
expect(parsed.paragraph).toBeUndefined();
|
||||
expect(parsed.clauses.map((c) => [c.number, c.text])).toEqual([['1', 'Only clause.']]);
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{{#each dynamicArticles}}
|
||||
<section class="article">
|
||||
<h2 class="article-heading"><span class="article-no">Article {{number}}</span><span class="article-name">{{title}}</span></h2>
|
||||
{{#if paragraph}}
|
||||
<p class="article-paragraph">{{paragraph}}</p>
|
||||
{{else}}
|
||||
<ol class="clauses">
|
||||
{{#each clauses}}
|
||||
<li class="clause depth-{{depth}}">
|
||||
<span class="clause-no">{{number}}.</span>
|
||||
{{text}}
|
||||
{{#if bullets.length}}
|
||||
<ul class="clause-bullets">
|
||||
{{#each bullets}}
|
||||
<li>{{this}}</li>
|
||||
{{/each}}
|
||||
</ul>
|
||||
{{/if}}
|
||||
</li>
|
||||
{{/each}}
|
||||
</ol>
|
||||
{{/if}}
|
||||
</section>
|
||||
{{/each}}
|
||||
@@ -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,80 @@
|
||||
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 {
|
||||
list-style: none;
|
||||
margin: 6px 0 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
ol.clauses > li.clause {
|
||||
margin-bottom: 6px;
|
||||
text-align: justify;
|
||||
}
|
||||
ol.clauses .clause-no {
|
||||
color: #0e5b45;
|
||||
font-family: Arial, sans-serif;
|
||||
font-size: 9.5pt;
|
||||
font-weight: 700;
|
||||
margin-right: 6px;
|
||||
}
|
||||
/* Sub-clause indentation: each outline level steps in. */
|
||||
ol.clauses > li.depth-2 { padding-left: 20px; }
|
||||
ol.clauses > li.depth-3 { padding-left: 40px; }
|
||||
ol.clauses > li.depth-4 { padding-left: 60px; }
|
||||
ol.clauses > li.depth-5 { padding-left: 80px; }
|
||||
ol.clauses > li.depth-6 { padding-left: 100px; }
|
||||
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 +331,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 +346,7 @@
|
||||
}
|
||||
.sig-image-box {
|
||||
align-items: center;
|
||||
border: 1px dashed #94a3b8;
|
||||
border: 1px dashed #7fbfa9;
|
||||
display: flex;
|
||||
height: 28mm;
|
||||
justify-content: center;
|
||||
@@ -231,21 +358,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 {
|
||||
|
||||
184
apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs
Normal file
184
apps/edr-freight-api/src/contracts/templates/edr-dynamic.hbs
Normal file
@@ -0,0 +1,184 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>{{dynamicDocumentTitle}} — {{reference}}</title>
|
||||
{{> styles}}
|
||||
</head>
|
||||
<body>
|
||||
<main class="contract">
|
||||
|
||||
{{!-- ─────────────────────────── Cover page ─────────────────────────── --}}
|
||||
<section class="cover page-section">
|
||||
<div class="brand-row">
|
||||
<div class="logo-mark">EDR</div>
|
||||
<div>
|
||||
<p class="kicker">Ethio-Djibouti Standard Gauge Railway Share Company</p>
|
||||
<p class="muted">Freight Transport Services</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cover-title">
|
||||
<p class="document-label">Contract Agreement</p>
|
||||
<div class="cover-rule"></div>
|
||||
<p class="cover-for">for</p>
|
||||
<h1>{{dynamicDocumentTitle}}</h1>
|
||||
<p class="cover-between">between</p>
|
||||
<p class="cover-party">Ethio-Djibouti Standard Gauge Railway Share Company</p>
|
||||
<p class="cover-between">and</p>
|
||||
<p class="cover-party">{{client.companyName}}</p>
|
||||
<div class="cover-rule"></div>
|
||||
</div>
|
||||
|
||||
<table class="meta-grid">
|
||||
<tr>
|
||||
<th>Contract Ref No.</th>
|
||||
<td>{{reference}}</td>
|
||||
<th>Contract Date</th>
|
||||
<td>{{contractDate}}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Trade Direction</th>
|
||||
<td>{{schedule.tradeDirection}}</td>
|
||||
<th>Freight Type</th>
|
||||
<td>{{schedule.freightType}}</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p class="cover-year">{{contractYear}}</p>
|
||||
</section>
|
||||
|
||||
{{!-- ──────────────────────────── Preamble ──────────────────────────── --}}
|
||||
<section class="page-section">
|
||||
<h2>Parties to the Agreement</h2>
|
||||
<p class="lead">
|
||||
This Contract Agreement is made on <strong>{{contractDate}}</strong>.
|
||||
</p>
|
||||
<p class="between-label">Between</p>
|
||||
<p>
|
||||
<strong>Ethio-Djibouti Standard Gauge Railway Share Company (EDR)</strong>, 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
|
||||
<strong>"Service Provider"</strong>);
|
||||
</p>
|
||||
<p class="between-label">And</p>
|
||||
<p>
|
||||
<strong>{{client.companyName}}</strong>, 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 <strong>"Client"</strong>).
|
||||
</p>
|
||||
|
||||
<div class="party-grid">
|
||||
<div class="party-card">
|
||||
<h3>Service Provider</h3>
|
||||
<p class="party-name">{{provider.name}}</p>
|
||||
<dl>
|
||||
<dt>Address</dt><dd>{{provider.address}}</dd>
|
||||
<dt>Phone</dt><dd>{{provider.phone}}</dd>
|
||||
<dt>Email</dt><dd>{{provider.email}}</dd>
|
||||
<dt>TIN</dt><dd>{{provider.tinNumber}}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="party-card">
|
||||
<h3>Client</h3>
|
||||
<p class="party-name">{{client.companyName}}</p>
|
||||
<dl>
|
||||
<dt>Address</dt><dd>{{client.companyAddress}}</dd>
|
||||
<dt>Location</dt><dd>{{client.companyLocation}}</dd>
|
||||
<dt>Phone</dt><dd>{{client.phone}}</dd>
|
||||
<dt>Email</dt><dd>{{client.email}}</dd>
|
||||
<dt>TIN</dt><dd>{{client.tinNumber}}</dd>
|
||||
<dt>VAT</dt><dd>{{client.vatNumber}}</dd>
|
||||
<dt>Business license</dt><dd>{{client.businessLicense}}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{{#if dynamicWhereas.length}}
|
||||
<section class="page-section">
|
||||
<h2>Recitals</h2>
|
||||
{{#each dynamicWhereas}}
|
||||
<p><span class="whereas-label">Whereas</span> {{this}}</p>
|
||||
{{/each}}
|
||||
<p class="now-therefore">Now, therefore, the parties agree as follows:</p>
|
||||
</section>
|
||||
{{/if}}
|
||||
|
||||
{{!-- ──────────────────────── Dynamic articles ──────────────────────── --}}
|
||||
{{> dynamic_articles}}
|
||||
|
||||
{{!-- ─────────────────── Commercial schedule (annex) ─────────────────── --}}
|
||||
<section class="page-section annex">
|
||||
<h2>Annex A — Commercial Schedule</h2>
|
||||
<table class="details-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Route</th>
|
||||
<td>{{schedule.originLabel}} → {{schedule.destinationLabel}}</td>
|
||||
<th>Service type</th>
|
||||
<td>{{schedule.serviceType}}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Cargo</th>
|
||||
<td>{{schedule.cargoDescription}}</td>
|
||||
<th>Hazardous cargo</th>
|
||||
<td>{{schedule.hazardousLabel}}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Equipment return</th>
|
||||
<td>{{schedule.equipmentReturn}}</td>
|
||||
<th>Payment currency</th>
|
||||
<td>{{paymentArticle}}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{{#if pricing.unitRates.length}}
|
||||
<h3>Agreed Unit Rates</h3>
|
||||
<p class="muted-note">
|
||||
The rates below are the frozen unit prices applicable to this contract. Quantities and resulting
|
||||
totals are determined per shipment at booking time.
|
||||
</p>
|
||||
<table class="schedule">
|
||||
<thead>
|
||||
<tr><th>Item</th><th>Unit price</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{#each pricing.unitRates}}
|
||||
<tr>
|
||||
<td>{{label}}</td>
|
||||
<td>{{currency}} {{unitPrice}} / {{unit}}</td>
|
||||
</tr>
|
||||
{{/each}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{/if}}
|
||||
</section>
|
||||
|
||||
{{!-- ────────────────────────── Signatures ───────────────────────────── --}}
|
||||
<section class="page-section">
|
||||
<h2>Execution</h2>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
{{> signatures_block}}
|
||||
|
||||
<div class="witnesses">
|
||||
<p class="sig-title">Witnesses</p>
|
||||
<table class="witness-table">
|
||||
<thead>
|
||||
<tr><th></th><th>Name</th><th>Signature</th><th>Date</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>1.</td><td></td><td></td><td></td></tr>
|
||||
<tr><td>2.</td><td></td><td></td><td></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
await queryRunner.query(`DROP TABLE IF EXISTS freight.contract_templates;`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
/**
|
||||
* Repairs `freight.warehouse_inventory.grn_number`.
|
||||
*
|
||||
* AddGrnNumberToWarehouseInventory1828000000000 is recorded in `migrations` but
|
||||
* the column is absent on at least one environment - it was added, then dropped
|
||||
* out-of-band (a stray `synchronize: true`, same class of damage that
|
||||
* RepairSynchronizeDrift1870000000000 already had to undo). Because TypeORM has
|
||||
* the original recorded, it will never re-run it.
|
||||
*
|
||||
* Without the column, everything that reads or writes a GRN fails with
|
||||
* `column ... grn_number does not exist`:
|
||||
* - bulkReceive() -> INSERT names grn_number (receive to warehouse)
|
||||
* - importQueueByStatuses() -> Unloaded + Dispatch queues
|
||||
* - exportInventoryByStatus() -> Received / Ready-To-Load / Loaded tabs
|
||||
* - grnDocument() -> GRN PDF
|
||||
*
|
||||
* Idempotent: a no-op on environments where the column survived.
|
||||
*/
|
||||
export class RepairGrnNumberColumn2090000000000 implements MigrationInterface {
|
||||
name = 'RepairGrnNumberColumn2090000000000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.warehouse_inventory
|
||||
ADD COLUMN IF NOT EXISTS grn_number VARCHAR(100) NULL
|
||||
`);
|
||||
|
||||
// Recover the GRN for rows received before the column existed: it was also
|
||||
// written into the receive note as "GRN Number: <value>".
|
||||
await queryRunner.query(`
|
||||
UPDATE freight.warehouse_inventory
|
||||
SET grn_number = substring(notes FROM 'GRN Number: ([^\\n\\r]+)')
|
||||
WHERE grn_number IS NULL
|
||||
AND notes IS NOT NULL
|
||||
AND notes ~ 'GRN Number: '
|
||||
`);
|
||||
|
||||
await queryRunner.query(`
|
||||
CREATE INDEX IF NOT EXISTS idx_warehouse_inventory_grn_number
|
||||
ON freight.warehouse_inventory(grn_number)
|
||||
WHERE grn_number IS NOT NULL
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliberately a no-op. Dropping the column is what broke these environments
|
||||
* in the first place, and the original 1828 migration already owns its own
|
||||
* down(). Reverting this repair must not re-introduce the outage.
|
||||
*/
|
||||
public async down(): Promise<void> {
|
||||
// intentionally empty
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
/**
|
||||
* `company_profiles.status` defaulted to 'active', so any insert that omitted
|
||||
* the column produced an operational role that was approved without ever being
|
||||
* reviewed. Every live write path already passes 'pending' explicitly; this
|
||||
* closes the hole at the schema level.
|
||||
*
|
||||
* Deliberately no data backfill. A role approved through setCompanyProfileStatus
|
||||
* always stamps `reviewed_at`, so `status = 'active' AND reviewed_at IS NULL`
|
||||
* flags a role that skipped review — but it also matches rows approved before
|
||||
* `reviewed_at` existed (migration 2000000000001). Auditing that set is a
|
||||
* judgement call about real customers, not something to automate here.
|
||||
*/
|
||||
export class CompanyProfileDefaultPending2100000000000
|
||||
implements MigrationInterface
|
||||
{
|
||||
name = 'CompanyProfileDefaultPending2100000000000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "freight"."company_profiles" ALTER COLUMN "status" SET DEFAULT 'pending'`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "freight"."company_profiles" ALTER COLUMN "status" SET DEFAULT 'active'`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
/**
|
||||
* Auto-load onto a selected train: a warehouse_loadings row now records WHICH
|
||||
* train the item was loaded onto (train_schedule_id), and wagon_id becomes
|
||||
* nullable because a schedule-level load may not resolve to a single wagon.
|
||||
*/
|
||||
export class WarehouseLoadingTrainAssociation2100000000000 implements MigrationInterface {
|
||||
name = 'WarehouseLoadingTrainAssociation2100000000000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.warehouse_loadings
|
||||
ADD COLUMN IF NOT EXISTS train_schedule_id UUID NULL
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.warehouse_loadings
|
||||
ALTER COLUMN wagon_id DROP NOT NULL
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
CREATE INDEX IF NOT EXISTS idx_warehouse_loadings_train_schedule
|
||||
ON freight.warehouse_loadings(train_schedule_id)
|
||||
WHERE train_schedule_id IS NOT NULL
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_warehouse_loadings_train_schedule`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.warehouse_loadings DROP COLUMN IF EXISTS train_schedule_id
|
||||
`);
|
||||
// wagon_id stays nullable on revert: restoring NOT NULL would fail on rows
|
||||
// recorded without a wagon and re-introduce the outage this fixes.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
/**
|
||||
* Repair migration. `SeparateVehicleAvailability1890000000000` is recorded in
|
||||
* public.migrations but the `availability` column is absent on some databases
|
||||
* (recorded-but-not-applied drift). Because the original is already recorded,
|
||||
* TypeORM will not re-run it, so `vehiclesService.findAll` (a query builder that
|
||||
* selects every entity column) 500s with `column "availability" does not exist`.
|
||||
*
|
||||
* This re-adds the column idempotently and backfills. Safe to run everywhere:
|
||||
* `IF NOT EXISTS` makes it a no-op where the column already exists.
|
||||
*/
|
||||
export class RepairVehicleAvailabilityColumn2110000000000
|
||||
implements MigrationInterface
|
||||
{
|
||||
name = "RepairVehicleAvailabilityColumn2110000000000";
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.vehicles
|
||||
ADD COLUMN IF NOT EXISTS availability varchar DEFAULT 'FREE'
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
UPDATE freight.vehicles SET availability = 'FREE' WHERE availability IS NULL
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(): Promise<void> {
|
||||
// No-op: dropping a column other code now depends on would reintroduce the
|
||||
// drift. The original SeparateVehicleAvailability migration owns the column.
|
||||
}
|
||||
}
|
||||
31
apps/edr-freight-api/src/modules/ai/ai.controller.ts
Normal file
31
apps/edr-freight-api/src/modules/ai/ai.controller.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '@edr/api-common';
|
||||
|
||||
import { AiBookingRequestDto } from './dto/ai-booking-request.dto';
|
||||
import { AiBookingResult } from './types/ai-booking-result.type';
|
||||
import { MockAiService } from './mock-ai.service';
|
||||
|
||||
// @Public() — TODO: swap for real guard when this leaves dev/testing.
|
||||
// Safe while public: extracts + validates text only, never creates or
|
||||
// dispatches anything.
|
||||
@Public()
|
||||
@ApiTags('AI Assistant (mock)')
|
||||
@Controller('ai')
|
||||
export class AiController {
|
||||
constructor(private readonly mockAiService: MockAiService) {}
|
||||
|
||||
@Post('booking/extract')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Mock AI: extract structured booking fields from free-text request',
|
||||
})
|
||||
@ApiOkResponse({
|
||||
description:
|
||||
'Extracted fields, validation result, and next-step recommendation',
|
||||
})
|
||||
extractBooking(@Body() dto: AiBookingRequestDto): AiBookingResult {
|
||||
return this.mockAiService.extractBooking(dto.text);
|
||||
}
|
||||
}
|
||||
11
apps/edr-freight-api/src/modules/ai/ai.module.ts
Normal file
11
apps/edr-freight-api/src/modules/ai/ai.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { AiController } from './ai.controller';
|
||||
import { MockAiService } from './mock-ai.service';
|
||||
|
||||
@Module({
|
||||
controllers: [AiController],
|
||||
providers: [MockAiService],
|
||||
exports: [MockAiService],
|
||||
})
|
||||
export class AiModule {}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class AiBookingRequestDto {
|
||||
@ApiProperty({
|
||||
description: 'Free-text customer booking request to extract fields from',
|
||||
example:
|
||||
'Book 2x40ft containers from Djibouti to Indode. Cargo electronics. Customer ABC Logistics.',
|
||||
minLength: 5,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'text must not be empty' })
|
||||
@MinLength(5, { message: 'text must be at least 5 characters' })
|
||||
text!: string;
|
||||
}
|
||||
277
apps/edr-freight-api/src/modules/ai/mock-ai.service.ts
Normal file
277
apps/edr-freight-api/src/modules/ai/mock-ai.service.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import {
|
||||
AiBookingResult,
|
||||
AiContainerType,
|
||||
AiDirection,
|
||||
AiExtractedBooking,
|
||||
AiRecommendation,
|
||||
AiValidationResult,
|
||||
} from './types/ai-booking-result.type';
|
||||
|
||||
/**
|
||||
* Deterministic keyword/regex "AI" for the booking assistant workflow.
|
||||
* No external AI calls — this class is the single seam to swap for a real
|
||||
* provider later (OllamaAiService / ClaudeAiService / OpenAiService): keep
|
||||
* the `extractBooking(text): AiBookingResult` contract and replace the body.
|
||||
*/
|
||||
|
||||
const KNOWN_LOCATIONS = [
|
||||
'Djibouti',
|
||||
'Indode',
|
||||
'Modjo',
|
||||
'Adama',
|
||||
'Dire Dawa',
|
||||
'Addis Ababa',
|
||||
] as const;
|
||||
|
||||
const INLAND_LOCATIONS = new Set<string>([
|
||||
'Indode',
|
||||
'Modjo',
|
||||
'Adama',
|
||||
'Dire Dawa',
|
||||
'Addis Ababa',
|
||||
]);
|
||||
|
||||
// Longest names first so "Dire Dawa" wins before a shorter partial could.
|
||||
const LOCATION_ALTERNATION = [...KNOWN_LOCATIONS]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map((name) => name.replace(/\s+/g, '\\s+'))
|
||||
.join('|');
|
||||
|
||||
// Checked in order; first hit wins, so specific cargo words beat the
|
||||
// generic "refrigerated" fallback.
|
||||
const CARGO_KEYWORDS: ReadonlyArray<readonly [RegExp, string]> = [
|
||||
[/\belectronics\b/i, 'electronics'],
|
||||
[/\bcoffee\b/i, 'coffee'],
|
||||
[/\bwheat\b/i, 'wheat'],
|
||||
[/\bfertilizers?\b/i, 'fertilizer'],
|
||||
[/\bchemicals?\b/i, 'chemical'],
|
||||
[/\bmachinery\b/i, 'machinery'],
|
||||
[/\bmedicines?\b/i, 'medicine'],
|
||||
[/\bsesame\b/i, 'sesame'],
|
||||
[/\b(?:vehicles?|cars?)\b/i, 'vehicles'],
|
||||
[/\brefrigerated\b/i, 'refrigerated cargo'],
|
||||
];
|
||||
|
||||
const WORD_NUMBERS: Record<string, number> = {
|
||||
one: 1,
|
||||
two: 2,
|
||||
three: 3,
|
||||
four: 4,
|
||||
five: 5,
|
||||
six: 6,
|
||||
seven: 7,
|
||||
eight: 8,
|
||||
nine: 9,
|
||||
ten: 10,
|
||||
};
|
||||
|
||||
// A capitalized-word run: "ABC Logistics", "Auto Import PLC", "Ethio Coffee
|
||||
// Export". Stops at the first lowercase word ("wants", "needs", …).
|
||||
const NAME_CAPTURE = String.raw`([A-Z][A-Za-z0-9&.'-]*(?:\s+[A-Z][A-Za-z0-9&.'-]*)*)`;
|
||||
|
||||
// No `i` flag: the capture relies on case ([A-Z] word starts) to know where
|
||||
// the company name ends ("Customer ABC Logistics wants…" → "ABC Logistics").
|
||||
const CUSTOMER_PATTERNS: ReadonlyArray<RegExp> = [
|
||||
new RegExp(String.raw`\b[Cc]ustomer(?:\s+is)?\s*:?\s+${NAME_CAPTURE}`),
|
||||
new RegExp(String.raw`\b[Ff]or\s+${NAME_CAPTURE}`),
|
||||
];
|
||||
|
||||
const RECOMMEND_CREATE: AiRecommendation = {
|
||||
action: 'CREATE_DRAFT_BOOKING',
|
||||
message:
|
||||
'Booking data looks complete. User can review and create a draft booking.',
|
||||
confidence: 0.85,
|
||||
};
|
||||
|
||||
const RECOMMEND_MISSING: AiRecommendation = {
|
||||
action: 'REQUEST_MISSING_INFORMATION',
|
||||
message:
|
||||
'Some required booking information is missing. Ask the customer for the missing fields before creating a draft booking.',
|
||||
confidence: 0.45,
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class MockAiService {
|
||||
extractBooking(text: string): AiBookingResult {
|
||||
const input = text.trim();
|
||||
|
||||
const { origin, destination } = this.extractRoute(input);
|
||||
|
||||
const extracted: AiExtractedBooking = {
|
||||
customerName: this.extractCustomerName(input),
|
||||
origin,
|
||||
destination,
|
||||
cargoType: this.extractCargoType(input),
|
||||
containerType: this.extractContainerType(input),
|
||||
quantity: this.extractQuantity(input),
|
||||
direction: this.resolveDirection(origin, destination),
|
||||
weightKg: this.extractWeightKg(input),
|
||||
pickupRequired: this.extractFlag(input, 'pickup'),
|
||||
deliveryRequired: this.extractFlag(input, 'delivery'),
|
||||
};
|
||||
|
||||
const validation = this.validate(extracted);
|
||||
|
||||
return {
|
||||
provider: 'mock',
|
||||
extracted,
|
||||
validation,
|
||||
recommendation: validation.valid ? RECOMMEND_CREATE : RECOMMEND_MISSING,
|
||||
};
|
||||
}
|
||||
|
||||
private extractCustomerName(text: string): string | null {
|
||||
for (const pattern of CUSTOMER_PATTERNS) {
|
||||
const match = text.match(pattern);
|
||||
if (match?.[1]) {
|
||||
const name = match[1].replace(/[.,;:!?]+$/, '').trim();
|
||||
if (name) return name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractRoute(text: string): {
|
||||
origin: string | null;
|
||||
destination: string | null;
|
||||
} {
|
||||
const fromMatch = text.match(
|
||||
new RegExp(String.raw`\bfrom\s+(${LOCATION_ALTERNATION})\b`, 'i'),
|
||||
);
|
||||
const toMatch = text.match(
|
||||
new RegExp(String.raw`\bto\s+(${LOCATION_ALTERNATION})\b`, 'i'),
|
||||
);
|
||||
|
||||
let origin = fromMatch ? this.canonicalLocation(fromMatch[1]) : null;
|
||||
let destination = toMatch ? this.canonicalLocation(toMatch[1]) : null;
|
||||
|
||||
if (!origin || !destination) {
|
||||
// Fall back to order of appearance ("Djibouti to Indode" without
|
||||
// "from", or a bare location mention).
|
||||
const mentions: string[] = [];
|
||||
const all = text.matchAll(
|
||||
new RegExp(String.raw`\b(${LOCATION_ALTERNATION})\b`, 'gi'),
|
||||
);
|
||||
for (const m of all) {
|
||||
const canonical = this.canonicalLocation(m[1]);
|
||||
if (canonical && !mentions.includes(canonical)) mentions.push(canonical);
|
||||
}
|
||||
|
||||
if (!origin && !destination) {
|
||||
origin = mentions[0] ?? null;
|
||||
destination = mentions[1] ?? null;
|
||||
} else if (!origin) {
|
||||
origin = mentions.find((loc) => loc !== destination) ?? null;
|
||||
} else {
|
||||
destination = mentions.find((loc) => loc !== origin) ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return { origin, destination };
|
||||
}
|
||||
|
||||
private canonicalLocation(raw: string): string | null {
|
||||
const normalized = raw.replace(/\s+/g, ' ').toLowerCase();
|
||||
return (
|
||||
KNOWN_LOCATIONS.find((loc) => loc.toLowerCase() === normalized) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
private resolveDirection(
|
||||
origin: string | null,
|
||||
destination: string | null,
|
||||
): AiDirection | null {
|
||||
if (!origin || !destination) return null;
|
||||
if (origin === 'Djibouti' && INLAND_LOCATIONS.has(destination)) {
|
||||
return 'IMPORT';
|
||||
}
|
||||
if (INLAND_LOCATIONS.has(origin) && destination === 'Djibouti') {
|
||||
return 'EXPORT';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractCargoType(text: string): string | null {
|
||||
for (const [pattern, cargo] of CARGO_KEYWORDS) {
|
||||
if (pattern.test(text)) return cargo;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractContainerType(text: string): AiContainerType | null {
|
||||
// Lookbehind instead of \b: "2x40ft" has no word boundary before "40",
|
||||
// but "140ft" must not read as a 40ft container.
|
||||
if (/(?<!\d)40[\s-]?(?:ft|foot)\b/i.test(text)) return '40FT';
|
||||
if (/(?<!\d)20[\s-]?(?:ft|foot)\b/i.test(text)) return '20FT';
|
||||
if (/\bbulk\b/i.test(text)) return 'BULK';
|
||||
if (/\b(?:vehicles?|cars?)\b/i.test(text)) return 'RO_RO';
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractQuantity(text: string): number | null {
|
||||
// "2x40ft", "2 x 40ft", "3x20ft", "1x20ft"
|
||||
let match = text.match(/(\d+)\s*x\s*\d+\s*-?\s*(?:ft|foot)\b/i);
|
||||
if (match) return parseInt(match[1], 10);
|
||||
|
||||
// "one 40ft container", "two containers"
|
||||
match = text.match(
|
||||
new RegExp(
|
||||
String.raw`\b(${Object.keys(WORD_NUMBERS).join('|')})\s+(?:\d+\s*-?\s*(?:ft|foot)\s+)?containers?\b`,
|
||||
'i',
|
||||
),
|
||||
);
|
||||
if (match) return WORD_NUMBERS[match[1].toLowerCase()];
|
||||
|
||||
// "3 containers", "2 refrigerated containers"
|
||||
match = text.match(/(\d+)\s+(?:[a-z]+\s+)?containers?\b/i);
|
||||
if (match) return parseInt(match[1], 10);
|
||||
|
||||
// "5 vehicles", "3 cars"
|
||||
match = text.match(/(\d+)\s+(?:vehicles?|cars?)\b/i);
|
||||
if (match) return parseInt(match[1], 10);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractWeightKg(text: string): number | null {
|
||||
const tons = text.match(/([\d,]+(?:\.\d+)?)\s*(?:tons?|tonnes?)\b/i);
|
||||
if (tons) return Math.round(this.parseNumber(tons[1]) * 1000);
|
||||
|
||||
const kg = text.match(/([\d,]+(?:\.\d+)?)\s*kgs?\b/i);
|
||||
if (kg) return Math.round(this.parseNumber(kg[1]));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseNumber(raw: string): number {
|
||||
return parseFloat(raw.replace(/,/g, ''));
|
||||
}
|
||||
|
||||
private extractFlag(
|
||||
text: string,
|
||||
kind: 'pickup' | 'delivery',
|
||||
): boolean | null {
|
||||
// "no pickup required" must read as false, so the negative wins.
|
||||
if (new RegExp(String.raw`\bno\s+${kind}\b`, 'i').test(text)) return false;
|
||||
if (new RegExp(String.raw`\b${kind}\s+required\b`, 'i').test(text)) {
|
||||
return true;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private validate(extracted: AiExtractedBooking): AiValidationResult {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (!extracted.customerName) errors.push('Customer name is missing');
|
||||
if (!extracted.origin) errors.push('Origin is missing');
|
||||
if (!extracted.destination) errors.push('Destination is missing');
|
||||
if (!extracted.cargoType) errors.push('Cargo type is missing');
|
||||
if (!extracted.containerType) errors.push('Container type is missing');
|
||||
if (extracted.quantity === null) errors.push('Quantity is missing');
|
||||
if (!extracted.direction) errors.push('Direction is missing');
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
export const AI_CONTAINER_TYPES = ['20FT', '40FT', 'BULK', 'RO_RO'] as const;
|
||||
export type AiContainerType = (typeof AI_CONTAINER_TYPES)[number];
|
||||
|
||||
export const AI_DIRECTIONS = ['IMPORT', 'EXPORT'] as const;
|
||||
export type AiDirection = (typeof AI_DIRECTIONS)[number];
|
||||
|
||||
export const AI_RECOMMENDATION_ACTIONS = [
|
||||
'CREATE_DRAFT_BOOKING',
|
||||
'REQUEST_MISSING_INFORMATION',
|
||||
] as const;
|
||||
export type AiRecommendationAction = (typeof AI_RECOMMENDATION_ACTIONS)[number];
|
||||
|
||||
export interface AiExtractedBooking {
|
||||
customerName: string | null;
|
||||
origin: string | null;
|
||||
destination: string | null;
|
||||
cargoType: string | null;
|
||||
containerType: AiContainerType | null;
|
||||
quantity: number | null;
|
||||
direction: AiDirection | null;
|
||||
weightKg: number | null;
|
||||
pickupRequired: boolean | null;
|
||||
deliveryRequired: boolean | null;
|
||||
}
|
||||
|
||||
export interface AiValidationResult {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export interface AiRecommendation {
|
||||
action: AiRecommendationAction;
|
||||
message: string;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload returned by the extract endpoint. The global
|
||||
* ResponseTransformInterceptor wraps it as
|
||||
* `{ success: true, data: AiBookingResult, timestamp }` on the wire.
|
||||
*/
|
||||
export interface AiBookingResult {
|
||||
provider: 'mock';
|
||||
extracted: AiExtractedBooking;
|
||||
validation: AiValidationResult;
|
||||
recommendation: AiRecommendation;
|
||||
}
|
||||
@@ -143,6 +143,20 @@ export function htmlToText(html: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Large rotated light-gray copy label (e.g. "Copy 1: Port Operations Copy"),
|
||||
* drawn FIRST so the page content sits on top of it. 30-degree rotation via a
|
||||
* text matrix; roughly centered on the page.
|
||||
*/
|
||||
export function watermarkOp(text: string, page: { width: number; height: number }): string {
|
||||
const label = clipText(text, 46);
|
||||
const size = 34;
|
||||
const w = textWidth(label, size);
|
||||
const x = page.width / 2 - (w * 0.866) / 2;
|
||||
const y = page.height / 2 - (w * 0.5) / 2;
|
||||
return `q BT 0.93 0.93 0.93 rg /F2 ${size} Tf 0.866 0.5 -0.5 0.866 ${x.toFixed(1)} ${y.toFixed(1)} Tm (${escapePdfText(label)}) Tj ET Q`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a "summary tiles + one <table> + notice + signature lines" document (the
|
||||
* marshalling / load-list layout the train-scheduling builders emit) and draw it as a
|
||||
@@ -150,11 +164,26 @@ export function htmlToText(html: string): string {
|
||||
* document, not a flat text dump. Switches to landscape when the table is wide.
|
||||
*/
|
||||
export function buildTabularFallbackPdf(html: string): Buffer {
|
||||
// Documents printed in duplicate wrap each copy in <section class="copy">
|
||||
// (freight order: Port Operations copy + Gate Security copy). Render one
|
||||
// page per copy, each with its own watermark and tile set — parsing the
|
||||
// whole HTML at once would merge both copies' tiles and drop the watermarks.
|
||||
const copies = [...html.matchAll(/<section class="copy">([\s\S]*?)<\/section>/gi)].map((m) => m[1]);
|
||||
const fragments = copies.length ? copies : [html];
|
||||
return assemblePdf(fragments.flatMap((fragment) => buildTabularPageOps(fragment)));
|
||||
}
|
||||
|
||||
function buildTabularPageOps(
|
||||
html: string,
|
||||
): Array<{ ops: string[]; page: { width: number; height: number } }> {
|
||||
const pick = (re: RegExp) => html.match(re)?.[1];
|
||||
const title = htmlToText(pick(/<h1[^>]*>([\s\S]*?)<\/h1>/i) ?? "Document");
|
||||
const subtitle = htmlToText(pick(/class="subtitle"[^>]*>([\s\S]*?)<\/div>/i) ?? "");
|
||||
const metaRef = htmlToText(pick(/class="meta"[\s\S]*?<strong>([\s\S]*?)<\/strong>/i) ?? "");
|
||||
const metaLabel =
|
||||
htmlToText(pick(/class="meta"[^>]*>([\s\S]*?)<strong/i) ?? "").toUpperCase() || "REFERENCE";
|
||||
const generated = htmlToText(pick(/Generated:\s*([^<]+)/i) ?? "");
|
||||
const watermark = htmlToText(pick(/class="watermark"[^>]*>([\s\S]*?)<\/div>/i) ?? "");
|
||||
|
||||
const tiles: Array<[string, string]> = [];
|
||||
for (const m of html.matchAll(
|
||||
@@ -180,24 +209,49 @@ export function buildTabularFallbackPdf(html: string): Buffer {
|
||||
const M = 32;
|
||||
const contentW = page.width - M * 2;
|
||||
const right = page.width - M;
|
||||
const ops: string[] = [];
|
||||
const MAX_PAGES = 12;
|
||||
|
||||
// Header
|
||||
ops.push(lineOp(M, page.height - 28, right, page.height - 28, PdfColor.teal, 2.4));
|
||||
ops.push(textOp("ETHIO-DJIBOUTI RAILWAY S.C.", M, page.height - 44, 8.5, "F2", PdfColor.gray));
|
||||
ops.push(textOp(clipText(title, landscape ? 82 : 52), M, page.height - 68, 19, "F2", PdfColor.dark));
|
||||
if (subtitle) ops.push(textOp(clipText(subtitle, 96), M, page.height - 82, 9, "F1", PdfColor.gray));
|
||||
if (metaRef) {
|
||||
ops.push(textOpRight("TRAIN / SCHEDULE", right, page.height - 42, 7.5, "F2", PdfColor.gray));
|
||||
ops.push(textOpRight(clipText(metaRef, 28), right, page.height - 58, 12, "F2", PdfColor.dark));
|
||||
}
|
||||
if (generated) {
|
||||
ops.push(textOpRight(clipText(`Generated ${generated}`, 40), right, page.height - 72, 8, "F1", PdfColor.gray));
|
||||
}
|
||||
ops.push(lineOp(M, page.height - 92, right, page.height - 92, PdfColor.line, 1));
|
||||
const pagesOut: Array<{ ops: string[]; page: { width: number; height: number } }> = [];
|
||||
let ops: string[] = [];
|
||||
let y = 0;
|
||||
|
||||
// Summary tiles
|
||||
let y = page.height - 100;
|
||||
const drawFullHeader = () => {
|
||||
ops.push(lineOp(M, page.height - 28, right, page.height - 28, PdfColor.teal, 2.4));
|
||||
ops.push(textOp("ETHIO-DJIBOUTI RAILWAY S.C.", M, page.height - 44, 8.5, "F2", PdfColor.gray));
|
||||
ops.push(textOp(clipText(title, landscape ? 82 : 52), M, page.height - 68, 19, "F2", PdfColor.dark));
|
||||
if (subtitle) ops.push(textOp(clipText(subtitle, 96), M, page.height - 82, 9, "F1", PdfColor.gray));
|
||||
if (metaRef) {
|
||||
ops.push(textOpRight(clipText(metaLabel, 26), right, page.height - 42, 7.5, "F2", PdfColor.gray));
|
||||
ops.push(textOpRight(clipText(metaRef, 28), right, page.height - 58, 12, "F2", PdfColor.dark));
|
||||
}
|
||||
if (generated) {
|
||||
ops.push(textOpRight(clipText(`Generated ${generated}`, 40), right, page.height - 72, 8, "F1", PdfColor.gray));
|
||||
}
|
||||
ops.push(lineOp(M, page.height - 92, right, page.height - 92, PdfColor.line, 1));
|
||||
y = page.height - 100;
|
||||
};
|
||||
|
||||
const drawContinuationHeader = (pageNo: number) => {
|
||||
ops.push(lineOp(M, page.height - 24, right, page.height - 24, PdfColor.teal, 1.6));
|
||||
ops.push(
|
||||
textOp(clipText(`${title} (continued — page ${pageNo})`, landscape ? 100 : 68), M, page.height - 42, 11, "F2", PdfColor.dark),
|
||||
);
|
||||
if (metaRef) ops.push(textOpRight(clipText(metaRef, 28), right, page.height - 42, 10, "F2", PdfColor.gray));
|
||||
y = page.height - 54;
|
||||
};
|
||||
|
||||
const startPage = (first: boolean) => {
|
||||
ops = [];
|
||||
if (watermark) ops.push(watermarkOp(watermark, page));
|
||||
if (first) drawFullHeader();
|
||||
else drawContinuationHeader(pagesOut.length + 1);
|
||||
};
|
||||
|
||||
const finishPage = () => pagesOut.push({ ops, page });
|
||||
|
||||
startPage(true);
|
||||
|
||||
// Summary tiles (first page only)
|
||||
if (tiles.length) {
|
||||
const cols = landscape ? 6 : 4;
|
||||
const tileW = contentW / cols;
|
||||
@@ -213,21 +267,34 @@ export function buildTabularFallbackPdf(html: string): Buffer {
|
||||
y -= tileH + 12;
|
||||
}
|
||||
|
||||
// Table
|
||||
// Table, paginated across as many pages as the rows need.
|
||||
if (headers.length) {
|
||||
const colW = contentW / headers.length;
|
||||
const headerH = 16;
|
||||
const rowH = 14;
|
||||
const cellChars = Math.max(4, Math.floor(colW / 3.9));
|
||||
ops.push(rectOp(M, y - headerH, contentW, headerH, PdfColor.tint, PdfColor.line, 0.6));
|
||||
headers.forEach((h, c) =>
|
||||
ops.push(textOp(clipText(h, cellChars), M + c * colW + 4, y - 11, 7, "F2", PdfColor.teal)),
|
||||
);
|
||||
y -= headerH;
|
||||
const bottomReserve = 46; // keep clear of the page edge on row-only pages
|
||||
|
||||
let shown = 0;
|
||||
for (const row of rows) {
|
||||
if (y < 96) break;
|
||||
const drawTableHeader = () => {
|
||||
ops.push(rectOp(M, y - headerH, contentW, headerH, PdfColor.tint, PdfColor.line, 0.6));
|
||||
headers.forEach((h, c) =>
|
||||
ops.push(textOp(clipText(h, cellChars), M + c * colW + 4, y - 11, 7, "F2", PdfColor.teal)),
|
||||
);
|
||||
y -= headerH;
|
||||
};
|
||||
|
||||
drawTableHeader();
|
||||
let truncated = 0;
|
||||
for (const [index, row] of rows.entries()) {
|
||||
if (y - rowH < bottomReserve) {
|
||||
if (pagesOut.length + 1 >= MAX_PAGES) {
|
||||
truncated = rows.length - index;
|
||||
break;
|
||||
}
|
||||
finishPage();
|
||||
startPage(false);
|
||||
drawTableHeader();
|
||||
}
|
||||
ops.push(rectOp(M, y - rowH, contentW, rowH, "1 1 1", PdfColor.line, 0.4));
|
||||
headers.forEach((_h, c) => {
|
||||
if (c > 0) ops.push(lineOp(M + c * colW, y - rowH, M + c * colW, y, PdfColor.line, 0.3));
|
||||
@@ -235,30 +302,33 @@ export function buildTabularFallbackPdf(html: string): Buffer {
|
||||
if (cell) ops.push(textOp(clipText(cell, cellChars), M + c * colW + 4, y - 10, 6.8, "F1", PdfColor.dark));
|
||||
});
|
||||
y -= rowH;
|
||||
shown += 1;
|
||||
}
|
||||
if (shown < rows.length) {
|
||||
ops.push(textOp(`... ${rows.length - shown} more row(s) not shown`, M, y - 10, 7, "F1", PdfColor.gray));
|
||||
if (truncated > 0) {
|
||||
ops.push(textOp(`... ${truncated} more row(s) not shown`, M, y - 10, 7, "F1", PdfColor.gray));
|
||||
}
|
||||
}
|
||||
|
||||
// Notice (verification clause)
|
||||
// Notice + signatures live on the final page; give them a fresh page when the
|
||||
// rows ran too deep for the fixed bottom band.
|
||||
if (y < 110 && (notice || signatures.length)) {
|
||||
finishPage();
|
||||
startPage(false);
|
||||
}
|
||||
if (notice) {
|
||||
ops.push(lineOp(M, 78, M, 54, PdfColor.teal, 2));
|
||||
wrapText(notice, landscape ? 155 : 104)
|
||||
.slice(0, 2)
|
||||
.forEach((ln, i) => ops.push(textOp(ln, M + 8, 72 - i * 11, 7.5, "F1", PdfColor.gray)));
|
||||
}
|
||||
|
||||
// Signatures
|
||||
const sigW = contentW / signatures.length;
|
||||
signatures.forEach((s, i) => {
|
||||
signatures.forEach((sig, i) => {
|
||||
const x = M + i * sigW;
|
||||
ops.push(lineOp(x, 40, x + sigW - 18, 40, PdfColor.dark, 0.7));
|
||||
ops.push(textOp(clipText(s, Math.floor((sigW - 18) / 3.6)), x, 30, 7, "F1", PdfColor.gray));
|
||||
ops.push(textOp(clipText(sig, Math.floor((sigW - 18) / 3.6)), x, 30, 7, "F1", PdfColor.gray));
|
||||
});
|
||||
finishPage();
|
||||
|
||||
return assembleSinglePagePdf(ops, page);
|
||||
return pagesOut;
|
||||
}
|
||||
|
||||
/** Greedy word-wrap to a maximum character width. */
|
||||
@@ -320,3 +390,41 @@ export function assembleSinglePagePdf(
|
||||
pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
|
||||
return Buffer.from(pdf, "latin1");
|
||||
}
|
||||
|
||||
/** Assemble a multi-page PDF; one content stream per page, shared Helvetica fonts. */
|
||||
export function assemblePdf(
|
||||
pages: Array<{ ops: string[]; page: { width: number; height: number } }>,
|
||||
): Buffer {
|
||||
const kids = pages.map((_, i) => `${5 + i * 2} 0 R`).join(" ");
|
||||
const objects: string[] = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
|
||||
];
|
||||
for (const [i, p] of pages.entries()) {
|
||||
const stream = p.ops.join("\n");
|
||||
objects.push(
|
||||
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${p.page.width} ${p.page.height}] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents ${6 + i * 2} 0 R >>`,
|
||||
);
|
||||
objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}\nendstream`);
|
||||
}
|
||||
|
||||
let pdf = "%PDF-1.4\n";
|
||||
const offsets: number[] = [0];
|
||||
objects.forEach((object, index) => {
|
||||
offsets.push(Buffer.byteLength(pdf, "latin1"));
|
||||
pdf += `${index + 1} 0 obj\n${object}\nendobj\n`;
|
||||
});
|
||||
while (Buffer.byteLength(pdf, "latin1") < MIN_VALID_PDF_BYTES) {
|
||||
pdf += "% fallback padding\n";
|
||||
}
|
||||
const xrefOffset = Buffer.byteLength(pdf, "latin1");
|
||||
pdf += `xref\n0 ${objects.length + 1}\n`;
|
||||
pdf += "0000000000 65535 f \n";
|
||||
for (const offset of offsets.slice(1)) {
|
||||
pdf += `${String(offset).padStart(10, "0")} 00000 n \n`;
|
||||
}
|
||||
pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
|
||||
return Buffer.from(pdf, "latin1");
|
||||
}
|
||||
|
||||
@@ -400,8 +400,18 @@ export class BookingPricingService {
|
||||
* All three components are produced by RuleEngineService.evaluate, so submit
|
||||
* simply re-runs the engine — there is no extra submit-time inflation.
|
||||
*/
|
||||
async computeSubmitPriorityScore(booking: Booking): Promise<number> {
|
||||
async computeSubmitPriorityScore(
|
||||
booking: Booking,
|
||||
totalWagonsOverride?: number,
|
||||
): Promise<number> {
|
||||
const evalInput = await this.buildEvalInputForBooking(booking);
|
||||
// BULK bookings have no container lines, so buildEvalInputForBooking yields
|
||||
// totalWagons = 0 and every wagon-range priority config misses. The batch
|
||||
// engine derives a bulk booking's wagon footprint from tonnage vs. live
|
||||
// wagon capacity and passes it here to score the booking properly.
|
||||
if (totalWagonsOverride != null && totalWagonsOverride > 0) {
|
||||
evalInput.totalWagons = totalWagonsOverride;
|
||||
}
|
||||
const ruleResult = await this.ruleEngineService.evaluate(evalInput);
|
||||
return ruleResult.priorityScore;
|
||||
}
|
||||
|
||||
@@ -14,9 +14,10 @@ describe('BookingTransitionService — finalizeClearance gate', () => {
|
||||
serviceType: { includesCustoms: false }, // no output set → only the input gate
|
||||
};
|
||||
|
||||
// Input set has two required docs.
|
||||
// Input set has two required docs. Non-customs bookings resolve to the
|
||||
// ONE_TIME self-clearance document set.
|
||||
const inputSetting = {
|
||||
code: 'clearance_import_container_without_customs',
|
||||
code: 'contract_clearance_selfclear_import_container',
|
||||
fields: [
|
||||
{ fileKey: 'commercial_invoice', isRequired: true },
|
||||
{ fileKey: 'packing_list', isRequired: true },
|
||||
@@ -198,7 +199,7 @@ describe('BookingTransitionService — finalizeClearance customs output gate', (
|
||||
*/
|
||||
describe('BookingTransitionService — submitClearanceDocuments required-fields gate', () => {
|
||||
const inputSetting = {
|
||||
code: 'clearance_import_container_without_customs',
|
||||
code: 'contract_clearance_selfclear_import_container',
|
||||
fields: [
|
||||
{ fileKey: 'commercial_invoice', fileLabel: 'Commercial invoice', isRequired: true },
|
||||
{ fileKey: 'packing_list', fileLabel: 'Packing list', isRequired: true },
|
||||
|
||||
@@ -988,6 +988,15 @@ export class BookingTransitionService {
|
||||
"OPERATION_CHANGES_REQUESTED",
|
||||
]);
|
||||
|
||||
// A bare initiated instance (clearance-first flow) carries no cargo or
|
||||
// price — it must go through the contract completion endpoint, which
|
||||
// persists cargo, prices, invoices and only then lands here itself.
|
||||
if (booking.contractId && !(Number(booking.totalAmount) > 0)) {
|
||||
throw new BadRequestException(
|
||||
"This booking must be completed (cargo and shipment day) before requesting operation.",
|
||||
);
|
||||
}
|
||||
|
||||
const date = new Date(scheduledDate);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
throw new BadRequestException("A valid schedule date is required");
|
||||
|
||||
@@ -11,6 +11,7 @@ import { RuleEngineModule } from '../rule-engine/rule-engine.module';
|
||||
import { FileUploadSettingsModule } from '../file-upload-settings/file-upload-settings.module';
|
||||
import { SignaturesModule } from '../signatures/signatures.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { DocumentsModule } from '../billing/documents/documents.module';
|
||||
import { FirstMileModule } from '../first-mile/first-mile.module';
|
||||
import { LastMileModule } from '../last-mile/last-mile.module';
|
||||
import { BookingContractService } from './booking-contract.service';
|
||||
@@ -68,6 +69,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
|
||||
CustomerTruckContainer,
|
||||
]),
|
||||
BillingModule,
|
||||
DocumentsModule,
|
||||
NotificationsModule,
|
||||
NotificationInboxModule,
|
||||
forwardRef(() => FirstMileModule),
|
||||
@@ -116,6 +118,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
|
||||
BookingPricingService,
|
||||
BookingInvoiceService,
|
||||
BookingLifecycleNotifierService,
|
||||
BookingTransitionService,
|
||||
ConsolidationService,
|
||||
CustomerTruckService,
|
||||
ContainerReceiptService,
|
||||
|
||||
@@ -7,6 +7,7 @@ function mockQueryBuilder() {
|
||||
const qb = {
|
||||
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
@@ -15,6 +16,8 @@ function mockQueryBuilder() {
|
||||
take: jest.fn().mockReturnThis(),
|
||||
getMany: jest.fn(),
|
||||
getManyAndCount: jest.fn().mockResolvedValue([[], 0]),
|
||||
getCount: jest.fn().mockResolvedValue(0),
|
||||
getRawAndEntities: jest.fn().mockResolvedValue({ entities: [], raw: [] }),
|
||||
};
|
||||
return qb;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,11 @@ export interface BookingListFilterOptions {
|
||||
customsClearingEnabled?: boolean;
|
||||
createdFrom?: string;
|
||||
createdTo?: string;
|
||||
scheduledFrom?: string;
|
||||
scheduledTo?: string;
|
||||
originYardId?: string;
|
||||
destinationYardId?: string;
|
||||
isGovernment?: 'true' | 'false';
|
||||
consolidationPaired?: string;
|
||||
}
|
||||
|
||||
@@ -799,9 +804,16 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
});
|
||||
}
|
||||
if (options.bookingType) {
|
||||
qb.andWhere('booking.bookingType = :bookingType', {
|
||||
bookingType: options.bookingType,
|
||||
});
|
||||
// The stored booking_type column is 'ONE_TIME' for every row (contract
|
||||
// drawdowns included — see contract-booking.service create), so the
|
||||
// one-time vs general split keys on the denormalized contract_kind:
|
||||
// GENERAL_CONTRACT tab = bookings under a GENERAL contract, ONE_TIME tab
|
||||
// = everything else (ONE_TIME contracts and legacy contract-less rows).
|
||||
if (options.bookingType === 'GENERAL_CONTRACT') {
|
||||
qb.andWhere("booking.contract_kind = 'GENERAL'");
|
||||
} else {
|
||||
qb.andWhere("booking.contract_kind IS DISTINCT FROM 'GENERAL'");
|
||||
}
|
||||
}
|
||||
if (options.createdFrom) {
|
||||
qb.andWhere('booking.created_at >= :createdFrom', {
|
||||
@@ -814,6 +826,32 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
createdTo: options.createdTo,
|
||||
});
|
||||
}
|
||||
if (options.scheduledFrom) {
|
||||
qb.andWhere('booking.scheduled_date >= :scheduledFrom', {
|
||||
scheduledFrom: options.scheduledFrom,
|
||||
});
|
||||
}
|
||||
if (options.scheduledTo) {
|
||||
// Inclusive end-of-day: callers pass a date; include the whole day.
|
||||
qb.andWhere('booking.scheduled_date <= :scheduledTo', {
|
||||
scheduledTo: options.scheduledTo,
|
||||
});
|
||||
}
|
||||
if (options.originYardId) {
|
||||
qb.andWhere('booking.origin_yard_id = :originYardId', {
|
||||
originYardId: options.originYardId,
|
||||
});
|
||||
}
|
||||
if (options.destinationYardId) {
|
||||
qb.andWhere('booking.destination_yard_id = :destinationYardId', {
|
||||
destinationYardId: options.destinationYardId,
|
||||
});
|
||||
}
|
||||
if (options.isGovernment === 'true') {
|
||||
qb.andWhere('booking.is_government = TRUE');
|
||||
} else if (options.isGovernment === 'false') {
|
||||
qb.andWhere('booking.is_government = FALSE');
|
||||
}
|
||||
if (options.tradeDirection) {
|
||||
qb.andWhere('booking.trade_direction = :tradeDirection', {
|
||||
tradeDirection: options.tradeDirection,
|
||||
@@ -999,6 +1037,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
|
||||
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
|
||||
.andWhere('sb.id IS NULL')
|
||||
@@ -1030,6 +1069,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
|
||||
.where('booking.origin_yard_id = :originYardId', { originYardId })
|
||||
.andWhere('booking.destination_yard_id = :destinationYardId', {
|
||||
@@ -1069,6 +1109,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.leftJoin(TrainScheduleBooking, 'sb', 'sb.booking_id = booking.id')
|
||||
.where('booking.origin_yard_id IN (:...corridorYardIds)', { corridorYardIds })
|
||||
.andWhere('booking.destination_yard_id IN (:...corridorYardIds)', {
|
||||
@@ -1134,6 +1175,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
|
||||
.orderBy('booking.is_government', 'DESC')
|
||||
.addOrderBy('booking.priority_score', 'DESC')
|
||||
@@ -1148,6 +1190,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.where('booking.train_schedule_id = :scheduleId', { scheduleId })
|
||||
.andWhere(`booking.status IN ('SELECTED_FOR_BATCH', 'AWAITING_PAYMENT')`)
|
||||
.getMany();
|
||||
@@ -1177,6 +1220,8 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
return this.repository
|
||||
.createQueryBuilder('booking')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.innerJoin(
|
||||
TrainScheduleBooking,
|
||||
'sb',
|
||||
|
||||
@@ -50,7 +50,8 @@ import { Booking } from './entities/booking.entity';
|
||||
import { BookingContainerAllocation } from './entities/booking-container-allocation.entity';
|
||||
import { FileRecord } from '../files/entities/file.entity';
|
||||
import { CustomerTruckAssignmentDto } from './dto/customer-truck-assignment.dto';
|
||||
import { ContractPdfService } from '../../contracts/contract-pdf.service';
|
||||
import { PdfRenderService } from '../billing/documents/pdf-render.service';
|
||||
import { buildTabularFallbackPdf } from '../billing/documents/styled-pdf.util';
|
||||
|
||||
/** Paginated booking list: flat `total` (backoffice) + `meta` block (portal). */
|
||||
export interface PaginatedBookings {
|
||||
@@ -99,7 +100,7 @@ export class BookingsService {
|
||||
private readonly containerTypesService: ContainerTypesService,
|
||||
private readonly consolidationService: ConsolidationService,
|
||||
private readonly vehiclesService: VehiclesService,
|
||||
private readonly contractPdfService: ContractPdfService,
|
||||
private readonly pdfRender: PdfRenderService,
|
||||
private readonly events: EventEmitter2,
|
||||
) {}
|
||||
|
||||
@@ -170,7 +171,12 @@ export class BookingsService {
|
||||
);
|
||||
|
||||
const html = this.buildCustomerTruckFreightOrderHtml(booking, trucks);
|
||||
const buffer = await this.contractPdfService.htmlToPdfBuffer(html);
|
||||
// Chromium when available; otherwise the styled tabular fallback (never the
|
||||
// generic text dump — the freight order is an outward-facing gate document).
|
||||
const buffer = await this.pdfRender.htmlToPdfBuffer(html, {
|
||||
label: 'freight order',
|
||||
fallback: (prepared) => buildTabularFallbackPdf(prepared),
|
||||
});
|
||||
return {
|
||||
filename: `freight-order-${booking.reference.replace(/[^a-zA-Z0-9_-]+/g, '-')}.pdf`,
|
||||
buffer,
|
||||
@@ -262,21 +268,10 @@ export class BookingsService {
|
||||
containers: string | null;
|
||||
}>,
|
||||
): string {
|
||||
const esc = (v: unknown) => this.escapeHtml(String(v ?? '-'));
|
||||
const assignedAt = booking.customerTruckAssignedAt
|
||||
? new Date(booking.customerTruckAssignedAt).toLocaleString('en-GB')
|
||||
: '-';
|
||||
const bookingRows: Array<[string, string | null | undefined]> = [
|
||||
['Booking Reference', booking.reference],
|
||||
['Client Name', booking.company?.name],
|
||||
['Client ID', booking.companyId],
|
||||
['Trade Direction', booking.tradeDirection],
|
||||
['Freight Type', booking.freightType],
|
||||
['Assigned At', assignedAt],
|
||||
['Booking Status', booking.status],
|
||||
];
|
||||
const bookingRowHtml = bookingRows
|
||||
.map(([label, value]) => `<tr><th>${this.escapeHtml(label)}</th><td>${this.escapeHtml(value || '-')}</td></tr>`)
|
||||
.join('');
|
||||
|
||||
// Fall back to the legacy single-truck booking columns when there are no
|
||||
// multi-truck rows (bookings assigned before the multi-truck feature).
|
||||
@@ -297,44 +292,63 @@ export class BookingsService {
|
||||
]
|
||||
: [];
|
||||
|
||||
const truckBlocks = truckList
|
||||
.map((t, i) => {
|
||||
const rows: Array<[string, string | null | undefined]> = [
|
||||
['Truck Plate Number', t.plateNumber],
|
||||
['Driver Name', t.driverName],
|
||||
['Truck Type', t.truckType],
|
||||
['Containers Loaded', t.containers],
|
||||
[
|
||||
'Arrival',
|
||||
t.arrivedAt ? new Date(t.arrivedAt).toLocaleString('en-GB') : 'Awaiting arrival',
|
||||
],
|
||||
];
|
||||
const html = rows
|
||||
.map(
|
||||
([label, value]) =>
|
||||
`<tr><th>${this.escapeHtml(label)}</th><td>${this.escapeHtml(value || '-')}</td></tr>`,
|
||||
)
|
||||
.join('');
|
||||
return `<div class="truck"><h2>Truck ${i + 1}</h2><table>${html}</table></div>`;
|
||||
})
|
||||
const truckRows = truckList
|
||||
.map(
|
||||
(t, i) => `<tr>
|
||||
<td class="num">${i + 1}</td>
|
||||
<td>${esc(t.plateNumber)}</td>
|
||||
<td>${esc(t.driverName)}</td>
|
||||
<td>${esc(t.truckType)}</td>
|
||||
<td>${esc(t.containers)}</td>
|
||||
<td>${t.arrivedAt ? esc(new Date(t.arrivedAt).toLocaleString('en-GB')) : 'Awaiting arrival'}</td>
|
||||
</tr>`,
|
||||
)
|
||||
.join('');
|
||||
|
||||
const copy = (watermark: string) => `
|
||||
<section class="copy">
|
||||
<div class="watermark">${this.escapeHtml(watermark)}</div>
|
||||
<header>
|
||||
<div class="watermark">${esc(watermark)}</div>
|
||||
<div class="top">
|
||||
<div>
|
||||
<div class="brand">Ethio-Djibouti Railway S.C.</div>
|
||||
<h1>Freight Order</h1>
|
||||
<p>Customer external truck assignment — ${truckList.length} truck${truckList.length !== 1 ? 's' : ''}</p>
|
||||
<div class="subtitle">Customer external truck assignment — ${truckList.length} truck${truckList.length !== 1 ? 's' : ''}</div>
|
||||
</div>
|
||||
<strong>${this.escapeHtml(booking.reference)}</strong>
|
||||
</header>
|
||||
<table>${bookingRowHtml}</table>
|
||||
${truckBlocks}
|
||||
<div class="meta">
|
||||
Booking
|
||||
<strong>${esc(booking.reference)}</strong>
|
||||
Generated: ${esc(new Date().toLocaleString('en-GB'))}
|
||||
</div>
|
||||
</div>
|
||||
<div class="summary">
|
||||
<div class="tile"><span>Client</span><strong>${esc(booking.company?.name)}</strong></div>
|
||||
<div class="tile"><span>Client ID</span><strong>${esc(booking.companyId)}</strong></div>
|
||||
<div class="tile"><span>Trade direction</span><strong>${esc(booking.tradeDirection)}</strong></div>
|
||||
<div class="tile"><span>Freight type</span><strong>${esc(booking.freightType)}</strong></div>
|
||||
<div class="tile"><span>Assigned at</span><strong>${esc(assignedAt)}</strong></div>
|
||||
<div class="tile"><span>Booking status</span><strong>${esc(booking.status)}</strong></div>
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th>Truck plate</th>
|
||||
<th>Driver</th>
|
||||
<th>Truck type</th>
|
||||
<th>Containers loaded</th>
|
||||
<th>Arrival</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${truckRows}</tbody>
|
||||
</table>
|
||||
<div class="notice">
|
||||
Present this freight order at the warehouse gate. Each truck may only collect the
|
||||
containers listed against it; the handover must be signed before any truck leaves.
|
||||
</div>
|
||||
<div class="signatures">
|
||||
<div>Customer / Carrier Signature</div>
|
||||
<div>Port Operations Verification</div>
|
||||
<div>Gate Security Verification</div>
|
||||
<div class="line">Customer / Carrier signature — date</div>
|
||||
<div class="line">Port operations verification — date</div>
|
||||
<div class="line">Gate security verification — date</div>
|
||||
</div>
|
||||
</section>`;
|
||||
|
||||
@@ -342,21 +356,30 @@ export class BookingsService {
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Freight Order</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; color: #10202f; margin: 0; }
|
||||
.copy { position: relative; min-height: 46vh; padding: 28px 32px; page-break-inside: avoid; border-bottom: 1px dashed #94a3b8; }
|
||||
.watermark { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 34px; font-weight: 800; color: rgba(16, 32, 47, 0.08); transform: rotate(-18deg); pointer-events: none; }
|
||||
header { display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 3px solid #0a9f6a; padding-bottom: 14px; margin-bottom: 18px; }
|
||||
h1 { margin: 0; font-size: 28px; letter-spacing: 0; }
|
||||
h2 { margin: 18px 0 8px; font-size: 14px; color: #0a6f4d; }
|
||||
p { margin: 4px 0 0; color: #64748b; }
|
||||
strong { font-size: 16px; color: #0a9f6a; }
|
||||
table { width: 100%; border-collapse: collapse; position: relative; z-index: 1; margin-bottom: 6px; }
|
||||
th, td { border: 1px solid #cbd5e1; padding: 9px 10px; text-align: left; font-size: 12px; }
|
||||
th { width: 34%; background: #f1f5f9; }
|
||||
.truck { page-break-inside: avoid; }
|
||||
.signatures { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 34px; font-size: 11px; color: #475569; position: relative; z-index: 1; }
|
||||
.signatures div { border-top: 1px solid #334155; padding-top: 8px; min-height: 28px; }
|
||||
@page { size: A4 portrait; margin: 10mm; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; color: #0f172a; font-family: Arial, sans-serif; }
|
||||
.copy { position: relative; padding: 24px 28px; page-break-inside: avoid; border-bottom: 1px dashed #94a3b8; }
|
||||
.watermark { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 30px; font-weight: 800; color: rgba(15, 23, 42, 0.07); transform: rotate(-18deg); pointer-events: none; }
|
||||
.top { display: flex; justify-content: space-between; border-bottom: 3px solid #0f766e; padding-bottom: 10px; gap: 24px; }
|
||||
.brand { font-size: 11px; color: #475569; text-transform: uppercase; letter-spacing: .08em; font-weight: 700; }
|
||||
h1 { margin: 6px 0 0; font-size: 25px; line-height: 1.05; }
|
||||
.subtitle { margin-top: 4px; color: #64748b; font-size: 12px; }
|
||||
.meta { text-align: right; font-size: 11px; color: #475569; min-width: 210px; }
|
||||
.meta strong { display: block; margin: 4px 0; color: #0f172a; font-size: 15px; }
|
||||
.summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 14px 0; }
|
||||
.tile { border: 1px solid #cbd5e1; padding: 8px; min-height: 48px; }
|
||||
.tile span { display: block; color: #64748b; font-size: 9px; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 4px; }
|
||||
.tile strong { font-size: 11px; }
|
||||
table { width: 100%; border-collapse: collapse; position: relative; z-index: 1; }
|
||||
th { background: #f8fafc; color: #475569; text-align: left; }
|
||||
th, td { border: 1px solid #cbd5e1; padding: 6px 7px; font-size: 10.5px; vertical-align: top; }
|
||||
.num { text-align: right; width: 26px; }
|
||||
.notice { margin-top: 10px; border-left: 4px solid #0f766e; background: #f0fdfa; padding: 8px 10px; font-size: 10px; color: #134e4a; }
|
||||
.signatures { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; margin-top: 30px; position: relative; z-index: 1; }
|
||||
.line { border-top: 1px solid #334155; padding-top: 7px; font-size: 9px; color: #475569; min-height: 30px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -1125,6 +1148,30 @@ export class BookingsService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Batched version of the findById flag: marks each page item whose booking
|
||||
* has a generated-but-unsigned SELF_HAUL handover, so list rows (portal
|
||||
* dashboard) can show "Approve delivery" for exactly the generated→signed
|
||||
* window. One query for the whole page.
|
||||
*/
|
||||
private async attachHandoverFlags(bookings: Booking[]): Promise<void> {
|
||||
const ids = bookings.map((b) => b.id);
|
||||
if (!ids.length) return;
|
||||
const rows: Array<{ bookingId: string }> = await this.dataSource.query(
|
||||
`SELECT DISTINCT booking_id AS "bookingId"
|
||||
FROM freight.booking_handovers
|
||||
WHERE booking_id = ANY($1::uuid[])
|
||||
AND signed_at IS NULL AND deleted_at IS NULL
|
||||
AND mile_type = 'SELF_HAUL'`,
|
||||
[ids],
|
||||
);
|
||||
const pending = new Set(rows.map((r) => r.bookingId));
|
||||
for (const b of bookings) {
|
||||
(b as Booking & { handoverAwaitingSignature?: boolean }).handoverAwaitingSignature =
|
||||
pending.has(b.id);
|
||||
}
|
||||
}
|
||||
|
||||
async findAll(
|
||||
filter: FilterBookingDto,
|
||||
forceCompanyId?: string,
|
||||
@@ -1135,7 +1182,7 @@ export class BookingsService {
|
||||
const statusFilter = this.parseStatusFilter(filter);
|
||||
const schedulingStatusFilter = this.parseSchedulingStatusFilter(filter);
|
||||
|
||||
return this.bookingsRepository.findAllPaginated({
|
||||
const result = await this.bookingsRepository.findAllPaginated({
|
||||
page,
|
||||
pageSize,
|
||||
...statusFilter,
|
||||
@@ -1158,10 +1205,17 @@ export class BookingsService {
|
||||
paymentStatus: filter.paymentStatus,
|
||||
createdFrom: filter.createdFrom,
|
||||
createdTo: filter.createdTo,
|
||||
scheduledFrom: filter.scheduledFrom,
|
||||
scheduledTo: filter.scheduledTo,
|
||||
originYardId: filter.originYardId,
|
||||
destinationYardId: filter.destinationYardId,
|
||||
isGovernment: filter.isGovernment,
|
||||
consolidationPaired: filter.consolidationPaired,
|
||||
sortBy: filter.sortBy,
|
||||
sortOrder: filter.sortOrder,
|
||||
});
|
||||
await this.attachHandoverFlags(result.items ?? []);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Booking statuses at which a customer can pay (mirrors booking-payment.service). */
|
||||
@@ -1371,11 +1425,17 @@ export class BookingsService {
|
||||
serviceTypeId: filter.serviceTypeId,
|
||||
cargoTypeId: filter.cargoTypeId,
|
||||
freightType: filter.freightType,
|
||||
bookingType: filter.bookingType,
|
||||
tradeDirection: filter.tradeDirection,
|
||||
paymentCurrency: filter.paymentCurrency,
|
||||
paymentStatus: filter.paymentStatus,
|
||||
createdFrom: filter.createdFrom,
|
||||
createdTo: filter.createdTo,
|
||||
scheduledFrom: filter.scheduledFrom,
|
||||
scheduledTo: filter.scheduledTo,
|
||||
originYardId: filter.originYardId,
|
||||
destinationYardId: filter.destinationYardId,
|
||||
isGovernment: filter.isGovernment,
|
||||
consolidationPaired: filter.consolidationPaired,
|
||||
};
|
||||
|
||||
|
||||
@@ -8,8 +8,10 @@ describe('clearance.util — clearanceSettingCode', () => {
|
||||
expect(clearanceSettingCode('IMPORT', 'CONTAINER', true)).toBe(
|
||||
'clearance_import_container_with_customs',
|
||||
);
|
||||
// Non-customs bookings self-clear with the same document set a ONE_TIME
|
||||
// self-clear contract uses.
|
||||
expect(clearanceSettingCode('IMPORT', 'CONTAINER', false)).toBe(
|
||||
'clearance_import_container_without_customs',
|
||||
'contract_clearance_selfclear_import_container',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -18,7 +20,7 @@ describe('clearance.util — clearanceSettingCode', () => {
|
||||
'clearance_export_bulk_with_customs',
|
||||
);
|
||||
expect(clearanceSettingCode('EXPORT', 'BULK', false)).toBe(
|
||||
'clearance_export_bulk_without_customs',
|
||||
'contract_clearance_selfclear_export_bulk',
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -29,8 +29,14 @@ export function clearanceSettingCode(
|
||||
const op = operationFor(tradeDirection);
|
||||
if (!op) return null;
|
||||
const freight = freightFor(freightType);
|
||||
const customs = includesCustoms ? 'with_customs' : 'without_customs';
|
||||
return `clearance_${op}_${freight}_${customs}`;
|
||||
// Non-customs (Path A) bookings self-clear: the customer proves his own
|
||||
// clearance with the SAME smaller document set a ONE_TIME self-clear
|
||||
// contract uses (customs declaration, release permit, …) — not the
|
||||
// GL-oriented booking sets.
|
||||
if (!includesCustoms) {
|
||||
return `contract_clearance_selfclear_${op}_${freight}`;
|
||||
}
|
||||
return `clearance_${op}_${freight}_with_customs`;
|
||||
}
|
||||
|
||||
/** The GL-output (customs output) setting code, keyed on op + freight. */
|
||||
|
||||
@@ -81,6 +81,31 @@ export class FilterBookingDto {
|
||||
@IsDateString()
|
||||
createdTo?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Filter bookings scheduled on/after this date (ISO)' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
scheduledFrom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Filter bookings scheduled on/before this date (ISO)' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
scheduledTo?: string;
|
||||
|
||||
@ApiPropertyOptional({ format: 'uuid', description: 'Filter by origin yard' })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
originYardId?: string;
|
||||
|
||||
@ApiPropertyOptional({ format: 'uuid', description: 'Filter by destination yard' })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
destinationYardId?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['true', 'false'], description: 'Filter government vs private bookings' })
|
||||
@IsOptional()
|
||||
@IsIn(['true', 'false'])
|
||||
isGovernment?: 'true' | 'false';
|
||||
|
||||
@ApiPropertyOptional({ enum: TRADE_DIRECTIONS })
|
||||
@IsOptional()
|
||||
@IsIn([...TRADE_DIRECTIONS])
|
||||
|
||||
@@ -34,7 +34,10 @@ import {
|
||||
ResponseCompanyDto,
|
||||
ResponseCompanyProfileDto,
|
||||
} from "./dto/response-company.dto";
|
||||
import { ProfileLicenseFileView } from "./entities/company-profile.entity";
|
||||
import {
|
||||
CompanyDocumentFileView,
|
||||
ProfileLicenseFileView,
|
||||
} from "./entities/company-profile.entity";
|
||||
import { ResponseExternalProfileDto } from "./dto/response-external-profile.dto";
|
||||
import { CompanyInfoResponseDto } from "./dto/company-info-response.dto";
|
||||
import { UpdateProfileDto } from "./dto/update-profile.dto";
|
||||
@@ -218,7 +221,7 @@ export class CompaniesController {
|
||||
@Post("company-profile")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Create a single operational profile for the current user's company and make it the active mode",
|
||||
"Create a single operational profile for the current user's company. The role starts pending and does not become the active mode",
|
||||
})
|
||||
async createCompanyProfile(
|
||||
@CurrentUser() user: CurrentIamUser,
|
||||
@@ -306,6 +309,49 @@ export class CompaniesController {
|
||||
return this.companiesService.listProfileLicenseFiles(user.id, profileId);
|
||||
}
|
||||
|
||||
@Get("poa-delegation")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"List the Power of Attorney delegation letter (with review state) for the current user's company",
|
||||
})
|
||||
async listPoaDelegation(
|
||||
@CurrentUser() user: CurrentIamUser,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
return this.companiesService.listPoaDelegationFiles(user.id);
|
||||
}
|
||||
|
||||
@Post("poa-delegation")
|
||||
@UseInterceptors(AnyFilesInterceptor())
|
||||
@ApiConsumes("multipart/form-data")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Upload the Power of Attorney delegation letter, replacing any existing one. " +
|
||||
"For an approved company the upload is staged for backoffice review; during " +
|
||||
"onboarding it goes live.",
|
||||
})
|
||||
async uploadPoaDelegation(
|
||||
@CurrentUser() user: CurrentIamUser,
|
||||
@UploadedFiles() files: Array<Express.Multer.File>,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
const file = files?.[0];
|
||||
if (!file) {
|
||||
throw new BadRequestException("A delegation letter file is required");
|
||||
}
|
||||
return this.companiesService.uploadPoaDelegationLetter(user.id, file);
|
||||
}
|
||||
|
||||
@Delete("poa-delegation/:fileId")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Remove the Power of Attorney delegation letter (staged for review on an approved company).",
|
||||
})
|
||||
async removePoaDelegation(
|
||||
@CurrentUser() user: CurrentIamUser,
|
||||
@Param("fileId", ParseUUIDPipe) fileId: string,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
return this.companiesService.removePoaDelegationLetter(user.id, fileId);
|
||||
}
|
||||
|
||||
@Patch("active-mode")
|
||||
@ApiOperation({
|
||||
summary: "Switch the current user's active operational mode (importer/exporter)",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { Module, forwardRef } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { HttpModule } from "@nestjs/axios";
|
||||
import { FilesModule } from "../files/files.module";
|
||||
import { FileUploadSettingsModule } from "../file-upload-settings/file-upload-settings.module";
|
||||
import { MinioModule } from "../minio/minio.module";
|
||||
import { NotificationsModule } from "../notifications/notifications.module";
|
||||
import { NotificationInboxModule } from "../notification-inbox/notification-inbox.module";
|
||||
import { CompaniesController } from "./companies.controller";
|
||||
import { CompaniesService } from "./companies.service";
|
||||
import { CompaniesRepository } from "./companies.repository";
|
||||
@@ -17,6 +19,7 @@ import { Booking } from "../bookings/entities/booking.entity";
|
||||
import { CompanyProfileRepository } from "./company-profile.repository";
|
||||
import { CompanyChangeRequestRepository } from "./company-change-request.repository";
|
||||
import { ETradeService } from "./services/etrade.service";
|
||||
import { CompanyNotifierService } from "./company-notifier.service";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -31,6 +34,10 @@ import { ETradeService } from "./services/etrade.service";
|
||||
FilesModule,
|
||||
FileUploadSettingsModule,
|
||||
MinioModule,
|
||||
// Account-status notifications (CompanyNotifierService). The inbox module
|
||||
// imports this module back for portal recipient targeting, hence forwardRef.
|
||||
NotificationsModule,
|
||||
forwardRef(() => NotificationInboxModule),
|
||||
],
|
||||
controllers: [CompaniesController],
|
||||
providers: [
|
||||
@@ -41,6 +48,7 @@ import { ETradeService } from "./services/etrade.service";
|
||||
CompanyChangeRequestRepository,
|
||||
CompanyDashboardRepository,
|
||||
ETradeService,
|
||||
CompanyNotifierService,
|
||||
],
|
||||
exports: [
|
||||
CompaniesService,
|
||||
|
||||
@@ -17,6 +17,7 @@ import { FilesService } from "../files/files.service";
|
||||
import { FileRecord } from "../files/entities/file.entity";
|
||||
import { FileUploadSettingsService } from "../file-upload-settings/file-upload-settings.service";
|
||||
import { ETradeService } from "./services/etrade.service";
|
||||
import { CompanyNotifierService } from "./company-notifier.service";
|
||||
import { OnboardingRequirementsResponseDto } from "./dto/onboarding-requirements-response.dto";
|
||||
import { normalizeE164 } from "../../common/validators/is-phone-number.validator";
|
||||
import { CreateCompanyDto } from "./dto/create-company.dto";
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
import { ExternalProfile } from "./entities/external-profile.entity";
|
||||
import {
|
||||
BusinessLicenseFile,
|
||||
CompanyDocumentFileView,
|
||||
CompanyProfile,
|
||||
ProfileLicenseFileView,
|
||||
ProfileType,
|
||||
@@ -45,6 +47,7 @@ import {
|
||||
import {
|
||||
ChangeRequestStatus,
|
||||
CompanyChangeRequest,
|
||||
DocumentChangeIntent,
|
||||
LicenseChangeIntent,
|
||||
} from "./entities/company-change-request.entity";
|
||||
|
||||
@@ -54,6 +57,27 @@ const LICENSE_CODE = "business_license";
|
||||
/** Code for a license file staged in an open change request (not yet live). */
|
||||
const LICENSE_PENDING_CODE = "business_license_pending";
|
||||
|
||||
/** Mirrors the field seeded in seed/file-upload-settings.seeder.ts. */
|
||||
const POA_DELEGATION_FILE_KEY = "poa_delegation_letter";
|
||||
/** Code for a PoA letter staged in an open change request (not yet live). */
|
||||
const POA_DELEGATION_PENDING_CODE = "poa_delegation_letter_pending";
|
||||
/** FileRecord resource that company-level documents are stored under. */
|
||||
const COMPANY_RESOURCE = "companies";
|
||||
/** company.attributes keys that together mean "a PoA was entered". */
|
||||
const POA_ATTRIBUTES = [
|
||||
"poaName",
|
||||
"poaPhone",
|
||||
"poaEmail",
|
||||
"poaLocation",
|
||||
"poaAddress",
|
||||
] as const;
|
||||
/** Mandatory once the company operates as a freight forwarder. */
|
||||
const REQUIRED_POA_FIELDS: { key: string; label: string }[] = [
|
||||
{ key: "poaName", label: "PoA name" },
|
||||
{ key: "poaEmail", label: "PoA email" },
|
||||
{ key: "poaPhone", label: "PoA phone" },
|
||||
];
|
||||
|
||||
export interface UserIdentity {
|
||||
userId: string;
|
||||
firstName: string;
|
||||
@@ -73,6 +97,7 @@ export class CompaniesService {
|
||||
private readonly filesService: FilesService,
|
||||
private readonly fileUploadSettingsService: FileUploadSettingsService,
|
||||
private readonly etradeService: ETradeService,
|
||||
private readonly companyNotifier: CompanyNotifierService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
@@ -562,9 +587,13 @@ export class CompaniesService {
|
||||
}
|
||||
|
||||
async updateCompany(id: string, dto: UpdateCompanyDto): Promise<Company> {
|
||||
await this.findCompanyById(id);
|
||||
const before = await this.findCompanyById(id);
|
||||
const updated = await this.companiesRepo.update(id, dto);
|
||||
if (!updated) throw new NotFoundException(`Company ${id} not found`);
|
||||
|
||||
// Suspending or blacklisting locks the customer out, so they must be told.
|
||||
// This is the only path that writes those statuses.
|
||||
this.companyNotifier.statusChanged(updated, before.status);
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -765,6 +794,7 @@ export class CompaniesService {
|
||||
const companyUpdates = this.mapProfileDtoToCompanyUpdates(company, snapshot);
|
||||
await this.companiesRepo.update(company.id, companyUpdates);
|
||||
await this.applyLicenseChanges(request);
|
||||
await this.applyDocumentChanges(request);
|
||||
|
||||
return (
|
||||
(await this.changeRequestRepo.update(id, {
|
||||
@@ -817,7 +847,12 @@ export class CompaniesService {
|
||||
if (existing) {
|
||||
const prev = existing.documents?.documentFileIds ?? [];
|
||||
await this.changeRequestRepo.update(existing.id, {
|
||||
documents: { documentFileIds: [...prev, ...fileIds] },
|
||||
// Spread the existing documents blob: a bare object would drop any
|
||||
// licenseChanges/documentChanges already staged on this request.
|
||||
documents: {
|
||||
...existing.documents,
|
||||
documentFileIds: [...prev, ...fileIds],
|
||||
},
|
||||
submittedBy: submittedBy ?? existing.submittedBy ?? null,
|
||||
submittedAt: now,
|
||||
note: null,
|
||||
@@ -849,12 +884,17 @@ export class CompaniesService {
|
||||
);
|
||||
}
|
||||
await this.discardLicenseChanges(request);
|
||||
await this.discardDocumentChanges(request);
|
||||
return (
|
||||
(await this.changeRequestRepo.update(id, {
|
||||
status: ChangeRequestStatus.Rejected,
|
||||
// Staged license uploads were just discarded; drop their intents so an
|
||||
// amended resubmit never re-references deleted files.
|
||||
documents: { ...request.documents, licenseChanges: [] },
|
||||
// Staged license/document uploads were just discarded; drop their intents
|
||||
// so an amended resubmit never re-references deleted files.
|
||||
documents: {
|
||||
...request.documents,
|
||||
licenseChanges: [],
|
||||
documentChanges: [],
|
||||
},
|
||||
note,
|
||||
reviewedBy: reviewerId ?? null,
|
||||
reviewedAt: new Date(),
|
||||
@@ -1017,13 +1057,12 @@ export class CompaniesService {
|
||||
);
|
||||
}
|
||||
|
||||
const reference = await this.companyProfilesRepo.generateReference(type);
|
||||
|
||||
// No reference is minted here: it is issued by setCompanyProfileStatus when
|
||||
// a reviewer approves the role. Creating it Active would bypass that review.
|
||||
return this.companyProfilesRepo.create({
|
||||
companyId,
|
||||
type,
|
||||
reference,
|
||||
status: ProfileStatus.Active,
|
||||
status: ProfileStatus.Pending,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1097,9 +1136,11 @@ export class CompaniesService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a single operational profile for the current user's company and
|
||||
* make it the active mode in the same call. Powers the header "Switch to
|
||||
* Exporter/Importer" flow when the target profile doesn't exist yet.
|
||||
* Create a single operational profile for the current user's company. The new
|
||||
* role starts Pending, so it deliberately does NOT become the active mode:
|
||||
* switching onto an unapproved profile would strip the user of `canBook` and
|
||||
* block them from creating contracts under the role they already had approved.
|
||||
* Callers switch explicitly via {@link setActiveMode} once the role is Active.
|
||||
*/
|
||||
async createCompanyProfileForUser(
|
||||
userId: string,
|
||||
@@ -1122,8 +1163,7 @@ export class CompaniesService {
|
||||
let created = await this.companyProfilesRepo.findByType(companyId, type);
|
||||
if (!created) {
|
||||
// New self-service roles start Pending (awaiting backoffice approval) and
|
||||
// carry no reference until approved. The customer can select this mode but
|
||||
// can't book under it until it's cleared.
|
||||
// carry no reference until approved.
|
||||
created = await this.companyProfilesRepo.create({
|
||||
companyId,
|
||||
type,
|
||||
@@ -1132,8 +1172,6 @@ export class CompaniesService {
|
||||
});
|
||||
}
|
||||
|
||||
await this.profilesRepo.update(profile.id, { activeProfileType: type });
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
@@ -1240,6 +1278,29 @@ export class CompaniesService {
|
||||
);
|
||||
const missingLicenses = licenseProfiles.filter((p) => !p.uploaded);
|
||||
|
||||
// 4. Power of Attorney. Optional in general, but a freight forwarder acts on
|
||||
// other companies' behalf so its PoA is mandatory. Either way, a PoA that
|
||||
// has been entered must be evidenced by the delegation letter.
|
||||
const poaRequired = (company.companyProfiles ?? []).some(
|
||||
(p) => p.type === ProfileType.freightForwarder,
|
||||
);
|
||||
const poaProvided = POA_ATTRIBUTES.some((k) =>
|
||||
(company.attributes?.[k] as string | undefined)?.trim(),
|
||||
);
|
||||
const missingPoaFields = poaRequired
|
||||
? REQUIRED_POA_FIELDS.filter(
|
||||
(f) => !(company.attributes?.[f.key] as string | undefined)?.trim(),
|
||||
)
|
||||
: [];
|
||||
// Only gate on the letter once the document set actually carries the field.
|
||||
const delegationField = (setting?.fields ?? []).find(
|
||||
(f) => f.fileKey === POA_DELEGATION_FILE_KEY,
|
||||
);
|
||||
const missingDelegation =
|
||||
Boolean(delegationField) &&
|
||||
(poaRequired || poaProvided) &&
|
||||
!uploadedCodes.has(POA_DELEGATION_FILE_KEY);
|
||||
|
||||
const outstanding = [
|
||||
...missingInfo.map((f) => `Add your ${f.label.toLowerCase()}`),
|
||||
...missingDocs.map((d) => `Upload your ${d.fileLabel}`),
|
||||
@@ -1247,18 +1308,31 @@ export class CompaniesService {
|
||||
(p) =>
|
||||
`Upload a business license for your ${p.type.replace(/_/g, " ")} profile`,
|
||||
),
|
||||
...missingPoaFields.map((f) => `Add your ${f.label.toLowerCase()}`),
|
||||
...(missingDelegation
|
||||
? ["Upload the delegation letter for your Power of Attorney"]
|
||||
: []),
|
||||
];
|
||||
|
||||
// Progress spans every required item the user has to satisfy: company-info
|
||||
// fields, required documents and one license per operational profile.
|
||||
// fields, required documents, one license per operational profile, and the
|
||||
// PoA details/letter whenever those are mandatory.
|
||||
const requiredDocCount = documents.filter((d) => d.isRequired).length;
|
||||
const poaItemCount =
|
||||
(poaRequired ? REQUIRED_POA_FIELDS.length : 0) +
|
||||
(delegationField && (poaRequired || poaProvided) ? 1 : 0);
|
||||
const total =
|
||||
this.REQUIRED_COMPANY_INFO.length +
|
||||
requiredDocCount +
|
||||
licenseProfiles.length;
|
||||
licenseProfiles.length +
|
||||
poaItemCount;
|
||||
const completed =
|
||||
total -
|
||||
(missingInfo.length + missingDocs.length + missingLicenses.length);
|
||||
(missingInfo.length +
|
||||
missingDocs.length +
|
||||
missingLicenses.length +
|
||||
missingPoaFields.length +
|
||||
(missingDelegation ? 1 : 0));
|
||||
|
||||
return new OnboardingRequirementsResponseDto({
|
||||
documentSettingCode,
|
||||
@@ -1266,6 +1340,13 @@ export class CompaniesService {
|
||||
companyInfo: { complete: missingInfo.length === 0, missingFields: missingInfo },
|
||||
documents,
|
||||
licenseProfiles,
|
||||
poa: {
|
||||
required: poaRequired,
|
||||
provided: poaProvided,
|
||||
delegationLetterUploaded: uploadedCodes.has(POA_DELEGATION_FILE_KEY),
|
||||
missingFields: missingPoaFields,
|
||||
complete: missingPoaFields.length === 0 && !missingDelegation,
|
||||
},
|
||||
progress: { completed, total },
|
||||
isComplete: outstanding.length === 0,
|
||||
onboardingCompleted: profile.onboardingCompleted,
|
||||
@@ -1365,10 +1446,12 @@ export class CompaniesService {
|
||||
// browser (which fails on the internal bucket endpoint).
|
||||
|
||||
/**
|
||||
* Upload business-license file(s) for one of the user's profiles. During
|
||||
* onboarding (company not yet Active) they go live immediately; for an Active
|
||||
* company they're staged under the pending code and recorded as `add` intents
|
||||
* on a pending change request for backoffice review. Returns the updated view.
|
||||
* Upload business-license file(s) for one of the user's profiles. For a role
|
||||
* not yet approved (a fresh onboarding profile, or a newly added service on an
|
||||
* already-active company) they go live immediately and are reviewed together
|
||||
* with the role itself. Only for an already-approved role are they staged under
|
||||
* the pending code and recorded as `add` intents on a pending change request —
|
||||
* a licence swap on a live role is a change; a licence on a new role is not.
|
||||
*/
|
||||
async addProfileLicenseFiles(
|
||||
userId: string,
|
||||
@@ -1377,7 +1460,7 @@ export class CompaniesService {
|
||||
): Promise<ProfileLicenseFileView[]> {
|
||||
const profile = await this.resolveOwnedProfile(userId, profileId);
|
||||
const company = await this.findCompanyById(profile.companyId);
|
||||
const gated = company.status === CompanyStatus.Active;
|
||||
const gated = profile.status === ProfileStatus.Active;
|
||||
const code = gated ? LICENSE_PENDING_CODE : LICENSE_CODE;
|
||||
|
||||
const uploaded = await Promise.all(
|
||||
@@ -1409,9 +1492,9 @@ export class CompaniesService {
|
||||
|
||||
/**
|
||||
* Remove a license file. A staged (pending) file is withdrawn outright
|
||||
* (soft-deleted, its `add` intent dropped). A live file on an Active company
|
||||
* is kept and recorded as a `remove` intent for review; during onboarding it
|
||||
* is deleted immediately.
|
||||
* (soft-deleted, its `add` intent dropped). A live file on an already-approved
|
||||
* role is kept and recorded as a `remove` intent for review; on a role still
|
||||
* awaiting approval it is deleted immediately.
|
||||
*/
|
||||
async removeProfileLicenseFile(
|
||||
userId: string,
|
||||
@@ -1427,7 +1510,7 @@ export class CompaniesService {
|
||||
throw new NotFoundException(`License file ${fileId} not found`);
|
||||
}
|
||||
const company = await this.findCompanyById(profile.companyId);
|
||||
const gated = company.status === CompanyStatus.Active;
|
||||
const gated = profile.status === ProfileStatus.Active;
|
||||
|
||||
if (record.code === LICENSE_PENDING_CODE) {
|
||||
// Withdraw a not-yet-approved upload: delete it and drop its add intent.
|
||||
@@ -1449,7 +1532,7 @@ export class CompaniesService {
|
||||
/**
|
||||
* Replace a live license file with a freshly uploaded one — recorded as a
|
||||
* `remove` of the old file plus an `add` of the new, so approval swaps them
|
||||
* atomically. During onboarding the swap is applied immediately.
|
||||
* atomically. On a role still awaiting approval the swap is applied immediately.
|
||||
*/
|
||||
async replaceProfileLicenseFile(
|
||||
userId: string,
|
||||
@@ -1463,7 +1546,7 @@ export class CompaniesService {
|
||||
throw new NotFoundException(`License file ${fileId} not found`);
|
||||
}
|
||||
const company = await this.findCompanyById(profile.companyId);
|
||||
const gated = company.status === CompanyStatus.Active;
|
||||
const gated = profile.status === ProfileStatus.Active;
|
||||
|
||||
const created = await this.filesService.upload({
|
||||
resourceId: profileId,
|
||||
@@ -1671,6 +1754,254 @@ export class CompaniesService {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Power of Attorney delegation letter
|
||||
//
|
||||
// A company-level document that follows the same staged-review model as the
|
||||
// business license: on an approved (Active) company an upload lands under the
|
||||
// pending code and the live letter is flagged for removal, so the reviewer
|
||||
// sees both and approval swaps them atomically. During onboarding it goes live.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** The company's PoA letter(s), with each file's review status resolved. */
|
||||
async listPoaDelegationFiles(
|
||||
userId: string,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
const { company } = await this.getCompanyInfoByUserId(userId);
|
||||
return this.getPoaDelegationView(company.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload the PoA delegation letter, replacing whatever is already on file.
|
||||
* On an Active company this stages an `add` for the new file plus a `remove`
|
||||
* for each live one; a letter still awaiting approval is withdrawn outright
|
||||
* rather than stacking a second pending upload.
|
||||
*/
|
||||
async uploadPoaDelegationLetter(
|
||||
userId: string,
|
||||
file: Express.Multer.File,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
const { company } = await this.getCompanyInfoByUserId(userId);
|
||||
const gated = company.status === CompanyStatus.Active;
|
||||
|
||||
const records = await this.filesService.findByResource(
|
||||
company.id,
|
||||
COMPANY_RESOURCE,
|
||||
);
|
||||
const live = records.filter((r) => r.code === POA_DELEGATION_FILE_KEY);
|
||||
const staged = records.filter(
|
||||
(r) => r.code === POA_DELEGATION_PENDING_CODE,
|
||||
);
|
||||
|
||||
// Supersede an unreviewed upload instead of queueing another one.
|
||||
for (const r of staged) {
|
||||
await this.filesService.remove(r.id);
|
||||
await this.withdrawDocumentIntent(company.id, r.id);
|
||||
}
|
||||
|
||||
const created = await this.filesService.upload({
|
||||
resourceId: company.id,
|
||||
resource: COMPANY_RESOURCE,
|
||||
code: gated ? POA_DELEGATION_PENDING_CODE : POA_DELEGATION_FILE_KEY,
|
||||
file,
|
||||
});
|
||||
|
||||
if (gated) {
|
||||
await this.stageDocumentIntent(
|
||||
company.id,
|
||||
[
|
||||
...live.map((r) => ({
|
||||
op: "remove" as const,
|
||||
fileId: r.id,
|
||||
code: POA_DELEGATION_FILE_KEY,
|
||||
fileName: r.name,
|
||||
})),
|
||||
{
|
||||
op: "add" as const,
|
||||
fileId: created.id,
|
||||
code: POA_DELEGATION_FILE_KEY,
|
||||
fileName: created.name,
|
||||
},
|
||||
],
|
||||
userId,
|
||||
);
|
||||
} else {
|
||||
// Onboarding: no review, so the old letter is simply replaced.
|
||||
for (const r of live) await this.filesService.remove(r.id);
|
||||
}
|
||||
|
||||
return this.getPoaDelegationView(company.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the PoA letter. A staged upload is withdrawn outright; a live file on
|
||||
* an Active company is kept and flagged for deletion on approval; during
|
||||
* onboarding it is deleted immediately.
|
||||
*/
|
||||
async removePoaDelegationLetter(
|
||||
userId: string,
|
||||
fileId: string,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
const { company } = await this.getCompanyInfoByUserId(userId);
|
||||
const record = await this.filesService.findById(fileId);
|
||||
if (
|
||||
record.resource !== COMPANY_RESOURCE ||
|
||||
record.resourceId !== company.id ||
|
||||
(record.code !== POA_DELEGATION_FILE_KEY &&
|
||||
record.code !== POA_DELEGATION_PENDING_CODE)
|
||||
) {
|
||||
throw new NotFoundException(`Delegation letter ${fileId} not found`);
|
||||
}
|
||||
|
||||
if (record.code === POA_DELEGATION_PENDING_CODE) {
|
||||
await this.filesService.remove(fileId);
|
||||
await this.withdrawDocumentIntent(company.id, fileId);
|
||||
} else if (company.status === CompanyStatus.Active) {
|
||||
await this.stageDocumentIntent(
|
||||
company.id,
|
||||
[
|
||||
{
|
||||
op: "remove",
|
||||
fileId,
|
||||
code: POA_DELEGATION_FILE_KEY,
|
||||
fileName: record.name,
|
||||
},
|
||||
],
|
||||
userId,
|
||||
);
|
||||
} else {
|
||||
await this.filesService.remove(fileId);
|
||||
}
|
||||
|
||||
return this.getPoaDelegationView(company.id);
|
||||
}
|
||||
|
||||
private async getPoaDelegationView(
|
||||
companyId: string,
|
||||
): Promise<CompanyDocumentFileView[]> {
|
||||
const pending =
|
||||
await this.changeRequestRepo.findPendingByCompanyId(companyId);
|
||||
const removeIds = new Set(
|
||||
(pending?.documents?.documentChanges ?? [])
|
||||
.filter((c) => c.op === "remove")
|
||||
.map((c) => c.fileId),
|
||||
);
|
||||
const records = await this.filesService.findByResource(
|
||||
companyId,
|
||||
COMPANY_RESOURCE,
|
||||
);
|
||||
return records
|
||||
.filter(
|
||||
(r) =>
|
||||
r.code === POA_DELEGATION_FILE_KEY ||
|
||||
r.code === POA_DELEGATION_PENDING_CODE,
|
||||
)
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
size: r.size,
|
||||
mimeType: r.mimeType,
|
||||
status:
|
||||
r.code === POA_DELEGATION_PENDING_CODE
|
||||
? ("pending_add" as const)
|
||||
: removeIds.has(r.id)
|
||||
? ("pending_remove" as const)
|
||||
: ("live" as const),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Open or append a pending change request recording document add/remove intents. */
|
||||
private async stageDocumentIntent(
|
||||
companyId: string,
|
||||
changes: DocumentChangeIntent[],
|
||||
submittedBy?: string,
|
||||
): Promise<void> {
|
||||
if (changes.length === 0) return;
|
||||
const now = new Date();
|
||||
const existing =
|
||||
await this.changeRequestRepo.findPendingByCompanyId(companyId);
|
||||
if (existing) {
|
||||
const prev = existing.documents?.documentChanges ?? [];
|
||||
// Re-uploading twice before review would otherwise stage a second `remove`
|
||||
// for the same live file, and the duplicate would fail on approval.
|
||||
const seen = new Set(prev.map((c) => `${c.op}:${c.fileId}`));
|
||||
const fresh = changes.filter((c) => !seen.has(`${c.op}:${c.fileId}`));
|
||||
if (fresh.length === 0) return;
|
||||
await this.changeRequestRepo.update(existing.id, {
|
||||
documents: {
|
||||
...existing.documents,
|
||||
documentChanges: [...prev, ...fresh],
|
||||
},
|
||||
submittedBy: submittedBy ?? existing.submittedBy ?? null,
|
||||
submittedAt: now,
|
||||
note: null,
|
||||
});
|
||||
} else {
|
||||
await this.changeRequestRepo.create({
|
||||
companyId,
|
||||
snapshot: {},
|
||||
documents: { documentChanges: changes },
|
||||
status: ChangeRequestStatus.Pending,
|
||||
submittedBy: submittedBy ?? null,
|
||||
submittedAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a staged document intent referencing `fileId`. If that empties the
|
||||
* request entirely, delete it so the customer's settings page unlocks.
|
||||
*/
|
||||
private async withdrawDocumentIntent(
|
||||
companyId: string,
|
||||
fileId: string,
|
||||
): Promise<void> {
|
||||
const existing =
|
||||
await this.changeRequestRepo.findPendingByCompanyId(companyId);
|
||||
if (!existing) return;
|
||||
const remaining = (existing.documents?.documentChanges ?? []).filter(
|
||||
(c) => c.fileId !== fileId,
|
||||
);
|
||||
const docs = existing.documents ?? {};
|
||||
const stillHasWork =
|
||||
remaining.length > 0 ||
|
||||
(docs.licenseChanges?.length ?? 0) > 0 ||
|
||||
(docs.documentFileIds?.length ?? 0) > 0 ||
|
||||
Object.keys(existing.snapshot ?? {}).length > 0;
|
||||
|
||||
if (stillHasWork) {
|
||||
await this.changeRequestRepo.update(existing.id, {
|
||||
documents: { ...docs, documentChanges: remaining },
|
||||
});
|
||||
} else {
|
||||
await this.changeRequestRepo.softDelete(existing.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply a request's staged document changes: promote adds, delete removes. */
|
||||
private async applyDocumentChanges(
|
||||
request: CompanyChangeRequest,
|
||||
): Promise<void> {
|
||||
for (const change of request.documents?.documentChanges ?? []) {
|
||||
if (change.op === "add") {
|
||||
await this.filesService.setCode(change.fileId, change.code);
|
||||
} else {
|
||||
await this.filesService.remove(change.fileId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Discard a rejected request's staged document uploads (adds only). */
|
||||
private async discardDocumentChanges(
|
||||
request: CompanyChangeRequest,
|
||||
): Promise<void> {
|
||||
for (const change of request.documents?.documentChanges ?? []) {
|
||||
if (change.op === "add") {
|
||||
await this.filesService.remove(change.fileId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which company_profile a new booking belongs to, from the company
|
||||
* and the booking's trade direction. IMPORT → importer profile, EXPORT →
|
||||
@@ -1719,13 +2050,17 @@ export class CompaniesService {
|
||||
}
|
||||
|
||||
async fetchETradeData(tin: string) {
|
||||
const { businessInfo } = await this.etradeService.resolveCompanyData(tin);
|
||||
const { businessInfo, companyInfo } =
|
||||
await this.etradeService.resolveCompanyData(tin);
|
||||
if (!businessInfo) {
|
||||
throw new BadRequestException(
|
||||
"We couldn't find a business license for this TIN with eTrade. Please double-check the number and try again.",
|
||||
);
|
||||
}
|
||||
const registrationData = this.etradeService.extractRegistrationData(businessInfo);
|
||||
const registrationData = this.etradeService.extractRegistrationData(
|
||||
businessInfo,
|
||||
companyInfo,
|
||||
);
|
||||
const tinTaken = await this.companiesRepo.existsByTin(tin);
|
||||
return { ...registrationData, tinTaken };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import {
|
||||
NotificationAudience,
|
||||
NotificationPriority,
|
||||
NotificationType,
|
||||
} from "@edr/types";
|
||||
|
||||
import { Company, CompanyStatus } from "./entities/company.entity";
|
||||
import { NotificationsService } from "../notifications/notifications.service";
|
||||
import { NotificationInboxService } from "../notification-inbox/notification-inbox.service";
|
||||
|
||||
/** Account statuses that lock the customer out and therefore must be told to them. */
|
||||
const PUNITIVE_STATUSES: readonly CompanyStatus[] = [
|
||||
CompanyStatus.Suspended,
|
||||
CompanyStatus.Blacklisted,
|
||||
];
|
||||
|
||||
/**
|
||||
* Customer notifications for company account-status changes. Mirrors
|
||||
* {@link ContractNotifierService}: SMS + email direct to the company contact,
|
||||
* plus a persisted in-app item. Every send is fire-and-forget and never throws —
|
||||
* a notification failure must not roll back the status change itself.
|
||||
*/
|
||||
@Injectable()
|
||||
export class CompanyNotifierService {
|
||||
private readonly logger = new Logger(CompanyNotifierService.name);
|
||||
|
||||
constructor(
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly inbox: NotificationInboxService,
|
||||
) {}
|
||||
|
||||
/** Send SMS + email to the company contact; log-only on failure. */
|
||||
private async notifyContact(company: Company, message: string): Promise<void> {
|
||||
const phone = company.contactPersonPhone ?? company.phone ?? null;
|
||||
const email = company.email ?? company.generalManagerEmail ?? null;
|
||||
|
||||
if (phone) {
|
||||
try {
|
||||
await this.notifications.directSend("sms", phone, message);
|
||||
} catch (err) {
|
||||
this.logger.warn(`SMS failed for ${company.id}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
if (email) {
|
||||
try {
|
||||
await this.notifications.directSend("email", email, message);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Email failed for ${company.id}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
if (!phone && !email) {
|
||||
this.logger.warn(`No contact on file for ${company.id} — not notified`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the customer their account was suspended or blacklisted. Called only on
|
||||
* a real transition into one of those statuses; other status writes are silent.
|
||||
*/
|
||||
statusChanged(company: Company, previous: CompanyStatus): void {
|
||||
const status = company.status;
|
||||
if (status === previous) return;
|
||||
if (!PUNITIVE_STATUSES.includes(status)) return;
|
||||
|
||||
const label = status === CompanyStatus.Suspended ? "suspended" : "blacklisted";
|
||||
const title = `Account ${label}`;
|
||||
const body =
|
||||
`Your company account has been ${label}. ` +
|
||||
`You will not be able to submit new contracts or bookings. ` +
|
||||
`Please contact EDR support for assistance.`;
|
||||
|
||||
this.logger.log(`ACCOUNT_${label.toUpperCase()} — ${company.id}`);
|
||||
void this.notifyContact(company, `${title}. ${body}`);
|
||||
void this.inbox.notify({
|
||||
recipients: { companyId: company.id },
|
||||
audience: NotificationAudience.PORTAL,
|
||||
type: NotificationType.ACCOUNT_STATUS,
|
||||
title,
|
||||
body,
|
||||
link: "/settings",
|
||||
data: { companyId: company.id, status },
|
||||
priority: NotificationPriority.HIGH,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ChangeRequestStatus,
|
||||
CompanyChangeRequest,
|
||||
DocumentChangeIntent,
|
||||
LicenseChangeIntent,
|
||||
} from "../entities/company-change-request.entity";
|
||||
|
||||
@@ -18,6 +19,8 @@ export class ChangeRequestResponseDto {
|
||||
documentFileIds: string[];
|
||||
/** Staged business-license add/remove intents attached to this request. */
|
||||
licenseChanges: LicenseChangeIntent[];
|
||||
/** Staged company-document add/remove intents (e.g. the PoA letter). */
|
||||
documentChanges: DocumentChangeIntent[];
|
||||
note: string | null;
|
||||
submittedBy: string | null;
|
||||
submittedAt: Date | null;
|
||||
@@ -33,6 +36,7 @@ export class ChangeRequestResponseDto {
|
||||
this.snapshot = req.snapshot ?? {};
|
||||
this.documentFileIds = req.documents?.documentFileIds ?? [];
|
||||
this.licenseChanges = req.documents?.licenseChanges ?? [];
|
||||
this.documentChanges = req.documents?.documentChanges ?? [];
|
||||
this.note = req.note ?? null;
|
||||
this.submittedBy = req.submittedBy ?? null;
|
||||
this.submittedAt = req.submittedAt ?? null;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CompanyRegistrationData } from "@edr/types";
|
||||
|
||||
export class ETradeResponseDto implements CompanyRegistrationData {
|
||||
companyName!: string;
|
||||
licenceNumber!: string;
|
||||
statusDescription!: string;
|
||||
dateRegistered!: string;
|
||||
@@ -20,6 +21,7 @@ export class ETradeResponseDto implements CompanyRegistrationData {
|
||||
tinTaken?: boolean;
|
||||
|
||||
constructor(data: CompanyRegistrationData) {
|
||||
this.companyName = data.companyName;
|
||||
this.licenceNumber = data.licenceNumber;
|
||||
this.statusDescription = data.statusDescription;
|
||||
this.dateRegistered = data.dateRegistered;
|
||||
|
||||
@@ -35,6 +35,19 @@ export interface OnboardingLicenseProfile {
|
||||
uploaded: boolean;
|
||||
}
|
||||
|
||||
export interface OnboardingPoaState {
|
||||
/** True when the company operates as a freight forwarder — PoA is mandatory. */
|
||||
required: boolean;
|
||||
/** True once any PoA detail has been entered. */
|
||||
provided: boolean;
|
||||
/** True when the delegation letter is stored for the company. */
|
||||
delegationLetterUploaded: boolean;
|
||||
/** PoA details still missing (only populated when `required`). */
|
||||
missingFields: OnboardingInfoField[];
|
||||
/** False while the PoA step still owes details or a delegation letter. */
|
||||
complete: boolean;
|
||||
}
|
||||
|
||||
export class OnboardingRequirementsResponseDto {
|
||||
/** Resolved document setting code (by nationality) the docs were drawn from. */
|
||||
documentSettingCode: string;
|
||||
@@ -52,6 +65,9 @@ export class OnboardingRequirementsResponseDto {
|
||||
/** Per-operational-profile business-license requirements. */
|
||||
licenseProfiles: OnboardingLicenseProfile[];
|
||||
|
||||
/** Power of Attorney state, so the wizard needn't re-derive the rule. */
|
||||
poa: OnboardingPoaState;
|
||||
|
||||
/** Overall setup progress across fields + documents + licenses. */
|
||||
progress: { completed: number; total: number };
|
||||
|
||||
@@ -70,6 +86,7 @@ export class OnboardingRequirementsResponseDto {
|
||||
this.companyInfo = init.companyInfo;
|
||||
this.documents = init.documents;
|
||||
this.licenseProfiles = init.licenseProfiles;
|
||||
this.poa = init.poa;
|
||||
this.progress = init.progress;
|
||||
this.isComplete = init.isComplete;
|
||||
this.onboardingCompleted = init.onboardingCompleted;
|
||||
|
||||
@@ -30,12 +30,34 @@ export interface LicenseChangeIntent {
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A staged change to a company-level document, awaiting review. Same semantics
|
||||
* as {@link LicenseChangeIntent} but keyed by the document's FileRecord `code`
|
||||
* (e.g. `poa_delegation_letter`) rather than a profile: `add` → uploaded under
|
||||
* the pending code, promoted to `code` on approval; `remove` → a live file that
|
||||
* is deleted on approval. A replace is a `remove` plus an `add`.
|
||||
*/
|
||||
export interface DocumentChangeIntent {
|
||||
op: "add" | "remove";
|
||||
fileId: string;
|
||||
/** The live FileRecord code this op targets (the upload setting's fileKey). */
|
||||
code: string;
|
||||
/** File name, snapshotted for the backoffice review screen. */
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
/** File references staged alongside a change request (documents/licenses). */
|
||||
export interface ChangeRequestDocuments {
|
||||
/** FileRecord ids uploaded against the company while this request was open. */
|
||||
/**
|
||||
* FileRecord ids uploaded against the company while this request was open.
|
||||
* These go live immediately — only their ids are recorded, for the reviewer.
|
||||
* Contrast `documentChanges`, which stages the file behind the pending code.
|
||||
*/
|
||||
documentFileIds?: string[];
|
||||
/** Staged per-profile business-license add/remove intents. */
|
||||
licenseChanges?: LicenseChangeIntent[];
|
||||
/** Staged company-level document add/remove intents (e.g. the PoA letter). */
|
||||
documentChanges?: DocumentChangeIntent[];
|
||||
}
|
||||
|
||||
@Entity({ schema: "freight", name: "company_change_request" })
|
||||
|
||||
@@ -31,17 +31,28 @@ export interface BusinessLicenseFile {
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `live` — approved & in effect; `pending_add` — uploaded, awaiting approval;
|
||||
* `pending_remove` — live but flagged for deletion on approval.
|
||||
*/
|
||||
export type StagedFileStatus = "live" | "pending_add" | "pending_remove";
|
||||
|
||||
/** A business-license file plus its change-review state, surfaced to clients. */
|
||||
export interface ProfileLicenseFileView {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
mimeType: string;
|
||||
/**
|
||||
* `live` — approved & in effect; `pending_add` — uploaded, awaiting approval;
|
||||
* `pending_remove` — live but flagged for deletion on approval.
|
||||
*/
|
||||
status: "live" | "pending_add" | "pending_remove";
|
||||
status: StagedFileStatus;
|
||||
}
|
||||
|
||||
/** A company-level document (e.g. the PoA letter) with its change-review state. */
|
||||
export interface CompanyDocumentFileView {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
mimeType: string;
|
||||
status: StagedFileStatus;
|
||||
}
|
||||
|
||||
@Entity({ schema: "freight", name: "company_profiles" })
|
||||
@@ -73,11 +84,17 @@ export class CompanyProfile extends BaseEntity {
|
||||
})
|
||||
reference!: string | null;
|
||||
|
||||
/**
|
||||
* A newly requested operational role is unreviewed, so it defaults to Pending.
|
||||
* Only {@link CompaniesService.setCompanyProfileStatus} may promote it to
|
||||
* Active — an approved-by-default role would let a customer self-grant a
|
||||
* service (e.g. importer) without any documentation review.
|
||||
*/
|
||||
@Column({
|
||||
name: "status",
|
||||
type: "varchar",
|
||||
length: 32,
|
||||
default: ProfileStatus.Active,
|
||||
default: ProfileStatus.Pending,
|
||||
})
|
||||
status!: ProfileStatus;
|
||||
|
||||
|
||||
@@ -87,12 +87,21 @@ export class ETradeService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `companyInfo` carries the registered organization name (`BusinessName`);
|
||||
* `businessInfo` only carries the licence's `TradeName`. Pass both so the
|
||||
* company name resolves to the legal entity rather than the trade name — and
|
||||
* never to `ManagerNameEng`, which is the manager's personal name.
|
||||
*/
|
||||
extractRegistrationData(
|
||||
businessInfo: ETradeBusinessInfo,
|
||||
companyInfo?: ETradeCompanyInfo,
|
||||
): CompanyRegistrationData {
|
||||
const primaryManager = businessInfo.AssociateShortInfos?.[0];
|
||||
|
||||
return {
|
||||
companyName:
|
||||
companyInfo?.BusinessName?.trim() || businessInfo.TradeName?.trim() || "",
|
||||
licenceNumber: businessInfo.LicenceNumber,
|
||||
statusDescription: businessInfo.StatusDescription,
|
||||
dateRegistered: businessInfo.DateRegistered,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { BaseRepository } from "@edr/api-common";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
|
||||
import {
|
||||
ContractTemplate,
|
||||
ContractTemplateCode,
|
||||
} from "./entities/contract-template.entity";
|
||||
|
||||
@Injectable()
|
||||
export class ContractTemplatesRepository extends BaseRepository<ContractTemplate> {
|
||||
constructor(
|
||||
@InjectRepository(ContractTemplate)
|
||||
repository: Repository<ContractTemplate>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
|
||||
findByCode(code: ContractTemplateCode): Promise<ContractTemplate | null> {
|
||||
return this.repository.findOne({ where: { code } });
|
||||
}
|
||||
|
||||
override findAll(): Promise<ContractTemplate[]> {
|
||||
return this.repository.find({ order: { code: "ASC" } });
|
||||
}
|
||||
|
||||
async saveTemplate(template: ContractTemplate): Promise<ContractTemplate> {
|
||||
return this.repository.save(template);
|
||||
}
|
||||
}
|
||||
@@ -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()}`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { ContractRendererService } from "../../contracts/contract-renderer.service";
|
||||
import { getTemplateMeta } from "../../contracts/contract-template.registry";
|
||||
import {
|
||||
ContractDynamicTemplateView,
|
||||
ContractViewModel,
|
||||
} from "../../contracts/contract-view-model.builder";
|
||||
import { ContractTemplatesRepository } from "./contract-templates.repository";
|
||||
import {
|
||||
CreateArticleDto,
|
||||
PreviewContractTemplateDto,
|
||||
ReplaceArticleDto,
|
||||
UpdateArticleDto,
|
||||
UpdateContractTemplateDto,
|
||||
} from "./dto/contract-template.dto";
|
||||
import {
|
||||
CONTRACT_TEMPLATE_CODES,
|
||||
ContractTemplate,
|
||||
ContractTemplateArticle,
|
||||
ContractTemplateCode,
|
||||
contractTemplateCodeFor,
|
||||
} from "./entities/contract-template.entity";
|
||||
|
||||
/** Registry keys used to derive labels for the mock preview per template code. */
|
||||
const PREVIEW_TEMPLATE_KEYS: Record<ContractTemplateCode, string> = {
|
||||
IMPORT_BULK: "IMP_BULK_USD_FORWARDING",
|
||||
EXPORT_BULK: "EXP_BULK_USD_TRANSPORT_ONLY",
|
||||
INTERCITY_BULK: "DOM_BULK_USD_TRANSPORT_ONLY",
|
||||
IMPORT_CONTAINER: "IMP_CON_USD_TRANSPORT_ONLY",
|
||||
EXPORT_CONTAINER: "EXP_CON_USD_FORWARDING",
|
||||
INTERCITY_CONTAINER: "DOM_CON_USD_TRANSPORT_ONLY",
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class ContractTemplatesService {
|
||||
constructor(
|
||||
private readonly repository: ContractTemplatesRepository,
|
||||
private readonly renderer: ContractRendererService,
|
||||
) {}
|
||||
|
||||
async list(): Promise<ContractTemplate[]> {
|
||||
const templates = await this.repository.findAll();
|
||||
const rank = new Map(CONTRACT_TEMPLATE_CODES.map((code, i) => [code, i] as const));
|
||||
return templates.sort(
|
||||
(a, b) => (rank.get(a.code) ?? 99) - (rank.get(b.code) ?? 99),
|
||||
);
|
||||
}
|
||||
|
||||
async getByCode(code: string): Promise<ContractTemplate> {
|
||||
const template = await this.repository.findByCode(this.assertCode(code));
|
||||
if (!template) {
|
||||
throw new NotFoundException(`Contract template ${code} not found`);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
/**
|
||||
* The active template used when generating a contract document for the given
|
||||
* direction/freight pair; null when missing or deactivated (the renderer then
|
||||
* falls back to the built-in generic layout).
|
||||
*/
|
||||
async findActiveForContract(
|
||||
tradeDirection?: string | null,
|
||||
freightType?: string | null,
|
||||
): Promise<ContractTemplate | null> {
|
||||
const code = contractTemplateCodeFor(tradeDirection, freightType);
|
||||
const template = await this.repository.findByCode(code);
|
||||
return template?.isActive ? template : null;
|
||||
}
|
||||
|
||||
async update(code: string, dto: UpdateContractTemplateDto): Promise<ContractTemplate> {
|
||||
const template = await this.getByCode(code);
|
||||
if (dto.name !== undefined) template.name = dto.name;
|
||||
if (dto.description !== undefined) template.description = dto.description;
|
||||
if (dto.documentTitle !== undefined) template.documentTitle = dto.documentTitle;
|
||||
if (dto.whereasClauses !== undefined) template.whereasClauses = dto.whereasClauses;
|
||||
if (dto.isActive !== undefined) template.isActive = dto.isActive;
|
||||
return this.repository.saveTemplate(template);
|
||||
}
|
||||
|
||||
async addArticle(code: string, dto: CreateArticleDto): Promise<ContractTemplate> {
|
||||
const template = await this.getByCode(code);
|
||||
const articles = this.sorted(template.articles);
|
||||
const article: ContractTemplateArticle = {
|
||||
id: randomUUID(),
|
||||
title: dto.title,
|
||||
body: dto.body,
|
||||
order: 0,
|
||||
};
|
||||
const index =
|
||||
dto.position && dto.position <= articles.length ? dto.position - 1 : articles.length;
|
||||
articles.splice(index, 0, article);
|
||||
template.articles = this.renumber(articles);
|
||||
return this.repository.saveTemplate(template);
|
||||
}
|
||||
|
||||
async updateArticle(
|
||||
code: string,
|
||||
articleId: string,
|
||||
dto: UpdateArticleDto,
|
||||
): Promise<ContractTemplate> {
|
||||
const template = await this.getByCode(code);
|
||||
const article = template.articles.find((item) => item.id === articleId);
|
||||
if (!article) {
|
||||
throw new NotFoundException(`Article ${articleId} not found on template ${code}`);
|
||||
}
|
||||
if (dto.title !== undefined) article.title = dto.title;
|
||||
if (dto.body !== undefined) article.body = dto.body;
|
||||
template.articles = this.renumber(this.sorted(template.articles));
|
||||
return this.repository.saveTemplate(template);
|
||||
}
|
||||
|
||||
async removeArticle(code: string, articleId: string): Promise<ContractTemplate> {
|
||||
const template = await this.getByCode(code);
|
||||
const remaining = template.articles.filter((item) => item.id !== articleId);
|
||||
if (remaining.length === template.articles.length) {
|
||||
throw new NotFoundException(`Article ${articleId} not found on template ${code}`);
|
||||
}
|
||||
template.articles = this.renumber(this.sorted(remaining));
|
||||
return this.repository.saveTemplate(template);
|
||||
}
|
||||
|
||||
/** Replace the full ordered article list (also how the editor reorders). */
|
||||
async replaceArticles(
|
||||
code: string,
|
||||
articles: ReplaceArticleDto[],
|
||||
): Promise<ContractTemplate> {
|
||||
const template = await this.getByCode(code);
|
||||
template.articles = this.renumber(
|
||||
articles.map((item) => ({
|
||||
id: item.id ?? randomUUID(),
|
||||
title: item.title,
|
||||
body: item.body,
|
||||
order: 0,
|
||||
})),
|
||||
);
|
||||
return this.repository.saveTemplate(template);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the template against a representative mock contract so admins can
|
||||
* see the final document without touching a real contract. Draft overrides
|
||||
* allow previewing unsaved editor state.
|
||||
*/
|
||||
async preview(
|
||||
code: string,
|
||||
overrides?: PreviewContractTemplateDto,
|
||||
): Promise<{ html: string }> {
|
||||
const template = await this.getByCode(code);
|
||||
|
||||
const dynamicTemplate: ContractDynamicTemplateView = {
|
||||
code: template.code,
|
||||
name: overrides?.name ?? template.name,
|
||||
documentTitle: overrides?.documentTitle ?? template.documentTitle,
|
||||
whereasClauses: overrides?.whereasClauses ?? template.whereasClauses,
|
||||
articles: overrides?.articles
|
||||
? overrides.articles.map((item, index) => ({
|
||||
id: item.id ?? randomUUID(),
|
||||
title: item.title,
|
||||
body: item.body,
|
||||
order: index + 1,
|
||||
}))
|
||||
: this.sorted(template.articles),
|
||||
};
|
||||
|
||||
const view = this.buildMockView(template.code, dynamicTemplate);
|
||||
return { html: this.renderer.render(view) };
|
||||
}
|
||||
|
||||
private buildMockView(
|
||||
code: ContractTemplateCode,
|
||||
dynamicTemplate: ContractDynamicTemplateView,
|
||||
): ContractViewModel {
|
||||
const meta = getTemplateMeta(PREVIEW_TEMPLATE_KEYS[code]);
|
||||
const isBulk = code.endsWith("_BULK");
|
||||
const now = new Date();
|
||||
|
||||
const unitRates = isBulk
|
||||
? [
|
||||
{ label: "Rail transport — per metric ton", unitPrice: 59.4, unit: "ton", currency: "USD" },
|
||||
{ label: "Origin handling and documentation", unitPrice: 18, unit: "ton", currency: "USD" },
|
||||
{ label: "Lashing material (when provided by EDR)", unitPrice: 150, unit: "unit", currency: "USD" },
|
||||
]
|
||||
: [
|
||||
{ label: "Rail transport — 40ft container", unitPrice: 1916, unit: "container", currency: "USD" },
|
||||
{ label: "Rail transport — 2 × 20ft containers", unitPrice: 1944, unit: "container", currency: "USD" },
|
||||
{ label: "Excess tonnage surcharge", unitPrice: 10, unit: "ton", currency: "USD" },
|
||||
];
|
||||
|
||||
return {
|
||||
bookingId: "00000000-0000-0000-0000-000000000000",
|
||||
reference: "EDR/CT/2026/0042",
|
||||
status: "CONTRACT_READY",
|
||||
templateKey: PREVIEW_TEMPLATE_KEYS[code],
|
||||
template: { ...meta, title: dynamicTemplate.name, templateFile: "edr-dynamic.hbs" },
|
||||
contractDate: now.toLocaleDateString("en-GB", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
}),
|
||||
contractYear: now.getFullYear(),
|
||||
client: {
|
||||
companyName: "Abyssinia Trading PLC",
|
||||
companyAddress: "Bole Sub-city, Woreda 03, H.No 1234, Addis Ababa",
|
||||
companyLocation: "Ethiopia",
|
||||
phone: "+251 91 123 4567",
|
||||
email: "logistics@abyssiniatrading.et",
|
||||
tinNumber: "0011223344",
|
||||
vatNumber: "VAT-556677",
|
||||
fanNumber: "FAN-889900",
|
||||
businessLicense: "BL/AA/12/345678",
|
||||
},
|
||||
provider: {
|
||||
name: "Ethio-Djibouti Standard Gauge Railway Share Company",
|
||||
address: "Nifas Silk Lafto Sub City, Addis Ababa, Ethiopia",
|
||||
phone: "+251 11 872 0000",
|
||||
email: "info@edr.gov.et",
|
||||
tinNumber: "—",
|
||||
},
|
||||
schedule: {
|
||||
originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station",
|
||||
destinationLabel: "Galaan Multipurpose Port (GMP)",
|
||||
tradeDirection: code.startsWith("IMPORT")
|
||||
? "IMPORT"
|
||||
: code.startsWith("EXPORT")
|
||||
? "EXPORT"
|
||||
: "DOMESTIC",
|
||||
freightType: isBulk ? "BULK" : "CONTAINER",
|
||||
serviceType: "Rail transport and customs clearance",
|
||||
scheduledDate: "—",
|
||||
contractType: "GENERAL",
|
||||
cargoDescription: isBulk ? "Steel billets — 2,800 MT" : "40ft containers — FMCG cargo",
|
||||
totalWeightVgm: "—",
|
||||
equipmentReturn: isBulk ? "—" : "With empty return",
|
||||
hazardousLabel: "No",
|
||||
firstMilePickupAddress: "—",
|
||||
lastMileDeliveryAddress: "—",
|
||||
},
|
||||
pricing: {
|
||||
displayMode: "UNIT_RATES",
|
||||
unitRates,
|
||||
currency: "USD",
|
||||
equipmentReturn: isBulk ? "—" : "With empty return",
|
||||
originLabel: isBulk ? "Nagad Railway Station" : "SGTD Freight Station",
|
||||
destinationLabel: "Galaan Multipurpose Port (GMP)",
|
||||
} as unknown as ContractViewModel["pricing"],
|
||||
signatures: [],
|
||||
canSignCustomer: false,
|
||||
canSignStaff: false,
|
||||
hasContractDocument: false,
|
||||
hasCustomerSignature: false,
|
||||
hasStaffSignature: false,
|
||||
dynamicTemplate,
|
||||
};
|
||||
}
|
||||
|
||||
private assertCode(code: string): ContractTemplateCode {
|
||||
const upper = code?.toUpperCase() as ContractTemplateCode;
|
||||
if (!CONTRACT_TEMPLATE_CODES.includes(upper)) {
|
||||
throw new BadRequestException(
|
||||
`Unknown contract template code "${code}". Valid codes: ${CONTRACT_TEMPLATE_CODES.join(", ")}`,
|
||||
);
|
||||
}
|
||||
return upper;
|
||||
}
|
||||
|
||||
private sorted(articles: ContractTemplateArticle[]): ContractTemplateArticle[] {
|
||||
return [...(articles ?? [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
||||
}
|
||||
|
||||
private renumber(articles: ContractTemplateArticle[]): ContractTemplateArticle[] {
|
||||
return articles.map((article, index) => ({ ...article, order: index + 1 }));
|
||||
}
|
||||
}
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -22,12 +22,15 @@ export class BookingRequestRepository extends BaseRepository<BookingRequest> {
|
||||
});
|
||||
}
|
||||
|
||||
/** GL queue: pending requests across all contracts, oldest first. */
|
||||
async findPending(): Promise<BookingRequest[]> {
|
||||
/**
|
||||
* GL queue: every request across all contracts, newest first. The queue page
|
||||
* filters by status client-side (pending work vs accepted/rejected history),
|
||||
* and surfaces the customer — so the contract's company rides along.
|
||||
*/
|
||||
async findQueue(): Promise<BookingRequest[]> {
|
||||
return this.repository.find({
|
||||
where: { status: 'PENDING' },
|
||||
order: { createdAt: 'ASC' },
|
||||
relations: { contract: true },
|
||||
order: { createdAt: 'DESC' },
|
||||
relations: { contract: { company: true } },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,11 @@ export class BookingRequestService {
|
||||
const contract = await this.contractsService.findById(contractId);
|
||||
await this.contractsService.assertCustomerCanAccessContract(userId, contract);
|
||||
this.assertGeneralCustoms(contract);
|
||||
if (contract.status === 'CONTRACT_CLOSED') {
|
||||
throw new ConflictException(
|
||||
'This contract is completed — the full contracted quantity has been booked.',
|
||||
);
|
||||
}
|
||||
if (contract.status !== 'CONTRACT_ACTIVE') {
|
||||
throw new ConflictException(
|
||||
'The contract must be active before requesting a shipment.',
|
||||
@@ -108,6 +113,17 @@ export class BookingRequestService {
|
||||
},
|
||||
};
|
||||
|
||||
// Clearance-first flow: the request immediately initiates a BARE booking
|
||||
// instance (no cargo, no date, no price) that enters per-booking phased
|
||||
// customs clearance. GL no longer screens the request up front — it
|
||||
// reviews the documents in the clearance queue and completes the booking
|
||||
// (container numbers, VGM, shipment day) once clearance is ready. The
|
||||
// instance is created first so a failure leaves no half-linked request.
|
||||
const booking = await this.contractBookingService.initiateForShipmentRequest(
|
||||
contract,
|
||||
{ contractRouteId: dto.contractRouteId, userId },
|
||||
);
|
||||
|
||||
const reference = await this.generateReference();
|
||||
const request = await this.repo.create({
|
||||
reference,
|
||||
@@ -115,7 +131,8 @@ export class BookingRequestService {
|
||||
requestedByUserId: userId ?? null,
|
||||
contractRouteId: dto.contractRouteId ?? null,
|
||||
scheduledDate: dto.scheduledDate ? new Date(dto.scheduledDate) : null,
|
||||
status: 'PENDING',
|
||||
status: 'ACCEPTED',
|
||||
createdBookingId: booking.id,
|
||||
requestedLines,
|
||||
notes: dto.notes ?? null,
|
||||
} as never);
|
||||
@@ -134,7 +151,7 @@ export class BookingRequestService {
|
||||
}
|
||||
|
||||
queue(): Promise<BookingRequest[]> {
|
||||
return this.repo.findPending();
|
||||
return this.repo.findQueue();
|
||||
}
|
||||
|
||||
private async findPending(requestId: string): Promise<BookingRequest> {
|
||||
|
||||
@@ -58,6 +58,31 @@ export class ClearanceMilestoneService {
|
||||
await this.seed(postBooking, { bookingId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed whichever pre/post-booking milestones the booking is still missing,
|
||||
* keyed by milestoneCode. Plain seeding is a blind insert, so paths that can
|
||||
* run more than once (completing an initiated instance whose pre-booking
|
||||
* milestones were seeded at initiation, or a consolidation pairing replay)
|
||||
* must go through this instead — a duplicate timeline breaks the phase
|
||||
* derivation.
|
||||
*/
|
||||
async ensureBookingMilestones(
|
||||
bookingId: string,
|
||||
tradeDirection: string,
|
||||
): Promise<void> {
|
||||
const existing = await this.repo.find({ where: { bookingId } });
|
||||
const have = new Set(existing.map((m) => m.milestoneCode));
|
||||
const { preBooking, postBooking } = splitMilestones(tradeDirection);
|
||||
await this.seed(
|
||||
preBooking.filter((d) => !have.has(d.code)),
|
||||
{ bookingId },
|
||||
);
|
||||
await this.seed(
|
||||
postBooking.filter((d) => !have.has(d.code)),
|
||||
{ bookingId },
|
||||
);
|
||||
}
|
||||
|
||||
private async seed(
|
||||
defs: MilestoneDef[],
|
||||
scope: { contractId?: string; clearanceCycleId?: string; bookingId?: string },
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
import { ContractBookingService } from './contract-booking.service';
|
||||
import { Contract } from './entities/contract.entity';
|
||||
|
||||
/**
|
||||
* Contract auto-completion by quantity cap. Once a GENERAL contract's capped
|
||||
* scope is fully consumed (e.g. a split remainder rebooked), the contract moves
|
||||
* to CONTRACT_CLOSED even inside its validity window, and further bookings are
|
||||
* blocked — including while a booking window is open. Released capacity
|
||||
* (cancelled/expired booking) reopens the contract on the next attempt.
|
||||
*/
|
||||
describe('ContractBookingService — quantity-cap completion', () => {
|
||||
function makeService() {
|
||||
const contractsRepository = {
|
||||
findByIdWithRelations: jest.fn(),
|
||||
update: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = new ContractBookingService(
|
||||
contractsRepository as never,
|
||||
{} as never, // bookingsRepository
|
||||
{} as never, // bookingPricingService
|
||||
{} as never, // consolidationService
|
||||
{} as never, // containerTypesService
|
||||
{} as never, // ruleEngineService
|
||||
{} as never, // milestoneService
|
||||
{} as never, // workflowService
|
||||
{} as never, // invoiceService
|
||||
{} as never, // dataSource
|
||||
{} as never, // trainSchedulingService
|
||||
{} as never, // bookingTransitionService
|
||||
);
|
||||
return { service, contractsRepository };
|
||||
}
|
||||
|
||||
type WithPrivate = {
|
||||
maybeCompleteContract: (c: Contract) => Promise<void>;
|
||||
};
|
||||
|
||||
const generalContract = (status: string): Contract =>
|
||||
({
|
||||
id: 'c-1',
|
||||
reference: 'CTR-1',
|
||||
contractKind: 'GENERAL',
|
||||
status,
|
||||
}) as Contract;
|
||||
|
||||
it('closes a GENERAL contract when every capped line is exhausted', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
jest.spyOn(service, 'computeCapacity').mockResolvedValue([
|
||||
{ containerSize: '20FT', cap: 10, booked: 10, remaining: 0 },
|
||||
{ containerSize: '40FT', cap: 4, booked: 4, remaining: 0 },
|
||||
]);
|
||||
|
||||
await (service as never as WithPrivate).maybeCompleteContract(
|
||||
generalContract('CONTRACT_ACTIVE'),
|
||||
);
|
||||
|
||||
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
|
||||
status: 'CONTRACT_CLOSED',
|
||||
});
|
||||
});
|
||||
|
||||
it('absorbs bulk-ton float dust when judging exhaustion', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
jest
|
||||
.spyOn(service, 'computeCapacity')
|
||||
.mockResolvedValue([{ cap: 100, booked: 99.9995, remaining: 0.0005 }]);
|
||||
|
||||
await (service as never as WithPrivate).maybeCompleteContract(
|
||||
generalContract('FULLY_EXECUTED'),
|
||||
);
|
||||
|
||||
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
|
||||
status: 'CONTRACT_CLOSED',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the contract open while any capped line has capacity left', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
jest.spyOn(service, 'computeCapacity').mockResolvedValue([
|
||||
{ containerSize: '20FT', cap: 10, booked: 10, remaining: 0 },
|
||||
{ containerSize: '40FT', cap: 4, booked: 3, remaining: 1 },
|
||||
]);
|
||||
|
||||
await (service as never as WithPrivate).maybeCompleteContract(
|
||||
generalContract('CONTRACT_ACTIVE'),
|
||||
);
|
||||
|
||||
expect(contractsRepository.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never closes an uncapped contract', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
jest.spyOn(service, 'computeCapacity').mockResolvedValue([]);
|
||||
|
||||
await (service as never as WithPrivate).maybeCompleteContract(
|
||||
generalContract('CONTRACT_ACTIVE'),
|
||||
);
|
||||
|
||||
expect(contractsRepository.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never closes a ONE_TIME contract (single-slot rule governs it)', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
const spy = jest.spyOn(service, 'computeCapacity');
|
||||
|
||||
await (service as never as WithPrivate).maybeCompleteContract({
|
||||
id: 'c-1',
|
||||
contractKind: 'ONE_TIME',
|
||||
status: 'FULLY_EXECUTED',
|
||||
} as Contract);
|
||||
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
expect(contractsRepository.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a new booking on a completed contract even inside an open window', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
contractsRepository.findByIdWithRelations.mockResolvedValue(
|
||||
generalContract('CONTRACT_CLOSED'),
|
||||
);
|
||||
jest
|
||||
.spyOn(service, 'computeCapacity')
|
||||
.mockResolvedValue([{ cap: 10, booked: 10, remaining: 0 }]);
|
||||
|
||||
await expect(
|
||||
service.createUnderContract('c-1', {} as never, null, null),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
expect(contractsRepository.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reopens a completed contract when capacity was released', async () => {
|
||||
const { service, contractsRepository } = makeService();
|
||||
contractsRepository.findByIdWithRelations.mockResolvedValue(
|
||||
generalContract('CONTRACT_CLOSED'),
|
||||
);
|
||||
jest
|
||||
.spyOn(service, 'computeCapacity')
|
||||
.mockResolvedValue([{ cap: 10, booked: 8, remaining: 2 }]);
|
||||
|
||||
// The create path continues past the gate and dies later on the bare mocks —
|
||||
// only the reopen transition is under test here.
|
||||
await service.createUnderContract('c-1', {} as never, null, null).catch(() => undefined);
|
||||
|
||||
expect(contractsRepository.update).toHaveBeenCalledWith('c-1', {
|
||||
status: 'CONTRACT_ACTIVE',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,7 @@ describe('ContractBookingService — drawdown consolidation gate', () => {
|
||||
const milestoneService = {
|
||||
seedPostBookingMilestones: jest.fn().mockResolvedValue(undefined),
|
||||
seedPreBookingMilestonesOnBooking: jest.fn().mockResolvedValue(undefined),
|
||||
ensureBookingMilestones: jest.fn().mockResolvedValue(undefined),
|
||||
...overrides.milestoneService,
|
||||
};
|
||||
const contractsRepository = {
|
||||
@@ -58,6 +59,7 @@ describe('ContractBookingService — drawdown consolidation gate', () => {
|
||||
invoiceService as never,
|
||||
{} as never, // dataSource
|
||||
{} as never, // trainSchedulingService
|
||||
{} as never, // bookingTransitionService
|
||||
);
|
||||
return {
|
||||
service,
|
||||
@@ -143,9 +145,13 @@ describe('ContractBookingService — drawdown consolidation gate', () => {
|
||||
await service.onConsolidationPaired({ bookingIds: ['b-1'] });
|
||||
|
||||
expect(invoiceService.ensureInvoiceForBooking).toHaveBeenCalledTimes(1);
|
||||
// GENERAL customs → per-booking pre + post milestones.
|
||||
expect(milestoneService.seedPreBookingMilestonesOnBooking).toHaveBeenCalled();
|
||||
expect(milestoneService.seedPostBookingMilestones).toHaveBeenCalled();
|
||||
// GENERAL customs → per-booking milestones, via the idempotent ensure so a
|
||||
// pairing replay (or an initiated instance's pre-seeded timeline) never
|
||||
// duplicates rows.
|
||||
expect(milestoneService.ensureBookingMilestones).toHaveBeenCalledWith(
|
||||
'b-1',
|
||||
'EXPORT',
|
||||
);
|
||||
});
|
||||
|
||||
it('onConsolidationPaired ignores a booking still PENDING_CONSOLIDATION', async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Inject,
|
||||
Injectable,
|
||||
@@ -16,6 +17,7 @@ import { BookingContainer } from '../bookings/entities/booking-container.entity'
|
||||
import { BookingContainerUnit } from '../bookings/entities/booking-container-unit.entity';
|
||||
import { BookingsRepository } from '../bookings/bookings.repository';
|
||||
import { BookingPricingService } from '../bookings/booking-pricing.service';
|
||||
import { BookingTransitionService } from '../bookings/booking-transition.service';
|
||||
import { ConsolidationService } from '../bookings/consolidation.service';
|
||||
import { PriceLineItemDto } from '../bookings/dto/generate-price-response.dto';
|
||||
import { BookingInvoiceService } from '../bookings/booking-invoice.service';
|
||||
@@ -72,6 +74,8 @@ export class ContractBookingService {
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject(forwardRef(() => TrainSchedulingService))
|
||||
private readonly trainSchedulingService: TrainSchedulingService,
|
||||
@Inject(forwardRef(() => BookingTransitionService))
|
||||
private readonly bookingTransitionService: BookingTransitionService,
|
||||
) {}
|
||||
|
||||
async createUnderContract(
|
||||
@@ -83,6 +87,24 @@ export class ContractBookingService {
|
||||
const contract = await this.contractsRepository.findByIdWithRelations(contractId);
|
||||
if (!contract) throw new NotFoundException(`Contract ${contractId} not found`);
|
||||
|
||||
// A contract whose quantity cap was fully booked is completed — no further
|
||||
// bookings, even while contract validity and a booking window are still
|
||||
// open. Capacity released after closure (a cancelled/expired booking)
|
||||
// reopens the contract on the next booking attempt.
|
||||
if (contract.status === 'CONTRACT_CLOSED') {
|
||||
const capacity = await this.computeCapacity(contract);
|
||||
const hasRoom = capacity.some((c) => c.remaining == null || c.remaining > 0);
|
||||
if (!hasRoom) {
|
||||
throw new BadRequestException(
|
||||
'This contract is completed — the full contracted quantity has been booked.',
|
||||
);
|
||||
}
|
||||
await this.contractsRepository.update(contract.id, {
|
||||
status: 'CONTRACT_ACTIVE',
|
||||
} as never);
|
||||
contract.status = 'CONTRACT_ACTIVE';
|
||||
}
|
||||
|
||||
// GL Ethiopia is identified by the dedicated contract create-booking permission
|
||||
// (granted to the edr_gl_ethiopia preset).
|
||||
const isGlActor =
|
||||
@@ -171,6 +193,11 @@ export class ContractBookingService {
|
||||
// their only chance to hard-block an unbalanceable set. Entry order is
|
||||
// irrelevant (the check sorts by weight before pairing).
|
||||
await this.assert20ftPairableAtCreate(dto);
|
||||
// A container number may appear once per train (same day + route).
|
||||
await this.assertContainerNumbersAvailable(dto, {
|
||||
originYardId: route?.originYardId ?? null,
|
||||
destinationYardId: route?.destinationYardId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// Denormalize route/direction/freight onto the booking for the scheduling engine.
|
||||
@@ -200,7 +227,7 @@ export class ContractBookingService {
|
||||
contractType: 'NEW',
|
||||
customsClearingEnabled: contract.customsClearingEnabled,
|
||||
customsClearingAgent: contract.customsClearingAgent ?? null,
|
||||
equipmentReturn: contract.equipmentReturn ?? 'WITHOUT_RETURN',
|
||||
equipmentReturn: dto.equipmentReturn ?? contract.equipmentReturn ?? 'WITHOUT_RETURN',
|
||||
originYardId: route?.originYardId ?? null,
|
||||
destinationYardId: route?.destinationYardId ?? null,
|
||||
tradeDirection: contract.tradeDirection,
|
||||
@@ -291,6 +318,9 @@ export class ContractBookingService {
|
||||
if (!parked.paired) {
|
||||
// Waiting for a partner — stop here. The booking sits in
|
||||
// PENDING_CONSOLIDATION, unbilled and unscheduled, until it pairs.
|
||||
// A parked booking still holds contract capacity, so the cap may
|
||||
// already be exhausted by it.
|
||||
await this.maybeCompleteContract(contract);
|
||||
const pendingResult = await this.bookingsRepository.findByIdWithFiles(
|
||||
booking.id,
|
||||
);
|
||||
@@ -304,10 +334,355 @@ export class ContractBookingService {
|
||||
generalCustoms,
|
||||
);
|
||||
|
||||
await this.maybeCompleteContract(contract);
|
||||
|
||||
const result = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
return { booking: result ?? booking, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate a BARE booking instance under a GENERAL non-customs contract
|
||||
* (Path A per-booking self-clearance). One click, zero input: no schedule
|
||||
* date, no cargo, no window check, no pricing. The instance starts in the
|
||||
* clearance gate (AWAITING_DOCUMENTS); the customer uploads clearance docs,
|
||||
* Operations reviews and finalizes, and only then does the customer complete
|
||||
* the booking (cargo + binding day + window check) via
|
||||
* {@link completeUnderContract} — the same machinery a one-time shipment uses.
|
||||
*/
|
||||
async initiateUnderContract(
|
||||
contractId: string,
|
||||
dto: Pick<CreateBookingUnderContractDto, 'contractRouteId'>,
|
||||
user?: { id?: string } | null,
|
||||
actorPermissions?: unknown,
|
||||
): Promise<CreateBookingUnderContractResult> {
|
||||
const contract = await this.contractsRepository.findByIdWithRelations(contractId);
|
||||
if (!contract) throw new NotFoundException(`Contract ${contractId} not found`);
|
||||
|
||||
const generalSelfClear =
|
||||
contract.contractKind === 'GENERAL' &&
|
||||
!contract.customsClearingEnabled &&
|
||||
contract.tradeDirection !== 'DOMESTIC';
|
||||
if (!generalSelfClear) {
|
||||
throw new BadRequestException(
|
||||
'Initiate booking applies only to general import/export contracts without customs clearing.',
|
||||
);
|
||||
}
|
||||
|
||||
if (contract.status === 'CONTRACT_CLOSED') {
|
||||
throw new BadRequestException(
|
||||
'This contract is completed — the full contracted quantity has been booked.',
|
||||
);
|
||||
}
|
||||
|
||||
const isGlActor =
|
||||
actorPermissions != null &&
|
||||
hasFreightPermission(actorPermissions, FREIGHT_PERMS.contracts.createBooking);
|
||||
const createdByRole = await this.assertGate(contract, isGlActor);
|
||||
|
||||
if (contract.contractValidUntil && contract.contractValidUntil.getTime() < Date.now()) {
|
||||
throw new BadRequestException('Contract validity has expired — no new bookings.');
|
||||
}
|
||||
|
||||
const route = await this.resolveRoute(contract, dto.contractRouteId);
|
||||
|
||||
// Bare instance: no cargo, no date, no price. Draws no contract capacity
|
||||
// until the customer completes it after clearance.
|
||||
const booking = await insertWithGeneratedReference(
|
||||
() => this.generateReference(),
|
||||
(reference) =>
|
||||
this.bookingsRepository.create({
|
||||
reference,
|
||||
companyId: contract.companyId ?? null,
|
||||
companyProfileId: contract.companyProfileId ?? null,
|
||||
isGovernment: contract.isGovernment,
|
||||
governmentInstitution: contract.governmentInstitution ?? null,
|
||||
status: 'AWAITING_DOCUMENTS',
|
||||
bookingType: 'ONE_TIME',
|
||||
contractId: contract.id,
|
||||
contractRouteId: route?.id ?? null,
|
||||
contractKind: contract.contractKind,
|
||||
createdByRole,
|
||||
createdByUserId: user?.id ?? null,
|
||||
scheduledDate: null,
|
||||
serviceTypeId: contract.serviceTypeId,
|
||||
paymentCurrency: contract.paymentCurrency,
|
||||
contractType: 'NEW',
|
||||
customsClearingEnabled: contract.customsClearingEnabled,
|
||||
customsClearingAgent: contract.customsClearingAgent ?? null,
|
||||
equipmentReturn: contract.equipmentReturn ?? 'WITHOUT_RETURN',
|
||||
originYardId: route?.originYardId ?? null,
|
||||
destinationYardId: route?.destinationYardId ?? null,
|
||||
tradeDirection: contract.tradeDirection,
|
||||
freightType: contract.freightType,
|
||||
cargoTypeId: this.resolveCargoTypeId(contract, {}),
|
||||
isHazardous: contract.isHazardous,
|
||||
isReefer: contract.isReefer,
|
||||
cargoTotalWeightVgm: 0,
|
||||
firstMilePickupAddress: contract.firstMilePickupAddress ?? null,
|
||||
firstMilePickupLat: contract.firstMilePickupLat ?? null,
|
||||
firstMilePickupLng: contract.firstMilePickupLng ?? null,
|
||||
lastMileDeliveryAddress: contract.lastMileDeliveryAddress ?? null,
|
||||
lastMileDeliveryLat: contract.lastMileDeliveryLat ?? null,
|
||||
lastMileDeliveryLng: contract.lastMileDeliveryLng ?? null,
|
||||
} as never),
|
||||
);
|
||||
|
||||
const result = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
return { booking: result ?? booking, warnings: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate a BARE booking instance for a GENERAL + customs shipment request
|
||||
* (Path B, clearance-first). Called by BookingRequestService.submit AFTER it
|
||||
* validated the contract (general customs, active, capacity) — the request
|
||||
* itself carries the quantities; the instance carries none. Pre-booking
|
||||
* customs milestones are seeded immediately so the instance enters the same
|
||||
* phased ET/DJ clearance a ONE_TIME customs contract runs, just per booking.
|
||||
* GL completes the booking (cargo + day) via {@link completeUnderContract}
|
||||
* once the clearance reaches CLEARANCE_READY.
|
||||
*/
|
||||
async initiateForShipmentRequest(
|
||||
contract: Contract,
|
||||
opts: { contractRouteId?: string; userId?: string | null },
|
||||
): Promise<Booking> {
|
||||
const generalCustoms =
|
||||
contract.contractKind === 'GENERAL' && Boolean(contract.customsClearingEnabled);
|
||||
if (!generalCustoms) {
|
||||
throw new BadRequestException(
|
||||
'Shipment-request initiation applies only to general customs contracts.',
|
||||
);
|
||||
}
|
||||
if (contract.contractValidUntil && contract.contractValidUntil.getTime() < Date.now()) {
|
||||
throw new BadRequestException('Contract validity has expired — no new bookings.');
|
||||
}
|
||||
|
||||
const route = await this.resolveRoute(contract, opts.contractRouteId);
|
||||
|
||||
const booking = await insertWithGeneratedReference(
|
||||
() => this.generateReference(),
|
||||
(reference) =>
|
||||
this.bookingsRepository.create({
|
||||
reference,
|
||||
companyId: contract.companyId ?? null,
|
||||
companyProfileId: contract.companyProfileId ?? null,
|
||||
isGovernment: contract.isGovernment,
|
||||
governmentInstitution: contract.governmentInstitution ?? null,
|
||||
status: 'AWAITING_DOCUMENTS',
|
||||
bookingType: 'ONE_TIME',
|
||||
contractId: contract.id,
|
||||
contractRouteId: route?.id ?? null,
|
||||
contractKind: contract.contractKind,
|
||||
createdByRole: 'CUSTOMER',
|
||||
createdByUserId: opts.userId ?? null,
|
||||
scheduledDate: null,
|
||||
serviceTypeId: contract.serviceTypeId,
|
||||
paymentCurrency: contract.paymentCurrency,
|
||||
contractType: 'NEW',
|
||||
customsClearingEnabled: contract.customsClearingEnabled,
|
||||
customsClearingAgent: contract.customsClearingAgent ?? null,
|
||||
equipmentReturn: contract.equipmentReturn ?? 'WITHOUT_RETURN',
|
||||
originYardId: route?.originYardId ?? null,
|
||||
destinationYardId: route?.destinationYardId ?? null,
|
||||
tradeDirection: contract.tradeDirection,
|
||||
freightType: contract.freightType,
|
||||
cargoTypeId: this.resolveCargoTypeId(contract, {}),
|
||||
isHazardous: contract.isHazardous,
|
||||
isReefer: contract.isReefer,
|
||||
cargoTotalWeightVgm: 0,
|
||||
firstMilePickupAddress: contract.firstMilePickupAddress ?? null,
|
||||
firstMilePickupLat: contract.firstMilePickupLat ?? null,
|
||||
firstMilePickupLng: contract.firstMilePickupLng ?? null,
|
||||
lastMileDeliveryAddress: contract.lastMileDeliveryAddress ?? null,
|
||||
lastMileDeliveryLat: contract.lastMileDeliveryLat ?? null,
|
||||
lastMileDeliveryLng: contract.lastMileDeliveryLng ?? null,
|
||||
} as never),
|
||||
);
|
||||
|
||||
// Pre-booking phase only — the post-booking milestones (loading, transit)
|
||||
// are seeded when GL completes the booking, mirroring the ONE_TIME flow
|
||||
// where GL's booking creation seeds them.
|
||||
await this.milestoneService.seedPreBookingMilestonesOnBooking(
|
||||
booking.id,
|
||||
contract.tradeDirection,
|
||||
);
|
||||
|
||||
return (await this.bookingsRepository.findByIdWithFiles(booking.id)) ?? booking;
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete a bare initiated booking after its per-booking clearance is
|
||||
* finalized (CLEARANCE_READY) or operations returned it for changes
|
||||
* (OPERATION_CHANGES_REQUESTED). This is the deferred half of
|
||||
* {@link createUnderContract}: cargo lines, quantity-cap drawdown, booking
|
||||
* window + open-departure checks, pricing, consolidation and invoicing all run
|
||||
* here — the same gates a one-time shipment passes at creation.
|
||||
*
|
||||
* Actor rules mirror {@link assertGate}: a customs (Path B) instance is
|
||||
* completed by GL Ethiopia only; a non-customs (Path A) instance by the
|
||||
* customer (or staff).
|
||||
*/
|
||||
async completeUnderContract(
|
||||
contractId: string,
|
||||
bookingId: string,
|
||||
dto: CreateBookingUnderContractDto,
|
||||
actorPermissions?: unknown,
|
||||
): Promise<CreateBookingUnderContractResult> {
|
||||
const contract = await this.contractsRepository.findByIdWithRelations(contractId);
|
||||
if (!contract) throw new NotFoundException(`Contract ${contractId} not found`);
|
||||
|
||||
const booking = await this.bookingsRepository.findByIdWithFiles(bookingId);
|
||||
if (!booking || booking.contractId !== contract.id) {
|
||||
throw new NotFoundException(`Booking ${bookingId} not found on this contract`);
|
||||
}
|
||||
if (!['CLEARANCE_READY', 'OPERATION_CHANGES_REQUESTED'].includes(booking.status)) {
|
||||
throw new BadRequestException(
|
||||
'Clearance must be finalized before the booking can be completed.',
|
||||
);
|
||||
}
|
||||
// Path B: only GL Ethiopia completes a customs instance — the customer
|
||||
// never enters shipment data on a customs contract.
|
||||
if (contract.customsClearingEnabled) {
|
||||
const isGlActor =
|
||||
actorPermissions != null &&
|
||||
hasFreightPermission(actorPermissions, FREIGHT_PERMS.contracts.createBooking);
|
||||
if (!isGlActor) {
|
||||
throw new ForbiddenException(
|
||||
'Customs-clearance bookings are completed by Global Logistics on behalf of the customer.',
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!dto.scheduledDate) {
|
||||
throw new BadRequestException('A binding shipment day is required');
|
||||
}
|
||||
if (contract.contractValidUntil && contract.contractValidUntil.getTime() < Date.now()) {
|
||||
throw new BadRequestException('Contract validity has expired — no new bookings.');
|
||||
}
|
||||
|
||||
// Completion is booking time: the route's booking window must be open —
|
||||
// the same config-driven gate a direct one-time booking passes at create.
|
||||
await this.trainSchedulingService.assertBookingWindowOpen({
|
||||
originYardId: booking.originYardId ?? null,
|
||||
destinationYardId: booking.destinationYardId ?? null,
|
||||
scheduledDate: dto.scheduledDate,
|
||||
direction: contract.tradeDirection ?? null,
|
||||
});
|
||||
|
||||
const freightType = contract.freightType;
|
||||
const hasCargo =
|
||||
(booking.bookingContainers?.length ?? 0) > 0 ||
|
||||
Number(booking.cargoTotalWeightVgm) > 0;
|
||||
const warnings: string[] = [];
|
||||
|
||||
// First completion persists cargo and draws contract capacity; a resubmit
|
||||
// after OPERATION_CHANGES_REQUESTED already has its cargo and only re-picks
|
||||
// the shipment day.
|
||||
if (!hasCargo) {
|
||||
await this.assertWithinQuantityCap(contract, dto);
|
||||
if (freightType === 'CONTAINER') {
|
||||
await this.assertWithinMaxCapacity(contract, dto);
|
||||
await this.assert20ftPairableAtCreate(dto);
|
||||
// A container number may appear once per train (same day + route).
|
||||
await this.assertContainerNumbersAvailable(
|
||||
dto,
|
||||
{
|
||||
originYardId: booking.originYardId,
|
||||
destinationYardId: booking.destinationYardId,
|
||||
},
|
||||
booking.id,
|
||||
);
|
||||
await this.persistContainers(booking.id, contract, dto);
|
||||
}
|
||||
await this.bookingsRepository.update(booking.id, {
|
||||
cargoTypeId: this.resolveCargoTypeId(contract, dto),
|
||||
cargoTotalWeightVgm: this.resolveBulkTons(dto),
|
||||
...(dto.equipmentReturn ? { equipmentReturn: dto.equipmentReturn } : {}),
|
||||
} as never);
|
||||
|
||||
const loaded = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
if (loaded) {
|
||||
if (freightType === 'CONTAINER') {
|
||||
await this.applyWeightResults(loaded);
|
||||
}
|
||||
const computed = await this.bookingPricingService.computePriceForBooking(loaded);
|
||||
// A zero price means no contract rate matches — roll the cargo back so
|
||||
// the instance stays CLEARANCE_READY and can be completed again once
|
||||
// the contract rates are fixed (the clearance work is not lost).
|
||||
if (!(computed.totalAmount > 0)) {
|
||||
await this.bookingsRepository.deleteContainers(booking.id);
|
||||
await this.bookingsRepository.update(booking.id, {
|
||||
cargoTotalWeightVgm: 0,
|
||||
} as never);
|
||||
throw new BadRequestException(
|
||||
'Booking price came out as 0 — no contract rate matches this ' +
|
||||
'route/cargo. Set the contract rate and try again.',
|
||||
);
|
||||
}
|
||||
await this.bookingsRepository.update(booking.id, {
|
||||
totalAmount: computed.totalAmount,
|
||||
priorityScore: computed.priorityScore,
|
||||
pricingBreakdown: {
|
||||
lineItems: computed.lineItems,
|
||||
totalAmount: computed.totalAmount,
|
||||
currency: computed.currency,
|
||||
generatedAt: new Date().toISOString(),
|
||||
},
|
||||
} as never);
|
||||
await this.bookingPricingService.createPricingSnapshots(
|
||||
booking.id,
|
||||
computed.usedRates,
|
||||
computed.appliedModifiers,
|
||||
);
|
||||
warnings.push(...computed.warnings);
|
||||
}
|
||||
|
||||
// Wagon consolidation gate — a partial-wagon 20ft set parks for a partner
|
||||
// exactly like a drawdown created with cargo does. The shipment day is
|
||||
// stored first so the pairing event can resume straight into the
|
||||
// operations queue.
|
||||
const withContainers = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
if (
|
||||
withContainers &&
|
||||
freightType === 'CONTAINER' &&
|
||||
(await this.consolidationService.needsConsolidationFromBooking(withContainers))
|
||||
) {
|
||||
await this.bookingsRepository.update(booking.id, {
|
||||
scheduledDate: new Date(dto.scheduledDate),
|
||||
} as never);
|
||||
const parked = await this.consolidateDrawdown(
|
||||
withContainers,
|
||||
'OPERATION_REQUEST_PENDING',
|
||||
);
|
||||
warnings.push(parked.message);
|
||||
if (!parked.paired) {
|
||||
await this.maybeCompleteContract(contract);
|
||||
const pendingResult = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
return { booking: pendingResult ?? booking, warnings };
|
||||
}
|
||||
}
|
||||
|
||||
// Invoice the now-priced booking and, for a customs instance, seed the
|
||||
// post-booking milestones (pre-booking ones exist since initiation —
|
||||
// ensure* fills only what is missing). Idempotent, non-blocking.
|
||||
const generalCustoms =
|
||||
contract.contractKind === 'GENERAL' &&
|
||||
Boolean(contract.customsClearingEnabled);
|
||||
await this.finalizeContractBooking(booking.id, contract, generalCustoms);
|
||||
await this.maybeCompleteContract(contract);
|
||||
} else if (freightType === 'CONTAINER') {
|
||||
// Resubmit only re-picks the shipment day — the persisted container
|
||||
// numbers must be free on the newly chosen train day too.
|
||||
await this.assertPersistedContainersAvailable(booking, dto.scheduledDate);
|
||||
}
|
||||
|
||||
// Binding day + open-departure validation, status OPERATION_REQUEST_PENDING
|
||||
// and the staff notification — the exact machine a one-time booking uses.
|
||||
const completed = await this.bookingTransitionService.requestOperation(
|
||||
booking.id,
|
||||
dto.scheduledDate,
|
||||
);
|
||||
return { booking: completed, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a complementary partner for a parked-eligible drawdown, pair it or
|
||||
* park it in PENDING_CONSOLIDATION with the resume status it should return to.
|
||||
@@ -380,12 +755,11 @@ export class ContractBookingService {
|
||||
clearanceStatus: 'ACTIVE_SHIPMENT_IN_PROGRESS',
|
||||
} as never);
|
||||
} else if (generalCustoms) {
|
||||
// Per-booking clearance: seed full milestone timeline on the booking.
|
||||
await this.milestoneService.seedPreBookingMilestonesOnBooking(
|
||||
bookingId,
|
||||
contract.tradeDirection,
|
||||
);
|
||||
await this.milestoneService.seedPostBookingMilestones(
|
||||
// Per-booking clearance: seed the full milestone timeline on the booking.
|
||||
// ensure* skips codes that already exist — an initiated instance carries
|
||||
// its pre-booking milestones from initiation, and a consolidation pairing
|
||||
// replay must not duplicate the timeline.
|
||||
await this.milestoneService.ensureBookingMilestones(
|
||||
bookingId,
|
||||
contract.tradeDirection,
|
||||
);
|
||||
@@ -606,6 +980,44 @@ export class ContractBookingService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the contract once its quantity cap is fully consumed. Runs after
|
||||
* every booking created under a GENERAL contract (including a split remainder
|
||||
* being rebooked): when no capped scope line has capacity left, the contract
|
||||
* moves to CONTRACT_CLOSED even though its validity window is still open —
|
||||
* blocking further bookings and shipment requests, including inside an open
|
||||
* booking window. Never throws: a status hiccup must not undo the booking
|
||||
* that was just created.
|
||||
*/
|
||||
private async maybeCompleteContract(contract: Contract): Promise<void> {
|
||||
try {
|
||||
// ONE_TIME contracts are governed by the single-active-booking slot (and
|
||||
// are promoted to GENERAL on split), so only GENERAL completes by cap.
|
||||
if (contract.contractKind !== 'GENERAL') return;
|
||||
if (!['CONTRACT_ACTIVE', 'FULLY_EXECUTED'].includes(contract.status)) return;
|
||||
const capacity = await this.computeCapacity(contract);
|
||||
if (capacity.length === 0) return; // uncapped — completes only by expiry
|
||||
// 0.001 tolerance absorbs bulk-ton float rounding (split weights round to
|
||||
// 3 decimals); container caps are integers and unaffected.
|
||||
const exhausted = capacity.every(
|
||||
(c) => c.remaining != null && c.remaining <= 0.001,
|
||||
);
|
||||
if (!exhausted) return;
|
||||
await this.contractsRepository.update(contract.id, {
|
||||
status: 'CONTRACT_CLOSED',
|
||||
} as never);
|
||||
this.logger.log(
|
||||
`Contract ${contract.reference} quantity cap fully booked — completed; no further bookings within validity.`,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Could not evaluate completion for contract ${contract.id}: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quantities already booked under a contract that still hold capacity. Excludes
|
||||
* bookings that never shipped (CANCELLED / REJECTED / EXPIRED).
|
||||
@@ -951,6 +1363,131 @@ export class ContractBookingService {
|
||||
* balanced onto wagons (pair diff over the global cap). Same rule the
|
||||
* shipment-form preview reports as `pairingErrors`, enforced server-side.
|
||||
*/
|
||||
/**
|
||||
* A physical container rides one train only. Reject the submission when a
|
||||
* container number is entered twice in the same booking (the portal checks
|
||||
* this client-side, the API must not trust it) or already sits on another
|
||||
* customer's active booking for the same train — same shipment day AND same
|
||||
* route (origin/destination yards).
|
||||
*/
|
||||
private async assertContainerNumbersAvailable(
|
||||
dto: CreateBookingUnderContractDto,
|
||||
route: { originYardId?: string | null; destinationYardId?: string | null },
|
||||
excludeBookingId?: string,
|
||||
): Promise<void> {
|
||||
const numbers = (dto.containers ?? []).flatMap((line) =>
|
||||
(line.units ?? [])
|
||||
.map((u) => (u.containerNumber ?? '').trim().toUpperCase())
|
||||
.filter((n) => n.length > 0),
|
||||
);
|
||||
if (!numbers.length) return;
|
||||
|
||||
const seen = new Set<string>();
|
||||
const withinBooking = new Set<string>();
|
||||
for (const n of numbers) {
|
||||
if (seen.has(n)) withinBooking.add(n);
|
||||
seen.add(n);
|
||||
}
|
||||
if (withinBooking.size) {
|
||||
throw new BadRequestException(
|
||||
`Duplicate container number(s) in this booking: ${[...withinBooking].join(', ')} — each container can only be entered once.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Intercity bookings have no shipment day yet — nothing to clash with.
|
||||
if (!dto.scheduledDate) return;
|
||||
|
||||
await this.assertNumbersFreeOnTrain(
|
||||
numbers,
|
||||
dto.scheduledDate,
|
||||
route,
|
||||
excludeBookingId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Same train guard for a booking whose containers are already persisted
|
||||
* (resubmit after OPERATION_CHANGES_REQUESTED only re-picks the day): its
|
||||
* stored numbers must be free on the newly chosen day for its route.
|
||||
*/
|
||||
private async assertPersistedContainersAvailable(
|
||||
booking: Booking,
|
||||
scheduledDate: string,
|
||||
): Promise<void> {
|
||||
const rows: Array<{ containerNumber: string }> = await this.dataSource
|
||||
.getRepository(BookingContainerUnit)
|
||||
.createQueryBuilder('unit')
|
||||
.innerJoin(BookingContainer, 'line', 'line.id = unit.booking_container_id')
|
||||
.select('unit.container_number', 'containerNumber')
|
||||
.where('line.booking_id = :bookingId', { bookingId: booking.id })
|
||||
.getRawMany();
|
||||
const numbers = rows.map((r) => r.containerNumber).filter(Boolean);
|
||||
if (!numbers.length) return;
|
||||
await this.assertNumbersFreeOnTrain(
|
||||
numbers,
|
||||
scheduledDate,
|
||||
{
|
||||
originYardId: booking.originYardId,
|
||||
destinationYardId: booking.destinationYardId,
|
||||
},
|
||||
booking.id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject when any of `numbers` sits on another active booking of the same
|
||||
* train — same day and same route. Bookings without route yards (legacy
|
||||
* rows) are matched on the day alone rather than let through.
|
||||
*/
|
||||
private async assertNumbersFreeOnTrain(
|
||||
numbers: string[],
|
||||
scheduledDate: string,
|
||||
route: { originYardId?: string | null; destinationYardId?: string | null },
|
||||
excludeBookingId?: string,
|
||||
): Promise<void> {
|
||||
const qb = this.dataSource
|
||||
.getRepository(BookingContainerUnit)
|
||||
.createQueryBuilder('unit')
|
||||
.innerJoin(BookingContainer, 'line', 'line.id = unit.booking_container_id')
|
||||
.innerJoin(Booking, 'b', 'b.id = line.booking_id')
|
||||
.select('unit.container_number', 'containerNumber')
|
||||
.addSelect('b.reference', 'reference')
|
||||
.where('unit.container_number IN (:...numbers)', { numbers })
|
||||
.andWhere('b.scheduled_date::date = :day::date', { day: scheduledDate })
|
||||
.andWhere('b.status NOT IN (:...terminal)', {
|
||||
terminal: TERMINAL_BOOKING_STATUSES,
|
||||
})
|
||||
.andWhere('b.deleted_at IS NULL');
|
||||
if (route.originYardId && route.destinationYardId) {
|
||||
// Same train = same day + same corridor. A clashing booking whose yards
|
||||
// were never denormalized still blocks (NULL yards match any route).
|
||||
qb.andWhere(
|
||||
'(b.origin_yard_id IS NULL OR b.origin_yard_id = :originYardId)',
|
||||
{ originYardId: route.originYardId },
|
||||
).andWhere(
|
||||
'(b.destination_yard_id IS NULL OR b.destination_yard_id = :destinationYardId)',
|
||||
{ destinationYardId: route.destinationYardId },
|
||||
);
|
||||
}
|
||||
if (excludeBookingId) {
|
||||
qb.andWhere('b.id != :excludeBookingId', { excludeBookingId });
|
||||
}
|
||||
const clashes: Array<{ containerNumber: string; reference: string }> =
|
||||
await qb.getRawMany();
|
||||
|
||||
if (clashes.length) {
|
||||
const detail = [
|
||||
...new Map(clashes.map((c) => [c.containerNumber, c])).values(),
|
||||
]
|
||||
.map((c) => `${c.containerNumber} (booking ${c.reference})`)
|
||||
.join(', ');
|
||||
throw new ConflictException(
|
||||
`Container(s) already booked on this route for ${scheduledDate}: ${detail}. ` +
|
||||
'A container can only be on one booking per train — remove it or pick another shipment day.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async assert20ftPairableAtCreate(
|
||||
dto: CreateBookingUnderContractDto,
|
||||
): Promise<void> {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ export class ContractsController {
|
||||
|
||||
@Get('booking-requests/queue')
|
||||
@BookingStaff(FREIGHT_PERMS.contracts.createBooking)
|
||||
@ApiOperation({ summary: 'GL queue: pending shipment requests across contracts' })
|
||||
@ApiOperation({ summary: 'GL queue: shipment requests across contracts (all statuses, newest first)' })
|
||||
bookingRequestQueue() {
|
||||
return this.bookingRequestService.queue();
|
||||
}
|
||||
@@ -799,6 +799,45 @@ export class ContractsController {
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':id/bookings/initiate')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Initiate a bare booking instance under a GENERAL non-customs contract — no cargo, no date; enters per-booking clearance (AWAITING_DOCUMENTS).',
|
||||
})
|
||||
initiateBooking(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() dto: CreateBookingUnderContractDto,
|
||||
@CurrentUser() user: AuthUserPayload,
|
||||
) {
|
||||
return this.contractBookingService.initiateUnderContract(
|
||||
id,
|
||||
{ contractRouteId: dto?.contractRouteId },
|
||||
{ id: user?.id ?? user?.sub },
|
||||
user,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':id/bookings/:bookingId/complete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Complete an initiated booking after Operations finalized its clearance — cargo + binding day, window and departure checks, pricing and invoicing.',
|
||||
})
|
||||
completeBooking(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Param('bookingId', ParseUUIDPipe) bookingId: string,
|
||||
@Body() dto: CreateBookingUnderContractDto,
|
||||
@CurrentUser() user: AuthUserPayload,
|
||||
) {
|
||||
// Customs (Path B) instances may only be completed by GL Ethiopia — the
|
||||
// service checks the actor's contracts:create_booking permission.
|
||||
return this.contractBookingService.completeUnderContract(
|
||||
id,
|
||||
bookingId,
|
||||
dto,
|
||||
user,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':id/validate-shipment')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -265,10 +265,11 @@ export class ContractsService {
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the company profile's onboarding / business-license documents to the
|
||||
// contract by reference. The separate "Documents" intake step was removed —
|
||||
// the profile documents are simply carried onto every contract automatically.
|
||||
await this.attachProfileDocuments(contract.id, companyProfileId);
|
||||
// Attach the company's onboarding documents (TIN, licenses, IDs) and the
|
||||
// profile's business-license documents to the contract by reference. The
|
||||
// separate "Documents" intake step was removed — the profile documents are
|
||||
// simply carried onto every contract automatically.
|
||||
await this.attachProfileDocuments(contract.id, companyId ?? null, companyProfileId);
|
||||
|
||||
return { contract: await this.findById(contract.id), warnings };
|
||||
}
|
||||
@@ -316,51 +317,95 @@ export class ContractsService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a company profile's stored business-license / onboarding documents onto
|
||||
* a contract by reference (no byte re-upload). Codes are slugged from each
|
||||
* document name so they group under "Profile documents" on the contract detail
|
||||
* page. No-op when the contract has no profile or the profile has no documents.
|
||||
* Copy the company's onboarding documents (TIN certificate, commercial /
|
||||
* investment license, national ID, passport — resource "companies", coded by
|
||||
* the upload-setting fileKey) and the company profile's business-license
|
||||
* documents (resource "company_profiles") onto a contract by reference (no
|
||||
* byte re-upload). Idempotent: codes already present on the contract — user
|
||||
* uploads or an earlier carry — are never duplicated or overwritten, so it is
|
||||
* safe to run on every create and update. No-op when there is nothing to copy.
|
||||
*/
|
||||
private async attachProfileDocuments(
|
||||
contractId: string,
|
||||
companyId: string | null,
|
||||
companyProfileId: string | null,
|
||||
): Promise<void> {
|
||||
if (!companyProfileId) return;
|
||||
// Business-license files are FileRecords (resource "company_profiles"); carry
|
||||
// the live ones by reference. Staged/pending uploads are excluded by code.
|
||||
const records = await this.filesService.findByResource(
|
||||
companyProfileId,
|
||||
'company_profiles',
|
||||
if (!companyId && !companyProfileId) return;
|
||||
|
||||
const existingCodes = new Set(
|
||||
(await this.filesService.findByResource(contractId, 'contracts')).map(
|
||||
(r) => r.code,
|
||||
),
|
||||
);
|
||||
const docs = records
|
||||
.filter((r) => r.code === 'business_license')
|
||||
.map((r) => ({
|
||||
name: r.name,
|
||||
url: r.url,
|
||||
size: r.size,
|
||||
mimeType: r.mimeType,
|
||||
}));
|
||||
const docs: Array<{
|
||||
code: string;
|
||||
name: string;
|
||||
url: string;
|
||||
size: number;
|
||||
mimeType?: string;
|
||||
}> = [];
|
||||
|
||||
if (companyId) {
|
||||
// Company onboarding documents keep their fileKey codes (tin_certificate,
|
||||
// commercial_license, …) so the portal can match them against the
|
||||
// onboarding upload-setting fields. Re-uploads append rows, so keep only
|
||||
// the newest record per code.
|
||||
const companyRecords = await this.filesService.findByResource(
|
||||
companyId,
|
||||
'companies',
|
||||
);
|
||||
const latestByCode = new Map<string, (typeof companyRecords)[number]>();
|
||||
for (const r of companyRecords) {
|
||||
const prev = latestByCode.get(r.code);
|
||||
if (!prev || r.createdAt > prev.createdAt) latestByCode.set(r.code, r);
|
||||
}
|
||||
for (const r of latestByCode.values()) {
|
||||
if (existingCodes.has(r.code)) continue;
|
||||
docs.push({
|
||||
code: r.code,
|
||||
name: r.name,
|
||||
url: r.url,
|
||||
size: r.size,
|
||||
mimeType: r.mimeType,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (companyProfileId) {
|
||||
// Business-license files are FileRecords (resource "company_profiles");
|
||||
// carry the live ones by reference. Staged/pending uploads are excluded by
|
||||
// code. Codes are slugged from each document name so they group under
|
||||
// "Profile documents" on the contract detail page.
|
||||
const records = await this.filesService.findByResource(
|
||||
companyProfileId,
|
||||
'company_profiles',
|
||||
);
|
||||
const slug = (name: string) =>
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/\.[a-z0-9]+$/, '')
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '') || 'profile_document';
|
||||
|
||||
records
|
||||
.filter((r) => r.code === 'business_license')
|
||||
.forEach((r, i) => {
|
||||
const code = `${slug(r.name)}_${i + 1}`;
|
||||
if (existingCodes.has(code)) return;
|
||||
docs.push({
|
||||
code,
|
||||
name: r.name,
|
||||
url: r.url,
|
||||
size: r.size,
|
||||
mimeType: r.mimeType,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (docs.length === 0) return;
|
||||
|
||||
const slug = (name: string) =>
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/\.[a-z0-9]+$/, '')
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '') || 'profile_document';
|
||||
|
||||
try {
|
||||
await this.filesService.attachExistingFiles(
|
||||
contractId,
|
||||
'contracts',
|
||||
docs.map((d, i) => ({
|
||||
code: `${slug(d.name)}_${i + 1}`,
|
||||
name: d.name,
|
||||
url: d.url,
|
||||
size: d.size,
|
||||
mimeType: d.mimeType,
|
||||
})),
|
||||
);
|
||||
await this.filesService.attachExistingFiles(contractId, 'contracts', docs);
|
||||
} catch {
|
||||
// Non-fatal — the contract is still valid without the carried documents.
|
||||
}
|
||||
@@ -481,6 +526,15 @@ export class ContractsService {
|
||||
await this.filesService.uploadMany(id, 'contracts', files);
|
||||
}
|
||||
|
||||
// Re-carry any company/profile document that is still missing from the
|
||||
// contract (runs after the upload so fresh replacements keep their slot).
|
||||
// Backfills contracts created before profile documents were carried over.
|
||||
await this.attachProfileDocuments(
|
||||
id,
|
||||
existing.companyId ?? null,
|
||||
existing.companyProfileId ?? null,
|
||||
);
|
||||
|
||||
return { contract: await this.findById(id), warnings };
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
@@ -14,6 +15,9 @@ import {
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
|
||||
/** Per-shipment equipment return — "NA" stays contract-level only. */
|
||||
const SHIPMENT_EQUIPMENT_RETURNS = ['WITH_RETURN', 'WITHOUT_RETURN'] as const;
|
||||
|
||||
/** One physical container under a booking line — entered at booking time. */
|
||||
export class CreateContainerUnitDto {
|
||||
@ApiProperty({ description: 'ISO 6346 container number, e.g. ABCD1234567' })
|
||||
@@ -134,6 +138,15 @@ export class CreateBookingUnderContractDto {
|
||||
@IsDateString()
|
||||
scheduledDate?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: SHIPMENT_EQUIPMENT_RETURNS,
|
||||
description:
|
||||
'Per-shipment equipment return override; omitted → the contract default applies.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsIn([...SHIPMENT_EQUIPMENT_RETURNS])
|
||||
equipmentReturn?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [CreateBookingContainerLineDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
|
||||
@@ -6,12 +6,15 @@ import { GpsPosition } from './entities/gps-position.entity';
|
||||
import { GpsDeviceRepository, GpsPositionRepository } from './gps-tracking.repository';
|
||||
import { GpsTrackingService } from './gps-tracking.service';
|
||||
import { GpsTrackingController } from './gps-tracking.controller';
|
||||
import { Gt06Server } from './gt06/gt06.server';
|
||||
|
||||
// NOTE: the GT06 TCP listener now lives in the standalone @edr/gps-tracker app.
|
||||
// This module is REST-only — it reads gps_devices / gps_positions that the
|
||||
// tracker app writes to the shared DB. Do not re-add Gt06Server here, or two
|
||||
// processes would fight for the tracker socket.
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([GpsDevice, GpsPosition])],
|
||||
controllers: [GpsTrackingController],
|
||||
providers: [GpsDeviceRepository, GpsPositionRepository, GpsTrackingService, Gt06Server],
|
||||
providers: [GpsDeviceRepository, GpsPositionRepository, GpsTrackingService],
|
||||
exports: [GpsTrackingService],
|
||||
})
|
||||
export class GpsTrackingModule {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { Module, forwardRef } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { Session } from "@tria-plc/iamapi-common/entities/iam/user/session.entity";
|
||||
import { User } from "@tria-plc/iamapi-common/entities/iam/user/user.entity";
|
||||
@@ -17,8 +17,9 @@ import { WsAuthService } from "./ws-auth.service";
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Notification, User, Session]),
|
||||
// ExternalProfileRepository + CompanyProfileRepository (portal targeting)
|
||||
CompaniesModule,
|
||||
// ExternalProfileRepository + CompanyProfileRepository (portal targeting).
|
||||
// CompaniesModule imports this module back for CompanyNotifierService.
|
||||
forwardRef(() => CompaniesModule),
|
||||
// BackofficeService.getOrganizationEmployees (staff targeting)
|
||||
BackofficeModule,
|
||||
// EmailClientService + SmsClientService (HIGH-priority fan-out)
|
||||
|
||||
@@ -43,11 +43,26 @@ export class Route extends BaseEntity {
|
||||
* Human-readable route label: yard names, not yard codes — "Addis Ababa → Dire Dawa",
|
||||
* not "ADDIS_ABABA → DIRE_DAWA". A yard's display name is its `label`; `code` is the
|
||||
* machine identifier and is only a fallback for a yard missing one.
|
||||
*
|
||||
* When the route's milestones are loaded (with their yards), the label is the FULL
|
||||
* ordered corridor — "Addis Ababa → Adama → Dire Dawa" — since milestones already
|
||||
* include the origin (first) and destination (last). Without milestones it falls
|
||||
* back to origin → destination.
|
||||
*/
|
||||
export function formatRouteLabel(route: {
|
||||
originYard?: { code?: string; label?: string } | null;
|
||||
destinationYard?: { code?: string; label?: string } | null;
|
||||
milestones?: Array<{
|
||||
sequenceNo: number;
|
||||
yard?: { code?: string; label?: string } | null;
|
||||
}> | null;
|
||||
}): string {
|
||||
const stops = [...(route.milestones ?? [])]
|
||||
.sort((a, b) => a.sequenceNo - b.sequenceNo)
|
||||
.map((m) => m.yard?.label ?? m.yard?.code)
|
||||
.filter((name): name is string => Boolean(name));
|
||||
if (stops.length >= 2) return stops.join(' → ');
|
||||
|
||||
const origin = route.originYard?.label ?? route.originYard?.code ?? 'Origin';
|
||||
const dest = route.destinationYard?.label ?? route.destinationYard?.code ?? 'Destination';
|
||||
return `${origin} → ${dest}`;
|
||||
|
||||
@@ -23,8 +23,9 @@ export class TrainSchedulesRepository extends BaseRepository<TrainSchedule> {
|
||||
where: { id },
|
||||
relations: {
|
||||
// Yards carry the route's display name; without them formatRouteLabel
|
||||
// degrades to the literal "Origin → Destination".
|
||||
route: { originYard: true, destinationYard: true },
|
||||
// degrades to the literal "Origin → Destination". Milestones (with
|
||||
// their yards) give it the full corridor path.
|
||||
route: { originYard: true, destinationYard: true, milestones: { yard: true } },
|
||||
trainSet: {
|
||||
locomotive: true,
|
||||
locomotives: { locomotive: true },
|
||||
|
||||
@@ -136,6 +136,7 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
expirePayable: jest.fn().mockResolvedValue(undefined),
|
||||
} as never,
|
||||
{ emitPhase: jest.fn() } as never,
|
||||
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -563,6 +564,7 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
trainSchedulingService as never,
|
||||
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
|
||||
{ emitPhase: jest.fn() } as never,
|
||||
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
|
||||
undefined,
|
||||
{ findOpenOffer: jest.fn() } as never,
|
||||
);
|
||||
@@ -585,6 +587,7 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
trainSchedulingService as never,
|
||||
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
|
||||
{ emitPhase: jest.fn() } as never,
|
||||
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
|
||||
undefined,
|
||||
{ findOpenOffer: jest.fn() } as never,
|
||||
);
|
||||
@@ -615,6 +618,7 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
trainSchedulingService as never,
|
||||
{ syncPayableDueDate: jest.fn(), expirePayable: jest.fn() } as never,
|
||||
{ emitPhase: jest.fn() } as never,
|
||||
{ computeSubmitPriorityScore: jest.fn().mockResolvedValue(0) } as never,
|
||||
undefined,
|
||||
{ findOpenOffer: jest.fn() } as never,
|
||||
);
|
||||
@@ -696,6 +700,16 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
bookingsRepository.findBatchPoolByCorridorDay
|
||||
.mockResolvedValueOnce([waiting])
|
||||
.mockResolvedValue([]);
|
||||
// expire()'s paid-guard and reserve()'s idempotency guard both re-read the
|
||||
// booking fresh — answer with the matching row, not the paidBooking default
|
||||
// (which would make the guard rescue-allocate the lapsed reservation).
|
||||
const byId: Record<string, Booking> = { lapsed, waiting };
|
||||
dataSource
|
||||
.getRepository()
|
||||
.findOne.mockImplementation(
|
||||
async (opts: { where?: { id?: string } }) =>
|
||||
byId[opts?.where?.id ?? ''] ?? null,
|
||||
);
|
||||
|
||||
await service.settleDueReservations(trainId);
|
||||
|
||||
@@ -721,6 +735,14 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
return Promise.resolve(reads === 1 ? [lapsed] : []);
|
||||
});
|
||||
bookingsRepository.findBatchPoolByCorridorDay.mockResolvedValue([]);
|
||||
// expire()'s paid-guard re-reads the booking fresh — answer with the
|
||||
// (unpaid) lapsed row, not the paidBooking default.
|
||||
dataSource
|
||||
.getRepository()
|
||||
.findOne.mockImplementation(
|
||||
async (opts: { where?: { id?: string } }) =>
|
||||
opts?.where?.id === 'lapsed' ? lapsed : null,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
service.settleDueReservations(trainId),
|
||||
@@ -729,6 +751,37 @@ describe('BookingBatchService — PAID reconcile', () => {
|
||||
|
||||
expect(notifier.expired).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('never expires a reservation whose payment landed — allocates it instead', async () => {
|
||||
const latePaid = booking('late-paid', 50, {
|
||||
status: 'SELECTED_FOR_BATCH',
|
||||
paymentDeadline: new Date(Date.now() - 60_000),
|
||||
});
|
||||
bookingsRepository.findReservedForSchedule
|
||||
.mockResolvedValueOnce([latePaid])
|
||||
.mockResolvedValue([]);
|
||||
bookingsRepository.findBatchPoolByCorridorDay.mockResolvedValue([]);
|
||||
// The payment webhook flipped paymentStatus between the settle's list
|
||||
// read and expire()'s fresh re-read — the deadline had already passed.
|
||||
dataSource
|
||||
.getRepository()
|
||||
.findOne.mockImplementation(
|
||||
async (opts: { where?: { id?: string } }) =>
|
||||
opts?.where?.id === 'late-paid'
|
||||
? { ...latePaid, paymentStatus: 'PAID' }
|
||||
: null,
|
||||
);
|
||||
|
||||
await service.settleDueReservations(trainId);
|
||||
|
||||
// Money was taken → the booking boards. Never expired.
|
||||
expect(notifier.expired).not.toHaveBeenCalled();
|
||||
expect(notifier.secured).toHaveBeenCalledTimes(1);
|
||||
expect(trainScheduleBookingsRepository.createMany).toHaveBeenCalledWith(
|
||||
[{ trainScheduleId: trainId, bookingId: 'late-paid' }],
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -745,14 +798,21 @@ describe('BookingBatchService — wagonsFor', () => {
|
||||
null as never,
|
||||
null as never,
|
||||
null as never,
|
||||
null as never,
|
||||
) as unknown as {
|
||||
wagonsFor(booking: unknown, dims: unknown): number;
|
||||
needFor(booking: unknown, dims: unknown): {
|
||||
wagons: number;
|
||||
weightTons: number;
|
||||
lengthMeters: number;
|
||||
};
|
||||
};
|
||||
|
||||
// PW2 box wagon: 70T rated payload, 25.2T tare, 17.066m.
|
||||
const dims = {
|
||||
container: { lengthMeters: 13.966, tareWeightTons: 22.4, capacityTons: 70 },
|
||||
bulk: { lengthMeters: 17.066, tareWeightTons: 25.2, capacityTons: 70 },
|
||||
byWagonTypeId: new Map(),
|
||||
};
|
||||
|
||||
const bulk = (cargoTons: number, over: Record<string, unknown> = {}) => ({
|
||||
@@ -780,6 +840,13 @@ describe('BookingBatchService — wagonsFor', () => {
|
||||
expect(service.wagonsFor(bulk(2590, { wagonsRequired: 40 }), dims)).toBe(40);
|
||||
});
|
||||
|
||||
it('ignores a stale undersized wagonsRequired: 700T of sugar rides 10 wagons, not 1', () => {
|
||||
// Rows written while sumWagonsRequired hardcoded BULK to 1 are still in the
|
||||
// DB; trusting them charged one tare for the whole consist (700 + 25.2
|
||||
// instead of 700 + 10 × 25.2 gross).
|
||||
expect(service.wagonsFor(bulk(700, { wagonsRequired: 1 }), dims)).toBe(10);
|
||||
});
|
||||
|
||||
it('takes the binding axis for containers: weight can exceed TEU geometry', () => {
|
||||
// Two 40ft units => 2 wagons by TEU geometry, but 210T needs 3 at 70T each.
|
||||
const booking = {
|
||||
@@ -803,4 +870,49 @@ describe('BookingBatchService — wagonsFor', () => {
|
||||
};
|
||||
expect(service.wagonsFor(booking, dims)).toBe(2);
|
||||
});
|
||||
|
||||
describe('per-booking wagon type (cargo/container type FK)', () => {
|
||||
// The booking's cargo type rides PW2 (25.2T tare / 70T), but the
|
||||
// representative bulk fallback is a CW3-ish 23.4T tare. Measuring the
|
||||
// booking on the fallback under-charged its gross (2100 + 30 × 23.4 =
|
||||
// 2802 instead of 2856), so the fill loop admitted sets that allocation's
|
||||
// real-consist check later rejected — after the customer had paid.
|
||||
const dimsWithTypes = {
|
||||
container: { lengthMeters: 13.966, tareWeightTons: 22.4, capacityTons: 70 },
|
||||
bulk: { lengthMeters: 17.066, tareWeightTons: 23.4, capacityTons: 70 },
|
||||
byWagonTypeId: new Map([
|
||||
['pw2-id', { lengthMeters: 17.066, tareWeightTons: 25.2, capacityTons: 70 }],
|
||||
]),
|
||||
};
|
||||
|
||||
it('charges a bulk booking the tare of ITS wagon type, not the representative', () => {
|
||||
const booking = bulk(2100, { cargoType: { wagonTypeId: 'pw2-id' } });
|
||||
const need = service.needFor(booking, dimsWithTypes);
|
||||
expect(need.wagons).toBe(30);
|
||||
expect(need.weightTons).toBe(2856); // 2100 + 30 × 25.2 — matches allocation
|
||||
});
|
||||
|
||||
it('falls back to the representative dims when no wagon type is configured', () => {
|
||||
const need = service.needFor(bulk(2100), dimsWithTypes);
|
||||
expect(need.weightTons).toBe(2802); // 2100 + 30 × 23.4 (legacy behavior)
|
||||
});
|
||||
|
||||
it('resolves a container booking through its container type', () => {
|
||||
const booking = {
|
||||
freightType: 'CONTAINER',
|
||||
cargoTotalWeightVgm: 140,
|
||||
bookingContainers: [
|
||||
{
|
||||
quantity: 2,
|
||||
wagonsRequired: 2,
|
||||
containerType: { wagonsPerUnit: 1, sizeFt: 40, wagonTypeId: 'pw2-id' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const need = service.needFor(booking, dimsWithTypes);
|
||||
expect(need.wagons).toBe(2);
|
||||
expect(need.weightTons).toBe(190.4); // 140 + 2 × 25.2
|
||||
expect(need.lengthMeters).toBeCloseTo(34.132, 3); // 2 × 17.066, not NW5's 13.966
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ import { ClearanceMilestoneService } from '../contracts/clearance-milestone.serv
|
||||
import { Yard } from '../rule-engine/entities/yard.entity';
|
||||
import { TrainSetWagon } from '../train-sets/entities/train-set-wagon.entity';
|
||||
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
|
||||
import { TrainScheduleBooking } from '../train-schedules/entities/train-schedule-booking.entity';
|
||||
import { WagonBookingAllocation } from '../train-schedules/entities/wagon-booking-allocation.entity';
|
||||
import { Wagon } from '../wagons/entities/wagon.entity';
|
||||
import { WagonMovement } from '../wagons/entities/wagon-movement.entity';
|
||||
@@ -28,6 +29,9 @@ import { TrainCheckpointEvent } from './entities/train-checkpoint-event.entity';
|
||||
* unload at its destination yard (IN_TRANSIT → ARRIVED for import/export,
|
||||
* → COMPLETED for intercity), possibly long before the train's final arrival.
|
||||
* Both are gated on the train's latest recorded checkpoint being at that yard.
|
||||
* Unload also fires automatically: recording a checkpoint at a yard auto-
|
||||
* unloads every booking destined there (autoUnloadAtYard), so the manual
|
||||
* unload endpoint remains only a fallback.
|
||||
*
|
||||
* Unloading also settles the physical wagons: each wagon that alights with the
|
||||
* booking is released at that yard and the move is written to the
|
||||
@@ -136,7 +140,7 @@ export class BookingJourneyService {
|
||||
.leftJoinAndSelect('booking.originYard', 'originYard')
|
||||
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
|
||||
.innerJoin(
|
||||
'freight.train_schedule_bookings',
|
||||
TrainScheduleBooking,
|
||||
'tsb',
|
||||
'tsb.booking_id = booking.id AND tsb.train_schedule_id = :scheduleId AND tsb.deleted_at IS NULL',
|
||||
{ scheduleId },
|
||||
@@ -198,6 +202,49 @@ export class BookingJourneyService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-unload on checkpoint: every IN_TRANSIT booking on this schedule whose
|
||||
* destination is the yard the train just reached alights automatically, so
|
||||
* the customer's booking flips to ARRIVED (COMPLETED for intercity) the
|
||||
* moment the train is recorded at their yard — no separate operator unload.
|
||||
* Runs through the same per-booking unload path (wagon settle + ledger +
|
||||
* milestones); one booking's failure is logged and never blocks the
|
||||
* checkpoint or the other bookings. Returns the unloaded booking ids.
|
||||
*/
|
||||
async autoUnloadAtYard(
|
||||
scheduleId: string,
|
||||
yardId: string,
|
||||
userId?: string | null,
|
||||
): Promise<string[]> {
|
||||
const bookings = await this.dataSource
|
||||
.getRepository(Booking)
|
||||
.createQueryBuilder('booking')
|
||||
// Entity-class join: a raw 'freight.table' string is parsed by TypeORM as
|
||||
// an alias.property path ("freight" alias was not found) — runtime 500.
|
||||
.innerJoin(
|
||||
TrainScheduleBooking,
|
||||
'tsb',
|
||||
'tsb.booking_id = booking.id AND tsb.train_schedule_id = :scheduleId AND tsb.deleted_at IS NULL',
|
||||
{ scheduleId },
|
||||
)
|
||||
.where('booking.destination_yard_id = :yardId', { yardId })
|
||||
.andWhere(`booking.status = 'IN_TRANSIT'`)
|
||||
.getMany();
|
||||
|
||||
const unloaded: string[] = [];
|
||||
for (const booking of bookings) {
|
||||
try {
|
||||
await this.unloadBooking(scheduleId, booking.id, userId);
|
||||
unloaded.push(booking.id);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Auto-unload failed for booking ${booking.id} at yard ${yardId}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return unloaded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk fallback at the train's FINAL arrival: any booking destined for the
|
||||
* final yard that operators didn't unload individually gets its per-booking
|
||||
@@ -306,7 +353,7 @@ export class BookingJourneyService {
|
||||
.createQueryBuilder('alloc')
|
||||
.innerJoinAndSelect('alloc.trainSetWagon', 'slot')
|
||||
.innerJoin(
|
||||
'freight.train_schedules',
|
||||
TrainSchedule,
|
||||
'schedule',
|
||||
'schedule.train_set_id = slot.train_set_id AND schedule.id = :scheduleId',
|
||||
{ scheduleId },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
NotificationAudience,
|
||||
NotificationPriority,
|
||||
NotificationType,
|
||||
NotifyInput,
|
||||
} from '@edr/types';
|
||||
@@ -114,11 +115,15 @@ export class BookingNotifierService {
|
||||
const eat = deadline.toLocaleString('en-GB', { timeZone: 'Africa/Addis_Ababa' });
|
||||
const msg =
|
||||
`Only ${offeredWagons} of ${totalWagons} wagons fit the train for booking ${b.reference ?? b.id}. ` +
|
||||
`Pay within ${payMinutes} minute${payMinutes === 1 ? '' : 's'} to accept and ship ${offeredWagons} wagon${offeredWagons === 1 ? '' : 's'} now ` +
|
||||
`(the rest returns to your contract to book later). If you do not pay, the booking stays whole and you can rebook in the next window. Deadline: ${eat} EAT.`;
|
||||
`Pay within ${payMinutes} minute${payMinutes === 1 ? '' : 's'} to accept and ship ${offeredWagons} wagon${offeredWagons === 1 ? '' : 's'} now. ` +
|
||||
`The remaining ${totalWagons - offeredWagons} return${totalWagons - offeredWagons === 1 ? 's' : ''} to your contract — book them yourself in a later window. ` +
|
||||
`If you do not pay, the booking stays whole and you can rebook in the next window. Deadline: ${eat} EAT.`;
|
||||
await this.notifyContact(b, msg, 'PAY NOW (PARTIAL)');
|
||||
// HIGH: a split is a change to what the customer ordered AND a live payment
|
||||
// deadline — it must reach email/SMS, not just the portal inbox.
|
||||
this.inApp(b, 'Partial allocation offer', msg, {
|
||||
type: NotificationType.INVOICE_ISSUED,
|
||||
priority: NotificationPriority.HIGH,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -136,6 +141,22 @@ export class BookingNotifierService {
|
||||
this.inApp(b, 'Payment window expired', msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every train on the booking's chosen day filled up (or no further train runs)
|
||||
* before the waiting list reached this booking — it expired unplaced. HIGH so
|
||||
* the customer hears about it by email/SMS and rebooks another day.
|
||||
*/
|
||||
expiredNoCapacity(b: Booking): void {
|
||||
const msg =
|
||||
`Booking ${b.reference ?? b.id} could not be placed: every train for your selected day ` +
|
||||
`is full and no other train is scheduled that day. The booking has expired — ` +
|
||||
`please rebook for another day. No re-approval is needed.`;
|
||||
void this.notifyContact(b, msg, 'EXPIRED (NO CAPACITY)');
|
||||
this.inApp(b, 'No capacity — booking expired', msg, {
|
||||
priority: NotificationPriority.HIGH,
|
||||
});
|
||||
}
|
||||
|
||||
scheduleFull(b: Booking): void {
|
||||
this.logger.warn(
|
||||
`SCHEDULE FULL — ${this.ref(b)} could not be placed; change schedule, pick another day, or cancel.`,
|
||||
|
||||
@@ -36,6 +36,9 @@ export interface SizedOffer {
|
||||
* rows, so reducing the lines releases it automatically) and can be rebooked in
|
||||
* any later window within contract validity. A ONE_TIME contract is promoted to
|
||||
* GENERAL on split (see applySplit) so its remainder is actually rebookable.
|
||||
* Once the remainder is rebooked and the cap hits zero, ContractBookingService
|
||||
* completes the contract (CONTRACT_CLOSED): no further bookings or shipment
|
||||
* requests, even while validity and a booking window are still open.
|
||||
*/
|
||||
@Injectable()
|
||||
export class BookingSplitService {
|
||||
@@ -55,12 +58,17 @@ export class BookingSplitService {
|
||||
* Size the largest part of the booking that fits `freeWagons`, priced via an
|
||||
* in-memory clone. Returns null when nothing meaningful fits (no whole
|
||||
* container unit / no bulk tonnage, or pricing failed).
|
||||
*
|
||||
* `maxOfferedWeightTons` caps the offered CARGO tonnage (bulk only) — on a
|
||||
* weight-limited train the wagons' own tare eats into the locomotive's
|
||||
* remaining pull weight, so the caller passes the room left after tare.
|
||||
*/
|
||||
async sizeOffer(
|
||||
booking: Booking,
|
||||
freeWagons: number,
|
||||
totalWagons: number,
|
||||
bulkWagonCapacityTons: number,
|
||||
maxOfferedWeightTons?: number,
|
||||
): Promise<SizedOffer | null> {
|
||||
if (freeWagons < 1 || freeWagons >= totalWagons) return null;
|
||||
|
||||
@@ -110,10 +118,15 @@ export class BookingSplitService {
|
||||
if (!offeredLines.length || offeredWagons <= 0) return null;
|
||||
clone.bookingContainers = clonedContainers;
|
||||
} else {
|
||||
// Bulk: split by weight — the offered part is what freeWagons can carry.
|
||||
// Bulk: split by weight — the offered part is what freeWagons can carry,
|
||||
// further capped by the caller's weight room when the pull limit binds.
|
||||
const totalWeight = Number(booking.cargoTotalWeightVgm ?? 0);
|
||||
if (totalWeight <= 0 || bulkWagonCapacityTons <= 0) return null;
|
||||
offeredWeightTons = Math.min(totalWeight, freeWagons * bulkWagonCapacityTons);
|
||||
offeredWeightTons = Math.min(
|
||||
totalWeight,
|
||||
freeWagons * bulkWagonCapacityTons,
|
||||
maxOfferedWeightTons ?? Number.POSITIVE_INFINITY,
|
||||
);
|
||||
if (offeredWeightTons <= 0) return null;
|
||||
offeredWagons = Math.min(
|
||||
freeWagons,
|
||||
|
||||
@@ -19,6 +19,7 @@ describe('BookingWindowService — window state machine', () => {
|
||||
isScheduleFull: jest.Mock;
|
||||
hasLiveReservations: jest.Mock;
|
||||
refreshWindowStatus: jest.Mock;
|
||||
expireLeftoverDayPool: jest.Mock;
|
||||
};
|
||||
let trainSchedulesRepository: { findById: jest.Mock; findAll: jest.Mock };
|
||||
let trainSchedulingService: { finalizeSchedule: jest.Mock; getWindowConfig: jest.Mock };
|
||||
@@ -73,6 +74,7 @@ describe('BookingWindowService — window state machine', () => {
|
||||
// No reservation is mid-pay-window by default, so the cycle concludes.
|
||||
hasLiveReservations: jest.fn().mockResolvedValue(false),
|
||||
refreshWindowStatus: jest.fn().mockResolvedValue(undefined),
|
||||
expireLeftoverDayPool: jest.fn().mockResolvedValue(0),
|
||||
};
|
||||
trainSchedulesRepository = {
|
||||
findById: jest.fn().mockResolvedValue(null),
|
||||
@@ -186,6 +188,8 @@ describe('BookingWindowService — window state machine', () => {
|
||||
expect(batch.setWindow).toHaveBeenCalledWith(scheduleId, 'FULL');
|
||||
expect(s.windowPhase).toBe('DONE');
|
||||
expect(trainSchedulingService.finalizeSchedule).toHaveBeenCalledWith(scheduleId);
|
||||
// The day's leftover waiting list is swept once this train is done.
|
||||
expect(batch.expireLeftoverDayPool).toHaveBeenCalledWith(scheduleId);
|
||||
});
|
||||
|
||||
it('conclude: NOT full + a cycle fits before departure → REOPEN (back to PRE_WINDOW)', async () => {
|
||||
@@ -210,6 +214,8 @@ describe('BookingWindowService — window state machine', () => {
|
||||
});
|
||||
await concludeCycle(s, new Date('2026-07-01T02:30:04.000Z'));
|
||||
expect(s.windowPhase).toBe('DONE');
|
||||
// No further train can run for this day → leftover waiting list is swept.
|
||||
expect(batch.expireLeftoverDayPool).toHaveBeenCalledWith(scheduleId);
|
||||
});
|
||||
|
||||
it('no transition fires before its deadline (idempotent tick)', async () => {
|
||||
|
||||
@@ -357,6 +357,10 @@ export class BookingWindowService implements OnModuleInit {
|
||||
this.logger.log(
|
||||
`[WINDOW] ${schedule.id} conclude → train FULL — window DONE, finalizing`,
|
||||
);
|
||||
// This train is done. If no other train on the route-day can still take
|
||||
// the waiting list, those bookings have nowhere to go — expire + notify
|
||||
// them now instead of leaving them FULLY_EXECUTED forever.
|
||||
await this.bookingBatchService.expireLeftoverDayPool(schedule.id);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -390,6 +394,9 @@ export class BookingWindowService implements OnModuleInit {
|
||||
`[WINDOW] ${schedule.id} conclude → not full but no cycle fits before ` +
|
||||
`departure — window DONE`,
|
||||
);
|
||||
// No further cycle on this train. Same sweep as the FULL branch: if no
|
||||
// sibling train can still take the day's waiting list, expire + notify.
|
||||
await this.bookingBatchService.expireLeftoverDayPool(schedule.id);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Capacity, CorridorBudget } from './corridor-capacity.util';
|
||||
import { sizePartialOfferWagons } from './train-capacity.util';
|
||||
|
||||
describe('corridor-capacity.util — overage tolerance', () => {
|
||||
const pw2 = { lengthMeters: 17.066, capacityTons: 70, tareWeightTons: 25.2 };
|
||||
const stops = ['yard-a', 'yard-b'];
|
||||
const base: Capacity = { wagons: 44, weightTons: 3500, lengthMeters: 760 };
|
||||
const tolerance = { weightTons: 90, lengthMeters: 0 };
|
||||
|
||||
const need = (weightTons: number, wagons = 1, lengthMeters = 17): Capacity => ({
|
||||
wagons,
|
||||
weightTons,
|
||||
lengthMeters,
|
||||
});
|
||||
|
||||
const budgetAt = (usedWeightTons: number): CorridorBudget => {
|
||||
const budget = new CorridorBudget(stops, base, tolerance);
|
||||
budget.subtract(need(usedWeightTons, 10, 170), budget.fullLeg());
|
||||
return budget;
|
||||
};
|
||||
|
||||
it('admits a whole booking that overflows the base cap by less than the tolerance', () => {
|
||||
// 3500T train, 90T tolerance, 3560T committed: a 25T booking still boards
|
||||
// entire (3585 ≤ 3590).
|
||||
const budget = budgetAt(3560);
|
||||
expect(budget.fits(need(25), budget.fullLeg())).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a whole booking that overflows past the tolerance — no partial admission', () => {
|
||||
// Same train at 3560T: a 210T booking would need 3770 > 3590 — skipped.
|
||||
const budget = budgetAt(3560);
|
||||
expect(budget.fits(need(210), budget.fullLeg())).toBe(false);
|
||||
});
|
||||
|
||||
it('caps stacked overage admissions at base + tolerance', () => {
|
||||
// Small units may keep boarding inside the overage zone, but never past it.
|
||||
const budget = budgetAt(3560);
|
||||
budget.subtract(need(25), budget.fullLeg()); // now 3585 committed
|
||||
expect(budget.fits(need(5), budget.fullLeg())).toBe(true); // 3590 exactly
|
||||
expect(budget.fits(need(6), budget.fullLeg())).toBe(false); // 3591 > 3590
|
||||
});
|
||||
|
||||
it('excludes the tolerance from remainingFor, so split room never reaches into it', () => {
|
||||
const budget = budgetAt(3400);
|
||||
expect(budget.remainingFor(budget.fullLeg()).weightTons).toBe(100);
|
||||
// Once a whole-unit admission spends the tolerance, base room goes negative.
|
||||
const over = budgetAt(3560);
|
||||
expect(over.remainingFor(over.fullLeg()).weightTons).toBe(-60);
|
||||
});
|
||||
|
||||
it('yields no split offer once the base cap is spent — tolerance is whole-bookings-only', () => {
|
||||
// The batch engine sizes splits from remainingFor; at/over base capacity
|
||||
// that room cannot carry even one part-loaded wagon, so no offer opens.
|
||||
const over = budgetAt(3560);
|
||||
const room = over.remainingFor(over.fullLeg());
|
||||
expect(sizePartialOfferWagons(room, 15, pw2)).toBeNull();
|
||||
});
|
||||
|
||||
it('still offers a split while committed weight is under the base cap', () => {
|
||||
// 744T of base room left: the boundary booking is offered the part that
|
||||
// fits up to 3500, not up to 3590.
|
||||
const budget = budgetAt(2756);
|
||||
const room = budget.remainingFor(budget.fullLeg());
|
||||
expect(sizePartialOfferWagons(room, 15, pw2)).toEqual({
|
||||
wagons: 8,
|
||||
maxCargoTons: 542.4,
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves fits() strict when no tolerance is configured', () => {
|
||||
const strict = new CorridorBudget(stops, base);
|
||||
strict.subtract(need(3500, 10, 170), strict.fullLeg());
|
||||
expect(strict.fits(need(1), strict.fullLeg())).toBe(false);
|
||||
});
|
||||
|
||||
describe('isExhausted — train-wide FULL across all axes', () => {
|
||||
// Lightest wagon at rated payload: PW2 25.2T tare + 70T = 95.2T gross.
|
||||
const perWagon = {
|
||||
grossWeightTons: pw2.tareWeightTons + pw2.capacityTons,
|
||||
lengthMeters: pw2.lengthMeters,
|
||||
};
|
||||
|
||||
it('reports FULL when weight binds first, with wagon slots still free', () => {
|
||||
// 37 loaded PW2 wagons = 3522.4T of 3500+90T. 7 length-derived slots
|
||||
// remain, but wagon 38 would need 95.2T against 67.6T of room — the
|
||||
// schedule must finalize and its window must disappear.
|
||||
const budget = new CorridorBudget(stops, base, tolerance);
|
||||
budget.subtract(need(3522.4, 37, 631.442), budget.fullLeg());
|
||||
expect(budget.maxRemaining().wagons).toBeGreaterThan(0); // slot check alone says "not full"
|
||||
expect(budget.isExhausted(perWagon)).toBe(true);
|
||||
});
|
||||
|
||||
it('is not FULL while one more loaded wagon still fits within base + tolerance', () => {
|
||||
const budget = budgetAt(3300); // 200T base room + 90T tolerance ≥ 95.2T
|
||||
expect(budget.isExhausted(perWagon)).toBe(false);
|
||||
});
|
||||
|
||||
it('reports FULL when wagon slots run out regardless of weight room', () => {
|
||||
const budget = new CorridorBudget(stops, base, tolerance);
|
||||
budget.subtract(need(1000, 44, 700), budget.fullLeg());
|
||||
expect(budget.isExhausted(perWagon)).toBe(true);
|
||||
});
|
||||
|
||||
it('reports FULL when length room cannot take one more wagon', () => {
|
||||
const budget = new CorridorBudget(stops, base, tolerance);
|
||||
budget.subtract(need(1000, 30, 750), budget.fullLeg()); // 10m left < 17.066m
|
||||
expect(budget.isExhausted(perWagon)).toBe(true);
|
||||
});
|
||||
|
||||
it('only counts an edge as open when EVERY axis has room on that same edge', () => {
|
||||
// Three stops → two edges. Edge 0 has weight but no slots; edge 1 has
|
||||
// slots but no weight. Neither can board a wagon, so the train is FULL
|
||||
// even though the per-axis maxima both look open.
|
||||
const budget = new CorridorBudget(['a', 'b', 'c'], base, tolerance);
|
||||
budget.subtract(need(0, 44, 0), { fromEdge: 0, toEdge: 1 });
|
||||
budget.subtract(need(3522.4, 0, 0), { fromEdge: 1, toEdge: 2 });
|
||||
expect(budget.isExhausted(perWagon)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -63,18 +63,40 @@ export function stopYardsFor(
|
||||
return [originStationId, destinationStationId];
|
||||
}
|
||||
|
||||
/** Per-edge capacity budget along a schedule's stop list. */
|
||||
/** Overage a locomotive may absorb beyond its base caps. */
|
||||
export interface OverageTolerance {
|
||||
weightTons: number;
|
||||
lengthMeters: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-edge capacity budget along a schedule's stop list.
|
||||
*
|
||||
* `initial` must be the BASE caps (locomotive floored by rule caps, WITHOUT the
|
||||
* overage tolerance). The tolerance is passed separately and is spendable only
|
||||
* by admitting a unit WHOLE via {@link fits} — e.g. base 3500T + 90T tolerance,
|
||||
* 3560T already committed: a 25T booking still boards entire (3585 ≤ 3590), a
|
||||
* 210T booking does not. {@link remainingFor} deliberately excludes the
|
||||
* tolerance (and goes negative once it is consumed), so split/partial offers
|
||||
* sized from it can only fill up to the base cap and never spend the tolerance.
|
||||
*/
|
||||
export class CorridorBudget {
|
||||
private readonly edges: Capacity[];
|
||||
private readonly stopIndex: Map<string, number>;
|
||||
private readonly tolerance: OverageTolerance;
|
||||
|
||||
constructor(
|
||||
readonly stops: string[],
|
||||
initial: Capacity,
|
||||
tolerance?: Partial<OverageTolerance> | null,
|
||||
) {
|
||||
const edgeCount = Math.max(1, stops.length - 1);
|
||||
this.edges = Array.from({ length: edgeCount }, () => ({ ...initial }));
|
||||
this.stopIndex = new Map(stops.map((yardId, i) => [yardId, i]));
|
||||
this.tolerance = {
|
||||
weightTons: tolerance?.weightTons ?? 0,
|
||||
lengthMeters: tolerance?.lengthMeters ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** The leg between two stops, or null when they aren't on this corridor in order. */
|
||||
@@ -99,7 +121,12 @@ export class CorridorBudget {
|
||||
return this.legOf(originYardId, destinationYardId) ?? this.fullLeg();
|
||||
}
|
||||
|
||||
/** Remaining capacity usable by this leg = min across its edges. */
|
||||
/**
|
||||
* Remaining BASE capacity usable by this leg = min across its edges. Excludes
|
||||
* the overage tolerance and goes negative once a whole-unit admission has
|
||||
* spent it — sizing a split from this can therefore never reach into the
|
||||
* tolerance, and yields nothing at all once the base cap is exhausted.
|
||||
*/
|
||||
remainingFor(leg: CorridorLeg): Capacity {
|
||||
let min = { ...this.edges[leg.fromEdge] };
|
||||
for (let i = leg.fromEdge + 1; i < leg.toEdge; i++) {
|
||||
@@ -113,8 +140,20 @@ export class CorridorBudget {
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a unit fits WHOLE on this leg. This is the only place the overage
|
||||
* tolerance may be spent: the unit boards entirely or not at all, so weight
|
||||
* and length may dip into the tolerance. Admission keeps the invariant
|
||||
* `remaining ≥ -tolerance` on every edge, i.e. the train never exceeds
|
||||
* base + tolerance no matter how many small units board in the overage zone.
|
||||
*/
|
||||
fits(need: Capacity, leg: CorridorLeg): boolean {
|
||||
return capacityFits(need, this.remainingFor(leg));
|
||||
const remaining = this.remainingFor(leg);
|
||||
return (
|
||||
need.wagons <= remaining.wagons &&
|
||||
need.weightTons <= remaining.weightTons + this.tolerance.weightTons &&
|
||||
need.lengthMeters <= remaining.lengthMeters + this.tolerance.lengthMeters
|
||||
);
|
||||
}
|
||||
|
||||
subtract(need: Capacity, leg: CorridorLeg): void {
|
||||
@@ -129,6 +168,25 @@ export class CorridorBudget {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Train-wide FULL across ALL capacity axes: true when no edge can board even
|
||||
* one more loaded wagon. `perWagon` is the smallest gross weight and length
|
||||
* a future wagon could add (lightest wagon type at rated payload); weight and
|
||||
* length may dip into the overage tolerance, mirroring {@link fits}. Checked
|
||||
* per edge — an edge with slots free but no pull weight is just as closed as
|
||||
* one with no slots. A slot-only check misses weight-bound trains: PW2 at
|
||||
* 37 × 95.2T = 3522.4T of 3500+90T has 7 length-derived slots free but no
|
||||
* weight room for wagon 38, and its window must read FULL.
|
||||
*/
|
||||
isExhausted(perWagon: { grossWeightTons: number; lengthMeters: number }): boolean {
|
||||
return this.edges.every(
|
||||
(e) =>
|
||||
e.wagons <= 0 ||
|
||||
e.weightTons + this.tolerance.weightTons < perWagon.grossWeightTons ||
|
||||
e.lengthMeters + this.tolerance.lengthMeters < perWagon.lengthMeters,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The most open edge — when even this has no wagon slots left, nothing can
|
||||
* board anywhere and the schedule's window is genuinely FULL. (A train can be
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
|
||||
export const BATCH_BOARD_STATUSES = [
|
||||
'DRAFT',
|
||||
'SCHEDULED',
|
||||
'DISPATCHED',
|
||||
'ARRIVED',
|
||||
'CANCELLED',
|
||||
] as const;
|
||||
|
||||
export const BATCH_BOARD_SORT_FIELDS = [
|
||||
'createdAt',
|
||||
'scheduledDepartureDate',
|
||||
'trainNumber',
|
||||
'status',
|
||||
] as const;
|
||||
export type BatchBoardSortField = (typeof BATCH_BOARD_SORT_FIELDS)[number];
|
||||
|
||||
/** Filters for the batch monitoring board list (import schedules, all statuses). */
|
||||
export class BatchBoardQueryDto {
|
||||
@ApiPropertyOptional({ default: 1, minimum: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional({ default: 12, minimum: 1, maximum: 100 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
pageSize?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'Comma-separated schedule statuses (DRAFT,SCHEDULED,DISPATCHED,ARRIVED,CANCELLED). Omit for all.',
|
||||
example: 'DISPATCHED,ARRIVED',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
statuses?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['OPEN', 'FULL', 'CLOSED'] })
|
||||
@IsOptional()
|
||||
@IsIn(['OPEN', 'FULL', 'CLOSED'])
|
||||
bookingWindowStatus?: 'OPEN' | 'FULL' | 'CLOSED';
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'Case-insensitive match on train number, route yards, stations, or locomotive code.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
search?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Departure date lower bound (ISO 8601).' })
|
||||
@IsOptional()
|
||||
@IsISO8601()
|
||||
departureFrom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Departure date upper bound (ISO 8601).' })
|
||||
@IsOptional()
|
||||
@IsISO8601()
|
||||
departureTo?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Created-at lower bound (ISO 8601).' })
|
||||
@IsOptional()
|
||||
@IsISO8601()
|
||||
createdFrom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Created-at upper bound (ISO 8601).' })
|
||||
@IsOptional()
|
||||
@IsISO8601()
|
||||
createdTo?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: BATCH_BOARD_SORT_FIELDS, default: 'createdAt' })
|
||||
@IsOptional()
|
||||
@IsIn(BATCH_BOARD_SORT_FIELDS as unknown as string[])
|
||||
sortBy?: BatchBoardSortField;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['ASC', 'DESC'], default: 'DESC' })
|
||||
@IsOptional()
|
||||
@IsIn(['ASC', 'DESC'])
|
||||
sortOrder?: 'ASC' | 'DESC';
|
||||
}
|
||||
@@ -107,7 +107,13 @@ export class IntercityService {
|
||||
for (const bookingId of bookingIds) {
|
||||
const booking = await this.dataSource
|
||||
.getRepository(Booking)
|
||||
.findOne({ where: { id: bookingId }, relations: { bookingContainers: true } });
|
||||
.findOne({
|
||||
where: { id: bookingId },
|
||||
relations: {
|
||||
bookingContainers: { containerType: true },
|
||||
cargoType: true,
|
||||
},
|
||||
});
|
||||
if (!booking) {
|
||||
rejected.push({ bookingId, reason: 'Booking not found' });
|
||||
continue;
|
||||
@@ -205,6 +211,8 @@ export class IntercityService {
|
||||
.createQueryBuilder('booking')
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.leftJoinAndSelect('booking.originYard', 'originYard')
|
||||
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
|
||||
.where(`booking.trade_direction = 'DOMESTIC'`)
|
||||
@@ -230,6 +238,8 @@ export class IntercityService {
|
||||
.createQueryBuilder('booking')
|
||||
.leftJoinAndSelect('booking.company', 'company')
|
||||
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
|
||||
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
|
||||
.leftJoinAndSelect('booking.cargoType', 'cargoType')
|
||||
.leftJoinAndSelect('booking.originYard', 'originYard')
|
||||
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
|
||||
.where(`booking.trade_direction = 'DOMESTIC'`)
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
deriveTrainCapacityFromLocomotive,
|
||||
grossWagonWeightTons,
|
||||
minLocomotiveLimits,
|
||||
sizePartialOfferWagons,
|
||||
} from './train-capacity.util';
|
||||
|
||||
describe('train-capacity.util', () => {
|
||||
@@ -73,6 +74,24 @@ describe('train-capacity.util', () => {
|
||||
expect(derived.maxWeightTons).toBe(3590);
|
||||
});
|
||||
|
||||
it('reports the base caps and tolerance separately so filling can budget on base', () => {
|
||||
const derived = deriveTrainCapacityFromLocomotive(
|
||||
{
|
||||
maxPullWeightTons: 3500,
|
||||
maxTrainLengthMeters: 760,
|
||||
overageToleranceTons: 90,
|
||||
overageToleranceMeters: 20,
|
||||
},
|
||||
[pw2],
|
||||
);
|
||||
expect(derived.baseWeightTons).toBe(3500);
|
||||
expect(derived.baseLengthMeters).toBe(760);
|
||||
expect(derived.toleranceTons).toBe(90);
|
||||
expect(derived.toleranceMeters).toBe(20);
|
||||
expect(derived.baseWeightTons + derived.toleranceTons).toBe(derived.maxWeightTons);
|
||||
expect(derived.baseLengthMeters + derived.toleranceMeters).toBe(derived.maxLengthMeters);
|
||||
});
|
||||
|
||||
it('ignores overage tolerance when unset (strict cap)', () => {
|
||||
const derived = deriveTrainCapacityFromLocomotive(
|
||||
{ maxPullWeightTons: 3500, maxTrainLengthMeters: 760 },
|
||||
@@ -185,4 +204,96 @@ describe('train-capacity.util', () => {
|
||||
expect(limits?.maxPullWeightTons).toBe(3500);
|
||||
expect(limits?.overageToleranceTons).toBe(20);
|
||||
});
|
||||
|
||||
describe('sizePartialOfferWagons', () => {
|
||||
it('sizes a bulk split by the WEIGHT axis when the pull limit binds, not wagon slots', () => {
|
||||
// The 3500T-train scenario: two 1000T bookings boarded gross (each 15 PW2
|
||||
// wagons: 1000 + 378 tare = 1378), leaving 744T of pull weight but plenty
|
||||
// of slots/length. The boundary 1000T booking (15 wagons) must be offered
|
||||
// the largest part 744T can carry: 8 wagons whose tare is 201.6T, hauling
|
||||
// 542.4T of cargo — gross exactly 744.
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 744, lengthMeters: 500 },
|
||||
15,
|
||||
pw2,
|
||||
);
|
||||
expect(offer).toEqual({ wagons: 8, maxCargoTons: 542.4 });
|
||||
});
|
||||
|
||||
it('still sizes by wagon slots when they bind first (legacy behavior)', () => {
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 3, weightTons: 100000, lengthMeters: 100000 },
|
||||
15,
|
||||
pw2,
|
||||
);
|
||||
expect(offer?.wagons).toBe(3);
|
||||
});
|
||||
|
||||
it('sizes by the LENGTH axis when it binds first', () => {
|
||||
// 60m of train left → 3 PW2 (17.066m) fit, the 4th does not.
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 100000, lengthMeters: 60 },
|
||||
15,
|
||||
pw2,
|
||||
);
|
||||
expect(offer?.wagons).toBe(3);
|
||||
});
|
||||
|
||||
it('never offers all of the booking — a split is a strict subset', () => {
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 100000, lengthMeters: 100000 },
|
||||
15,
|
||||
pw2,
|
||||
);
|
||||
expect(offer?.wagons).toBe(14);
|
||||
});
|
||||
|
||||
it('returns null when not even one part-loaded wagon fits the weight room', () => {
|
||||
expect(
|
||||
sizePartialOfferWagons({ wagons: 5, weightTons: 20, lengthMeters: 500 }, 15, pw2),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
describe('fullWagonsOnly (bulk)', () => {
|
||||
it('offers only whole full wagons — each costs capacity + tare of gross room', () => {
|
||||
// 704T of pull weight left. A full PW2 wagon is 70 + 25.2 = 95.2T gross,
|
||||
// so 7 fit (666.4T) and the 8th (761.6T) does not. Cargo is exactly
|
||||
// 7 × 70 = 490T — the last wagon is never part-loaded into the leftover.
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 704, lengthMeters: 500 },
|
||||
9,
|
||||
pw2,
|
||||
{ fullWagonsOnly: true },
|
||||
);
|
||||
expect(offer).toEqual({ wagons: 7, maxCargoTons: 490 });
|
||||
});
|
||||
|
||||
it('never squeezes a part-loaded wagon into leftover weight room', () => {
|
||||
// Same 744T room as the part-load scenario above: the scan would pick
|
||||
// 8 wagons hauling 542.4T (last wagon at 52.4/70). Full-wagon sizing
|
||||
// stops at 7 fully loaded wagons.
|
||||
const offer = sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 744, lengthMeters: 500 },
|
||||
15,
|
||||
pw2,
|
||||
{ fullWagonsOnly: true },
|
||||
);
|
||||
expect(offer).toEqual({ wagons: 7, maxCargoTons: 490 });
|
||||
});
|
||||
|
||||
it('returns null when the room cannot take even one FULL wagon', () => {
|
||||
// 67.6T left (3590 cap − 3522.4 boarded): a part-loaded wagon would fit
|
||||
// (25.2 tare + 42.4 cargo) but a full one (95.2 gross) does not — the
|
||||
// booking must be skipped entirely, not trimmed onto the train.
|
||||
expect(
|
||||
sizePartialOfferWagons(
|
||||
{ wagons: 40, weightTons: 67.6, lengthMeters: 500 },
|
||||
3,
|
||||
pw2,
|
||||
{ fullWagonsOnly: true },
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,6 +52,12 @@ export type DerivedTrainCapacity = {
|
||||
maxLengthMeters: number;
|
||||
/** Length-derived slot count. Weight is enforced separately against real cargo. */
|
||||
maxWagonSlots: number;
|
||||
/** Caps WITHOUT the overage tolerance — what batch filling budgets against. */
|
||||
baseWeightTons: number;
|
||||
baseLengthMeters: number;
|
||||
/** Overage spendable only by admitting a booking whole, never by a split. */
|
||||
toleranceTons: number;
|
||||
toleranceMeters: number;
|
||||
};
|
||||
|
||||
/** What a consist currently uses, and what is left on each axis. */
|
||||
@@ -88,28 +94,48 @@ export function grossWagonWeightTons(slot: Pick<ConsistSlot, 'tareWeightTons' |
|
||||
/**
|
||||
* Hard caps for a train: the locomotive's own limits, floored by the global rule
|
||||
* caps, then widened by the locomotive's overage tolerance.
|
||||
*
|
||||
* `base*` are the caps BEFORE the tolerance is added. The tolerance is not
|
||||
* general-purpose headroom: batch filling budgets against the base caps and may
|
||||
* spend the tolerance only to admit a booking WHOLE (never to size a split), so
|
||||
* both figures are returned. `base + tolerance === max` always holds, including
|
||||
* the fallback path.
|
||||
*/
|
||||
export function trainHardCaps(
|
||||
locomotive: LocomotiveLimits,
|
||||
ruleCaps?: { maxTrainWeightTons?: number; maxTrainLengthMeters?: number },
|
||||
): { maxWeightTons: number; maxLengthMeters: number } {
|
||||
): {
|
||||
maxWeightTons: number;
|
||||
maxLengthMeters: number;
|
||||
baseWeightTons: number;
|
||||
baseLengthMeters: number;
|
||||
toleranceTons: number;
|
||||
toleranceMeters: number;
|
||||
} {
|
||||
const overageTons = num(locomotive.overageToleranceTons);
|
||||
const overageMeters = num(locomotive.overageToleranceMeters);
|
||||
|
||||
const weight =
|
||||
Math.min(
|
||||
num(locomotive.maxPullWeightTons, Infinity) || Infinity,
|
||||
ruleCaps?.maxTrainWeightTons ?? Infinity,
|
||||
) + overageTons;
|
||||
const length =
|
||||
Math.min(
|
||||
num(locomotive.maxTrainLengthMeters, Infinity) || Infinity,
|
||||
ruleCaps?.maxTrainLengthMeters ?? Infinity,
|
||||
) + overageMeters;
|
||||
const baseWeight = Math.min(
|
||||
num(locomotive.maxPullWeightTons, Infinity) || Infinity,
|
||||
ruleCaps?.maxTrainWeightTons ?? Infinity,
|
||||
);
|
||||
const baseLength = Math.min(
|
||||
num(locomotive.maxTrainLengthMeters, Infinity) || Infinity,
|
||||
ruleCaps?.maxTrainLengthMeters ?? Infinity,
|
||||
);
|
||||
|
||||
const baseWeightTons = Number.isFinite(baseWeight) ? baseWeight : MAX_FALLBACK_WEIGHT;
|
||||
const baseLengthMeters = Number.isFinite(baseLength) ? baseLength : MAX_FALLBACK_LENGTH;
|
||||
const toleranceTons = Number.isFinite(baseWeight) ? overageTons : 0;
|
||||
const toleranceMeters = Number.isFinite(baseLength) ? overageMeters : 0;
|
||||
|
||||
return {
|
||||
maxWeightTons: Number.isFinite(weight) ? weight : MAX_FALLBACK_WEIGHT,
|
||||
maxLengthMeters: Number.isFinite(length) ? length : MAX_FALLBACK_LENGTH,
|
||||
maxWeightTons: baseWeightTons + toleranceTons,
|
||||
maxLengthMeters: baseLengthMeters + toleranceMeters,
|
||||
baseWeightTons,
|
||||
baseLengthMeters,
|
||||
toleranceTons,
|
||||
toleranceMeters,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -129,7 +155,7 @@ export function deriveTrainCapacityFromLocomotive(
|
||||
wagonTypes: WagonTypeDimensions[],
|
||||
ruleCaps?: { maxTrainWeightTons?: number; maxTrainLengthMeters?: number },
|
||||
): DerivedTrainCapacity {
|
||||
const { maxWeightTons, maxLengthMeters } = trainHardCaps(locomotive, ruleCaps);
|
||||
const caps = trainHardCaps(locomotive, ruleCaps);
|
||||
|
||||
const lengths = wagonTypes
|
||||
.map((w) => num(w.lengthMeters))
|
||||
@@ -137,9 +163,9 @@ export function deriveTrainCapacityFromLocomotive(
|
||||
const minLength = lengths.length ? Math.min(...lengths) : DEFAULT_WAGON_LENGTH_M;
|
||||
|
||||
const maxWagonSlots =
|
||||
minLength > 0 ? Math.max(0, Math.floor(maxLengthMeters / minLength)) : 0;
|
||||
minLength > 0 ? Math.max(0, Math.floor(caps.maxLengthMeters / minLength)) : 0;
|
||||
|
||||
return { maxWeightTons, maxLengthMeters, maxWagonSlots };
|
||||
return { ...caps, maxWagonSlots };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -256,6 +282,58 @@ export function bookingGrossWeightTons(
|
||||
return round3(num(cargoTons) + wagonCount * num(tarePerWagonTons));
|
||||
}
|
||||
|
||||
/**
|
||||
* Size a partial (split-on-payment) offer against the room left on a train,
|
||||
* across ALL THREE capacity axes — not just wagon slots. Each wagon adds
|
||||
* `capacityTons` of payload headroom but its own tare spends the same weight
|
||||
* room the cargo needs, so on a weight-limited train more wagons is not always
|
||||
* more cargo. Scans wagon counts (the last wagon may run part-loaded) and
|
||||
* returns the count that maximizes the cargo carried, with the cargo cap the
|
||||
* caller should apply. Null when not even one part-loaded wagon fits. The
|
||||
* offer is a strict subset of the booking: never all `bookingWagons`.
|
||||
*
|
||||
* `fullWagonsOnly` (bulk): every offered wagon rides at its full rated payload,
|
||||
* so each wagon costs `capacityTons + tareWeightTons` of gross weight room and
|
||||
* the offer is the largest whole-wagon count whose gross fits — never a
|
||||
* part-loaded last wagon squeezed into leftover pull weight.
|
||||
*/
|
||||
export function sizePartialOfferWagons(
|
||||
room: { wagons: number; weightTons: number; lengthMeters: number },
|
||||
bookingWagons: number,
|
||||
perWagon: { capacityTons: number; tareWeightTons: number; lengthMeters: number },
|
||||
opts?: { fullWagonsOnly?: boolean },
|
||||
): { wagons: number; maxCargoTons: number } | null {
|
||||
const maxByLength =
|
||||
perWagon.lengthMeters > 0
|
||||
? Math.floor(room.lengthMeters / perWagon.lengthMeters)
|
||||
: room.wagons;
|
||||
const ceiling = Math.min(room.wagons, maxByLength, bookingWagons - 1);
|
||||
|
||||
if (opts?.fullWagonsOnly) {
|
||||
const grossPerWagon = perWagon.capacityTons + perWagon.tareWeightTons;
|
||||
const maxByWeight =
|
||||
grossPerWagon > 0 ? Math.floor(room.weightTons / grossPerWagon) : 0;
|
||||
const wagons = Math.min(ceiling, maxByWeight);
|
||||
if (wagons < 1) return null;
|
||||
return { wagons, maxCargoTons: round3(wagons * perWagon.capacityTons) };
|
||||
}
|
||||
|
||||
let wagons = 0;
|
||||
let bestCargoTons = 0;
|
||||
for (let w = 1; w <= ceiling; w += 1) {
|
||||
const cargoAt = Math.min(
|
||||
w * perWagon.capacityTons,
|
||||
room.weightTons - w * perWagon.tareWeightTons,
|
||||
);
|
||||
if (cargoAt > bestCargoTons) {
|
||||
bestCargoTons = cargoAt;
|
||||
wagons = w;
|
||||
}
|
||||
}
|
||||
if (wagons < 1) return null;
|
||||
return { wagons, maxCargoTons: round3(room.weightTons - wagons * perWagon.tareWeightTons) };
|
||||
}
|
||||
|
||||
export function wagonTypeDimensionsFromEntity(wt: {
|
||||
lengthMeters?: number | string | null;
|
||||
capacityTons?: number | string | null;
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
UploadImportDjiboutiDocumentDto,
|
||||
} from "./dto/import-djibouti-operation.dto";
|
||||
import { AvailableLocomotivesQueryDto } from "./dto/available-locomotives-query.dto";
|
||||
import { BatchBoardQueryDto } from "./dto/batch-board-query.dto";
|
||||
import { BookableSchedulesQueryDto } from "./dto/bookable-schedules-query.dto";
|
||||
import { AvailableDaysQueryDto } from "./dto/available-days-query.dto";
|
||||
import { AvailableDaysForCargoQueryDto } from "./dto/available-days-for-cargo-query.dto";
|
||||
@@ -124,10 +125,11 @@ export class TrainSchedulingController {
|
||||
@Get("batch-board")
|
||||
@TrainSchedulingView()
|
||||
@ApiOperation({
|
||||
summary: "Batch monitoring board: schedules with bookings grouped by state",
|
||||
summary:
|
||||
"Batch monitoring board: paginated import schedules (all statuses) with bookings grouped by state",
|
||||
})
|
||||
getBatchBoard() {
|
||||
return this.bookingBatchService.getBatchBoard();
|
||||
getBatchBoard(@Query() query: BatchBoardQueryDto) {
|
||||
return this.bookingBatchService.getBatchBoard(query);
|
||||
}
|
||||
|
||||
@Get("batch-board/:scheduleId")
|
||||
|
||||
@@ -1083,7 +1083,7 @@ export class TrainSchedulingService {
|
||||
{
|
||||
schedulingStatus: SchedulingStatus.Scheduled,
|
||||
scheduledAt,
|
||||
wagonsRequired: sumWagonsRequired(booking),
|
||||
wagonsRequired: sumWagonsRequired(booking, wagonPlan),
|
||||
},
|
||||
manager,
|
||||
);
|
||||
@@ -2514,6 +2514,12 @@ export class TrainSchedulingService {
|
||||
|
||||
if (dto.sequenceNo === finalSeq) {
|
||||
await this.arriveSchedule(scheduleId);
|
||||
} else {
|
||||
// Mid-corridor auto-unload: bookings destined for this yard alight the
|
||||
// moment the train is recorded here — the yard operator no longer has to
|
||||
// unload each one by hand. The final station is covered by
|
||||
// arriveSchedule's bulk fallback above.
|
||||
await this.bookingJourneyService.autoUnloadAtYard(scheduleId, station.yardId);
|
||||
}
|
||||
|
||||
return this.getScheduleCheckpoints(scheduleId);
|
||||
@@ -2639,8 +2645,9 @@ export class TrainSchedulingService {
|
||||
const schedules = await this.trainSchedulesRepository.findAll({
|
||||
relations: {
|
||||
trainSet: { locomotive: true, locomotives: { locomotive: true } },
|
||||
// Yards carry the route's display name used by mapScheduleListItem.
|
||||
route: { originYard: true, destinationYard: true },
|
||||
// Yards carry the route's display name used by mapScheduleListItem;
|
||||
// milestones (with yards) let it show the full corridor path.
|
||||
route: { originYard: true, destinationYard: true, milestones: { yard: true } },
|
||||
originStation: true,
|
||||
destinationStation: true,
|
||||
scheduleBookings: { booking: true },
|
||||
@@ -3105,6 +3112,10 @@ export class TrainSchedulingService {
|
||||
const wagonTypes = await this.loadSchedulingWagonTypeDimensions();
|
||||
|
||||
if (locomotive) {
|
||||
// With a locomotive assigned its own limits are the single source of
|
||||
// truth — global-rules / env caps do not floor them (a mis-set global
|
||||
// row once capped every train at 14m). Only an explicit per-request dto
|
||||
// override still applies.
|
||||
const derived = deriveTrainCapacityFromLocomotive(
|
||||
{
|
||||
maxPullWeightTons: Number(locomotive.maxPullWeightTons),
|
||||
@@ -3114,8 +3125,8 @@ export class TrainSchedulingService {
|
||||
},
|
||||
wagonTypes,
|
||||
{
|
||||
maxTrainWeightTons: ruleWeightCap,
|
||||
maxTrainLengthMeters: ruleLengthCap,
|
||||
maxTrainWeightTons: dto?.maxTrainWeightTons,
|
||||
maxTrainLengthMeters: dto?.maxTrainLengthMeters,
|
||||
},
|
||||
);
|
||||
return {
|
||||
@@ -4518,6 +4529,11 @@ export class TrainSchedulingService {
|
||||
capacityTons: roundTons(Number(wagon.capacityTons)),
|
||||
lengthMeters: roundTons(Number(wagon.lengthMeters)),
|
||||
assignedWeightTons: roundTons(Number(wagon.assignedWeightTons)),
|
||||
// Empty-wagon weight — the pull limit hauls tare + cargo, so the
|
||||
// frontend needs it to show the gross train weight.
|
||||
tareWeightTons: wagon.wagonType
|
||||
? roundTons(Number(wagon.wagonType.tareWeightTons))
|
||||
: null,
|
||||
status: wagon.status,
|
||||
physicalWagonId: wagon.physicalWagonId ?? null,
|
||||
physicalWagonNumber: wagon.physicalWagon?.wagonNumber ?? null,
|
||||
|
||||
@@ -82,6 +82,29 @@ describe('wagon-plan.util', () => {
|
||||
expect(plan).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('counts a bulk booking\'s wagons from the plan, not a flat 1', () => {
|
||||
// 700T of sugar on 60T CW3 gondolas = 12 wagons; the stored wagonsRequired
|
||||
// must carry all of them so gross weight charges 12 tares downstream.
|
||||
const booking = {
|
||||
id: 'bulk-700',
|
||||
reference: 'bulk-700',
|
||||
freightType: 'BULK',
|
||||
cargoTotalWeightVgm: 700,
|
||||
bookingContainers: [],
|
||||
} as unknown as Booking;
|
||||
const plan = buildBulkWagonPlan([booking], cw3);
|
||||
expect(plan).toHaveLength(12);
|
||||
expect(sumWagonsRequired(booking, plan)).toBe(12);
|
||||
// Without a plan the pre-plan fallback still applies.
|
||||
expect(sumWagonsRequired(booking)).toBe(1);
|
||||
});
|
||||
|
||||
it('counts container wagons from the plan TEU packing', () => {
|
||||
const booking = makeContainerBooking('c-plan', [{ quantity: 6, wagonsRequired: 3 }]);
|
||||
const plan = buildContainerWagonPlan([booking], nw5);
|
||||
expect(sumWagonsRequired(booking, plan)).toBe(3);
|
||||
});
|
||||
|
||||
it('6×20ft containers = 3 wagon slots (2 per wagon)', () => {
|
||||
// 20ft containers have wagonsPerUnit = 0.5, so 6 * 0.5 = 3 wagons
|
||||
const booking = makeContainerBooking('b6x20', [{ quantity: 6, wagonsRequired: 3 }]);
|
||||
|
||||
@@ -436,7 +436,21 @@ export function expandContainerItems(
|
||||
return items;
|
||||
}
|
||||
|
||||
export function sumWagonsRequired(booking: Booking): number {
|
||||
/**
|
||||
* Wagons a booking actually occupies. Prefer counting the built wagon plan's
|
||||
* slots that carry one of the booking's allocations — for BULK that is its
|
||||
* tonnage spread over real wagons (a 700T booking on 70T wagons rides 10
|
||||
* wagons, and downstream gross-weight math charges 10 tares, not 1). Without
|
||||
* a plan there is no capacity to divide by, so fall back to the pre-plan
|
||||
* estimates: 1 for bulk, the lines' stored counts for containers.
|
||||
*/
|
||||
export function sumWagonsRequired(booking: Booking, wagonPlan?: WagonPlanSlot[]): number {
|
||||
const occupiedSlots = (wagonPlan ?? []).filter((slot) =>
|
||||
slot.allocations.some((allocation) => allocation.bookingId === booking.id),
|
||||
).length;
|
||||
if (occupiedSlots > 0) {
|
||||
return occupiedSlots;
|
||||
}
|
||||
if (booking.freightType === 'BULK') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { WagonStatus } from '@edr/types';
|
||||
import { ArrayNotEmpty, IsArray, IsEnum, IsUUID } from 'class-validator';
|
||||
|
||||
export class BulkSetWagonStatusDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsUUID('4', { each: true })
|
||||
wagonIds!: string[];
|
||||
|
||||
@IsEnum(WagonStatus)
|
||||
status!: WagonStatus;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ArrayNotEmpty, IsArray, IsUUID } from 'class-validator';
|
||||
|
||||
export class BulkTransferWagonsDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsUUID('4', { each: true })
|
||||
wagonIds!: string[];
|
||||
|
||||
@IsUUID()
|
||||
toYardId!: string;
|
||||
}
|
||||
@@ -10,12 +10,16 @@ import {
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '@edr/api-common';
|
||||
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
|
||||
import { FleetManage, FleetView } from '../../common/booking-guards';
|
||||
import { CreateWagonDto } from './dto/create-wagon.dto';
|
||||
import { ListWagonsQueryDto } from './dto/list-wagons-query.dto';
|
||||
import { UpdateWagonDto } from './dto/update-wagon.dto';
|
||||
import { AssignWagonToTrainDto } from './dto/assign-wagon-to-train.dto';
|
||||
import { ReorderWagonsDto } from './dto/reorder-wagons.dto';
|
||||
import { BulkTransferWagonsDto } from './dto/bulk-transfer-wagons.dto';
|
||||
import { BulkSetWagonStatusDto } from './dto/bulk-set-wagon-status.dto';
|
||||
import { WagonsService } from './wagons.service';
|
||||
|
||||
@ApiTags('wagons')
|
||||
@@ -78,6 +82,20 @@ export class WagonsController {
|
||||
unassignFromTrain(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.wagonsService.unassignFromTrain(id);
|
||||
}
|
||||
|
||||
@Post('bulk-transfer')
|
||||
@FleetManage()
|
||||
@ApiOperation({ summary: 'Transfer multiple wagons to a destination yard' })
|
||||
bulkTransfer(@Body() dto: BulkTransferWagonsDto, @CurrentUser() user: TCurrentUser) {
|
||||
return this.wagonsService.bulkTransfer(dto, user?.id);
|
||||
}
|
||||
|
||||
@Post('bulk-status')
|
||||
@FleetManage()
|
||||
@ApiOperation({ summary: 'Set the status of multiple wagons' })
|
||||
bulkSetStatus(@Body() dto: BulkSetWagonStatusDto) {
|
||||
return this.wagonsService.bulkSetStatus(dto);
|
||||
}
|
||||
}
|
||||
|
||||
// Separate controller for train‑specific reorder (registered in module)
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { WagonMovementKind, WagonStatus } from '@edr/types';
|
||||
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, DataSource, FindOptionsOrder, FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { Repository, DataSource, FindOptionsOrder, FindOptionsWhere, ILike, In } from 'typeorm';
|
||||
import { CreateWagonDto } from './dto/create-wagon.dto';
|
||||
import { ListWagonsQueryDto } from './dto/list-wagons-query.dto';
|
||||
import { UpdateWagonDto } from './dto/update-wagon.dto';
|
||||
import { AssignWagonToTrainDto } from './dto/assign-wagon-to-train.dto';
|
||||
import { ReorderWagonsDto } from './dto/reorder-wagons.dto';
|
||||
import { BulkTransferWagonsDto } from './dto/bulk-transfer-wagons.dto';
|
||||
import { BulkSetWagonStatusDto } from './dto/bulk-set-wagon-status.dto';
|
||||
import { Wagon } from './entities/wagon.entity';
|
||||
import { WagonMovement } from './entities/wagon-movement.entity';
|
||||
import { Train } from '../trains/entities/train.entity';
|
||||
import { Yard } from '../rule-engine/entities/yard.entity';
|
||||
|
||||
@Injectable()
|
||||
export class WagonsService {
|
||||
@@ -168,6 +171,101 @@ export class WagonsService {
|
||||
return this.wagonRepo.save(wagon);
|
||||
}
|
||||
|
||||
/**
|
||||
* Relocate many wagons to one destination yard in a single transaction. Each
|
||||
* wagon whose yard actually changes gets a `wagon_movements` ledger row (kind
|
||||
* `Manual`) so the yard history stays auditable — mirrors the single-wagon
|
||||
* `update` path. Wagons already in the destination yard are skipped.
|
||||
*/
|
||||
async bulkTransfer(
|
||||
dto: BulkTransferWagonsDto,
|
||||
userId?: string | null,
|
||||
): Promise<{ moved: number }> {
|
||||
const { wagonIds, toYardId } = dto;
|
||||
if (!wagonIds.length) return { moved: 0 };
|
||||
|
||||
const yard = await this.dataSource
|
||||
.getRepository(Yard)
|
||||
.findOne({ where: { id: toYardId } });
|
||||
if (!yard) throw new NotFoundException('Destination yard not found');
|
||||
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const wagons = await queryRunner.manager.find(Wagon, {
|
||||
where: { id: In(wagonIds) },
|
||||
});
|
||||
if (wagons.length !== wagonIds.length) {
|
||||
throw new NotFoundException('One or more wagons not found');
|
||||
}
|
||||
|
||||
let moved = 0;
|
||||
for (const wagon of wagons) {
|
||||
const previousYardId = wagon.currentYardId ?? null;
|
||||
if (previousYardId === toYardId) continue;
|
||||
wagon.currentYardId = toYardId;
|
||||
// Drop the eager relation so the scalar FK wins on save (see `update`).
|
||||
wagon.currentYard = null;
|
||||
await queryRunner.manager.save(Wagon, wagon);
|
||||
await queryRunner.manager.save(
|
||||
queryRunner.manager.create(WagonMovement, {
|
||||
wagonId: wagon.id,
|
||||
fromYardId: previousYardId,
|
||||
toYardId,
|
||||
kind: WagonMovementKind.Manual,
|
||||
movedByUserId: userId ?? null,
|
||||
occurredAt: new Date(),
|
||||
}),
|
||||
);
|
||||
moved++;
|
||||
}
|
||||
|
||||
await queryRunner.commitTransaction();
|
||||
return { moved };
|
||||
} catch (err) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the same status on many wagons in one transaction (e.g. flip a batch
|
||||
* from Available to Assigned in the yard workspace). Only the `status` column
|
||||
* is touched — train assignment is managed through the assign/unassign flow.
|
||||
*/
|
||||
async bulkSetStatus(dto: BulkSetWagonStatusDto): Promise<{ updated: number }> {
|
||||
const { wagonIds, status } = dto;
|
||||
if (!wagonIds.length) return { updated: 0 };
|
||||
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const wagons = await queryRunner.manager.find(Wagon, {
|
||||
where: { id: In(wagonIds) },
|
||||
});
|
||||
if (wagons.length !== wagonIds.length) {
|
||||
throw new NotFoundException('One or more wagons not found');
|
||||
}
|
||||
|
||||
for (const wagon of wagons) {
|
||||
wagon.status = status;
|
||||
}
|
||||
await queryRunner.manager.save(Wagon, wagons);
|
||||
|
||||
await queryRunner.commitTransaction();
|
||||
return { updated: wagons.length };
|
||||
} catch (err) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
|
||||
async reorderWagons(_trainId: string, dto: ReorderWagonsDto): Promise<void> {
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
@@ -6,6 +6,11 @@ export class LoadInventoryDto {
|
||||
@IsUUID()
|
||||
wagonId!: string;
|
||||
|
||||
@ApiPropertyOptional({ format: 'uuid', description: 'Train schedule this load belongs to (recorded on the loading).' })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
trainScheduleId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Weight loaded onto the wagon (t)' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsDateString, IsNumber, IsOptional, IsString, Min } from 'class-validator';
|
||||
import { IsBoolean, IsDateString, IsNumber, IsOptional, IsString, Min } from 'class-validator';
|
||||
|
||||
/** Records a DO / release order being sent to the customer for import pickup. */
|
||||
export class ReleaseOrderDto {
|
||||
@@ -90,4 +90,13 @@ export class ReleaseOrderDto {
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
gateOutTime?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'Container bookings only: the operator chose not to weigh this truck. ' +
|
||||
'Tare/gross become optional and the container weight match is skipped. Bulk always weighs.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
weighingSkipped?: boolean;
|
||||
}
|
||||
|
||||
@@ -36,7 +36,9 @@ export const WAREHOUSE_INVENTORY_TRANSITIONS: Record<WarehouseInventoryStatus, W
|
||||
RECEIVED: ['STORED', 'READY_FOR_PICKUP'],
|
||||
// Reserve is retired from the operator flow — a stored export item advances
|
||||
// straight to loading prep. RESERVED kept for any in-flight/legacy items.
|
||||
STORED: ['RESERVED', 'READY_FOR_LOADING'],
|
||||
// READY_FOR_PICKUP is the way back out for an IMPORT item that was parked in
|
||||
// storage from READY_FOR_PICKUP; without it, Store is a one-way door.
|
||||
STORED: ['RESERVED', 'READY_FOR_LOADING', 'READY_FOR_PICKUP'],
|
||||
RESERVED: ['READY_FOR_LOADING'],
|
||||
READY_FOR_LOADING: ['LOADED'],
|
||||
LOADED: ['DISPATCHED'],
|
||||
|
||||
@@ -28,9 +28,17 @@ export class WarehouseLoading extends BaseEntity {
|
||||
@JoinColumn({ name: 'booking_id' })
|
||||
booking?: Booking | null;
|
||||
|
||||
/** Physical wagon the item was loaded onto. References freight.wagons (read-only link). */
|
||||
@Column({ name: 'wagon_id', type: 'uuid' })
|
||||
wagonId!: string;
|
||||
/**
|
||||
* Physical wagon the item was loaded onto. References freight.wagons
|
||||
* (read-only link). Nullable: a schedule-level auto-load may not resolve to
|
||||
* one wagon — the train association then lives in trainScheduleId.
|
||||
*/
|
||||
@Column({ name: 'wagon_id', type: 'uuid', nullable: true })
|
||||
wagonId?: string | null;
|
||||
|
||||
/** Train schedule the item was loaded onto (read-only link to scheduling). */
|
||||
@Column({ name: 'train_schedule_id', type: 'uuid', nullable: true })
|
||||
trainScheduleId?: string | null;
|
||||
|
||||
@Column({ name: 'loaded_at', type: 'timestamptz' })
|
||||
loadedAt!: Date;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { NotificationAudience, NotificationType } from '@edr/types';
|
||||
import { DataSource, EntityManager, IsNull } from 'typeorm';
|
||||
|
||||
@@ -150,6 +151,37 @@ export class HandoverService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reminder loop: until a self-haul handover is signed, re-send the sign
|
||||
* notification (in-app + SMS + email) every 5 minutes. One reminder per
|
||||
* booking per tick, newest unsigned handover's reference. Stops the moment
|
||||
* signForBooking() stamps signed_at.
|
||||
*
|
||||
* NB: runs in every API instance — keep a single instance in dev or the
|
||||
* customer is reminded once per instance per tick.
|
||||
*/
|
||||
@Cron(CronExpression.EVERY_5_MINUTES, { name: 'handover-sign-reminder' })
|
||||
async remindUnsignedHandovers(): Promise<void> {
|
||||
try {
|
||||
const rows: Array<{ bookingId: string; reference: string }> = await this.dataSource.query(
|
||||
`SELECT DISTINCT ON (booking_id)
|
||||
booking_id AS "bookingId", reference
|
||||
FROM freight.booking_handovers
|
||||
WHERE signed_at IS NULL
|
||||
AND deleted_at IS NULL
|
||||
AND mile_type = 'SELF_HAUL'
|
||||
ORDER BY booking_id, generated_at DESC`,
|
||||
);
|
||||
if (!rows.length) return;
|
||||
this.logger.log(`Handover sign reminder: ${rows.length} booking(s) still unsigned`);
|
||||
for (const row of rows) {
|
||||
await this.notifySignNeeded(row.bookingId, row.reference);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`Handover sign reminder tick failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sign all unsigned handovers on a booking (self-haul: before the truck leaves). */
|
||||
async signForBooking(bookingId: string, userId?: string | null): Promise<void> {
|
||||
await this.dataSource
|
||||
|
||||
@@ -77,11 +77,6 @@ export class WarehouseInventoryController {
|
||||
return this.inventoryService.bulkReceive(dto);
|
||||
}
|
||||
|
||||
@Post('load-passed-export')
|
||||
@ApiOperation({ summary: 'Bulk-load all EXPORT inventory that passed inspection (READY_FOR_LOADING)' })
|
||||
loadPassedExport(@Body('performedBy') performedBy?: string) {
|
||||
return this.inventoryService.loadPassedExport(performedBy);
|
||||
}
|
||||
|
||||
@Get('ready-to-load-export')
|
||||
@ApiOperation({ summary: 'EXPORT inventory that passed inspection and is READY_FOR_LOADING' })
|
||||
|
||||
@@ -2,7 +2,11 @@ import { BadRequestException, Injectable, Logger, NotFoundException } from '@nes
|
||||
import { Between, DataSource, EntityManager, FindManyOptions, ILike, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
|
||||
|
||||
import { deriveTradeDirection } from '../../common/derive-trade-direction.util';
|
||||
import { Booking } from '../bookings/entities/booking.entity';
|
||||
import { Cargo } from '../cargoes/entities/cargoes.entity';
|
||||
import { Company } from '../companies/entities/company.entity';
|
||||
import { Container } from '../container-management/entities/container.entity';
|
||||
import { CargoType } from '../rule-engine/entities/cargo-type.entity';
|
||||
import { InterchangeDocumentsService } from '../interchange-documents/interchange-documents.service';
|
||||
import type { InterchangeDocument } from '../interchange-documents/entities/interchange-document.entity';
|
||||
import { LastMileService } from '../last-mile/last-mile.service';
|
||||
@@ -207,6 +211,7 @@ export interface EligibleBookingRow {
|
||||
customerTin: string | null;
|
||||
customerPhone: string | null;
|
||||
containerNumber: string | null;
|
||||
sealNumbers: string | null;
|
||||
containerQuantity: number | null;
|
||||
containerPackagingType: string | null;
|
||||
cargoDescription: string | null;
|
||||
@@ -242,11 +247,6 @@ export interface BulkReceiveResult {
|
||||
results: { bookingId: string; status: string; inventoryId?: string; grnNumber?: string; reason?: string }[];
|
||||
}
|
||||
|
||||
export interface LoadPassedExportResult {
|
||||
loadedCount: number;
|
||||
skippedCount: number;
|
||||
results: { inventoryId: string; status: string; reason?: string }[];
|
||||
}
|
||||
|
||||
export interface BulkInspectResult {
|
||||
inspectedCount: number;
|
||||
@@ -774,7 +774,8 @@ export class WarehouseInventoryService {
|
||||
company.name AS "customer",
|
||||
company.tin AS "customerTin",
|
||||
COALESCE(company.contact_person_phone, company.phone, company.general_manager_phone, company.etrade_phone) AS "customerPhone",
|
||||
bc.container_numbers AS "containerNumber",
|
||||
COALESCE(bcu.unit_numbers, bc.container_numbers) AS "containerNumber",
|
||||
bcu.seal_numbers AS "sealNumbers",
|
||||
bc.container_quantity AS "containerQuantity",
|
||||
bc.container_packaging_type AS "containerPackagingType",
|
||||
(NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NOT NULL
|
||||
@@ -831,6 +832,14 @@ export class WarehouseInventoryService {
|
||||
LEFT JOIN freight.container_types container_type ON container_type.id = booking_container.container_type_id
|
||||
WHERE booking_container.booking_id = b.id AND booking_container.deleted_at IS NULL
|
||||
) bc ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT string_agg(NULLIF(unit.container_number, ''), ', ' ORDER BY unit.container_number) AS unit_numbers,
|
||||
string_agg(DISTINCT NULLIF(unit.seal_number, ''), ', ') AS seal_numbers
|
||||
FROM freight.booking_container_units unit
|
||||
JOIN freight.booking_container line
|
||||
ON line.id = unit.booking_container_id AND line.deleted_at IS NULL
|
||||
WHERE line.booking_id = b.id AND unit.deleted_at IS NULL
|
||||
) bcu ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT first_mile.id, first_mile.status, first_mile.vehicle_id
|
||||
FROM freight.first_mile first_mile
|
||||
@@ -881,11 +890,18 @@ export class WarehouseInventoryService {
|
||||
}> = [];
|
||||
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await this.validateLocation(manager, {
|
||||
const { warehouse, yard, zone } = await this.validateLocation(manager, {
|
||||
warehouseId: dto.warehouseId,
|
||||
yardId: dto.yardId,
|
||||
zoneId: dto.zoneId,
|
||||
});
|
||||
// The receive location is whatever the operator selected above — never a
|
||||
// hand-typed string. Stamp it on the truck entrance for the GRN/notes.
|
||||
if (dto.truckEntrance && !dto.truckEntrance.warehouseCodeLocation) {
|
||||
dto.truckEntrance.warehouseCodeLocation = [warehouse.code, yard.code, zone.code]
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
}
|
||||
|
||||
for (const bookingId of dto.bookingIds) {
|
||||
const skip = (reason: string) => {
|
||||
@@ -1081,46 +1097,6 @@ export class WarehouseInventoryService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Bulk-load all EXPORT inventory that passed inspection and is READY_FOR_LOADING. */
|
||||
async loadPassedExport(performedBy?: string): Promise<LoadPassedExportResult> {
|
||||
const ready = await this.inventoryRepository.findAll({ where: { status: 'READY_FOR_LOADING' } });
|
||||
const result: LoadPassedExportResult = { loadedCount: 0, skippedCount: 0, results: [] };
|
||||
|
||||
for (const item of ready) {
|
||||
const skip = (reason: string) => {
|
||||
result.skippedCount += 1;
|
||||
result.results.push({ inventoryId: item.id, status: 'SKIPPED', reason });
|
||||
};
|
||||
|
||||
if (item.inspectionStatus !== 'PASSED') { skip('Inspection not PASSED'); continue; }
|
||||
const direction = item.bookingId ? await this.getBookingDirection(item.bookingId) : null;
|
||||
if (direction !== 'EXPORT') { skip('Not an EXPORT item'); continue; }
|
||||
const bookingStatus = item.bookingId ? await this.getBookingStatus(item.bookingId) : null;
|
||||
if (bookingStatus !== 'PAID') { skip('Booking not PAID'); continue; }
|
||||
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.getRepository(WarehouseInventory).update(item.id, {
|
||||
status: 'LOADED',
|
||||
loadedAt: new Date(),
|
||||
});
|
||||
await this.activityLog.record(
|
||||
{
|
||||
activityType: 'INVENTORY_LOADED',
|
||||
inventoryId: item.id,
|
||||
warehouseId: item.warehouseId,
|
||||
description: 'Bulk loaded (passed export)',
|
||||
performedBy,
|
||||
},
|
||||
manager,
|
||||
);
|
||||
});
|
||||
|
||||
result.loadedCount += 1;
|
||||
result.results.push({ inventoryId: item.id, status: 'LOADED' });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** EXPORT inventory rows at a given status (route-derived direction), with booking detail. */
|
||||
private async exportInventoryByStatus(
|
||||
@@ -1302,6 +1278,29 @@ export class WarehouseInventoryService {
|
||||
performedBy?: string,
|
||||
): Promise<TrainLoadResult> {
|
||||
const result: TrainLoadResult = { loadedCount: 0, skippedCount: 0, results: [] };
|
||||
const [schedule]: Array<{
|
||||
trainNumber: string | null;
|
||||
origin: string | null;
|
||||
destination: string | null;
|
||||
departure: string | null;
|
||||
}> = await this.dataSource.query(
|
||||
`SELECT ts.train_number AS "trainNumber",
|
||||
COALESCE(oy.label, oy.code) AS "origin",
|
||||
COALESCE(dy.label, dy.code) AS "destination",
|
||||
ts.scheduled_departure_date AS "departure"
|
||||
FROM freight.train_schedules ts
|
||||
LEFT JOIN freight.yards oy ON oy.id = ts.origin_station_id
|
||||
LEFT JOIN freight.yards dy ON dy.id = ts.destination_station_id
|
||||
WHERE ts.id = $1 AND ts.deleted_at IS NULL`,
|
||||
[scheduleId],
|
||||
);
|
||||
const trainNote = schedule
|
||||
? `Loaded onto train ${schedule.trainNumber ?? scheduleId.slice(0, 8)}` +
|
||||
(schedule.origin || schedule.destination
|
||||
? ` (${schedule.origin ?? '?'} -> ${schedule.destination ?? '?'})`
|
||||
: '') +
|
||||
(schedule.departure ? `, departure ${new Date(schedule.departure).toISOString()}` : '')
|
||||
: undefined;
|
||||
const items = await this.trainLoadableItems(scheduleId);
|
||||
const byId = new Map(items.map((i) => [i.id, i]));
|
||||
const affectedBookingIds = new Set<string>();
|
||||
@@ -1318,7 +1317,12 @@ export class WarehouseInventoryService {
|
||||
if (!item.wagonId) { skip('No wagon allocated — allocate a wagon first'); continue; }
|
||||
|
||||
try {
|
||||
await this.load(inventoryId, { wagonId: item.wagonId, loadedBy: performedBy });
|
||||
await this.load(inventoryId, {
|
||||
wagonId: item.wagonId,
|
||||
loadedBy: performedBy,
|
||||
trainScheduleId: scheduleId,
|
||||
notes: trainNote,
|
||||
});
|
||||
result.loadedCount += 1;
|
||||
result.results.push({ inventoryId, status: 'LOADED' });
|
||||
if (item.bookingId) affectedBookingIds.add(item.bookingId);
|
||||
@@ -1597,6 +1601,8 @@ export class WarehouseInventoryService {
|
||||
status: 'UNLOADED',
|
||||
unloadedAt: now,
|
||||
arrivedAt: existing.arrivedAt ?? now,
|
||||
// Import GRN is issued automatically at train unload.
|
||||
...(existing.grnNumber ? {} : { grnNumber: this.generateGrnNumber('IMPORT', booking.id, now) }),
|
||||
});
|
||||
await this.activityLog.record({
|
||||
activityType: 'INVENTORY_UNLOADED',
|
||||
@@ -1630,6 +1636,7 @@ export class WarehouseInventoryService {
|
||||
quantity: 1,
|
||||
weight: Number(booking.weight) || 0,
|
||||
status: 'UNLOADED',
|
||||
grnNumber: this.generateGrnNumber('IMPORT', booking.id, now),
|
||||
arrivedAt: now,
|
||||
unloadedAt: now,
|
||||
notes: allocated?.rule ? `Unloaded → ${allocated.path}` : 'Unloaded from arrived import train',
|
||||
@@ -2357,6 +2364,27 @@ export class WarehouseInventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-haul = the customer's own truck collects the goods: either a truck
|
||||
* assigned via the portal (customer_truck_assigned_at), or a walk-in truck
|
||||
* registered at the gate on a booking with no EDR last-mile leg. EDR
|
||||
* last-mile bookings are never self-haul.
|
||||
*/
|
||||
private async isSelfHaulBooking(bookingId: string, manager?: EntityManager): Promise<boolean> {
|
||||
const runner = manager ?? this.dataSource;
|
||||
const [row]: Array<{ ok: number }> = await runner.query(
|
||||
`SELECT 1 AS ok
|
||||
FROM freight.bookings b
|
||||
LEFT JOIN freight.service_types st ON st.id = b.service_type_id
|
||||
WHERE b.id = $1 AND b.deleted_at IS NULL
|
||||
AND (b.customer_truck_assigned_at IS NOT NULL
|
||||
OR (NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NULL
|
||||
AND COALESCE(st.includes_last_mile, false) = false))`,
|
||||
[bookingId],
|
||||
);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
/** Record a DO / release order sent to the customer. Item stays READY_FOR_PICKUP. */
|
||||
async release(id: string, dto: ReleaseOrderDto): Promise<WarehouseInventory> {
|
||||
const item = await this.findById(id);
|
||||
@@ -2366,19 +2394,17 @@ export class WarehouseInventoryService {
|
||||
);
|
||||
}
|
||||
|
||||
const isTruckLeaving = dto.grossWeight !== undefined && Boolean(dto.gateOutTime);
|
||||
// Leaving = gate-out captured, with either a weighed gross or an explicit
|
||||
// container weighing skip (bulk always weighs).
|
||||
const isTruckLeaving =
|
||||
Boolean(dto.gateOutTime) && (dto.grossWeight !== undefined || dto.weighingSkipped === true);
|
||||
if (isTruckLeaving) {
|
||||
await this.invoices.assertClearanceAllowed(id);
|
||||
|
||||
if (item.bookingId) {
|
||||
const [truckInfo]: Array<{ customerTruckAssignedAt: string | null }> =
|
||||
await this.dataSource.query(
|
||||
`SELECT customer_truck_assigned_at AS "customerTruckAssignedAt"
|
||||
FROM freight.bookings
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
[item.bookingId],
|
||||
);
|
||||
const usesCustomerTruck = Boolean(truckInfo?.customerTruckAssignedAt);
|
||||
// Self-haul = customer collects: a truck assigned via the portal, OR a
|
||||
// walk-in truck registered at the gate on a booking with no EDR last mile.
|
||||
const usesCustomerTruck = await this.isSelfHaulBooking(item.bookingId);
|
||||
// Self-haul: the handover must be signed before the exit paper is issued.
|
||||
// Prefer the structured handover record; fall back to the legacy note.
|
||||
const handoverSigned =
|
||||
@@ -2392,7 +2418,8 @@ export class WarehouseInventoryService {
|
||||
|
||||
// Authoritative weight match: the truck's net (gross − tare) must equal the
|
||||
// total VGM cargo weight of the containers selected as loaded on it.
|
||||
if (dto.containerNumber && dto.grossWeight != null && dto.tareWeight != null) {
|
||||
// Skipped when the operator chose not to weigh (containers only).
|
||||
if (!dto.weighingSkipped && dto.containerNumber && dto.grossWeight != null && dto.tareWeight != null) {
|
||||
const selected = dto.containerNumber
|
||||
.split(/[,;\n]+/)
|
||||
.map((n) => n.trim())
|
||||
@@ -2462,13 +2489,10 @@ export class WarehouseInventoryService {
|
||||
[item.bookingId],
|
||||
);
|
||||
// Self-haul: generate the per-booking handover on first truck arrival
|
||||
// (idempotent). It must be signed before the truck leaves.
|
||||
const [selfHaul]: Array<{ ok: number }> = await manager.query(
|
||||
`SELECT 1 AS ok FROM freight.bookings
|
||||
WHERE id = $1 AND customer_truck_assigned_at IS NOT NULL AND deleted_at IS NULL`,
|
||||
[item.bookingId],
|
||||
);
|
||||
if (selfHaul) {
|
||||
// (idempotent) and notify the customer to sign it. Covers BOTH portal-
|
||||
// assigned trucks and walk-in trucks registered manually at the gate
|
||||
// (no portal assignment, no EDR last mile). Must be signed before leaving.
|
||||
if (await this.isSelfHaulBooking(item.bookingId, manager)) {
|
||||
await this.handover.ensureForArrivedTruck(item.bookingId, {}, manager);
|
||||
}
|
||||
}
|
||||
@@ -2740,11 +2764,12 @@ export class WarehouseInventoryService {
|
||||
const rows: Array<{ containerNumber: string; weightTons: string }> =
|
||||
await this.dataSource.query(
|
||||
`SELECT bcu.container_number AS "containerNumber",
|
||||
COALESCE(bcu.vgm_tons, 0) AS "weightTons"
|
||||
MAX(COALESCE(bcu.vgm_tons, 0)) AS "weightTons"
|
||||
FROM freight.booking_container_units bcu
|
||||
JOIN freight.booking_container bc
|
||||
ON bc.id = bcu.booking_container_id AND bc.deleted_at IS NULL
|
||||
WHERE bc.booking_id = $1 AND bcu.deleted_at IS NULL
|
||||
GROUP BY bcu.container_number
|
||||
ORDER BY bcu.container_number`,
|
||||
[bookingId],
|
||||
);
|
||||
@@ -3369,6 +3394,8 @@ export class WarehouseInventoryService {
|
||||
warehouseInventoryId: id,
|
||||
bookingId: item.bookingId ?? null,
|
||||
wagonId: dto.wagonId,
|
||||
// Which train this load belongs to — durable even if wagons reshuffle.
|
||||
trainScheduleId: dto.trainScheduleId ?? null,
|
||||
loadedAt: now,
|
||||
loadedBy: dto.loadedBy ?? null,
|
||||
loadedWeight,
|
||||
@@ -3407,7 +3434,7 @@ export class WarehouseInventoryService {
|
||||
});
|
||||
|
||||
// Enrich with wagon numbers (read-only lookup into the scheduling domain).
|
||||
const wagonIds = [...new Set(loadings.map((l) => l.wagonId))];
|
||||
const wagonIds = [...new Set(loadings.map((l) => l.wagonId).filter((id): id is string => Boolean(id)))];
|
||||
const wagonNumbers = new Map<string, string>();
|
||||
if (wagonIds.length > 0) {
|
||||
const rows: Array<{ id: string; wagon_number: string }> = await this.dataSource.query(
|
||||
@@ -3418,7 +3445,7 @@ export class WarehouseInventoryService {
|
||||
}
|
||||
|
||||
return loadings.map((loading) =>
|
||||
Object.assign(loading, { wagonNumber: wagonNumbers.get(loading.wagonId) ?? null }),
|
||||
Object.assign(loading, { wagonNumber: (loading.wagonId && wagonNumbers.get(loading.wagonId)) ?? null }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3632,23 +3659,25 @@ export class WarehouseInventoryService {
|
||||
.leftJoinAndSelect('inv.warehouse', 'warehouse')
|
||||
.leftJoinAndSelect('inv.yard', 'yard')
|
||||
.leftJoinAndSelect('inv.zone', 'zone')
|
||||
.leftJoin('freight.bookings', 'booking', 'booking.id = inv.booking_id')
|
||||
.leftJoin('freight.companies', 'company', 'company.id = booking.company_id')
|
||||
// Entity-class joins: TypeORM parses a raw 'freight.table' string as an
|
||||
// alias.property path ("freight" alias was not found) — runtime 500.
|
||||
.leftJoin(Booking, 'booking', 'booking.id = inv.booking_id')
|
||||
.leftJoin(Company, 'company', 'company.id = booking.company_id')
|
||||
.leftJoin(
|
||||
'freight.containers',
|
||||
Container,
|
||||
'container',
|
||||
`((inv.container_id IS NOT NULL AND container.id = inv.container_id)
|
||||
OR (inv.container_id IS NULL AND container.booking_id = inv.booking_id))
|
||||
AND container.deleted_at IS NULL`,
|
||||
)
|
||||
.leftJoin(
|
||||
'freight.cargoes',
|
||||
Cargo,
|
||||
'cargo',
|
||||
`((inv.cargo_id IS NOT NULL AND cargo.id = inv.cargo_id)
|
||||
OR (inv.cargo_id IS NULL AND cargo.booking_id = inv.booking_id))
|
||||
AND cargo.deleted_at IS NULL`,
|
||||
)
|
||||
.leftJoin('freight.cargo_types', 'cargo_type', 'cargo_type.id = cargo.cargo_type_id')
|
||||
.leftJoin(CargoType, 'cargo_type', 'cargo_type.id = cargo.cargo_type_id')
|
||||
.addSelect('booking.reference', 'b_reference')
|
||||
.addSelect('company.name', 'c_name')
|
||||
.addSelect('container.container_number', 'ct_number')
|
||||
@@ -4453,14 +4482,17 @@ export class WarehouseInventoryService {
|
||||
if (!dto.driverName?.trim()) {
|
||||
throw new BadRequestException('Driver name is required for exit inspection');
|
||||
}
|
||||
if (dto.tareWeight === undefined) {
|
||||
// Container bookings may skip the weighbridge entirely (weighingSkipped);
|
||||
// bulk always weighs.
|
||||
const weighingSkipped = dto.weighingSkipped === true;
|
||||
if (dto.tareWeight === undefined && !weighingSkipped) {
|
||||
throw new BadRequestException('Tare weight is required for truck arrival');
|
||||
}
|
||||
|
||||
const tareWeight = Number(dto.tareWeight);
|
||||
const tareWeight = dto.tareWeight === undefined ? null : Number(dto.tareWeight);
|
||||
const grossWeight = dto.grossWeight === undefined ? null : Number(dto.grossWeight);
|
||||
const computedNetWeight =
|
||||
grossWeight == null ? null : Number((grossWeight - tareWeight).toFixed(3));
|
||||
grossWeight == null || tareWeight == null ? null : Number((grossWeight - tareWeight).toFixed(3));
|
||||
const submittedNetWeight =
|
||||
dto.netWeight === undefined || computedNetWeight == null ? computedNetWeight : Number(dto.netWeight);
|
||||
|
||||
@@ -4472,7 +4504,11 @@ export class WarehouseInventoryService {
|
||||
throw new BadRequestException('Weight mismatch: net weight must equal gross weight minus tare weight.');
|
||||
}
|
||||
}
|
||||
if ((dto.grossWeight !== undefined || dto.gateOutTime || dto.netWeight !== undefined) && grossWeight == null) {
|
||||
if (
|
||||
!weighingSkipped &&
|
||||
(dto.grossWeight !== undefined || dto.gateOutTime || dto.netWeight !== undefined) &&
|
||||
grossWeight == null
|
||||
) {
|
||||
throw new BadRequestException('Gross weight is required for truck exit');
|
||||
}
|
||||
|
||||
@@ -4488,7 +4524,8 @@ export class WarehouseInventoryService {
|
||||
dto.truckType?.trim() ? `Truck Type: ${dto.truckType.trim()}` : null,
|
||||
dto.containerNumber?.trim() ? `Container Number: ${dto.containerNumber.trim()}` : null,
|
||||
dto.gateInTime ? `Gate In Time: ${dto.gateInTime}` : null,
|
||||
`Tare Weight: ${tareWeight} t`,
|
||||
weighingSkipped ? 'Weighing: SKIPPED' : null,
|
||||
tareWeight == null ? null : `Tare Weight: ${tareWeight} t`,
|
||||
grossWeight == null ? null : `Gross Weight: ${grossWeight} t`,
|
||||
computedNetWeight == null ? null : `Net Weight: ${computedNetWeight} t`,
|
||||
dto.gateOutTime ? `Gate Out Time: ${dto.gateOutTime}` : null,
|
||||
@@ -4512,6 +4549,8 @@ export class WarehouseInventoryService {
|
||||
containerNumber: this.extractExitInspectionLine(inspection, 'Container Number') || dto.containerNumber,
|
||||
gateInTime: this.extractExitInspectionLine(inspection, 'Gate In Time') || dto.gateInTime,
|
||||
tareWeight: this.extractExitInspectionNumber(inspection, 'Tare Weight') ?? dto.tareWeight,
|
||||
// The weigh/skip decision is made at arrival and sticks for the exit.
|
||||
weighingSkipped: dto.weighingSkipped || /^Weighing:\s*SKIPPED/im.test(inspection) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { Booking } from '../bookings/entities/booking.entity';
|
||||
import { Route } from '../routes/entities/route.entity';
|
||||
import { WarehouseInventory } from './entities/warehouse-inventory.entity';
|
||||
|
||||
/**
|
||||
@@ -50,9 +52,11 @@ export class WarehouseSchedulingAdapterService {
|
||||
.leftJoinAndSelect('inv.warehouse', 'warehouse')
|
||||
.leftJoinAndSelect('inv.yard', 'yard')
|
||||
.leftJoinAndSelect('inv.zone', 'zone')
|
||||
.innerJoin('freight.bookings', 'booking', 'booking.id = inv.booking_id')
|
||||
// Entity-class joins: TypeORM parses a raw 'freight.table' string as an
|
||||
// alias.property path ("freight" alias was not found) — runtime 500.
|
||||
.innerJoin(Booking, 'booking', 'booking.id = inv.booking_id')
|
||||
.innerJoin(
|
||||
'freight.routes',
|
||||
Route,
|
||||
'route',
|
||||
'route.id = :routeId AND (route.origin_yard_id = booking.origin_yard_id OR route.destination_yard_id = booking.destination_yard_id)',
|
||||
{ routeId },
|
||||
|
||||
873
apps/edr-freight-api/src/seed/data/contract-template-defaults.ts
Normal file
873
apps/edr-freight-api/src/seed/data/contract-template-defaults.ts
Normal file
@@ -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<Omit<ContractTemplateArticle, "order">>;
|
||||
}
|
||||
|
||||
const a = (id: string, title: string, body: string): Omit<ContractTemplateArticle, "order"> => ({
|
||||
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,
|
||||
];
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user