diff --git a/.github/scripts/scan.js b/.github/scripts/scan.js index 7b1924b3f..2526dff2b 100644 --- a/.github/scripts/scan.js +++ b/.github/scripts/scan.js @@ -35,23 +35,50 @@ const CONFIG = { "tailwind.config.js", "tailwind.config.ts", "tailwind.config.cjs", + "tailwind.config.mjs", "tailwind.js", "postcss.config.js", + "postcss.config.ts", "postcss.config.mjs", "postcss.config.cjs", "babel.config.js", + "babel.config.ts", + "babel.config.mjs", "babel.config.cjs", "next.config.js", + "next.config.ts", "next.config.mjs", "next.config.cjs", + "eslint.config.js", + "eslint.config.ts", + "eslint.config.mjs", + "eslint.config.cjs", "astro.config.mjs", "astro.config.js", "vite.config.js", "vite.config.ts", + "vite.config.mjs", + "vite.config.cjs", "webpack.config.js", "webpack.mix.js", + "svelte.config.js", + "nuxt.config.ts", ], + // Font files — the campaign appends JS payloads to web fonts, which are + // never executed directly but are fetched by the build and used as a + // staging blob. Binary formats, so they are read as latin1. + fontExtensions: [".woff", ".woff2", ".ttf", ".otf", ".eot"], + + // Minimum number of \uXXXX escape sequences in one file before it is + // treated as deliberately obfuscated. Legitimate source files use a + // handful at most; PolinRider samples carry 400–600. + maxLegitUnicodeEscapes: 20, + + // Any single line longer than this inside a config file means code was + // appended past the real export block. + maxLegitConfigLineLength: 1000, + // Files intentionally containing malware indicators for scanner logic/tests. // These filenames are skipped before malware rules are evaluated. ignoredFilenames: ["scan.js"], @@ -187,14 +214,166 @@ const RULES = [ }, }, + { + id: "POLINRIDER-018", + severity: "CRITICAL", + description: + "Unicode-escape string obfuscation — the payload writes plain ASCII literals such as require and https as \\u0068\\u0074\\u0074\\u0070 so that grep, code review, and GitHub diff search cannot see the API calls it makes", + test(content) { + // Only printable-ASCII escapes count. Minified vendor bundles legitimately + // carry hundreds of \uXXXX escapes, but those decode to emoji, diacritics + // and CJK ranges — escaping ASCII that could have been written literally + // has no purpose other than hiding it from a reader. + const asciiEscapes = (content.match(/\\u00[0-7][0-9a-fA-F]/g) || []).filter( + (e) => { + const code = parseInt(e.slice(2), 16); + return code >= 0x20 && code <= 0x7e; + }, + ); + return asciiEscapes.length >= CONFIG.maxLegitUnicodeEscapes + ? [ + `${asciiEscapes.length} printable-ASCII \\uXXXX escapes (threshold: ${CONFIG.maxLegitUnicodeEscapes})`, + ] + : []; + }, + }, + + { + id: "POLINRIDER-019", + severity: "CRITICAL", + description: + "Ethereum dead-drop C2 resolver — the attacker wallet's latest transaction encodes the C2 IP addresses in the 'to' field, so the C2 can be rotated without touching the implant", + test(_content, _filePath, _lines, decoded) { + const iocs = [ + "0xa322e5f3d311d3080e6f0121063e9adc2490ef1a", + "eth.blockscout.com", + "eth_getBlockByNumber", + "eth_getTransactionCount", + "eth_blockNumber", + "ethereum-rpc.publicnode.com", + "eth-mainnet.public.blastapi.io", + "1rpc.io/eth", + "eth.drpc.org", + ]; + const hay = decoded.toLowerCase(); + return iocs.filter((i) => hay.includes(i)); + }, + }, + + { + id: "POLINRIDER-020", + severity: "CRITICAL", + description: + "Remote code execution stager — fetches a payload over HTTP, XOR-decrypts it, eval()s it in-process and re-launches it as a detached hidden node -e child process that survives the build exiting", + test(_content, _filePath, _lines, decoded) { + const hits = []; + if (/spawn\s*\(\s*["']node["']\s*,\s*\[\s*["']-e["']/.test(decoded)) + hits.push('spawn("node", ["-e", ])'); + if (/detached\s*:\s*(!0|true)/.test(decoded)) + hits.push("detached child process"); + if (/stdio\s*:\s*["']ignore["']/.test(decoded)) + hits.push('stdio:"ignore" (output suppressed)'); + if (/\beval\s*\(\s*\w+\s*\+/.test(decoded)) + hits.push("eval() of concatenated remote string"); + if (/x-payload-b64/i.test(decoded)) + hits.push("x-payload-b64 C2 response header"); + // Only report when this is a genuine stager, not an isolated keyword. + return hits.length >= 2 ? hits : []; + }, + }, + + { + id: "POLINRIDER-021", + severity: "CRITICAL", + description: + "Campaign marker + Node internals capture via dot notation — the implant stores its victim/campaign ID and re-exposes require/module on globalThis so later stages can load native modules from inside an ES module", + test(_content, _filePath, _lines, decoded) { + const hits = []; + const marker = decoded.match( + /global\s*\.\s*[a-zA-Z_$]\w*\s*=\s*["']([A-Z]{0,2}\d[\d-]{3,})["']/, + ); + if (marker) hits.push(`campaign marker: "${marker[1]}"`); + if (/global\s*\.\s*\w+\s*=\s*require\b/.test(decoded)) + hits.push("global. = require"); + if (/global\s*\.\s*\w+\s*=\s*module\b/.test(decoded)) + hits.push("global. = module"); + return hits; + }, + }, + + { + id: "POLINRIDER-022", + severity: "CRITICAL", + description: + "Web font file carrying an executable payload — .woff/.woff2 files are treated as opaque binary assets by reviewers and linters, so the campaign uses them to smuggle JavaScript past code review", + test(content, filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (!CONFIG.fontExtensions.includes(ext)) return []; + + const hits = []; + const magic = content.slice(0, 4); + const expected = { ".woff": "wOFF", ".woff2": "wOF2", ".otf": "OTTO" }; + if (expected[ext] && magic !== expected[ext]) { + hits.push( + `bad magic bytes: expected "${expected[ext]}", got "${magic.replace(/[^\x20-\x7e]/g, ".")}"`, + ); + } + const codeMarkers = [ + "require(", + "eval(", + "child_process", + "global.", + "createRequire", + "process.env", + ]; + const found = codeMarkers.filter((m) => content.includes(m)); + if (found.length > 0) { + hits.push(`embedded JS markers: ${found.join(", ")}`); + } + return hits; + }, + }, + + { + id: "POLINRIDER-023", + severity: "CRITICAL", + description: + ".vscode/tasks.json configured to auto-execute on folder open — gives the campaign code execution the moment a developer opens the repo in VS Code, before any build or install command is run", + test(content, filePath) { + if (!/\.vscode[\\/]tasks\.json$/.test(filePath.replace(/\\/g, "/"))) + return []; + const hits = []; + if (/"runOn"\s*:\s*"folderOpen"/.test(content)) + hits.push('runOn: "folderOpen" (executes without user action)'); + const cmd = content.match(/"command"\s*:\s*"([^"]{0,120})"/); + if (cmd && /node|curl|wget|powershell|bash|-e\b|eval/i.test(cmd[1])) + hits.push(`command: "${cmd[1]}"`); + return hits.length >= 1 ? hits : []; + }, + }, + + { + id: "POLINRIDER-024", + severity: "HIGH", + description: + ".gitignore lists this campaign's persistence artifacts — the implant appends these entries so its own dropped files never appear in git status and the developer never sees them", + test(content, filePath) { + if (path.basename(filePath) !== ".gitignore") return []; + const lines = content.split("\n").map((l) => l.trim()); + return CONFIG.persistenceArtifacts.filter((a) => lines.includes(a)).map( + (a) => `.gitignore hides "${a}"`, + ); + }, + }, + // ── Tier 2: Behavioral / structural indicators ───────────────────────────── { id: "POLINRIDER-009", severity: "HIGH", description: - "Blockchain RPC infrastructure contact — campaign uses TRON, Aptos, and BSC as dead-drop C2 resolvers", - test(content) { + "Blockchain RPC infrastructure contact — campaign uses TRON, Aptos, BSC and Ethereum as dead-drop C2 resolvers", + test(_content, _filePath, _lines, decoded) { const endpoints = [ "trongrid.io", "aptoslabs.com", @@ -202,7 +381,7 @@ const RULES = [ "bsc-rpc.publicnode.com", "eth_getTransactionByHash", ]; - return endpoints.filter((e) => content.includes(e)); + return endpoints.filter((e) => decoded.includes(e)); }, }, @@ -210,11 +389,10 @@ const RULES = [ id: "POLINRIDER-010", severity: "HIGH", description: - "Hidden process spawn with windowsHide:true — used by InvisibleFerret / BeaverTail stager to launch detached Node.js child processes invisibly", - test(content) { - return /windowsHide\s*:\s*true/.test(content) - ? ["windowsHide:true found"] - : []; + "Hidden process spawn with windowsHide — used by InvisibleFerret / BeaverTail stager to launch detached Node.js child processes invisibly. Matches both true and its minified form !0", + test(_content, _filePath, _lines, decoded) { + const m = decoded.match(/windowsHide\s*:\s*(true|!0)/); + return m ? [`windowsHide:${m[1]} found`] : []; }, }, @@ -237,7 +415,10 @@ const RULES = [ severity: "HIGH", description: "Payload hidden after large horizontal whitespace (>100 spaces on one line) — evasion technique to hide code off-screen in editors and GitHub diff views", - test(content, _filePath, lines) { + test(_content, filePath, lines) { + // Binary assets contain long runs of 0x20 as padding — not an indicator. + if (CONFIG.fontExtensions.includes(path.extname(filePath).toLowerCase())) + return []; const hits = []; lines.forEach((line, i) => { const spaceRun = line.match(/\s{100,}/); @@ -269,6 +450,27 @@ const RULES = [ }, }, + { + id: "POLINRIDER-025", + severity: "HIGH", + description: + "Minified code appended past the end of a config file — real config files are hand-written and line-wrapped; a single multi-thousand-character line means a payload was concatenated onto the original file", + test(_content, filePath, lines) { + const base = path.basename(filePath).toLowerCase(); + if (!CONFIG.targetedFilenames.some((f) => f.toLowerCase() === base)) + return []; + const hits = []; + lines.forEach((line, i) => { + if (line.length > CONFIG.maxLegitConfigLineLength) { + hits.push( + `line ${i + 1}: ${line.length} chars (threshold: ${CONFIG.maxLegitConfigLineLength})`, + ); + } + }); + return hits; + }, + }, + { id: "POLINRIDER-014", severity: "HIGH", @@ -330,25 +532,58 @@ const RULES = [ // ─── Scanner Engine ──────────────────────────────────────────────────────────── +/** + * Resolve \uXXXX and \xXX escapes so string-matching rules see the real API + * calls. The campaign writes every literal as escapes specifically to defeat + * grep, so rules that match on plain text must run against this form. + * The decoded text is appended to the original rather than replacing it, so a + * rule can still match either representation with one pass. + */ +function deobfuscate(content) { + if (!/\\[ux]/.test(content)) return content; + const decoded = content + .replace(/\\u\{([0-9a-fA-F]{1,6})\}/g, (m, h) => { + try { + return String.fromCodePoint(parseInt(h, 16)); + } catch { + return m; + } + }) + .replace(/\\u([0-9a-fA-F]{4})/g, (_m, h) => + String.fromCharCode(parseInt(h, 16)), + ) + .replace(/\\x([0-9a-fA-F]{2})/g, (_m, h) => + String.fromCharCode(parseInt(h, 16)), + ); + return content + "\n/* --- deobfuscated --- */\n" + decoded; +} + function scanFile(filePath) { if (shouldIgnoreFile(filePath)) { return { filePath, findings: [], skipped: true }; } + // Fonts are binary. latin1 maps bytes 1:1 to chars, so magic-byte checks and + // ASCII payload searches both work without mangling the content. + const isBinary = CONFIG.fontExtensions.includes( + path.extname(filePath).toLowerCase(), + ); + let content; try { - content = fs.readFileSync(filePath, "utf8"); + content = fs.readFileSync(filePath, isBinary ? "latin1" : "utf8"); } catch (err) { return { filePath, error: err.message, findings: [] }; } const lines = content.split("\n"); + const decoded = deobfuscate(content); const findings = []; for (const rule of RULES) { let matches; try { - matches = rule.test(content, filePath, lines); + matches = rule.test(content, filePath, lines, decoded); } catch (err) { matches = [`[rule error: ${err.message}]`]; } @@ -388,6 +623,7 @@ function walkDir(dir, results = []) { } else if (entry.isFile() && !shouldIgnoreFile(full)) { const ext = path.extname(entry.name).toLowerCase(); const base = entry.name.toLowerCase(); + const rel = full.replace(/\\/g, "/"); // Scan all JS/TS config files + any file matching a targeted name const isTargetedName = CONFIG.targetedFilenames.some( @@ -399,8 +635,18 @@ function walkDir(dir, results = []) { const isJsLike = [".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"].includes( ext, ); + const isFont = CONFIG.fontExtensions.includes(ext); + const isGitignore = base === ".gitignore"; + const isVsCodeTask = /\.vscode\/tasks\.json$/.test(rel); - if (isTargetedName || isPersistenceArtifact || isJsLike) { + if ( + isTargetedName || + isPersistenceArtifact || + isJsLike || + isFont || + isGitignore || + isVsCodeTask + ) { results.push(full); } } @@ -532,10 +778,141 @@ function printReport(allResults, { json = false, outputFile = null } = {}) { return infected.length > 0; } +// ─── Self-test ───────────────────────────────────────────────────────────────── + +/** + * Runs the rule set against synthetic samples. Guards the two properties that + * matter: the live payload is still caught, and minified vendor bundles that + * legitimately contain \uXXXX escapes are still not flagged. + * Run with: node scan.js --self-test + */ +function selfTest() { + const os = require("os"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "polinrider-selftest-")); + const write = (name, body) => { + const p = path.join(tmp, name); + fs.mkdirSync(path.dirname(p), { recursive: true }); + fs.writeFileSync(p, body); + return p; + }; + + const esc = (s) => + [...s].map((c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")).join(""); + + const cases = []; + + // 1. The live payload shape: ASCII-escaped strings + ETH dead drop + stager. + cases.push({ + name: "infected postcss.config.js", + file: write( + "infected/postcss.config.js", + `export default { plugins: {} };` + + " ".repeat(300) + + `global.i="A8-4299";global.r=require;global.m=module;` + + `const http=require("${esc("http")}"),{spawn}=require("${esc("child_process")}");` + + `S="0xa322E5f3D311D3080e6f0121063e9aDC2490Ef1a".toLowerCase(),` + + `I="${esc("https://eth.blockscout.com/api")}";` + + `rc(t,"${esc("eth_getBlockByNumber")}");eval(r+o);` + + `spawn("node",["-e",r+o],{detached:!0,stdio:"${esc("ignore")}",windowsHide:!0});`, + ), + expect: true, + }); + + // 2. Clean config — must stay silent. + cases.push({ + name: "clean postcss.config.js", + file: write( + "clean/postcss.config.js", + "export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n};\n", + ), + expect: false, + }); + + // 3. Minified vendor bundle with many non-ASCII escapes — must stay silent. + cases.push({ + name: "minified vendor bundle", + file: write( + "vendor/emoji.min.js", + "var e=[" + + Array.from({ length: 400 }, (_, i) => `"\\ud83d\\ude${(i % 90) + 10}"`).join(",") + + "];", + ), + expect: false, + }); + + // 4. Font carrying an appended JS payload. + cases.push({ + name: "trojanised .woff2", + file: write( + "fonts/bad.woff2", + "wOF2" + "".repeat(64) + 'require("child_process");global.x=1;eval(a+b);', + ), + expect: true, + }); + + // 5. Clean font — correct magic, no code markers. + cases.push({ + name: "clean .woff2", + file: write("fonts/good.woff2", "wOF2" + "".repeat(200)), + expect: false, + }); + + // 6. .gitignore hiding persistence artifacts. + cases.push({ + name: ".gitignore with persistence artifacts", + file: write( + "ignore/.gitignore", + "node_modules/\ntemp_auto_push.bat\nbranch_structure.json\n", + ), + expect: true, + }); + + // 7. VS Code task auto-executing on folder open. + cases.push({ + name: ".vscode/tasks.json auto-exec", + file: write( + "vscode/.vscode/tasks.json", + JSON.stringify({ + version: "2.0.0", + tasks: [ + { + label: "build", + command: "node -e require('http')", + runOptions: { runOn: "folderOpen" }, + }, + ], + }), + ), + expect: true, + }); + + let failed = 0; + for (const c of cases) { + const { findings } = scanFile(c.file); + const detected = findings.length > 0; + const ok = detected === c.expect; + if (!ok) failed++; + const ids = findings.map((f) => f.id).join(", ") || "none"; + console.log( + ` ${ok ? `${ANSI.green}PASS${ANSI.reset}` : `${ANSI.red}FAIL${ANSI.reset}`} ` + + `${c.name} — expected ${c.expect ? "detection" : "clean"}, got: ${ids}`, + ); + } + + fs.rmSync(tmp, { recursive: true, force: true }); + console.log( + failed === 0 + ? `\n${ANSI.green}${ANSI.bold}Self-test passed (${cases.length}/${cases.length}).${ANSI.reset}\n` + : `\n${ANSI.red}${ANSI.bold}Self-test FAILED: ${failed}/${cases.length} case(s).${ANSI.reset}\n`, + ); + process.exit(failed === 0 ? 0 : 1); +} + // ─── CLI Entry Point ─────────────────────────────────────────────────────────── function main() { const args = process.argv.slice(2); + if (args.includes("--self-test")) return selfTest(); const jsonFlag = args.includes("--json"); const outputFileIdx = args.indexOf("--output"); const outputFile = outputFileIdx !== -1 ? args[outputFileIdx + 1] : null; diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bdb4c5ff5..f8a1eb68e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -10,8 +10,16 @@ permissions: contents: read jobs: + # Supply-chain gate. Every other job depends on this, so a malware detection + # blocks the entire deploy before any build, migration or container starts. + malware-scan: + name: Malware gate + uses: ./.github/workflows/malware-scan.yml + secrets: inherit + detect-changes: name: Detect changed services + needs: malware-scan runs-on: ${{ fromJson(format('["self-hosted", "{0}"]', github.ref_name)) }} outputs: matrix: ${{ steps.filter.outputs.matrix }} @@ -90,7 +98,7 @@ jobs: deploy: name: Deploy ${{ matrix.service }} - needs: detect-changes + needs: [malware-scan, detect-changes] if: ${{ needs.detect-changes.outputs.matrix != '[]' }} runs-on: ${{ fromJson(format('["self-hosted", "{0}"]', github.ref_name)) }} strategy: diff --git a/.github/workflows/malware-scan.yml b/.github/workflows/malware-scan.yml new file mode 100644 index 000000000..15ca4faeb --- /dev/null +++ b/.github/workflows/malware-scan.yml @@ -0,0 +1,161 @@ +name: Malware Scan + +# Supply-chain malware gate for the PolinRider / Famous Chollima campaign. +# +# Runs standalone on every push and pull request, and is also called by +# deploy.yml as a required first job — a detection fails this workflow, which +# blocks every downstream deploy job from starting. + +on: + push: + # dev and staging are already gated through deploy.yml's required + # malware-scan job — no need to scan those pushes twice. + branches-ignore: + - dev + - staging + pull_request: + workflow_call: + secrets: + TELEGRAM_BOT_TOKEN: + required: false + TELEGRAM_CHAT_ID: + required: false + +permissions: + contents: read + +# A detection on a ref should not be raced by a newer run of the same ref. +concurrency: + group: malware-scan-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + scan: + name: Scan for PolinRider malware + # Plain `self-hosted` — GitHub applies this label to every self-hosted + # runner automatically. The scan is host-agnostic, unlike the deploy jobs + # which pin to a branch-specific runner. + runs-on: [self-hosted, dev] + outputs: + infected: ${{ steps.scan.outputs.infected }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Verify scanner rules still work + # Fails if someone weakens a detection rule or introduces a false + # positive against minified vendor bundles. + run: node .github/scripts/scan.js --self-test + + - name: Scan repository + id: scan + run: | + set -uo pipefail + + # Actions runs this with `bash -e`, so the non-zero exit must be + # caught with `||` rather than read back from $? afterwards. + STATUS=0 + node .github/scripts/scan.js --json --output malware-report.json . || STATUS=$? + + if [ "$STATUS" -eq 0 ]; then + echo "infected=false" >> "$GITHUB_OUTPUT" + echo "No malware detected." + exit 0 + fi + + echo "infected=true" >> "$GITHUB_OUTPUT" + + # Human-readable run for the log, so the failure is legible in the UI. + node .github/scripts/scan.js . || true + exit 1 + + - name: Build alert message + id: message + if: failure() && steps.scan.outputs.infected == 'true' + run: | + set -euo pipefail + + FILES=$(jq -r '.results[].filePath' malware-report.json | head -20) + COUNT=$(jq -r '.infectedFiles' malware-report.json) + RULES=$(jq -r '[.results[].findings[] | select(.severity=="CRITICAL") | .id] | unique | join(", ")' malware-report.json) + + { + echo "message<> "$GITHUB_OUTPUT" + + - name: Notify Telegram + if: failure() && steps.scan.outputs.infected == 'true' + env: + BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + TEXT: ${{ steps.message.outputs.message }} + run: | + set -uo pipefail + + if [ -z "${BOT_TOKEN:-}" ] || [ -z "${CHAT_ID:-}" ]; then + echo "::warning::TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID not set — skipping notification." + exit 0 + fi + + # No parse_mode: the payload contains characters Telegram's Markdown + # parser would reject, and a failed notification is worse than plain text. + HTTP=$(curl -sS -o /tmp/tg.out -w '%{http_code}' \ + -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${CHAT_ID}" \ + --data-urlencode "text=${TEXT}" \ + --data-urlencode "disable_web_page_preview=true") || true + + if [ "${HTTP:-000}" != "200" ]; then + echo "::warning::Telegram notification failed (HTTP ${HTTP:-000}): $(cat /tmp/tg.out 2>/dev/null | head -c 300)" + else + echo "Telegram alert sent." + fi + rm -f /tmp/tg.out + + - name: Upload scan report + if: always() && hashFiles('malware-report.json') != '' + uses: actions/upload-artifact@v4 + with: + name: malware-report-${{ github.run_id }} + path: malware-report.json + retention-days: 30 + + - name: Job summary + if: always() + run: | + set -uo pipefail + RESULT="${{ steps.scan.outputs.infected }}" + + if [ "$RESULT" = "true" ]; then + { + echo "## 🚨 Malware detected — deployment blocked" + echo "" + echo '```' + jq -r '.results[] | .filePath, (.findings[] | " [\(.id)] \(.severity) — \(.description)")' \ + malware-report.json 2>/dev/null | head -100 || true + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + elif [ "$RESULT" = "false" ]; then + echo "## ✅ No malware detected" >> "$GITHUB_STEP_SUMMARY" + else + # The scan step never produced a verdict — treat as inconclusive + # rather than clean, so a broken scanner is never read as a pass. + echo "## ⚠️ Scan did not complete — verdict unknown" >> "$GITHUB_STEP_SUMMARY" + fi diff --git a/.gitignore b/.gitignore index 18fdae9c2..63784b865 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ RUNNING_LOCALLY.md # Generated per-shard compose file for the integration suite (it.mjs). integration/.it-shards.yaml + diff --git a/apps/edr-freight-api/.env.example b/apps/edr-freight-api/.env.example index 16ee9cd57..96af26034 100644 --- a/apps/edr-freight-api/.env.example +++ b/apps/edr-freight-api/.env.example @@ -122,3 +122,7 @@ FAYDA_SESSION_TTL_MINUTES=10 EXPIRATION_TIME=15 ALGORITHM=RS256 EMAIL_QUEUE=email_queue + +# Shared secret for service-to-service calls (payment microservice <-> freight). +# Required at boot; set ALLOW_UNAUTH_INTERNAL=true instead ONLY for local dev. +SERVICE_AUTH_TOKEN=change-me diff --git a/apps/edr-freight-api/src/app.module.ts b/apps/edr-freight-api/src/app.module.ts index d41b77dce..c98990d25 100644 --- a/apps/edr-freight-api/src/app.module.ts +++ b/apps/edr-freight-api/src/app.module.ts @@ -53,7 +53,6 @@ import { OtpModule } from "./modules/otp/otp.module"; import { HealthModule } from "./modules/health/health.module"; import { RuleEngineModule } from "./modules/rule-engine/rule-engine.module"; import { BackofficeModule } from "./modules/backoffice/backoffice.module"; -import { DemoPermissionsModule } from "./modules/demo-permissions/demo-permissions.module"; import { FreightAuthModule } from "./modules/auth/freight-auth.module"; import { EDR_FREIGHT_APPLICATION, @@ -100,6 +99,7 @@ import { MaintenanceModule } from "./modules/maintenance/maintenance.module"; import { ComplianceModule } from "./modules/compliance/compliance.module"; import { IncidentsModule } from "./modules/incidents/incidents.module"; import { ProcurementModule } from "./modules/procurement/procurement.module"; +import { FacilitiesModule } from "./modules/facilities/facilities.module"; import { GpsTrackingModule } from "./modules/gps-tracking/gps-tracking.module"; import { FirstMileModule } from "./modules/first-mile/first-mile.module"; import { LastMileModule } from "./modules/last-mile/last-mile.module"; @@ -110,6 +110,7 @@ import { AiModule } from "./modules/ai/ai.module"; import { AuditModule } from "./modules/audit/audit.module"; import { LoggerMiddleware } from "./logger.middleware"; import { LoginAudienceMiddleware } from "./modules/auth/login-audience.middleware"; +import { PositionTypePermissionsCache } from "./common/position-type-permissions.cache"; if (!process.env.APPLICATION_NAME) { process.env.APPLICATION_NAME = "freight"; @@ -219,7 +220,6 @@ if (!process.env.APPLICATION_NAME) { HealthModule, RuleEngineModule, BackofficeModule, - DemoPermissionsModule, FreightAuthModule, PaymentModule, //New Modules @@ -239,6 +239,7 @@ if (!process.env.APPLICATION_NAME) { ComplianceModule, IncidentsModule, ProcurementModule, + FacilitiesModule, GpsTrackingModule, FirstMileModule, LastMileModule, @@ -273,6 +274,9 @@ if (!process.env.APPLICATION_NAME) { ApprovedFirstLastMileDemoBookingsSeeder, PaidImportExportMileDemoSeeder, LoginAudienceMiddleware, + // Feeds position-TYPE grants to the synchronous permission checks — without + // it, staff whose permissions live on their position type resolve to none. + PositionTypePermissionsCache, ], }) export class AppModule implements OnApplicationBootstrap { diff --git a/apps/edr-freight-api/src/common/booking-guards.ts b/apps/edr-freight-api/src/common/booking-guards.ts index 854594ffc..49bd31c61 100644 --- a/apps/edr-freight-api/src/common/booking-guards.ts +++ b/apps/edr-freight-api/src/common/booking-guards.ts @@ -1,7 +1,11 @@ import { applyDecorators, UseGuards } from '@nestjs/common'; import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; -import { FreightPermissionGuard } from './freight-permission.guard'; +import { + FreightPermissionGuard, + MixedAudienceGuard, + PortalCustomerGuard, +} from './freight-permission.guard'; import { FREIGHT_PERMS } from '../seed/freight-permissions.registry'; export const BookingStaff = (permission: string | string[]) => @@ -18,8 +22,30 @@ export const BookingStaff = (permission: string | string[]) => * Read-only reference data (yard dropdowns, search filters): any signed-in * staff. Menu/page visibility stays permission-gated in the frontend — this * only lets forms populate their lookups. + * Deprecated for new routes — it never checked the caller was staff. Prefer + * BookingStaff() or MixedAudience(); kept for routes not yet swept. */ -export const StaffReference = () => applyDecorators(UseGuards(JwtGuard)); +export const StaffReference = () => + applyDecorators(UseGuards(JwtGuard, FreightPermissionGuard([]))); + +/** Portal routes: customer accounts only; ownership scoping stays in services. */ +export const PortalCustomer = () => + applyDecorators(UseGuards(JwtGuard, PortalCustomerGuard)); + +/** + * Routes both audiences call (sign, shared document reads, handover): staff + * need one of the given permissions, customers pass through to the service's + * ownership checks. + */ +export const MixedAudience = (permission: string | string[]) => + applyDecorators( + UseGuards( + JwtGuard, + MixedAudienceGuard( + Array.isArray(permission) ? permission : [permission], + ), + ), + ); export const BookingView = () => BookingStaff(FREIGHT_PERMS.bookings.view); @@ -31,6 +57,18 @@ export const BookingView = () => BookingStaff(FREIGHT_PERMS.bookings.view); export const BookingDocReviewAlert = () => BookingStaff(FREIGHT_PERMS.bookings.docReviewAlert); +/** Staff wagon-cancellation history list (admin side). */ +export const WagonCancellationView = () => + BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationView); + +/** Staff void of a customer's pending (fee-unpaid) wagon cancellation. */ +export const WagonCancellationVoid = () => + BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationVoid); + +/** Staff rebook of a customer's wagon-cancellation credit on their behalf. */ +export const WagonCancellationRebook = () => + BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationRebook); + export const TrainSchedulingView = () => BookingStaff(FREIGHT_PERMS.trainScheduling.view); diff --git a/apps/edr-freight-api/src/common/freight-permission.guard.ts b/apps/edr-freight-api/src/common/freight-permission.guard.ts index 68def6440..db6275c07 100644 --- a/apps/edr-freight-api/src/common/freight-permission.guard.ts +++ b/apps/edr-freight-api/src/common/freight-permission.guard.ts @@ -8,7 +8,19 @@ import { } from '@nestjs/common'; import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type'; -import { hasFreightPermission } from './freight-permission.util'; +import { hasFreightPermission, isSuperAdmin } from './freight-permission.util'; + +// String literals on purpose (same reasoning as login-audience.middleware.ts): +// the values are wire-format constants from iam.users.user_type, and importing +// the vendored enum couples us to its package layout for no gain. +const CUSTOMER_USER_TYPES = ['individual', 'external_organization']; + +const userTypeOf = (user: TCurrentUser): string | undefined => + (user as { userType?: string }).userType; + +/** Staff routes are employee-only; a missing userType (stale session) also fails. */ +const isEmployee = (user: TCurrentUser): boolean => + userTypeOf(user) === 'employee' || isSuperAdmin(user); export function FreightPermissionGuard( permissions: string[], @@ -19,11 +31,14 @@ export function FreightPermissionGuard( const request = context.switchToHttp().getRequest<{ user?: TCurrentUser }>(); const user = request.user; - if (!permissions?.length) return true; if (!user) { throw new UnauthorizedException('Authentication required'); } + if (!isEmployee(user)) { + throw new ForbiddenException('Staff account required'); + } + if (!permissions?.length) return true; if (permissions.some((p) => hasFreightPermission(user, p))) { return true; } @@ -36,3 +51,57 @@ export function FreightPermissionGuard( return FreightPermissionsGuard; } + +/** Portal routes: customer accounts only (individual / external organization). */ +@Injectable() +export class PortalCustomerGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const request = context.switchToHttp().getRequest<{ user?: TCurrentUser }>(); + const user = request.user; + + if (!user) { + throw new UnauthorizedException('Authentication required'); + } + if (!CUSTOMER_USER_TYPES.includes(userTypeOf(user) ?? '')) { + throw new ForbiddenException('Customer account required'); + } + return true; + } +} + +/** + * Routes both audiences legitimately call (contract sign, shared document + * reads, warehouse handover). Staff callers must hold one of the given + * permissions; customer callers pass here and are scoped by the service's + * ownership checks. + */ +export function MixedAudienceGuard(permissions: string[]): Type { + @Injectable() + class MixedAudiencesGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const request = context.switchToHttp().getRequest<{ user?: TCurrentUser }>(); + const user = request.user; + + if (!user) { + throw new UnauthorizedException('Authentication required'); + } + if (CUSTOMER_USER_TYPES.includes(userTypeOf(user) ?? '')) { + return true; + } + if (!isEmployee(user)) { + throw new ForbiddenException('Unrecognized account type'); + } + if ( + !permissions?.length || + permissions.some((p) => hasFreightPermission(user, p)) + ) { + return true; + } + throw new ForbiddenException( + `Missing permission. Required one of: ${permissions.join(', ')}`, + ); + } + } + + return MixedAudiencesGuard; +} diff --git a/apps/edr-freight-api/src/common/freight-permission.util.spec.ts b/apps/edr-freight-api/src/common/freight-permission.util.spec.ts index d0d01535a..f3931f78a 100644 --- a/apps/edr-freight-api/src/common/freight-permission.util.spec.ts +++ b/apps/edr-freight-api/src/common/freight-permission.util.spec.ts @@ -1,6 +1,9 @@ import { assertCanApproveContractStep, canEditContractStep, + collectPermissionKeys, + hasFreightPermission, + setPositionTypePermissionResolver, } from './freight-permission.util'; import { FREIGHT_PERMS } from '../seed/freight-permissions.registry'; @@ -49,3 +52,72 @@ describe('canEditContractStep (strict per-step edit gate)', () => { ); }); }); + +/** + * The GL lockout regression: positions created through the admin UI keep their + * grants on the position TYPE, and the JWT only ever snapshots DIRECT position + * permissions. Without the type resolver those staff resolved to zero + * permissions, so every gated route rejected them — which is what kept GL + * officers out of their own clearance detail pages. + */ +describe('collectPermissionKeys — position-type grants', () => { + const CLEARANCE = FREIGHT_PERMS.contracts.clearanceReview; + + afterEach(() => { + setPositionTypePermissionResolver(() => []); + }); + + const glOfficer = { + roles: [], + permissions: [], + employee: { + position: { + permissions: [], // admin-created position carries NO direct grants + positionType: { key: 'commercial-global-logistics-(et)-officer' }, + }, + }, + }; + + it('resolves permissions carried by the position type', () => { + setPositionTypePermissionResolver((key) => + key === 'commercial-global-logistics-(et)-officer' ? [CLEARANCE] : [], + ); + + expect(collectPermissionKeys(glOfficer)).toContain(CLEARANCE); + expect(hasFreightPermission(glOfficer, CLEARANCE)).toBe(true); + }); + + it('handles the array-shaped employee payload too', () => { + setPositionTypePermissionResolver(() => [CLEARANCE]); + + const arrayShaped = { + roles: [], + permissions: [], + employee: [ + { + positions: [ + { permissions: [], positionType: { key: 'djibouti-gl-officer' } }, + ], + }, + ], + }; + + expect(hasFreightPermission(arrayShaped, CLEARANCE)).toBe(true); + }); + + it('still rejects when neither the position nor its type grants it', () => { + setPositionTypePermissionResolver(() => []); + + expect(hasFreightPermission(glOfficer, CLEARANCE)).toBe(false); + }); + + it('keeps direct position permissions working with no resolver installed', () => { + const direct = { + roles: [], + permissions: [], + employee: { position: { permissions: [{ key: CLEARANCE }] } }, + }; + + expect(hasFreightPermission(direct, CLEARANCE)).toBe(true); + }); +}); diff --git a/apps/edr-freight-api/src/common/freight-permission.util.ts b/apps/edr-freight-api/src/common/freight-permission.util.ts index 56c0e77c2..bc98a6df4 100644 --- a/apps/edr-freight-api/src/common/freight-permission.util.ts +++ b/apps/edr-freight-api/src/common/freight-permission.util.ts @@ -42,12 +42,41 @@ export function isFreightApprovalAdmin(user: MeLikeUser | null | undefined): boo return isSuperAdmin(user) || isOrganizationAdmin(user); } -/** Flat permission keys from JWT / session user (roles + position permissions). */ +/** + * Permissions carried by a position TYPE rather than the position itself. + * + * The JWT snapshots only DIRECT position permissions, so type-level grants — + * which is where admin-created positions keep theirs — are absent from the + * token entirely. This resolver is installed at startup + * (see `PositionTypePermissionsCache`) so the synchronous permission checks + * below can still see them. Left as a no-op resolver until then, which + * degrades to the old position-only behaviour rather than throwing. + */ +let positionTypePermissionResolver: (positionTypeKey: string) => string[] = () => + []; + +export function setPositionTypePermissionResolver( + resolver: (positionTypeKey: string) => string[], +): void { + positionTypePermissionResolver = resolver; +} + +/** + * Flat permission keys from JWT / session user: roles, position permissions, + * and the grants held by each position's TYPE. + */ export function collectPermissionKeys(user: MeLikeUser | null | undefined): string[] { if (!user) return []; const keys = new Set(); + const addTypePermissions = (positionType: PositionTypeLike | null | undefined) => { + if (!positionType?.key) return; + for (const key of positionTypePermissionResolver(positionType.key)) { + keys.add(key); + } + }; + for (const p of user.permissions ?? []) { if (p.key) keys.add(p.key); } @@ -63,6 +92,7 @@ export function collectPermissionKeys(user: MeLikeUser | null | undefined): stri for (const p of pos.permissions ?? []) { if (p.key) keys.add(p.key); } + addTypePermissions(pos.positionType); } } return [...keys]; @@ -71,6 +101,7 @@ export function collectPermissionKeys(user: MeLikeUser | null | undefined): stri for (const p of employee.position?.permissions ?? []) { if (p.key) keys.add(p.key); } + addTypePermissions(employee.position?.positionType); for (const delegated of employee.delegatedPositions ?? []) { for (const p of delegated.permissions ?? []) { if (p.key) keys.add(p.key); diff --git a/apps/edr-freight-api/src/common/guards/service-auth.guard.ts b/apps/edr-freight-api/src/common/guards/service-auth.guard.ts index 9165e54d5..2d2863dd5 100644 --- a/apps/edr-freight-api/src/common/guards/service-auth.guard.ts +++ b/apps/edr-freight-api/src/common/guards/service-auth.guard.ts @@ -20,8 +20,12 @@ export class ServiceAuthGuard implements CanActivate { private warned = false; constructor() { - if (!this.token && process.env.NODE_ENV === "production") { - throw new Error("SERVICE_AUTH_TOKEN must be set in production"); + // Fail closed everywhere: a missing secret must never silently open the + // internal payment surface. Local dev can opt out explicitly. + if (!this.token && process.env.ALLOW_UNAUTH_INTERNAL !== "true") { + throw new Error( + "SERVICE_AUTH_TOKEN must be set (or ALLOW_UNAUTH_INTERNAL=true for local dev)", + ); } } @@ -29,7 +33,7 @@ export class ServiceAuthGuard implements CanActivate { if (!this.token) { if (!this.warned) { this.logger.warn( - "SERVICE_AUTH_TOKEN unset — internal endpoints are UNGUARDED (dev only)", + "ALLOW_UNAUTH_INTERNAL=true — internal endpoints are UNGUARDED (dev only)", ); this.warned = true; } diff --git a/apps/edr-freight-api/src/common/last-mile-charge.util.spec.ts b/apps/edr-freight-api/src/common/last-mile-charge.util.spec.ts index e2ff1bfd9..e60bf4f4e 100644 --- a/apps/edr-freight-api/src/common/last-mile-charge.util.spec.ts +++ b/apps/edr-freight-api/src/common/last-mile-charge.util.spec.ts @@ -85,6 +85,48 @@ describe('computeLastMileCharge', () => { expect(charge).toMatchObject({ mode: 'BULK', total: 60 * 26 * 25, currency: 'ETB' }); }); + it('picks the bulk rate whose distance band holds the km (half-open boundary)', () => { + const bulkNear = rate({ rateUnit: 'PER_TON_KM', rateValue: 30, minKm: 0, maxKm: 30 }); + const bulkFar = rate({ rateUnit: 'PER_TON_KM', rateValue: 22, minKm: 30, maxKm: null }); + const near = computeLastMileCharge({ + freightType: 'BULK', + tons: 10, + km: 12, + containers: [], + liveRates: [bulkNear, bulkFar], + }); + expect(near).toMatchObject({ mode: 'BULK', total: 10 * 12 * 30 }); + const boundary = computeLastMileCharge({ + freightType: 'BULK', + tons: 10, + km: 30, + containers: [], + liveRates: [bulkNear, bulkFar], + }); + expect(boundary).toMatchObject({ total: 10 * 30 * 22 }); + }); + + it('bulk falls back to the legacy bandless rate when no band holds the km, null when nothing covers it', () => { + const bulkNear = rate({ rateUnit: 'PER_TON_KM', rateValue: 30, minKm: 0, maxKm: 30 }); + const fallback = computeLastMileCharge({ + freightType: 'BULK', + tons: 10, + km: 50, + containers: [], + liveRates: [bulkNear, bulkRate], // bulkRate has no band + }); + expect(fallback).toMatchObject({ total: 10 * 50 * 25 }); + expect( + computeLastMileCharge({ + freightType: 'BULK', + tons: 10, + km: 50, + containers: [], + liveRates: [bulkNear], + }), + ).toBeNull(); + }); + it('returns null on mixed currencies, unknown km, and uncovered freight types', () => { const usd40 = rate({ ...band40a, currency: 'USD' }); expect( diff --git a/apps/edr-freight-api/src/common/last-mile-charge.util.ts b/apps/edr-freight-api/src/common/last-mile-charge.util.ts index 706e21238..055e8e5f9 100644 --- a/apps/edr-freight-api/src/common/last-mile-charge.util.ts +++ b/apps/edr-freight-api/src/common/last-mile-charge.util.ts @@ -30,10 +30,12 @@ const round2 = (n: number): number => Math.round(n * 100) / 100; /** * Price a last-mile leg off the LIVE rate rules. Pure — pass the live rates in. * - * BULK: one PER_TON_KM rate → price = tons × km × rate. + * BULK: the PER_TON_KM rate whose distance band holds the km (a legacy + * bandless row — NULL minKm — is the fallback and prices every distance) → + * price = tons × km × rate. * CONTAINER: per container size, the PER_KM rate whose distance band holds the - * km (bands are half-open [minKm, maxKm), NULL maxKm = open-ended) → price = - * km × rate × quantity, summed across sizes. + * km → price = km × rate × quantity, summed across sizes. + * Bands are half-open [minKm, maxKm), NULL maxKm = open-ended. * * Returns null whenever the rules don't fully cover the shipment (no rate, a * container size without a matching band, mixed currencies, km/tons unknown) — @@ -56,7 +58,15 @@ export function computeLastMileCharge(input: { if (freightType === 'BULK') { if (!tons || tons <= 0) return null; - const rate = candidates.find((r) => r.rateUnit === 'PER_TON_KM'); + const bulkRates = candidates.filter((r) => r.rateUnit === 'PER_TON_KM'); + const rate = + bulkRates.find( + (r) => + r.minKm !== null && + r.minKm !== undefined && + Number(r.minKm) <= km && + (r.maxKm === null || r.maxKm === undefined || km < Number(r.maxKm)), + ) ?? bulkRates.find((r) => r.minKm === null || r.minKm === undefined); if (!rate) return null; const unitRate = Number(rate.rateValue); const amount = round2(tons * km * unitRate); diff --git a/apps/edr-freight-api/src/common/position-type-permissions.cache.ts b/apps/edr-freight-api/src/common/position-type-permissions.cache.ts new file mode 100644 index 000000000..2848ed0b2 --- /dev/null +++ b/apps/edr-freight-api/src/common/position-type-permissions.cache.ts @@ -0,0 +1,83 @@ +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import { InjectDataSource } from '@nestjs/typeorm'; +import { DataSource } from 'typeorm'; + +import { setPositionTypePermissionResolver } from './freight-permission.util'; + +/** + * Permissions granted to a position TYPE (`iam.position_type_permissions`). + * + * A position type is the platform's notion of a role, and positions created + * through the admin UI carry their grants there rather than on the position + * itself. The JWT only ever snapshots DIRECT position permissions, so those + * grants are invisible to `collectPermissionKeys` — staff on such a position + * resolve to zero permissions and every permission-gated route rejects them. + * + * The permission checks (`hasFreightPermission`, `FreightPermissionGuard`) are + * synchronous and sit on the request path, so the mapping is held in memory and + * refreshed periodically rather than queried per request. The dataset is tiny + * (tens of types, a few hundred rows), so a full reload is cheaper than any + * incremental scheme. + */ +@Injectable() +export class PositionTypePermissionsCache implements OnModuleInit { + private readonly logger = new Logger(PositionTypePermissionsCache.name); + + /** position_type key → permission keys. Empty until the first load lands. */ + private byPositionTypeKey = new Map(); + + // ponytail: fixed 5-min refresh, no invalidation hook. A permission granted + // in the admin UI takes up to one interval to reach the guards. Wire the + // grant mutation to call `refresh()` if that lag ever matters. + private static readonly REFRESH_INTERVAL_MS = 5 * 60 * 1000; + + constructor(@InjectDataSource() private readonly dataSource: DataSource) {} + + async onModuleInit(): Promise { + await this.refresh(); + // Hand the lookup to the permission utils, whose checks are synchronous and + // therefore cannot query IAM themselves. + setPositionTypePermissionResolver((positionTypeKey) => + this.get(positionTypeKey), + ); + const timer = setInterval(() => { + void this.refresh(); + }, PositionTypePermissionsCache.REFRESH_INTERVAL_MS); + // Never hold the process open for a cache refresh. + timer.unref?.(); + } + + /** Permission keys for a position-type key ([] when unknown/not loaded). */ + get(positionTypeKey: string | undefined | null): string[] { + if (!positionTypeKey) return []; + return this.byPositionTypeKey.get(positionTypeKey) ?? []; + } + + /** Reload the whole mapping. Failures keep the previous snapshot in place. */ + async refresh(): Promise { + try { + const rows: { position_type_key: string; permission_key: string }[] = + await this.dataSource.query( + `SELECT pt.key AS position_type_key, perm.key AS permission_key + FROM iam.position_type_permissions ptp + JOIN iam.position_types pt ON pt.id = ptp.position_type_id + JOIN iam.permissions perm ON perm.id = ptp.permission_id`, + ); + + const next = new Map(); + for (const row of rows) { + if (!row.position_type_key || !row.permission_key) continue; + const keys = next.get(row.position_type_key); + if (keys) keys.push(row.permission_key); + else next.set(row.position_type_key, [row.permission_key]); + } + this.byPositionTypeKey = next; + } catch (err) { + // iam schema unreachable — keep serving the previous snapshot rather than + // dropping every type-derived permission and locking staff out. + this.logger.warn( + `Position-type permission refresh failed: ${(err as Error).message}`, + ); + } + } +} diff --git a/apps/edr-freight-api/src/migrations/3300000000000-BookingWagonCancellations.ts b/apps/edr-freight-api/src/migrations/3300000000000-BookingWagonCancellations.ts new file mode 100644 index 000000000..0d506cff0 --- /dev/null +++ b/apps/edr-freight-api/src/migrations/3300000000000-BookingWagonCancellations.ts @@ -0,0 +1,65 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +/** + * Partial wagon cancellation with rebooking credit. + * + * One row per cancellation cycle on a PAID booking: the customer asks to drop + * N wagons, pays a per-wagon cancellation fee (rates row + * rate_type = 'CANCELLATION_FEE', rate_unit = 'PER_WAGON'), and the dropped cargo becomes a + * rebookable credit. The credit is redeemed by creating a fresh booking + * through the normal under-contract create path (which re-checks contract + * validity and caps), immediately marked PAID — the freight was already paid + * on the original booking, only the fee is new money. + * + * cancelled_quantities carries what was cut, in the booking's own terms: + * `{ bulkTons }` for bulk, `{ bySize: { "20": 4, "40": 3 } }` for container. + * Container numbers are NOT stored here — they are recovered at rebook time + * from the unit rows the reduction soft-deleted (same hybrid pattern as + * RemainderPlacementService). + */ +export class BookingWagonCancellations3300000000000 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE IF NOT EXISTS freight.booking_wagon_cancellations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + booking_id uuid NOT NULL REFERENCES freight.bookings(id), + rebooked_booking_id uuid REFERENCES freight.bookings(id), + wagons_cancelled numeric(6,2) NOT NULL CHECK (wagons_cancelled > 0), + weight_tons numeric(12,3) NOT NULL DEFAULT 0, + cancelled_quantities jsonb NOT NULL, + credit_amount numeric(14,2) NOT NULL DEFAULT 0, + fee_rate_id uuid REFERENCES freight.rates(id), + fee_amount numeric(14,2) NOT NULL CHECK (fee_amount >= 0), + fee_currency varchar(8) NOT NULL DEFAULT 'ETB', + fee_invoice_id uuid REFERENCES freight.invoices(id), + fee_paid_at timestamptz, + status varchar(30) NOT NULL DEFAULT 'FEE_PENDING', + reason text, + requested_by_user_id uuid, + rebooked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz + ) + `); + // One open (fee-unpaid) cancellation per booking — closes the double-click + // race without app-level locking. + await queryRunner.query(` + CREATE UNIQUE INDEX IF NOT EXISTS uq_open_wagon_cancellation_per_booking + ON freight.booking_wagon_cancellations (booking_id) + WHERE status = 'FEE_PENDING' AND deleted_at IS NULL + `); + await queryRunner.query(` + CREATE INDEX IF NOT EXISTS idx_bwc_booking + ON freight.booking_wagon_cancellations (booking_id) + `); + await queryRunner.query(` + CREATE INDEX IF NOT EXISTS idx_bwc_status + ON freight.booking_wagon_cancellations (status) + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_wagon_cancellations`); + } +} diff --git a/apps/edr-freight-api/src/modules/ai/ai.controller.ts b/apps/edr-freight-api/src/modules/ai/ai.controller.ts index eb87fe97d..d71795066 100644 --- a/apps/edr-freight-api/src/modules/ai/ai.controller.ts +++ b/apps/edr-freight-api/src/modules/ai/ai.controller.ts @@ -1,15 +1,13 @@ import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common'; import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { Public } from '@edr/api-common'; +import { BookingStaff } from '../../common/booking-guards'; import { AiBookingRequestDto } from './dto/ai-booking-request.dto'; import { AiBookingResult } from './types/ai-booking-result.type'; import { MockAiService } from './mock-ai.service'; +import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; -// @Public() — TODO: swap for real guard when this leaves dev/testing. -// Safe while public: extracts + validates text only, never creates or -// dispatches anything. -@Public() +@BookingStaff(FREIGHT_PERMS.bookings.view) @ApiTags('AI Assistant (mock)') @Controller('ai') export class AiController { diff --git a/apps/edr-freight-api/src/modules/auth/freight-me.service.ts b/apps/edr-freight-api/src/modules/auth/freight-me.service.ts index 006b482f4..6bcfd964d 100644 --- a/apps/edr-freight-api/src/modules/auth/freight-me.service.ts +++ b/apps/edr-freight-api/src/modules/auth/freight-me.service.ts @@ -35,10 +35,57 @@ export class FreightMeService { } } + /** + * Permissions granted to the position's TYPE (`iam.position_type_permissions`). + * A position type is the platform's notion of a role, and admin-created + * positions carry their grants there rather than on the position itself — but + * the JWT only ever snapshots direct position permissions. Without this, staff + * on such a position resolve to zero permissions and every permission-gated + * route rejects them (this is what locked GL officers out of their clearance + * detail pages). Resolved live from IAM, same as the position type above. + */ + private async lookupPositionTypePermissions( + positionId: string | undefined, + ): Promise { + if (!positionId) return []; + try { + const rows: { key: string }[] = await this.dataSource.query( + `SELECT DISTINCT perm.key + FROM iam.positions p + JOIN iam.position_type_permissions ptp + ON ptp.position_type_id = p.position_type_id + JOIN iam.permissions perm ON perm.id = ptp.permission_id + WHERE p.id = $1`, + [positionId], + ); + return rows.map((r) => r.key).filter(Boolean); + } catch { + return []; // iam schema unreachable — degrade to position-only permissions + } + } + async getEnrichedProfile(user: TCurrentUser) { - const positionType = await this.lookupPositionType( - user.employee?.position?.id, + const positionId = user.employee?.position?.id; + const [positionType, positionTypePermissionKeys] = await Promise.all([ + this.lookupPositionType(positionId), + this.lookupPositionTypePermissions(positionId), + ]); + + // Merge the type-level grants into the position's own permission list so + // BOTH consumers see them: `collectPermissionKeys` below, and the + // backoffice's `getPermissionKeys`, which walks this same nested array. + const positionPermissions = [ + ...(user.employee?.position?.permissions ?? []), + ]; + const seenPermissionKeys = new Set( + positionPermissions.map((p) => p?.key).filter(Boolean), ); + for (const key of positionTypePermissionKeys) { + if (!seenPermissionKeys.has(key)) { + seenPermissionKeys.add(key); + positionPermissions.push({ key } as (typeof positionPermissions)[number]); + } + } const employee = user.employee ? [ @@ -56,7 +103,7 @@ export class FreightMeService { name: user.employee.position.name, isDelegate: user.employee.position.isDelegate, parentPositionId: user.employee.position.parentPositionId, - permissions: user.employee.position.permissions ?? [], + permissions: positionPermissions, positionType, }, ] @@ -65,7 +112,15 @@ export class FreightMeService { ] : []; - const permissionKeys = collectPermissionKeys(user); + // `collectPermissionKeys` reads the raw token (position-level only), so + // union the type-level grants in — the backoffice prefers this flat list + // over the nested array and would otherwise still see none of them. + const permissionKeys = [ + ...new Set([ + ...collectPermissionKeys(user), + ...positionTypePermissionKeys, + ]), + ]; return { id: user.id, diff --git a/apps/edr-freight-api/src/modules/auth/list-users.controller.ts b/apps/edr-freight-api/src/modules/auth/list-users.controller.ts index e7fbfd771..e2f06f065 100644 --- a/apps/edr-freight-api/src/modules/auth/list-users.controller.ts +++ b/apps/edr-freight-api/src/modules/auth/list-users.controller.ts @@ -3,7 +3,8 @@ import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import { ListUsersQueryDto } from './dto/list-users-query.dto'; import { ListUsersService } from './list-users.service'; -import { StaffReference } from '../../common/booking-guards'; +import { BookingStaff } from '../../common/booking-guards'; +import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; @ApiTags('auth') @Controller('staff/users') @@ -12,7 +13,7 @@ export class ListUsersController { constructor(private readonly service: ListUsersService) {} @Get() - @StaffReference() + @BookingStaff(FREIGHT_PERMS.staff.users.view) @ApiOperation({ summary: 'List IAM users (paginated) for backoffice pickers', }) diff --git a/apps/edr-freight-api/src/modules/backoffice/backoffice.controller.ts b/apps/edr-freight-api/src/modules/backoffice/backoffice.controller.ts index b3305ba68..d25fb74ba 100644 --- a/apps/edr-freight-api/src/modules/backoffice/backoffice.controller.ts +++ b/apps/edr-freight-api/src/modules/backoffice/backoffice.controller.ts @@ -10,18 +10,19 @@ import { } from "@nestjs/common"; import { ApiOperation, ApiTags } from "@nestjs/swagger"; -import { FreightAdmin } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { BackofficeService } from "./backoffice.service"; import { CreateOrganizationUserDto } from "./dto/create-organization-user.dto"; import { UpdateEmployeeUserRolesDto } from "./dto/update-employee-user-roles.dto"; @ApiTags("backoffice") @Controller("backoffice") -@FreightAdmin() export class BackofficeController { constructor(private readonly backofficeService: BackofficeService) {} @Post("organizations/:orgId/users") + @BookingStaff([FREIGHT_PERMS.staff.employeeRegistration.create, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Create an organization user without assigning positions" }) createOrganizationUser( @Param("orgId", ParseUUIDPipe) organizationId: string, @@ -31,6 +32,7 @@ export class BackofficeController { } @Get("organizations/:orgId/employees") + @BookingStaff([FREIGHT_PERMS.staff.roleAssignment.view, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Get deduplicated organization employees for backoffice" }) getOrganizationEmployees( @Param("orgId", ParseUUIDPipe) organizationId: string, @@ -44,6 +46,7 @@ export class BackofficeController { } @Get("organizations/:orgId/employee-users/:userId/roles") + @BookingStaff([FREIGHT_PERMS.staff.roleAssignment.view, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Get org-scoped roles assigned to an employee user" }) getEmployeeUserRoles( @Param("orgId", ParseUUIDPipe) organizationId: string, @@ -53,6 +56,7 @@ export class BackofficeController { } @Put("organizations/:orgId/employee-users/:userId/roles") + @BookingStaff([FREIGHT_PERMS.staff.roleAssignment.replace, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Replace org-scoped roles assigned to an employee user" }) replaceEmployeeUserRoles( @Param("orgId", ParseUUIDPipe) organizationId: string, diff --git a/apps/edr-freight-api/src/modules/billing/billing.controller.ts b/apps/edr-freight-api/src/modules/billing/billing.controller.ts index 49772316a..d72528310 100644 --- a/apps/edr-freight-api/src/modules/billing/billing.controller.ts +++ b/apps/edr-freight-api/src/modules/billing/billing.controller.ts @@ -12,14 +12,15 @@ import type { Response } from "express"; import { CurrentUser } from "@edr/api-common"; import type { TCurrentUser } from "@tria-plc/api-common/modules/auth/types/current-user.type"; -import { BookingView } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { UserTradeAccessService } from "../user-trade-access/user-trade-access.service"; import { BillingService } from "./billing.service"; import { FilterInvoiceDto } from "./dto/filter-invoice.dto"; @ApiTags("billing") @Controller("billing") -@BookingView() +@BookingStaff(FREIGHT_PERMS.invoices.view) @ApiBearerAuth() export class BillingController { constructor( @@ -51,6 +52,7 @@ export class BillingController { } @Get("invoices/:id/document") + @BookingStaff(FREIGHT_PERMS.invoices.export) @ApiOperation({ summary: "Download the sealed invoice PDF" }) async document(@Param("id", ParseUUIDPipe) id: string, @Res() res: Response) { const { filename, buffer } = await this.billingService.document(id); @@ -58,6 +60,7 @@ export class BillingController { } @Get("invoices/:id/receipt") + @BookingStaff(FREIGHT_PERMS.invoices.export) @ApiOperation({ summary: "Download the sealed payment receipt PDF" }) async receipt(@Param("id", ParseUUIDPipe) id: string, @Res() res: Response) { const { filename, buffer } = await this.billingService.receipt(id); diff --git a/apps/edr-freight-api/src/modules/billing/billing.service.spec.ts b/apps/edr-freight-api/src/modules/billing/billing.service.spec.ts index 1356f8cfa..6e25c72aa 100644 --- a/apps/edr-freight-api/src/modules/billing/billing.service.spec.ts +++ b/apps/edr-freight-api/src/modules/billing/billing.service.spec.ts @@ -668,3 +668,66 @@ describe("BillingService — CAC Bank (OTP debit)", () => { expect(confirmOtp).toHaveBeenCalledWith("intent-1", "123456"); }); }); + +describe("BillingService — CBE bill amounts round UP to whole birr", () => { + // CBE bills whole birr. Ceil, never Math.round: a .40 balance rounded down + // settles 0.40 short while markInvoiceAsPaid still writes paidAmount = + // totalAmount — money missing from the bank with the books saying paid. + // payInvoice and billQuery must agree, or /cbe/payment sees a mismatch. + const invoice = { + id: "inv-1", + status: Freight.InvoiceStatus.Pending, + source: Freight.InvoiceSource.Booking, + sourceId: "booking-1", + type: "PREPAID", + invoiceNumber: "INV-20260101-00001", + currency: "ETB", + // .40 — the case Math.round gets wrong (rounds down, underpays). + balanceAmount: 12345.4, + totalAmount: 12345.4, + company: { name: "Acme PLC" }, + paymentId: null, + dueAt: null, + }; + + const build = (payment: Record = {}) => { + const repo = { + findOne: jest.fn().mockResolvedValue(invoice), + update: jest.fn().mockResolvedValue(undefined), + }; + const service = new BillingService( + { getRepository: () => repo } as never, + {} as never, + {} as never, + makeEvents() as never, + payment as never, + {} as never, + {} as never, + ); + return { service, repo }; + }; + + it("opens the intent for the ceiled balance, never below it", async () => { + const initiate = jest.fn().mockResolvedValue({ + intentId: "intent-1", + immediateSuccess: false, + response: { intentId: "intent-1", status: "REQUIRES_ACTION" }, + }); + const { service } = build({ initiate }); + + await service.payInvoice("inv-1", { method: "CBE_BILL" }); + + expect(initiate).toHaveBeenCalledWith( + expect.objectContaining({ amountMinor: 12346 }), + ); + }); + + it("quotes the same ceiled amount on bill-query as payInvoice opened", async () => { + const { service } = build(); + + await expect(service.billQuery("booking-1")).resolves.toMatchObject({ + stillPayable: true, + currentAmountMinor: 12346, + }); + }); +}); diff --git a/apps/edr-freight-api/src/modules/billing/billing.service.ts b/apps/edr-freight-api/src/modules/billing/billing.service.ts index ea4413638..5051afd6e 100644 --- a/apps/edr-freight-api/src/modules/billing/billing.service.ts +++ b/apps/edr-freight-api/src/modules/billing/billing.service.ts @@ -1191,7 +1191,11 @@ export class BillingService { // service branches on a domain-specific reference type. referenceType: PaymentReferenceType.SHIPMENT, orderRef: invoice.invoiceNumber.replace(/-/g, "_"), - amountMinor: Math.round(Number(invoice.balanceAmount)), + // Whole birr, always UP. CBE bills this amount verbatim, so it must never + // land below the outstanding balance — Math.round would let a .40 balance + // settle 0.40 short. Ceil overcharges by <1 birr instead, and the same + // ceil in billQuery keeps the quoted and debited amounts identical. + amountMinor: Math.ceil(Number(invoice.balanceAmount)), currency: invoice.currency, reason: `Payment for invoice ${invoice.invoiceNumber}`, method: opts.method ?? "TELEBIRR", @@ -1336,7 +1340,9 @@ export class BillingService { }); if (open) { - const balance = Math.round(Number(open.balanceAmount ?? open.totalAmount)); + // Ceil, matching payInvoice — the amount CBE quotes at the counter has to + // be the amount the intent was opened for, or /cbe/payment sees a mismatch. + const balance = Math.ceil(Number(open.balanceAmount ?? open.totalAmount)); const expired = open.dueAt && open.dueAt.getTime() < Date.now(); return { stillPayable: balance > 0 && !expired, @@ -1371,7 +1377,7 @@ export class BillingService { return { stillPayable: false, payerName: latest.company?.name ?? null, - currentAmountMinor: Math.round(Number(latest.totalAmount)), + currentAmountMinor: Math.ceil(Number(latest.totalAmount)), currency: latest.currency, paymentReason: `Freight invoice ${latest.invoiceNumber}`, reason: closedInvoiceReason(latest.status), diff --git a/apps/edr-freight-api/src/modules/billing/portal-billing.controller.ts b/apps/edr-freight-api/src/modules/billing/portal-billing.controller.ts index 981233df0..90f6a32a4 100644 --- a/apps/edr-freight-api/src/modules/billing/portal-billing.controller.ts +++ b/apps/edr-freight-api/src/modules/billing/portal-billing.controller.ts @@ -12,6 +12,7 @@ import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger"; import type { Response } from "express"; import { CurrentUser } from "@edr/api-common"; +import { PortalCustomer } from "../../common/booking-guards"; import { type AuthUserPayload, resolveAuthUserId, @@ -28,6 +29,7 @@ import { ConfirmOtpDto, PayInvoiceDto } from "./dto/pay-invoice.dto"; @ApiTags("billing") @ApiBearerAuth() @Controller("billing") +@PortalCustomer() export class PortalBillingController { constructor(private readonly billingService: BillingService) {} diff --git a/apps/edr-freight-api/src/modules/bookings/booking-invoice.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-invoice.service.ts index cd803d719..91b8362e4 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-invoice.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-invoice.service.ts @@ -20,6 +20,10 @@ import { FirstMileService } from "../first-mile/first-mile.service"; import { BookingBatchService } from "../train-scheduling/booking-batch.service"; import { PriceLineItemDto } from "./dto/generate-price-response.dto"; import { BookingsRepository } from "./bookings.repository"; +import { + BookingWagonCancellationService, + WAGON_CANCEL_FEE_INVOICE_TYPE, +} from "./booking-wagon-cancellation.service"; import { Booking } from "./entities/booking.entity"; /** Snapshot written onto `booking.pricingBreakdown` by the pricing service. */ @@ -58,6 +62,8 @@ export class BookingInvoiceService { private readonly firstMile: FirstMileService, @Inject(forwardRef(() => BookingBatchService)) private readonly bookingBatch: BookingBatchService, + @Inject(forwardRef(() => BookingWagonCancellationService)) + private readonly wagonCancellations: BookingWagonCancellationService, ) { } /** @@ -90,6 +96,21 @@ export class BookingInvoiceService { return this.billing.generateInvoice(input); } + /** + * Cancel the booking's open PREPAID invoice, if any — used when a + * changes-requested resubmit restates the cargo, so the re-priced booking can + * be re-invoiced. Throws when the invoice already has payments recorded + * (cargo must not change out from under recorded money). + */ + async cancelUnpaidInvoiceForBooking(bookingId: string): Promise { + const existing = await this.billing.findPayable( + Freight.InvoiceSource.Booking, + bookingId, + "PREPAID", + ); + if (existing) await this.billing.cancelInvoice(existing.id); + } + /** * React to a booking invoice being paid — the settlement branch point. Per-type * reactions live here (not in the payment process): each invoice type advances @@ -108,6 +129,11 @@ export class BookingInvoiceService { await this.bookingBatch.reviveOfferForInvoice(payload.invoiceId); await this.advanceBookingOnPayment(payload.sourceId); break; + case WAGON_CANCEL_FEE_INVOICE_TYPE: + // Partial wagon cancellation: the fee settled — reduce the booking and + // release the cancelled wagons (T2 of the cancellation cycle). + await this.wagonCancellations.onFeePaid(payload.invoiceId); + break; default: this.logger.warn( `Unhandled booking invoice type "${payload.type}" paid (${payload.invoiceId})`, diff --git a/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts index df81fd5f6..ba6fece8c 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-pricing.service.ts @@ -279,7 +279,9 @@ export class BookingPricingService { return { lineItems, - totalAmount: total, + // Grand total is billed in whole currency units — fractional line sums + // (rate × tons can yield e.g. 260519.2) round to the nearest whole birr/USD. + totalAmount: Math.round(total), currency: booking.paymentCurrency, usedRates: [...usedRatesMap.values()], appliedModifiers: ruleResult.appliedModifiers, diff --git a/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts index 181c47b2d..7cc92be87 100644 --- a/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/booking-transition.service.ts @@ -8,6 +8,9 @@ import { Optional, } from "@nestjs/common"; import { EventEmitter2, OnEvent } from "@nestjs/event-emitter"; +import { DataSource } from "typeorm"; + +import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity'; import { BookingBatchService, @@ -56,11 +59,18 @@ export class BookingTransitionService { private readonly bookingClearanceService: BookingClearanceService, @Inject(forwardRef(() => ClearanceWorkflowService)) private readonly workflowService: ClearanceWorkflowService, - private readonly invoiceService: BookingInvoiceService, + // forwardRef: booking-invoice.service now pulls in the wagon-cancellation + // service, whose cross-module imports close a require cycle through this + // file — without it the class is undefined at decorator time. + @Inject(forwardRef(() => BookingInvoiceService)) + private readonly invoiceService: BookingInvoiceService, private readonly containerValidationService: ContainerValidationService, private readonly notifier: BookingLifecycleNotifierService, private readonly events: EventEmitter2, @Optional() private readonly milestoneService?: ClearanceMilestoneService, + // Optional + last so the hand-constructed service in *.spec.ts files keeps + // compiling; Nest injects it normally at runtime. + @Optional() private readonly dataSource?: DataSource, ) {} private isPhasedCustoms(booking: Booking): boolean { @@ -429,6 +439,20 @@ export class BookingTransitionService { return fresh; } + /** + * Customer self-service cancel, allowed only before payment — no fee. + * SELECTED_FOR_BATCH releases the wagon hold immediately; earlier statuses + * take the plain cancel path (open invoices expired, nothing reserved yet). + * Anything past payment falls through to cancel()'s status assertion. + */ + async customerCancel(bookingId: string, reason?: string): Promise { + const booking = await this.bookingsService.findById(bookingId); + if (booking.status === "SELECTED_FOR_BATCH") { + return this.cancelHold(bookingId, reason); + } + return this.cancel(bookingId, reason ?? "Customer cancelled before payment"); + } + async cancel(bookingId: string, reason: string): Promise { const booking = await this.bookingsService.findById(bookingId); assertBookingStatus(booking, [ @@ -978,6 +1002,15 @@ export class BookingTransitionService { // booking through the space checks below AND is persisted so the accept / // reserve path locks onto that train (pickExportSchedule honors it). const requestedId = isExportTrain ? (requestedTrainScheduleId ?? null) : null; + // Export rail rides the exact train the customer picked — never an + // auto-assigned one. Both portal flows (clearance + contract completion) + // surface a picker, so a missing id is an invalid submission, not a + // legitimate "let the system choose". + if (isExportTrain && !requestedId) { + throw new BadRequestException( + "Select a train for the chosen shipment day.", + ); + } const scheduledBooking = { ...booking, scheduledDate: date, @@ -1244,6 +1277,12 @@ export class BookingTransitionService { /** Flat list of physical container numbers on this booking (for the * customer truck-assignment container picker). */ containerNumbers: string[]; + /** The allocated train, when the booking is placed on a schedule. */ + trainSchedule?: { + trainNumber: string | null; + reference: string | null; + scheduledDepartureDate: Date | null; + } | null; } > { // This enrichment runs AFTER the transition has committed. A failure here @@ -1296,6 +1335,32 @@ export class BookingTransitionService { `enrichBookingResponse: batch-offer lookup failed for ${booking.id}: ${(err as Error).message}`, ); } + // Allocated train: number + schedule reference for the detail headers + // (portal and backoffice). Degrades to null like every fragile field here. + let trainSchedule: { + trainNumber: string | null; + reference: string | null; + scheduledDepartureDate: Date | null; + } | null = null; + if (booking.trainScheduleId && this.dataSource) { + try { + const s = await this.dataSource.getRepository(TrainSchedule).findOne({ + where: { id: booking.trainScheduleId }, + }); + if (s) { + trainSchedule = { + trainNumber: s.trainNumber ?? null, + reference: s.reference ?? null, + scheduledDepartureDate: s.scheduledDepartureDate ?? null, + }; + } + } catch (err) { + this.logger.warn( + `enrichBookingResponse: train-schedule lookup failed for ${booking.id}: ${(err as Error).message}`, + ); + } + } + // Physical container numbers entered at booking time (booking_container // units), flattened for the customer truck-assignment container picker. const containerNumbers = (booking.bookingContainers ?? []) @@ -1310,6 +1375,7 @@ export class BookingTransitionService { nextStep, activeBatchOffer, containerNumbers, + trainSchedule, }; } } diff --git a/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellation.service.ts b/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellation.service.ts new file mode 100644 index 000000000..c576f5a43 --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellation.service.ts @@ -0,0 +1,1124 @@ +import { + BadRequestException, + ConflictException, + forwardRef, + Inject, + Injectable, + Logger, + NotFoundException, +} from '@nestjs/common'; +import { Freight, NotificationAudience, NotificationType } from '@edr/types'; +import { DataSource, EntityManager, In } from 'typeorm'; + +import { BillingService } from '../billing/billing.service'; +import { ContractBookingService } from '../contracts/contract-booking.service'; +import { ClearanceMilestoneService } from '../contracts/clearance-milestone.service'; +import { CreateBookingUnderContractDto } from '../contracts/dto/create-booking-under-contract.dto'; +import { ClearanceMilestone } from '../contracts/entities/clearance-milestone.entity'; +import { FirstMileService } from '../first-mile/first-mile.service'; +import { NotificationInboxService } from '../notification-inbox/notification-inbox.service'; +import { wagonsPerUnitForSize } from '../rule-engine/container-type.util'; +import { Rate } from '../rule-engine/entities/rate.entity'; +import { BookingBatchService } from '../train-scheduling/booking-batch.service'; +import { TrainSchedulingService } from '../train-scheduling/train-scheduling.service'; +import { WagonAllocationBulkLoad } from '../train-schedules/entities/wagon-allocation-bulk-load.entity'; +import { WagonAllocationContainerItem } from '../train-schedules/entities/wagon-allocation-container-item.entity'; +import { WagonBookingAllocation } from '../train-schedules/entities/wagon-booking-allocation.entity'; +import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; +import { + BookingWagonCancellationsRepository, + WagonCancellationListFilter, +} from './booking-wagon-cancellations.repository'; +import { BookingsRepository } from './bookings.repository'; +import { + RebookCancelledWagonsDto, + RequestWagonCancellationDto, +} from './dto/wagon-cancellation.dto'; +import { Booking } from './entities/booking.entity'; +import { BookingContainer } from './entities/booking-container.entity'; +import { BookingContainerUnit } from './entities/booking-container-unit.entity'; +import { + BookingWagonCancellation, + CancelledQuantities, + CancelledUnitSnapshot, +} from './entities/booking-wagon-cancellation.entity'; + +/** + * rates.rate_type of the cancellation fee — an existing rate-engine type + * (trigger CANCELLATION, never auto-applied to booking pricing). Staff + * configure it in the normal rates UI; the wagon flow requires the PER_WAGON + * unit so the fee scales with the cancelled wagon count. + */ +export const WAGON_CANCELLATION_FEE_RATE_TYPE = 'CANCELLATION_FEE'; +/** invoices.type of the fee invoice — the settlement branch key in BookingInvoiceService. */ +export const WAGON_CANCEL_FEE_INVOICE_TYPE = 'WAGON_CANCEL_FEE'; + +const round2 = (n: number): number => Math.round(n * 100) / 100; +const round3 = (n: number): number => Math.round(n * 1000) / 1000; + +interface RequestedCut { + wagons: number; + weightTons: number; + quantities: CancelledQuantities; +} + +/** + * Partial wagon cancellation on a PAID booking, with a rebooking credit. + * + * Lifecycle (one ledger row per cycle, see BookingWagonCancellation): + * T1 request — validate + price the fee, open the fee invoice. Nothing else + * moves: the wagons stay allocated until the fee is money. + * T2 fee paid — reduce the booking in place (applySplit mechanics: soft-delete + * the cut units LIFO), release the surplus wagon allocations, + * snapshot the cut units on the ledger row → CREDIT_AVAILABLE. + * T3 rebook — customer picks a day only. The credit becomes a REAL booking + * via ContractBookingService.createUnderContract (which re-checks + * contract validity + caps), immediately marked PAID — the + * freight was paid on the original booking; only the fee was new + * money. Clearance milestones are copied from the source booking + * (the cargo is already cleared; clearance follows cargo, not + * train date). + * + * The cycle is repeatable by construction: the rebooked booking is a normal + * PAID booking, so it can itself be partially cancelled again. + */ +@Injectable() +export class BookingWagonCancellationService { + private readonly logger = new Logger(BookingWagonCancellationService.name); + + constructor( + private readonly dataSource: DataSource, + private readonly repo: BookingWagonCancellationsRepository, + private readonly bookingsRepository: BookingsRepository, + private readonly billing: BillingService, + @Inject(forwardRef(() => ContractBookingService)) + private readonly contractBooking: ContractBookingService, + @Inject(forwardRef(() => ClearanceMilestoneService)) + private readonly clearanceMilestones: ClearanceMilestoneService, + @Inject(forwardRef(() => BookingBatchService)) + private readonly bookingBatch: BookingBatchService, + @Inject(forwardRef(() => TrainSchedulingService)) + private readonly trainScheduling: TrainSchedulingService, + @Inject(forwardRef(() => FirstMileService)) + private readonly firstMile: FirstMileService, + private readonly inbox: NotificationInboxService, + ) {} + + // ── T1: request ──────────────────────────────────────────────────────────── + + /** Fee/credit preview for the confirm dialog — same math as the request, no writes. */ + async previewCancellation( + bookingId: string, + dto: RequestWagonCancellationDto, + ): Promise<{ + wagons: number; + weightTons: number; + feePerWagon: number; + feeAmount: number; + feeCurrency: string; + creditAmount: number; + }> { + const booking = await this.loadCancellableBooking(bookingId); + const cut = await this.resolveRequestedCut(booking, dto); + const rate = await this.feeRate(); + const feeAmount = round2(Number(rate.rateValue) * cut.wagons); + return { + wagons: cut.wagons, + weightTons: cut.weightTons, + feePerWagon: Number(rate.rateValue), + feeAmount, + feeCurrency: rate.currency, + creditAmount: this.creditFor(booking, cut.wagons), + }; + } + + async requestCancellation( + bookingId: string, + dto: RequestWagonCancellationDto, + userId?: string, + ): Promise { + const booking = await this.loadCancellableBooking(bookingId); + const open = await this.repo.findOpenForBooking(bookingId); + if (open) { + throw new ConflictException( + 'This booking already has a cancellation awaiting its fee. Pay or withdraw it first.', + ); + } + + const cut = await this.resolveRequestedCut(booking, dto); + const rate = await this.feeRate(); + const feeAmount = round2(Number(rate.rateValue) * cut.wagons); + const creditAmount = this.creditFor(booking, cut.wagons); + + const row = await this.repo.create({ + bookingId, + wagonsCancelled: cut.wagons, + weightTons: cut.weightTons, + cancelledQuantities: cut.quantities, + creditAmount, + feeRateId: rate.id, + feeAmount, + feeCurrency: rate.currency, + status: 'FEE_PENDING', + reason: dto.reason ?? null, + requestedByUserId: userId ?? null, + }); + + // The fee invoice rides the booking's own invoice list (source=booking), so + // the portal's existing invoice/pay stack picks it up with zero new payment + // code. Settlement branches on type in BookingInvoiceService. + const invoice = await this.billing.generateInvoice({ + source: Freight.InvoiceSource.Booking, + sourceId: bookingId, + type: WAGON_CANCEL_FEE_INVOICE_TYPE, + companyId: booking.companyId, + companyProfileId: booking.companyProfileId, + currency: rate.currency, + lines: [ + { + chargeType: 'CANCELLATION_FEE', + description: `Wagon cancellation fee — ${cut.wagons} wagon(s) of booking ${booking.reference}`, + quantity: cut.wagons, + unitRate: Number(rate.rateValue), + amount: feeAmount, + currency: rate.currency, + metadata: { wagonCancellationId: row.id }, + }, + ], + totalAmount: feeAmount, + status: Freight.InvoiceStatus.Issued, + }); + let updated = await this.repo.update(row.id, { feeInvoiceId: invoice.id }); + + // Policy: the cancelled wagons leave the schedule NOW — capacity frees for + // other customers immediately; the fee is still owed before the credit can + // be rebooked. A withdraw/void re-allocates (or errors when the train has + // no room left). If this release fails, T2 releases instead (flag unset). + try { + const released = await this.releaseAtRequest(bookingId, cut); + if (released) { + updated = await this.repo.update(row.id, { + cancelledQuantities: { ...cut.quantities, releasedAtRequest: true }, + }); + } + } catch (err) { + this.logger.error( + `Request-time wagon release failed for cancellation ${row.id}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + + this.notifyStaff( + booking, + 'Wagon cancellation requested', + `${booking.reference}: customer asked to cancel ${cut.wagons} wagon(s); fee invoice ${invoice.invoiceNumber} issued.`, + ); + return updated ?? row; + } + + /** + * Void a FEE_PENDING request (customer withdraw or staff void). The wagons + * left the schedule at request time, so voiding must first put them back: + * the schedule's auto-allocation is re-run and the result verified — if the + * train has no room left, the void FAILS with a clear error and the request + * stays FEE_PENDING (pay the fee and rebook the credit instead). + */ + async withdraw(cancellationId: string): Promise { + const row = await this.mustFind(cancellationId); + if (row.status !== 'FEE_PENDING') { + throw new BadRequestException( + `Only a fee-pending cancellation can be withdrawn (status is ${row.status}).`, + ); + } + + if (row.cancelledQuantities.releasedAtRequest) { + const booking = await this.bookingsRepository.findById(row.bookingId); + const scheduleId = booking?.trainScheduleId; + if (booking && scheduleId) { + try { + await this.trainScheduling.tryAutoWagonAllocation(scheduleId); + } catch (err) { + this.logger.warn( + `Re-allocation on withdraw failed for booking ${row.bookingId}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + // ponytail: allocation rows ≈ wagons (20ft pairs share one row/wagon); + // switch to a weight-based check if mixed loads ever make this lie. + const rows = await this.dataSource.getRepository(WagonBookingAllocation).count({ + where: { bookingId: row.bookingId }, + }); + if (rows < Math.round(Number(booking.wagonsRequired ?? 0))) { + throw new ConflictException( + 'The train has no free wagon space left to restore the cancelled wagons — the request cannot be withdrawn. Pay the cancellation fee and rebook the credit on another day instead.', + ); + } + } + } + + if (row.feeInvoiceId) await this.billing.cancelInvoice(row.feeInvoiceId); + return (await this.repo.update(row.id, { status: 'WITHDRAWN' }))!; + } + + // ── T2: fee settled ───────────────────────────────────────────────────────── + + /** + * The fee invoice settled — reduce the booking and free the wagons. Called + * from BookingInvoiceService's paid handler. Idempotent: a duplicate webhook + * finds the row already past FEE_PENDING and returns. + */ + async onFeePaid(feeInvoiceId: string): Promise { + const row = await this.repo.findByFeeInvoiceId(feeInvoiceId); + if (!row) { + this.logger.warn(`No wagon cancellation for paid fee invoice ${feeInvoiceId}.`); + return; + } + if (row.status !== 'FEE_PENDING') return; + + // The fee can settle after loading started (slow payment). Never cut + // loaded cargo: leave the row FEE_PENDING and alert staff to resolve + // (reschedule the cut or refund the fee by hand). Skipped when the wagons + // already left the schedule at request time — loading of the KEPT wagons + // is then irrelevant to this cut. + const releasedEarly = !!row.cancelledQuantities.releasedAtRequest; + const bookingNow = await this.bookingsRepository.findById(row.bookingId); + const movingNow = releasedEarly + ? 0 + : await this.dataSource.getRepository(WagonBookingAllocation).count({ + where: { bookingId: row.bookingId, status: In(['LOADED', 'DEPARTED']) }, + }); + if (!releasedEarly && (bookingNow?.loadedAt || movingNow > 0)) { + this.logger.error( + `Wagon cancellation ${row.id}: fee paid but loading already started on booking ${row.bookingId} — left FEE_PENDING for manual resolution.`, + ); + if (bookingNow) { + this.notifyStaff( + bookingNow, + 'Wagon cancellation fee paid after loading started', + `${bookingNow.reference}: the customer paid the cancellation fee for ${row.wagonsCancelled} wagon(s), but loading has already started. Resolve manually (adjust the cut or refund the fee).`, + ); + } + return; + } + + await this.dataSource.transaction(async (manager) => { + const booking = await manager.getRepository(Booking).findOne({ + where: { id: row.bookingId }, + lock: { mode: 'pessimistic_write' }, + }); + if (!booking) throw new NotFoundException(`Booking ${row.bookingId} not found.`); + + const quantities = { ...row.cancelledQuantities }; + let droppedWeight = 0; + + if (quantities.bySize && Object.keys(quantities.bySize).length) { + // Specific-wagon requests already carry the exact unit snapshots; + // quantity requests trim LIFO and snapshot here. + const units = quantities.units?.length + ? await this.reduceContainerUnitsExact(manager, booking, quantities.units) + : await this.reduceContainerLines(manager, booking, quantities.bySize); + quantities.units = units; + droppedWeight = round3(units.reduce((s, u) => s + Number(u.vgmTons || 0), 0)); + if (!releasedEarly) { + await this.releaseContainerAllocations( + manager, + booking.id, + units.map((u) => u.containerNumber), + ); + } + } else { + droppedWeight = Number(quantities.bulkTons ?? row.weightTons); + await this.reduceBulk(manager, booking, droppedWeight); + if (!releasedEarly) { + await this.releaseBulkAllocations( + manager, + booking.id, + Number(row.wagonsCancelled), + quantities.allocationIds, + ); + } + } + + // Mirror applySplit's bookkeeping: preSplitQuantities feeds the ONE_TIME + // exact-remainder assertion at rebook time; isSplit releases the + // single-active-booking slot so the rebooked booking may be created. + const preSplitQuantities = + booking.preSplitQuantities ?? (await this.currentQuantities(manager, booking, droppedWeight)); + + await manager.getRepository(Booking).update(booking.id, { + wagonsRequired: round2(Number(booking.wagonsRequired ?? 0) - Number(row.wagonsCancelled)), + cargoTotalWeightVgm: round3(Number(booking.cargoTotalWeightVgm) - droppedWeight), + totalAmount: round2(Number(booking.totalAmount) - Number(row.creditAmount)), + isSplit: true, + preSplitQuantities, + } as never); + + await manager.getRepository(BookingWagonCancellation).update(row.id, { + status: 'CREDIT_AVAILABLE', + feePaidAt: new Date(), + weightTons: droppedWeight, + cancelledQuantities: quantities, + }); + }); + + const booking = await this.bookingsRepository.findById(row.bookingId); + if (booking) { + this.notifyCustomer( + booking, + 'Wagon cancellation confirmed', + `${row.wagonsCancelled} wagon(s) of ${booking.reference} are cancelled. Your paid freight is kept as credit — rebook any day while your contract is valid.`, + ); + } + this.logger.log( + `Wagon cancellation ${row.id}: fee paid, booking ${row.bookingId} reduced by ${row.wagonsCancelled} wagon(s).`, + ); + } + + // ── T3: rebook ────────────────────────────────────────────────────────────── + + async rebook( + cancellationId: string, + dto: RebookCancelledWagonsDto, + userId?: string, + ): Promise<{ cancellation: BookingWagonCancellation; bookingId: string }> { + const row = await this.mustFind(cancellationId); + if (row.status !== 'CREDIT_AVAILABLE') { + throw new BadRequestException( + `This credit cannot be rebooked (status is ${row.status}).`, + ); + } + const source = await this.bookingsRepository.findById(row.bookingId); + if (!source) throw new NotFoundException(`Booking ${row.bookingId} not found.`); + if (!source.contractId) { + throw new BadRequestException('The original booking has no contract to rebook under.'); + } + // Friendly pre-check; createUnderContract re-asserts inside its own guards. + if ( + source.contractValidUntil && + new Date(source.contractValidUntil).getTime() < Date.now() + ) { + throw new BadRequestException( + 'Contract validity has expired — ask EDR staff to extend the contract before rebooking.', + ); + } + + const createDto = this.buildRebookDto(row, dto.scheduledDate); + const created = await this.contractBooking.createUnderContract( + source.contractId, + createDto, + { id: userId ?? source.createdByUserId ?? undefined }, + // System actor: carries the create-booking key so the GL gate passes on + // Path B (customs-clearance) contracts; harmless on Path A. + { permissions: [{ key: FREIGHT_PERMS.contracts.createBooking }] }, + ); + const newBookingId = created.booking.id; + + // The freight is already paid (credit) — mark PAID and let the existing + // paid-booking machinery place it. No invoice is generated for it. + await this.dataSource.getRepository(Booking).update(newBookingId, { + paymentStatus: 'PAID', + status: 'PAID', + }); + await this.copyClearanceState(source, newBookingId); + + try { + await this.firstMile.acceptBooking(newBookingId); + } catch (err) { + this.logger.error( + `First-mile accept failed for rebooked ${newBookingId}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + try { + await this.bookingBatch.ensurePaidBookingAllocated(newBookingId); + } catch (err) { + this.logger.error( + `Allocation failed for rebooked ${newBookingId}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + + const updated = (await this.repo.update(row.id, { + status: 'REBOOKED', + rebookedBookingId: newBookingId, + rebookedAt: new Date(), + }))!; + + this.notifyCustomer( + source, + 'Cancelled wagons rebooked', + `Your ${row.wagonsCancelled} cancelled wagon(s) from ${source.reference} are rebooked for ${dto.scheduledDate}. No new freight charge — your credit covered it.`, + newBookingId, + ); + return { cancellation: updated, bookingId: newBookingId }; + } + + // ── History ──────────────────────────────────────────────────────────────── + + list(filter: WagonCancellationListFilter) { + return this.repo.list(filter); + } + + findById(id: string): Promise { + return this.mustFind(id); + } + + // ── internals ────────────────────────────────────────────────────────────── + + private async mustFind(id: string): Promise { + const row = await this.repo.findById(id); + if (!row) throw new NotFoundException(`Wagon cancellation ${id} not found.`); + return row; + } + + /** PAID booking, not yet moving, with a contract to rebook under later. */ + private async loadCancellableBooking(bookingId: string): Promise { + const booking = await this.bookingsRepository.findById(bookingId); + if (!booking) throw new NotFoundException(`Booking ${bookingId} not found.`); + if (booking.paymentStatus !== 'PAID' || booking.status !== 'PAID') { + throw new BadRequestException( + 'Only a paid booking can cancel wagons. Before payment, cancel the booking itself — no fee applies.', + ); + } + if (!booking.contractId) { + throw new BadRequestException( + 'Wagon cancellation needs a contract booking (the credit is rebooked under the contract).', + ); + } + // Cancellation is allowed strictly BEFORE loading/dispatch: both signals + // checked — per-wagon allocation status and the booking-level loading stamp + // (some flows confirm loading on the booking without flipping allocations). + if (booking.loadedAt) { + throw new BadRequestException( + 'Cargo loading is confirmed for this booking — wagons can no longer be cancelled.', + ); + } + const moving = await this.dataSource.getRepository(WagonBookingAllocation).count({ + where: { bookingId, status: In(['LOADED', 'DEPARTED']) }, + }); + if (moving > 0) { + throw new BadRequestException( + 'Loading has started for this booking — wagons can no longer be cancelled.', + ); + } + return booking; + } + + /** Validate the requested cut against the live booking and size it in wagons/tons. */ + private async resolveRequestedCut( + booking: Booking, + dto: RequestWagonCancellationDto, + ): Promise { + const totalWagons = Number(booking.wagonsRequired ?? 0); + if (totalWagons <= 0) { + throw new BadRequestException('This booking has no wagon requirement to cancel from.'); + } + + if (dto.wagonAllocationIds?.length) { + return this.resolveCutFromAllocations(booking, dto.wagonAllocationIds, totalWagons); + } + + if (booking.freightType === 'CONTAINER') { + if (!dto.containers?.length) { + throw new BadRequestException('Specify the container units to cancel per size.'); + } + const lines = await this.dataSource.getRepository(BookingContainer).find({ + where: { bookingId: booking.id }, + }); + const liveBySize = new Map(); + for (const line of lines) { + const size = line.containerSize ?? ''; + liveBySize.set(size, (liveBySize.get(size) ?? 0) + Number(line.quantity ?? 0)); + } + const bySize: Record = {}; + let wagons = 0; + for (const cut of dto.containers) { + const live = liveBySize.get(cut.containerSize) ?? 0; + if (cut.quantity > live) { + throw new BadRequestException( + `Cannot cancel ${cut.quantity} × ${cut.containerSize}ft — the booking only has ${live}.`, + ); + } + bySize[cut.containerSize] = cut.quantity; + wagons += cut.quantity * wagonsPerUnitForSize(Number(cut.containerSize)); + } + wagons = round2(wagons); + if (wagons >= totalWagons) { + throw new BadRequestException( + 'That would cancel the whole booking — use booking cancellation instead of a partial wagon cancel.', + ); + } + // Snapshot the LIFO-picked physical units up front (read-only — cargo is + // cut only when the fee settles) so the wagons carrying them can be + // released from the schedule at request time and the portal can show + // which containers are leaving. + const unitRepo = this.dataSource.getRepository(BookingContainerUnit); + const units: CancelledUnitSnapshot[] = []; + let requested = 0; + for (const cut of dto.containers) { + requested += cut.quantity; + let need = cut.quantity; + const sizeLines = lines + .filter((l) => (l.containerSize ?? '') === cut.containerSize) + .sort((a, b) => +new Date(b.createdAt) - +new Date(a.createdAt)); + for (const line of sizeLines) { + if (need <= 0) break; + const us = await unitRepo.find({ + where: { bookingContainerId: line.id }, + order: { sortOrder: 'DESC', createdAt: 'DESC' }, + take: need, + }); + for (const u of us) { + units.push({ + containerSize: cut.containerSize, + containerNumber: u.containerNumber, + sealNumber: u.sealNumber ?? null, + vgmTons: Number(u.vgmTons), + isHazardous: u.isHazardous, + isReefer: u.isReefer, + }); + need--; + } + } + } + const weightShare = round3( + Number(booking.cargoTotalWeightVgm) * (wagons / totalWagons), + ); + return { + wagons, + weightTons: weightShare, + // Bookings without unit records fall back to the T2 LIFO trim. + quantities: { bySize, ...(units.length === requested ? { units } : {}) }, + }; + } + + // BULK: the customer cancels wagons; tons follow the booking's own + // tons-per-wagon ratio. + const wagons = round2(Number(dto.wagons ?? 0)); + if (!wagons || wagons <= 0) { + throw new BadRequestException('Specify how many wagons to cancel.'); + } + if (wagons >= totalWagons) { + throw new BadRequestException( + 'That would cancel the whole booking — use booking cancellation instead of a partial wagon cancel.', + ); + } + // ponytail: proportional sizing (tons/wagon = total/wagons). PER_ITEM item + // rounding happens here too; switch to items_per_wagon_map sizing if bulk + // PER_ITEM cancels ever need to be exact per item. + let tons = Number(booking.cargoTotalWeightVgm) * (wagons / totalWagons); + const isPerItem = booking.bulkTotalWeightTons != null; + tons = isPerItem ? Math.floor(tons) : round3(tons); + if (tons <= 0) { + throw new BadRequestException('The requested cut is too small to release cargo.'); + } + return { wagons, weightTons: tons, quantities: { bulkTons: tons } }; + } + + /** + * Specific-wagon cancellation: the customer picked wagons in the Wagons tab. + * Everything is derived from the selected allocations — container bookings + * get their exact unit snapshots up front (T2 then cuts precisely these, + * not a LIFO guess), bulk gets the wagons' actual allocated tonnage. + */ + private async resolveCutFromAllocations( + booking: Booking, + allocationIds: string[], + totalWagons: number, + ): Promise { + const allocations = await this.dataSource.getRepository(WagonBookingAllocation).find({ + where: { id: In(allocationIds), bookingId: booking.id }, + relations: { containerItems: true }, + }); + if (allocations.length !== allocationIds.length) { + throw new BadRequestException( + 'Some selected wagons no longer belong to this booking — refresh and pick again.', + ); + } + const notCancellable = allocations.filter( + (a) => a.status !== 'PLANNED' && a.status !== 'RESERVED', + ); + if (notCancellable.length) { + throw new BadRequestException( + 'A selected wagon is already loaded or departed and cannot be cancelled.', + ); + } + + const wagons = allocations.length; + if (wagons >= totalWagons) { + throw new BadRequestException( + 'That would cancel the whole booking — use booking cancellation instead of a partial wagon cancel.', + ); + } + + if (booking.freightType !== 'CONTAINER') { + const allocated = allocations.reduce( + (s, a) => s + Number(a.allocatedWeightTons || 0), + 0, + ); + const tons = + allocated > 0 + ? round3(allocated) + : round3(Number(booking.cargoTotalWeightVgm) * (wagons / totalWagons)); + return { + wagons, + weightTons: tons, + quantities: { bulkTons: tons, allocationIds }, + }; + } + + // Container: the selected wagons' items name the exact physical boxes. + const numbers = allocations + .flatMap((a) => a.containerItems ?? []) + .map((i) => i.containerNumber) + .filter((n): n is string => !!n); + if (!numbers.length) { + throw new BadRequestException( + 'The selected wagons carry no container records — cancel by quantity instead.', + ); + } + const lines = await this.dataSource.getRepository(BookingContainer).find({ + where: { bookingId: booking.id }, + }); + const unitRepo = this.dataSource.getRepository(BookingContainerUnit); + const units: CancelledUnitSnapshot[] = []; + const bySize: Record = {}; + for (const line of lines) { + const size = line.containerSize ?? ''; + const lineUnits = await unitRepo.find({ where: { bookingContainerId: line.id } }); + for (const u of lineUnits) { + if (!numbers.includes(u.containerNumber)) continue; + units.push({ + containerSize: size, + containerNumber: u.containerNumber, + sealNumber: u.sealNumber ?? null, + vgmTons: Number(u.vgmTons), + isHazardous: u.isHazardous, + isReefer: u.isReefer, + }); + bySize[size] = (bySize[size] ?? 0) + 1; + } + } + if (units.length !== numbers.length) { + throw new BadRequestException( + 'Wagon container records are out of sync with the booking — contact EDR support.', + ); + } + return { + wagons, + weightTons: round3(units.reduce((s, u) => s + Number(u.vgmTons || 0), 0)), + quantities: { bySize, units, allocationIds }, + }; + } + + /** Credit = the cancelled share of the ORIGINAL price (old-price rebooking). */ + private creditFor(booking: Booking, wagons: number): number { + const totalWagons = Number(booking.wagonsRequired ?? 0); + if (totalWagons <= 0) return 0; + return round2(Number(booking.totalAmount) * (wagons / totalWagons)); + } + + private async feeRate(): Promise { + const rate = await this.dataSource.getRepository(Rate).findOne({ + where: { + rateType: WAGON_CANCELLATION_FEE_RATE_TYPE, + rateUnit: 'PER_WAGON', + status: 'LIVE', + }, + order: { createdAt: 'DESC' }, + }); + if (!rate) { + throw new BadRequestException( + 'No LIVE per-wagon CANCELLATION_FEE rate is configured — ask EDR to set it in the rate engine (unit PER_WAGON).', + ); + } + return rate; + } + + /** + * Trim `bySize` units off the booking's container lines, newest line first, + * LIFO within a line — the exact applySplit mechanics. Returns snapshots of + * every physical unit soft-deleted, for later reconstruction. + */ + private async reduceContainerLines( + manager: EntityManager, + booking: Booking, + bySize: Record, + ): Promise { + const snapshots: CancelledUnitSnapshot[] = []; + for (const [size, toDrop] of Object.entries(bySize)) { + let remaining = toDrop; + const lines = await manager.getRepository(BookingContainer).find({ + where: { bookingId: booking.id, containerSize: size }, + order: { createdAt: 'DESC' }, + }); + const live = lines.reduce((s, l) => s + Number(l.quantity ?? 0), 0); + if (live < toDrop) { + throw new BadRequestException( + `Booking changed since the request: only ${live} × ${size}ft left, cannot cancel ${toDrop}.`, + ); + } + for (const line of lines) { + if (remaining <= 0) break; + const qty = Number(line.quantity ?? 0); + const drop = Math.min(remaining, qty); + remaining -= drop; + + const units = await manager.getRepository(BookingContainerUnit).find({ + where: { bookingContainerId: line.id }, + order: { sortOrder: 'DESC', createdAt: 'DESC' }, + take: drop, + }); + for (const u of units) { + snapshots.push({ + containerSize: size, + containerNumber: u.containerNumber, + sealNumber: u.sealNumber ?? null, + vgmTons: Number(u.vgmTons), + isHazardous: u.isHazardous, + isReefer: u.isReefer, + }); + } + if (units.length < drop) { + throw new BadRequestException( + `Booking line ${line.id} has ${units.length} physical unit record(s) but ${drop} must be cancelled — units out of sync.`, + ); + } + const droppedVgm = round3(units.reduce((s, u) => s + Number(u.vgmTons || 0), 0)); + + if (drop === qty) { + await manager.getRepository(BookingContainer).softDelete(line.id); + await manager + .getRepository(BookingContainerUnit) + .softDelete(units.map((u) => u.id)); + continue; + } + await manager.getRepository(BookingContainerUnit).softDelete(units.map((u) => u.id)); + const keptUnits = await manager.getRepository(BookingContainerUnit).find({ + where: { bookingContainerId: line.id }, + }); + await manager.getRepository(BookingContainer).update(line.id, { + quantity: qty - drop, + wagonsRequired: round2((qty - drop) * wagonsPerUnitForSize(Number(size))), + totalVgmTons: round3(Number(line.totalVgmTons) - droppedVgm), + hazardousQuantity: keptUnits.filter((u) => u.isHazardous).length, + reeferQuantity: keptUnits.filter((u) => u.isReefer).length, + }); + } + } + return snapshots; + } + + /** + * Release the cancelled wagons from the schedule at REQUEST time. Returns + * true when something was actually released (booking was on a train) — the + * caller then stamps `releasedAtRequest` so T2 skips its release step. + */ + private async releaseAtRequest(bookingId: string, cut: RequestedCut): Promise { + const had = await this.dataSource.getRepository(WagonBookingAllocation).count({ + where: { bookingId }, + }); + if (had === 0) return false; + + await this.dataSource.transaction(async (manager) => { + if (cut.quantities.units?.length) { + await this.releaseContainerAllocations( + manager, + bookingId, + cut.quantities.units.map((u) => u.containerNumber), + ); + } else if (!cut.quantities.bySize) { + await this.releaseBulkAllocations( + manager, + bookingId, + cut.wagons, + cut.quantities.allocationIds, + ); + } + // Container booking without unit records: nothing to match on — the + // wagons release at T2 via the LIFO trim instead. + }); + + const left = await this.dataSource.getRepository(WagonBookingAllocation).count({ + where: { bookingId }, + }); + return left < had; + } + + /** + * Cut EXACTLY the snapshotted units (specific-wagon cancellation): soft-delete + * them and rebalance each affected line. Returns the snapshots of the units + * actually cut, so drift since the request fails loudly instead of guessing. + */ + private async reduceContainerUnitsExact( + manager: EntityManager, + booking: Booking, + wanted: CancelledUnitSnapshot[], + ): Promise { + const numbers = wanted.map((u) => u.containerNumber); + const lines = await manager.getRepository(BookingContainer).find({ + where: { bookingId: booking.id }, + }); + const cut: CancelledUnitSnapshot[] = []; + for (const line of lines) { + const size = line.containerSize ?? ''; + const lineUnits = await manager.getRepository(BookingContainerUnit).find({ + where: { bookingContainerId: line.id }, + }); + const doomed = lineUnits.filter((u) => numbers.includes(u.containerNumber)); + if (!doomed.length) continue; + + await manager.getRepository(BookingContainerUnit).softDelete(doomed.map((u) => u.id)); + for (const u of doomed) { + cut.push({ + containerSize: size, + containerNumber: u.containerNumber, + sealNumber: u.sealNumber ?? null, + vgmTons: Number(u.vgmTons), + isHazardous: u.isHazardous, + isReefer: u.isReefer, + }); + } + const kept = lineUnits.filter((u) => !numbers.includes(u.containerNumber)); + if (!kept.length) { + await manager.getRepository(BookingContainer).softDelete(line.id); + continue; + } + const doomedVgm = round3(doomed.reduce((s, u) => s + Number(u.vgmTons || 0), 0)); + await manager.getRepository(BookingContainer).update(line.id, { + quantity: kept.length, + wagonsRequired: round2(kept.length * wagonsPerUnitForSize(Number(size))), + totalVgmTons: round3(Number(line.totalVgmTons) - doomedVgm), + hazardousQuantity: kept.filter((u) => u.isHazardous).length, + reeferQuantity: kept.filter((u) => u.isReefer).length, + }); + } + if (cut.length !== wanted.length) { + throw new BadRequestException( + `Booking changed since the request: ${cut.length}/${wanted.length} selected container(s) still on it.`, + ); + } + return cut; + } + + private async reduceBulk( + manager: EntityManager, + booking: Booking, + tons: number, + ): Promise { + if (tons >= Number(booking.cargoTotalWeightVgm)) { + throw new BadRequestException( + 'Booking changed since the request: the cut no longer leaves any cargo.', + ); + } + if (booking.bulkTotalWeightTons != null) { + const share = tons / Number(booking.cargoTotalWeightVgm); + await manager.getRepository(Booking).update(booking.id, { + bulkTotalWeightTons: round3(Number(booking.bulkTotalWeightTons) * (1 - share)), + }); + } + } + + /** + * Free the wagon capacity of the cancelled container units. Items are matched + * by container number; an allocation left with no items is deleted whole + * (hard delete — the unassignBooking convention for allocation rows). + * A booking not yet placed on a train simply has nothing to release. + */ + private async releaseContainerAllocations( + manager: EntityManager, + bookingId: string, + containerNumbers: string[], + ): Promise { + if (!containerNumbers.length) return; + const allocations = await manager.getRepository(WagonBookingAllocation).find({ + where: { bookingId }, + relations: { containerItems: true }, + }); + for (const alloc of allocations) { + const items = alloc.containerItems ?? []; + const cut = items.filter( + (i) => i.containerNumber && containerNumbers.includes(i.containerNumber), + ); + if (!cut.length) continue; + await manager + .getRepository(WagonAllocationContainerItem) + .delete(cut.map((i) => i.id)); + if (cut.length === items.length) { + await manager.getRepository(WagonBookingAllocation).delete(alloc.id); + } else { + const cutWeight = cut.reduce((s, i) => s + Number(i.grossWeightTons ?? 0), 0); + await manager.getRepository(WagonBookingAllocation).update(alloc.id, { + allocatedWeightTons: round3(Number(alloc.allocatedWeightTons) - cutWeight), + }); + } + } + } + + /** + * Free whole bulk wagons — the customer-picked allocations when given + * (specific-wagon cancel), topping up newest-first for any picked id that no + * longer exists (re-batch between request and fee payment). + */ + private async releaseBulkAllocations( + manager: EntityManager, + bookingId: string, + wagons: number, + pickedIds?: string[], + ): Promise { + const toFree = Math.round(wagons); + if (toFree <= 0) return; + let allocations: WagonBookingAllocation[] = []; + if (pickedIds?.length) { + allocations = await manager.getRepository(WagonBookingAllocation).find({ + where: { id: In(pickedIds), bookingId }, + }); + } + if (allocations.length < toFree) { + const have = new Set(allocations.map((a) => a.id)); + const fill = await manager.getRepository(WagonBookingAllocation).find({ + where: { bookingId }, + order: { createdAt: 'DESC' }, + }); + for (const a of fill) { + if (allocations.length >= toFree) break; + if (!have.has(a.id)) allocations.push(a); + } + } + allocations = allocations.slice(0, toFree); + if (!allocations.length) return; + const ids = allocations.map((a) => a.id); + await manager + .getRepository(WagonAllocationBulkLoad) + .delete({ wagonBookingAllocationId: In(ids) }); + await manager.getRepository(WagonBookingAllocation).delete(ids); + } + + /** Pre-reduction quantities snapshot (only when the booking was never split before). */ + private async currentQuantities( + manager: EntityManager, + booking: Booking, + _droppedWeight: number, + ): Promise<{ bulkTons?: number; bySize?: Record }> { + if (booking.freightType !== 'CONTAINER') { + return { bulkTons: Number(booking.cargoTotalWeightVgm) }; + } + // Lines were already reduced inside this transaction — read them with + // deleted rows included to reconstruct the pre-cut ledger. + const lines = await manager.getRepository(BookingContainer).find({ + where: { bookingId: booking.id }, + withDeleted: true, + }); + const bySize: Record = {}; + for (const line of lines) { + const size = line.containerSize ?? ''; + bySize[size] = (bySize[size] ?? 0) + Number(line.quantity ?? 0); + } + return { bySize }; + } + + /** The create-DTO that reconstructs the cancelled cargo on the chosen day. */ + private buildRebookDto( + row: BookingWagonCancellation, + scheduledDate: string, + ): CreateBookingUnderContractDto { + const dto: CreateBookingUnderContractDto = { scheduledDate }; + const q = row.cancelledQuantities; + + if (q.bySize && Object.keys(q.bySize).length) { + const units = q.units ?? []; + dto.containers = Object.entries(q.bySize).map(([size, quantity]) => { + const sized = units.filter((u) => u.containerSize === size); + if (sized.length !== quantity) { + throw new BadRequestException( + `Credit is missing unit snapshots for size ${size} (${sized.length}/${quantity}) — contact EDR support.`, + ); + } + return { + containerSize: size, + quantity, + units: sized.map((u) => ({ + containerNumber: u.containerNumber, + sealNumber: u.sealNumber ?? undefined, + vgmTons: u.vgmTons, + isHazardous: u.isHazardous, + isReefer: u.isReefer, + })), + hazardousQuantity: sized.filter((u) => u.isHazardous).length, + reeferQuantity: sized.filter((u) => u.isReefer).length, + }; + }); + return dto; + } + + dto.bulkLines = [{ cargoWeightTons: Number(q.bulkTons ?? row.weightTons) }]; + return dto; + } + + /** + * Carry the source booking's finished clearance onto the rebooked one: the + * cargo is already cleared; a new train date needs no new customs cycle. + * Seeds the standard milestone set idempotently, then mirrors every + * non-pending milestone status from the source by milestone code. + */ + private async copyClearanceState(source: Booking, newBookingId: string): Promise { + const repo = this.dataSource.getRepository(ClearanceMilestone); + const sourceMilestones = await repo.find({ where: { bookingId: source.id } }); + if (!sourceMilestones.length) return; + + try { + await this.clearanceMilestones.ensureBookingMilestones( + newBookingId, + source.tradeDirection, + ); + const targets = await repo.find({ where: { bookingId: newBookingId } }); + const byCode = new Map(targets.map((m) => [m.milestoneCode, m])); + for (const src of sourceMilestones) { + if (src.status === 'PENDING') continue; + const target = byCode.get(src.milestoneCode); + if (!target) continue; + await repo.update(target.id, { + status: src.status, + triggeredAt: src.triggeredAt, + triggeredByUserId: src.triggeredByUserId, + triggeredByDoc: src.triggeredByDoc, + note: src.note, + metadata: src.metadata, + }); + } + if (source.clearanceCurrentPhase) { + await this.dataSource.getRepository(Booking).update(newBookingId, { + clearanceCurrentPhase: source.clearanceCurrentPhase, + preClearanceFinalizedAt: source.preClearanceFinalizedAt, + dutyRequired: source.dutyRequired, + }); + } + } catch (err) { + // Clearance copy must never lose a paid rebooking — staff can re-complete + // milestones by hand if this ever fails. + this.logger.error( + `Clearance copy ${source.id} → ${newBookingId} failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + + private notifyCustomer(booking: Booking, title: string, body: string, linkBookingId?: string): void { + void this.inbox.notify({ + recipients: { companyId: booking.companyId }, + audience: NotificationAudience.PORTAL, + type: NotificationType.BOOKING_STATUS, + title, + body, + link: `/bookings/${linkBookingId ?? booking.id}`, + data: { bookingId: linkBookingId ?? booking.id, reference: booking.reference }, + }); + } + + private notifyStaff(booking: Booking, title: string, body: string): void { + void this.inbox.notify({ + recipients: { allBackoffice: true }, + audience: NotificationAudience.BACKOFFICE, + type: NotificationType.BOOKING_STATUS, + title, + body, + link: `/bookings/${booking.id}`, + data: { bookingId: booking.id, reference: booking.reference }, + }); + } +} diff --git a/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellations.repository.ts b/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellations.repository.ts new file mode 100644 index 000000000..64cde269f --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/booking-wagon-cancellations.repository.ts @@ -0,0 +1,85 @@ +import { BaseRepository } from '@edr/api-common'; +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository, SelectQueryBuilder } from 'typeorm'; + +import { BookingWagonCancellation } from './entities/booking-wagon-cancellation.entity'; + +export interface WagonCancellationListFilter { + status?: string[]; + /** Booking reference / company name search (staff list). */ + search?: string; + companyId?: string; + bookingId?: string; + from?: Date; + to?: Date; + page?: number; + pageSize?: number; +} + +@Injectable() +export class BookingWagonCancellationsRepository extends BaseRepository { + constructor( + @InjectRepository(BookingWagonCancellation) + repository: Repository, + ) { + super(repository); + } + + /** The one open (fee-unpaid) cancellation of a booking, if any. */ + findOpenForBooking(bookingId: string): Promise { + return this.repository.findOne({ + where: { bookingId, status: 'FEE_PENDING' }, + }); + } + + findByFeeInvoiceId(feeInvoiceId: string): Promise { + return this.repository.findOne({ where: { feeInvoiceId } }); + } + + /** Paged history — staff see everything, customers are scoped by companyId. */ + async list( + filter: WagonCancellationListFilter, + ): Promise<{ items: BookingWagonCancellation[]; total: number }> { + const page = Math.max(1, filter.page ?? 1); + const pageSize = Math.min(100, Math.max(1, filter.pageSize ?? 10)); + + const qb = this.baseQuery(); + if (filter.bookingId) { + qb.andWhere('(bwc.booking_id = :bookingId OR bwc.rebooked_booking_id = :bookingId)', { + bookingId: filter.bookingId, + }); + } + if (filter.companyId) { + qb.andWhere('booking.company_id = :companyId', { companyId: filter.companyId }); + } + if (filter.status?.length) { + qb.andWhere('bwc.status IN (:...statuses)', { statuses: filter.status }); + } + if (filter.search) { + qb.andWhere('(booking.reference ILIKE :search OR company.name ILIKE :search)', { + search: `%${filter.search}%`, + }); + } + if (filter.from) qb.andWhere('bwc.created_at >= :from', { from: filter.from }); + if (filter.to) qb.andWhere('bwc.created_at <= :to', { to: filter.to }); + + // Property path (not raw column): skip/take builds a distinct-id subquery + // and the ORDER BY must resolve inside it. + const [items, total] = await qb + .orderBy('bwc.createdAt', 'DESC') + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); + return { items, total }; + } + + private baseQuery(): SelectQueryBuilder { + return this.repository + .createQueryBuilder('bwc') + .leftJoinAndSelect('bwc.booking', 'booking') + .leftJoinAndSelect('booking.company', 'company') + .leftJoinAndSelect('bwc.rebookedBooking', 'rebookedBooking') + .leftJoinAndSelect('bwc.feeInvoice', 'feeInvoice'); + } +} diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts b/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts index 837d0d801..b7eb526a3 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.controller.ts @@ -15,13 +15,17 @@ import { UnauthorizedException, UploadedFile, UploadedFiles, - UseGuards, UseInterceptors, } from '@nestjs/common'; import { CurrentUser } from '@edr/api-common'; import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type'; -import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; -import { BookingStaff, BookingView } from '../../common/booking-guards'; +import { + BookingStaff, + BookingView, + MixedAudience, + PortalCustomer, + WagonCancellationView, +} from '../../common/booking-guards'; import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; import { AnyFilesInterceptor, FileInterceptor } from '@nestjs/platform-express'; import { @@ -74,6 +78,12 @@ import { GenerateGrnDto } from './dto/generate-grn.dto'; import { ContainerReceiptService } from './container-receipt.service'; import { SignContractDto } from './dto/sign-contract.dto'; import { UpdateBookingDto } from './dto/update-booking.dto'; +import { BookingWagonCancellationService } from './booking-wagon-cancellation.service'; +import { + FilterWagonCancellationsDto, + RebookCancelledWagonsDto, + RequestWagonCancellationDto, +} from './dto/wagon-cancellation.dto'; import { type AuthUserPayload, resolveAuthUserId, @@ -153,9 +163,11 @@ export class BookingsController { private readonly firstMileService: FirstMileService, private readonly lastMileService: LastMileService, private readonly userTradeAccessService: UserTradeAccessService, + private readonly wagonCancellationService: BookingWagonCancellationService, ) {} @Post() + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ summary: "Create a new freight booking (DRAFT)" }) @@ -196,6 +208,7 @@ export class BookingsController { } @Patch(":id") + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ @@ -212,6 +225,7 @@ export class BookingsController { } @Get() + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "List freight bookings (paginated)" }) async findAll( @Query() filter: FilterBookingDto, @@ -287,6 +301,7 @@ export class BookingsController { } @Get("my") + @PortalCustomer() @ApiOperation({ summary: "List the current customer's bookings ready for payment", description: @@ -317,6 +332,7 @@ export class BookingsController { } @Get("reference-data") + @MixedAudience([]) @ApiOperation({ summary: "Booking form catalog" }) @ApiOkResponse({ type: BookingReferenceDataDto }) getReferenceData(): Promise { @@ -324,6 +340,7 @@ export class BookingsController { } @Get("by-reference/:reference") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Get booking by reference" }) async findByReference( @Param("reference") reference: string, @@ -341,6 +358,7 @@ export class BookingsController { } @Get(":id") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Get booking by ID" }) async findOne( @Param("id", ParseUUIDPipe) id: string, @@ -362,6 +380,7 @@ export class BookingsController { } @Get(':id/available-days') + @MixedAudience([]) @ApiOperation({ summary: 'Days bookable for THIS booking (cargo-aware wagon-TYPE gate; days only, no capacity counts)', @@ -384,6 +403,7 @@ export class BookingsController { } @Get(':id/day-availability') + @MixedAudience([]) @ApiOperation({ summary: 'Advisory free-wagon count for a shipment day (planning hint, not enforced). ' + @@ -409,6 +429,7 @@ export class BookingsController { } @Get(':id/mile-summary') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: 'First/last-mile operational summary for a booking (customer-safe)', }) @@ -436,6 +457,7 @@ export class BookingsController { } @Post(':id/customer-truck-assignment') + @PortalCustomer() @ApiOperation({ summary: 'Customer assigns external truck and driver for terminal pickup' }) async assignCustomerTruck( @Param('id', ParseUUIDPipe) id: string, @@ -451,6 +473,7 @@ export class BookingsController { } @Get(':id/customer-truck-assignment/freight-order') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: 'Download freight order copies. The 2 gate copies always print; ?copies=1,2,8 adds waybill-style copies (catalog indexes 1-8).', @@ -477,6 +500,7 @@ export class BookingsController { } @Get(':id/carriage-acceptance-sheet') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: 'Download the carriage acceptance sheet (one per booking, lists every allocated wagon)', @@ -496,7 +520,156 @@ export class BookingsController { res.send(buffer); } + @Get(':id/wagons') + @ApiOperation({ + summary: + 'Allocated wagons for a booking (JSON) — empty until the paid booking is placed on a train', + }) + async wagonAllocations( + @Param('id', ParseUUIDPipe) id: string, + @CurrentUser() user: TCurrentUser, + ) { + const booking = await this.bookingsService.findById(id); + if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) { + await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking); + } + return this.bookingsService.wagonAllocations(id); + } + + // ── Partial wagon cancellation (paid bookings) ──────────────────────────── + // Customer endpoints are ownership-scoped (no portal permission keys); the + // staff history/void/rebook variants are permission-gated below. + + @Post(':id/wagon-cancellations/preview') + @ApiOperation({ summary: 'Preview the fee/credit of a partial wagon cancellation (no writes)' }) + async previewWagonCancellation( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: RequestWagonCancellationDto, + @CurrentUser() user: TCurrentUser, + ) { + const booking = await this.bookingsService.findById(id); + if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) { + await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking); + } + return this.wagonCancellationService.previewCancellation(id, dto); + } + + @Post(':id/wagon-cancellations') + @ApiOperation({ + summary: + 'Request a partial wagon cancellation on a PAID booking — opens the cancellation-fee invoice; wagons are released only once the fee settles', + }) + async requestWagonCancellation( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: RequestWagonCancellationDto, + @CurrentUser() user: TCurrentUser, + ) { + const booking = await this.bookingsService.findById(id); + if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) { + await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking); + } + return this.wagonCancellationService.requestCancellation(id, dto, user?.id); + } + + @Get(':id/wagon-cancellations') + @ApiOperation({ summary: 'Wagon-cancellation history of one booking (owner or staff)' }) + async listBookingWagonCancellations( + @Param('id', ParseUUIDPipe) id: string, + @CurrentUser() user: TCurrentUser, + ) { + const booking = await this.bookingsService.findById(id); + const staff = + hasFreightPermission(user, FREIGHT_PERMS.bookings.view) || + hasFreightPermission(user, FREIGHT_PERMS.bookings.wagonCancellationView); + if (!staff) { + await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking); + } + return this.wagonCancellationService.list({ bookingId: id, pageSize: 100 }); + } + + @Get('wagon-cancellations/my') + @ApiOperation({ summary: 'Wagon-cancellation history of the calling customer (paginated, filterable)' }) + async listMyWagonCancellations( + @Query() filter: FilterWagonCancellationsDto, + @CurrentUser() user: TCurrentUser, + ) { + const companyId = await this.bookingsService.resolveCustomerCompanyId(user?.id ?? ''); + if (!companyId) throw new ForbiddenException('No customer company for this user.'); + return this.wagonCancellationService.list({ + companyId, + status: filter.statuses, + search: filter.search, + from: filter.from ? new Date(filter.from) : undefined, + to: filter.to ? new Date(filter.to) : undefined, + page: filter.page, + pageSize: filter.pageSize, + }); + } + + @Get('wagon-cancellations/history') + @WagonCancellationView() + @ApiOperation({ summary: 'All wagon cancellations (staff, paginated, filterable)' }) + async listAllWagonCancellations(@Query() filter: FilterWagonCancellationsDto) { + return this.wagonCancellationService.list({ + status: filter.statuses, + search: filter.search, + from: filter.from ? new Date(filter.from) : undefined, + to: filter.to ? new Date(filter.to) : undefined, + page: filter.page, + pageSize: filter.pageSize, + }); + } + + @Post('wagon-cancellations/:cancellationId/withdraw') + @ApiOperation({ summary: 'Withdraw a fee-pending wagon cancellation (owner, or staff with the void permission)' }) + async withdrawWagonCancellation( + @Param('cancellationId', ParseUUIDPipe) cancellationId: string, + @CurrentUser() user: TCurrentUser, + ) { + await this.assertWagonCancellationActor( + cancellationId, + user, + FREIGHT_PERMS.bookings.wagonCancellationVoid, + ); + return this.wagonCancellationService.withdraw(cancellationId); + } + + @Post('wagon-cancellations/:cancellationId/rebook') + @ApiOperation({ + summary: + 'Rebook a wagon-cancellation credit: pick a shipment day only — the new booking is created under the contract and marked PAID (freight already paid; contract must still be valid)', + }) + async rebookWagonCancellation( + @Param('cancellationId', ParseUUIDPipe) cancellationId: string, + @Body() dto: RebookCancelledWagonsDto, + @CurrentUser() user: TCurrentUser, + ) { + await this.assertWagonCancellationActor( + cancellationId, + user, + FREIGHT_PERMS.bookings.wagonCancellationRebook, + ); + return this.wagonCancellationService.rebook(cancellationId, dto, user?.id); + } + + /** Owner-or-staff gate shared by the per-cancellation actions. */ + private async assertWagonCancellationActor( + cancellationId: string, + user: TCurrentUser, + staffPermission: string, + ): Promise { + if (hasFreightPermission(user, staffPermission)) return; + const row = await this.wagonCancellationService.findById(cancellationId); + const booking = await this.bookingsService.findById(row.bookingId); + await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking); + } + @Get(':id/customer-trucks') + @MixedAudience([ + FREIGHT_PERMS.bookings.view, + FREIGHT_PERMS.bookings.operations, + FREIGHT_PERMS.warehouseInventory.view, + ]) @ApiOperation({ summary: 'List customer self-haul trucks (multi-truck) for a booking' }) async listCustomerTrucks( @Param('id', ParseUUIDPipe) id: string, @@ -510,6 +683,7 @@ export class BookingsController { } @Post(':id/customer-trucks') + @PortalCustomer() @ApiOperation({ summary: 'Add a customer self-haul truck carrying 1–2 of the booking containers' }) async addCustomerTruck( @Param('id', ParseUUIDPipe) id: string, @@ -524,6 +698,7 @@ export class BookingsController { } @Post(':id/customer-trucks/bulk') + @PortalCustomer() @ApiOperation({ summary: 'Bulk add customer trucks from array payload (Excel parsed)' }) async bulkAddCustomerTrucks( @Param('id', ParseUUIDPipe) id: string, @@ -538,6 +713,7 @@ export class BookingsController { } @Patch(':id/customer-trucks/:assignmentId') + @PortalCustomer() @ApiOperation({ summary: 'Edit a not-yet-arrived customer truck (plate/driver/type + containers)' }) async updateCustomerTruck( @Param('id', ParseUUIDPipe) id: string, @@ -553,6 +729,7 @@ export class BookingsController { } @Delete(':id/customer-trucks/:assignmentId') + @PortalCustomer() @ApiOperation({ summary: 'Remove a not-yet-arrived customer truck from a booking' }) async removeCustomerTruck( @Param('id', ParseUUIDPipe) id: string, @@ -567,6 +744,7 @@ export class BookingsController { } @Get(':id/customer-trucks/loadable-containers') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: 'Booking containers not yet loaded onto a truck' }) async loadableContainers( @Param('id', ParseUUIDPipe) id: string, @@ -580,6 +758,7 @@ export class BookingsController { } @Post(':id/customer-trucks/:assignmentId/load') + @BookingStaff(FREIGHT_PERMS.bookings.operations) @ApiOperation({ summary: 'Truck_dispatch: load selected containers onto a truck (staff)' }) async loadCustomerTruck( @Param('id', ParseUUIDPipe) id: string, @@ -594,6 +773,7 @@ export class BookingsController { } @Post(':id/customer-trucks/:assignmentId/depart') + @BookingStaff(FREIGHT_PERMS.bookings.operations) @ApiOperation({ summary: 'Register an import truck leaving: containers loaded + weighed gross (staff)', }) @@ -611,6 +791,7 @@ export class BookingsController { } @Get(':id/received-pending-grn') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: 'Containers received into port but not yet on a GRN' }) async receivedPendingGrn( @Param('id', ParseUUIDPipe) id: string, @@ -624,6 +805,7 @@ export class BookingsController { } @Post(':id/generate-grn') + @BookingStaff(FREIGHT_PERMS.bookings.operations) @ApiOperation({ summary: 'Generate a GRN over the received containers (all received, or a subset) — one GRN per batch', @@ -641,6 +823,7 @@ export class BookingsController { } @Get(':id/tracking') + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Shipment tracking timeline for a booking", description: @@ -663,6 +846,7 @@ export class BookingsController { } @Delete(":id") + @MixedAudience([]) @HttpCode(204) @ApiOperation({ summary: "Soft-delete DRAFT booking" }) remove(@Param("id", ParseUUIDPipe) id: string) { @@ -670,6 +854,7 @@ export class BookingsController { } @Post(":id/documents") + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ summary: "Upload documents for a booking (DRAFT only)" }) @@ -682,6 +867,7 @@ export class BookingsController { } @Post(":id/generate-price") + @MixedAudience([]) @ApiOperation({ summary: "Generate price preview (DRAFT or CHANGES_REQUESTED)", description: @@ -693,6 +879,7 @@ export class BookingsController { } @Post(":id/submit") + @MixedAudience([]) @ApiOperation({ summary: "Customer submit booking", description: @@ -704,6 +891,7 @@ export class BookingsController { } @Post(":id/confirm-submit") + @MixedAudience([]) @ApiOperation({ summary: "Confirm submit after price change", description: @@ -715,6 +903,7 @@ export class BookingsController { } @Post(":id/reject") + @PortalCustomer() @ApiOperation({ summary: "Customer reject price estimate", description: @@ -745,6 +934,7 @@ export class BookingsController { } @Get(':id/clearance') + @MixedAudience([FREIGHT_PERMS.bookings.clearanceView, FREIGHT_PERMS.bookings.reviewDocuments]) @ApiOperation({ summary: "Document-clearance grid (required docs + upload + GL review status)", @@ -754,6 +944,7 @@ export class BookingsController { } @Post(":id/clearance/documents") + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ @@ -770,7 +961,10 @@ export class BookingsController { return this.transitionService.enrichBookingResponse(booking); } + // Customer requests the operation; GL ET also resubmits here on the + // customer's behalf after operations requests changes (BookingChangesRequestedAlert). @Post(":id/clearance/proceed") + @MixedAudience(FREIGHT_PERMS.contracts.createBooking) @ApiOperation({ summary: "Customer requests operation with a schedule day " + @@ -789,6 +983,7 @@ export class BookingsController { } @Get(":id/export-trains") + @MixedAudience([]) @ApiOperation({ summary: "Export train picker: the day's export trains on the booking's corridor " + @@ -990,6 +1185,7 @@ export class BookingsController { } @Post(':id/clearance/draft-declaration/accept') + @PortalCustomer() @ApiOperation({ summary: 'Customer accepts the draft customs declaration — unlocks the real customs declaration step for GL Ethiopia', @@ -1000,6 +1196,7 @@ export class BookingsController { } @Post(':id/clearance/draft-declaration/change') + @PortalCustomer() @ApiOperation({ summary: 'Customer requests a change to the draft customs declaration with a reason — GL Ethiopia sends a corrected draft (repeatable)', @@ -1026,6 +1223,7 @@ export class BookingsController { } @Post(':id/clearance/duty-slip') + @PortalCustomer() @UseInterceptors(FileInterceptor('file')) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer uploads duty/tax payment slip on booking' }) @@ -1177,7 +1375,7 @@ export class BookingsController { } @Post(":id/government-expedite") - @BookingStaff(FREIGHT_PERMS.bookings.staffAccept) + @BookingStaff(FREIGHT_PERMS.bookings.governmentExpedite) @ApiOperation({ summary: "Expedite government booking to PAID / ELIGIBLE for scheduling", }) @@ -1201,6 +1399,7 @@ export class BookingsController { } @Get(":id/contract/view") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOkResponse({ type: ContractViewDto }) @ApiOperation({ summary: "Contract HTML view for portal and backoffice" }) getContractView( @@ -1212,6 +1411,7 @@ export class BookingsController { } @Get(":id/contract/document") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Download contract PDF" }) async downloadContractDocument( @Param("id", ParseUUIDPipe) id: string, @@ -1227,6 +1427,7 @@ export class BookingsController { } @Get(":id/contract") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Download contract file (alias)" }) async downloadContract( @Param("id", ParseUUIDPipe) id: string, @@ -1236,7 +1437,7 @@ export class BookingsController { } @Post(":id/contract/sign") - @UseGuards(JwtGuard) + @MixedAudience(FREIGHT_PERMS.bookings.signStaff) @ApiOperation({ summary: "Apply digital signature (customer or staff)" }) async signContract( @Param("id", ParseUUIDPipe) id: string, @@ -1257,18 +1458,21 @@ export class BookingsController { } @Get(":id/contract/signatures") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "List contract signatures" }) getContractSignatures(@Param("id", ParseUUIDPipe) id: string) { return this.contractService.getSignatures(id); } @Get(":id/summary") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Contract summary string for dashboard" }) getSummary(@Param("id", ParseUUIDPipe) id: string) { return this.contractService.getSummary(id); } @Post(":id/customer/sign") + @PortalCustomer() @ApiOperation({ summary: "Customer digital signature (deprecated — use POST contract/sign)", }) @@ -1335,7 +1539,21 @@ export class BookingsController { return this.transitionService.enrichBookingResponse(booking); } + @Post(":id/customer-cancel") + @ApiOperation({ + summary: + "Customer cancels their own booking before payment — no cancellation fee", + }) + async customerCancel( + @Param("id", ParseUUIDPipe) id: string, + @Body() dto: RejectBookingDto, + ) { + const booking = await this.transitionService.customerCancel(id, dto.reason); + return this.transitionService.enrichBookingResponse(booking); + } + @Post(":id/cancel-hold") + @PortalCustomer() @ApiOperation({ summary: "Customer cancels an unpaid hold (SELECTED_FOR_BATCH → CANCELLED); " + @@ -1350,18 +1568,21 @@ export class BookingsController { } @Post(":id/consolidation") + @PortalCustomer() @ApiOperation({ summary: "Request freight consolidation" }) requestConsolidation(@Param("id", ParseUUIDPipe) id: string) { return this.bookingsService.requestConsolidation(id); } @Delete(":id/consolidation") + @PortalCustomer() @ApiOperation({ summary: "Remove consolidation pairing" }) removeConsolidation(@Param("id", ParseUUIDPipe) id: string) { return this.bookingsService.removeConsolidation(id); } @Get(":id/consolidation") + @MixedAudience(FREIGHT_PERMS.bookings.view) @ApiOperation({ summary: "Get consolidation details" }) getConsolidationDetails(@Param("id", ParseUUIDPipe) id: string) { return this.bookingsService.getConsolidationDetails(id); diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.module.ts b/apps/edr-freight-api/src/modules/bookings/bookings.module.ts index 84354d860..658629592 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.module.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.module.ts @@ -25,6 +25,7 @@ import { BookingLifecycleNotifierService } from './booking-lifecycle-notifier.se import { BookingTransitionService } from './booking-transition.service'; import { NotificationsModule } from '../notifications/notifications.module'; import { NotificationInboxModule } from '../notification-inbox/notification-inbox.module'; +import { BookingAllocationController } from './booking-allocation.controller'; import { BookingsController } from './bookings.controller'; // import { PayController } from './pay.controller'; import { BookingsRepository } from './bookings.repository'; @@ -38,6 +39,9 @@ import { BookingRateSnapshot } from './entities/booking-rate-snapshot.entity'; import { BookingContractSignature } from './entities/booking-contract-signature.entity'; import { BookingReviewNote } from './entities/booking-review-note.entity'; import { Booking } from './entities/booking.entity'; +import { BookingWagonCancellation } from './entities/booking-wagon-cancellation.entity'; +import { BookingWagonCancellationsRepository } from './booking-wagon-cancellations.repository'; +import { BookingWagonCancellationService } from './booking-wagon-cancellation.service'; import { CustomerTruckAssignment } from './entities/customer-truck-assignment.entity'; import { CustomerTruckContainer } from './entities/customer-truck-container.entity'; import { CustomerTruckAssignmentsRepository } from './customer-truck-assignments.repository'; @@ -65,6 +69,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module"; BookingReviewNote, BookingContractSignature, BookingContainerAllocation, + BookingWagonCancellation, CustomerTruckAssignment, CustomerTruckContainer, ]), @@ -88,7 +93,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module"; SignaturesModule, registerExchangeModule(), ], - controllers: [BookingsController], + controllers: [BookingsController, BookingAllocationController], providers: [ BookingsService, BookingsRepository, @@ -109,6 +114,8 @@ import { VehiclesModule } from "../vehicles/vehicles.module"; CustomerTruckAssignmentsRepository, CustomerTruckService, ContainerReceiptService, + BookingWagonCancellationsRepository, + BookingWagonCancellationService, ], exports: [ BookingsService, @@ -120,6 +127,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module"; ConsolidationService, CustomerTruckService, ContainerReceiptService, + BookingWagonCancellationService, ], }) export class BookingsModule { } diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.service.ts b/apps/edr-freight-api/src/modules/bookings/bookings.service.ts index 12c56ac13..e4b902fe1 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.service.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.service.ts @@ -339,6 +339,64 @@ export class BookingsService { }; } + /** + * Allocated wagons of a booking as JSON — the portal's "Wagons" tab. Same + * join chain as the carriage acceptance sheet, but structured (containers as + * an array per wagon, bulk load description when the wagon carries bulk). + * Empty array until the booking has been allocated onto a train. + */ + async wagonAllocations(bookingId: string): Promise { + return this.dataSource.query( + `SELECT a.id AS "allocationId", + tsw.sequence_no AS "sequenceNo", + w.wagon_number AS "wagonNumber", + COALESCE(wt.name, wt.code) AS "wagonType", + wt.code AS "wagonTypeCode", + wt.tare_weight_tons AS "tareWeightTons", + tsw.capacity_tons AS "capacityTons", + tsw.length_meters AS "lengthMeters", + a.allocated_weight_tons AS "allocatedWeightTons", + a.load_type AS "loadType", + a.status AS "status", + s.train_number AS "trainNumber", + s.scheduled_departure_date AS "departureAt", + so.label AS "originStation", + sd.label AS "destinationStation", + bl.cargo_description AS "bulkCargoDescription", + bl.quantity AS "bulkQuantity", + COALESCE( + json_agg( + json_build_object( + 'containerNumber', ci.container_number, + 'sealNumber', ci.seal_number, + 'positionOnWagon', ci.position_on_wagon, + 'grossWeightTons', ci.gross_weight_tons + ) ORDER BY ci.position_on_wagon, ci.container_number + ) FILTER (WHERE ci.id IS NOT NULL), + '[]' + ) AS "containers" + FROM freight.wagon_booking_allocations a + JOIN freight.train_set_wagons tsw + ON tsw.id = a.train_set_wagon_id AND tsw.deleted_at IS NULL + LEFT JOIN freight.wagon_types wt ON wt.id = tsw.wagon_type_id + LEFT JOIN freight.wagons w ON w.id = tsw.physical_wagon_id + LEFT JOIN freight.train_schedules s + ON s.train_set_id = tsw.train_set_id AND s.deleted_at IS NULL + LEFT JOIN freight.yards so ON so.id = s.origin_station_id + LEFT JOIN freight.yards sd ON sd.id = s.destination_station_id + LEFT JOIN freight.wagon_allocation_container_items ci + ON ci.wagon_booking_allocation_id = a.id AND ci.deleted_at IS NULL + LEFT JOIN freight.wagon_allocation_bulk_loads bl + ON bl.wagon_booking_allocation_id = a.id AND bl.deleted_at IS NULL + WHERE a.booking_id = $1 AND a.deleted_at IS NULL + GROUP BY tsw.id, a.id, w.wagon_number, wt.name, wt.code, wt.tare_weight_tons, + s.train_number, s.scheduled_departure_date, so.label, sd.label, + bl.cargo_description, bl.quantity + ORDER BY tsw.sequence_no`, + [bookingId], + ); + } + /** * Split the booking amount across its wagons, proportional to allocated weight * (equal shares when no weights are recorded). The last row absorbs the rounding @@ -1425,7 +1483,46 @@ export class BookingsService { tradeDirection, ); } - if (dto.scheduledDate) updates.scheduledDate = new Date(dto.scheduledDate); + // Re-pinning the departure day on an edit (e.g. fixing a CHANGES_REQUESTED + // booking) must obey the same gate as creation: the route needs an OPEN + // departure on that EAT day that can carry the cargo. Skipped when the day + // didn't change, for general contracts (period-based, no pinned day) and + // for intercity (staff assign a passing train later). + if (dto.scheduledDate) { + const day = eatDay(new Date(dto.scheduledDate)); + const dayChanged = + !existing.scheduledDate || eatDay(existing.scheduledDate) !== day; + if ( + dayChanged && + existing.bookingType !== 'GENERAL_CONTRACT' && + tradeDirection !== 'DOMESTIC' + ) { + const { hasDeparture, hasCompatible } = + await this.trainSchedulingService.checkDayCargoCompatibility( + originYardId, + destinationYardId, + day, + { + freightType: freightType as 'CONTAINER' | 'BULK', + cargoTypeId, + containerTypeIds: containers + .map((c) => c.containerTypeId) + .filter((cid): cid is string => Boolean(cid)), + }, + ); + if (!hasDeparture) { + throw new BadRequestException( + 'No departures available on the selected day for this route', + ); + } + if (!hasCompatible) { + throw new BadRequestException( + 'No wagon on the selected day can carry this cargo type — please choose another day', + ); + } + } + updates.scheduledDate = new Date(dto.scheduledDate); + } if (dto.estimatedShipmentDate) updates.estimatedShipmentDate = new Date(dto.estimatedShipmentDate); if (dto.startDate) updates.startDate = new Date(dto.startDate); diff --git a/apps/edr-freight-api/src/modules/bookings/dto/wagon-cancellation.dto.ts b/apps/edr-freight-api/src/modules/bookings/dto/wagon-cancellation.dto.ts new file mode 100644 index 000000000..6a5dfe112 --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/dto/wagon-cancellation.dto.ts @@ -0,0 +1,112 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + ArrayNotEmpty, + IsArray, + IsDateString, + IsIn, + IsInt, + IsNumber, + IsOptional, + IsString, + IsUUID, + MaxLength, + Min, + ValidateNested, +} from 'class-validator'; + +import { WAGON_CANCELLATION_STATUSES } from '../entities/booking-wagon-cancellation.entity'; + +export class CancelContainerLineDto { + @ApiProperty({ description: 'Container size (ft) as stored on the booking line, e.g. "20", "40"' }) + @IsString() + containerSize!: string; + + @ApiProperty({ description: 'How many units of this size to cancel' }) + @IsInt() + @Min(1) + quantity!: number; +} + +export class RequestWagonCancellationDto { + @ApiPropertyOptional({ + description: + 'Cancel SPECIFIC allocated wagons: wagon_booking_allocation ids from GET /bookings/:id/wagons. ' + + 'When set, wagons/containers are derived from the selected wagons and the other fields are ignored.', + type: [String], + }) + @IsOptional() + @IsArray() + @ArrayNotEmpty() + @IsUUID('4', { each: true }) + wagonAllocationIds?: string[]; + + @ApiPropertyOptional({ + description: 'BULK bookings: number of wagons to cancel (tons derived proportionally)', + }) + @IsOptional() + @IsNumber() + @Min(0.5) + wagons?: number; + + @ApiPropertyOptional({ + description: 'CONTAINER bookings: units to cancel per size (wagons derived per size)', + type: [CancelContainerLineDto], + }) + @IsOptional() + @IsArray() + @ArrayNotEmpty() + @ValidateNested({ each: true }) + @Type(() => CancelContainerLineDto) + containers?: CancelContainerLineDto[]; + + @ApiPropertyOptional({ description: 'Customer reason for the cancellation' }) + @IsOptional() + @IsString() + @MaxLength(1000) + reason?: string; +} + +export class RebookCancelledWagonsDto { + @ApiProperty({ description: 'Shipment day the credit is rebooked onto (ISO date)' }) + @IsDateString() + scheduledDate!: string; +} + +export class FilterWagonCancellationsDto { + @ApiPropertyOptional({ enum: WAGON_CANCELLATION_STATUSES, isArray: true }) + @IsOptional() + @IsArray() + @IsIn(WAGON_CANCELLATION_STATUSES as readonly string[], { each: true }) + statuses?: string[]; + + @ApiPropertyOptional({ description: 'Booking reference / company name search' }) + @IsOptional() + @IsString() + @MaxLength(120) + search?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsDateString() + from?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsDateString() + to?: string; + + @ApiPropertyOptional({ default: 1 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page?: number; + + @ApiPropertyOptional({ default: 10 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + pageSize?: number; +} diff --git a/apps/edr-freight-api/src/modules/bookings/entities/booking-wagon-cancellation.entity.ts b/apps/edr-freight-api/src/modules/bookings/entities/booking-wagon-cancellation.entity.ts new file mode 100644 index 000000000..723ea5d1c --- /dev/null +++ b/apps/edr-freight-api/src/modules/bookings/entities/booking-wagon-cancellation.entity.ts @@ -0,0 +1,137 @@ +import { BaseEntity } from '@edr/api-common'; +import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm'; + +import { Invoice } from '../../billing/entities/invoice.entity'; +import { Rate } from '../../rule-engine/entities/rate.entity'; +import { Booking } from './booking.entity'; + +export const WAGON_CANCELLATION_STATUSES = [ + // Requested; fee invoice open; wagons still allocated to the customer. + 'FEE_PENDING', + // Fee settled; booking reduced, wagons freed; credit waiting for a rebook. + 'CREDIT_AVAILABLE', + // Credit redeemed into a new PAID booking (rebookedBookingId). + 'REBOOKED', + // Customer/staff voided the request before paying the fee. Nothing changed. + 'WITHDRAWN', + // Reserved for a future expiry policy; not set by code today. + 'EXPIRED', +] as const; + +export type WagonCancellationStatus = (typeof WAGON_CANCELLATION_STATUSES)[number]; + +/** Snapshot of one physical container unit cut by the cancellation. */ +export interface CancelledUnitSnapshot { + containerSize: string; + containerNumber: string; + sealNumber?: string | null; + vgmTons: number; + isHazardous: boolean; + isReefer: boolean; +} + +/** What the cancellation cut, in the booking's own quantity terms. */ +export interface CancelledQuantities { + /** Bulk bookings: tons cut (PER_ITEM cargo: item count, matching cargoTotalWeightVgm). */ + bulkTons?: number; + /** Container bookings: units cut per container size. */ + bySize?: Record; + /** + * Container bookings: the exact physical units cut. Snapshotted at request + * time when the customer picked specific wagons, otherwise at fee settlement + * (LIFO trim). The rebook reconstructs the new booking from THESE — never + * from a soft-deleted-row scan, which could pick up units dropped by an + * unrelated batch split on the same booking. + */ + units?: CancelledUnitSnapshot[]; + /** + * Specific-wagon cancellation: the wagon_booking_allocation ids the customer + * picked in the Wagons tab. T2 releases exactly these (fallback to + * newest-first for any id that no longer exists, e.g. after a re-batch). + */ + allocationIds?: string[]; + /** + * The wagon allocations were already released from the schedule at REQUEST + * time (policy: wagons free up immediately; the fee is still owed before the + * credit can be rebooked). Tells T2 to skip its release step so it never + * deletes wagons the batch engine re-assigned in between. + */ + releasedAtRequest?: boolean; +} + +/** + * One partial-wagon-cancellation cycle on a PAID booking — the audit trail and + * the state machine. The credit itself is not a wallet balance: redeeming it + * creates a real booking through the under-contract create path and marks it + * PAID (see BookingWagonCancellationService). + */ +@Entity({ schema: 'freight', name: 'booking_wagon_cancellations' }) +@Index(['bookingId']) +@Index(['status']) +export class BookingWagonCancellation extends BaseEntity { + @Column({ name: 'booking_id', type: 'uuid' }) + bookingId!: string; + + @ManyToOne(() => Booking) + @JoinColumn({ name: 'booking_id' }) + booking?: Booking; + + @Column({ name: 'rebooked_booking_id', type: 'uuid', nullable: true }) + rebookedBookingId?: string | null; + + @ManyToOne(() => Booking, { nullable: true }) + @JoinColumn({ name: 'rebooked_booking_id' }) + rebookedBooking?: Booking | null; + + @Column({ name: 'wagons_cancelled', type: 'numeric', precision: 6, scale: 2 }) + wagonsCancelled!: number; + + @Column({ name: 'weight_tons', type: 'numeric', precision: 12, scale: 3, default: 0 }) + weightTons!: number; + + @Column({ name: 'cancelled_quantities', type: 'jsonb' }) + cancelledQuantities!: CancelledQuantities; + + /** + * The freight value of the cancelled part at the ORIGINAL booking's price — + * informational (shown to the customer as "credit worth"); no refund is ever + * issued from it, the credit is redeemed by rebooking. + */ + @Column({ name: 'credit_amount', type: 'numeric', precision: 14, scale: 2, default: 0 }) + creditAmount!: number; + + @Column({ name: 'fee_rate_id', type: 'uuid', nullable: true }) + feeRateId?: string | null; + + @ManyToOne(() => Rate, { nullable: true }) + @JoinColumn({ name: 'fee_rate_id' }) + feeRate?: Rate | null; + + @Column({ name: 'fee_amount', type: 'numeric', precision: 14, scale: 2 }) + feeAmount!: number; + + @Column({ name: 'fee_currency', type: 'varchar', length: 8, default: 'ETB' }) + feeCurrency!: string; + + @Column({ name: 'fee_invoice_id', type: 'uuid', nullable: true }) + feeInvoiceId?: string | null; + + @ManyToOne(() => Invoice, { nullable: true }) + @JoinColumn({ name: 'fee_invoice_id' }) + feeInvoice?: Invoice | null; + + @Column({ name: 'fee_paid_at', type: 'timestamptz', nullable: true }) + feePaidAt?: Date | null; + + @Column({ name: 'status', type: 'varchar', length: 30, default: 'FEE_PENDING' }) + status!: string; + + @Column({ name: 'reason', type: 'text', nullable: true }) + reason?: string | null; + + @Column({ name: 'requested_by_user_id', type: 'uuid', nullable: true }) + requestedByUserId?: string | null; + + @Column({ name: 'rebooked_at', type: 'timestamptz', nullable: true }) + rebookedAt?: Date | null; +} diff --git a/apps/edr-freight-api/src/modules/companies/companies.controller.ts b/apps/edr-freight-api/src/modules/companies/companies.controller.ts index 1c9d75487..810d4d46a 100644 --- a/apps/edr-freight-api/src/modules/companies/companies.controller.ts +++ b/apps/edr-freight-api/src/modules/companies/companies.controller.ts @@ -11,7 +11,6 @@ import { HttpCode, HttpStatus, UseInterceptors, - UseGuards, UploadedFiles, BadRequestException, NotFoundException, @@ -20,8 +19,7 @@ import { AnyFilesInterceptor } from "@nestjs/platform-express"; import { ApiOperation, ApiTags, ApiConsumes } from "@nestjs/swagger"; import { CurrentUser } from "@edr/api-common"; import type { TCurrentUser } from "@tria-plc/api-common/modules/auth/types/current-user.type"; -import { JwtGuard } from "@tria-plc/api-common/modules/auth/services/jwt.guard"; -import { BookingStaff } from "../../common/booking-guards"; +import { BookingStaff, MixedAudience, PortalCustomer } from "../../common/booking-guards"; import { assertFreightPermission, hasFreightPermission, @@ -118,6 +116,7 @@ export class CompaniesController { } @Get("getInfo") + @PortalCustomer() @ApiOperation({ summary: "Get company info for the current user" }) async getInfo( @CurrentUser() user: CurrentIamUser, @@ -131,6 +130,7 @@ export class CompaniesController { } @Get("profile") + @PortalCustomer() @ApiOperation({ summary: "Get flattened profile for the settings page" }) async getProfile( @CurrentUser() user: CurrentIamUser, @@ -146,6 +146,7 @@ export class CompaniesController { } @Get("profile/change-request") + @PortalCustomer() @ApiOperation({ summary: "Current user's open profile change request (pending/rejected)", }) @@ -161,6 +162,7 @@ export class CompaniesController { } @Post("company-profiles/:profileId/reapply") + @PortalCustomer() @ApiOperation({ summary: "Resubmit a rejected operational role for approval (→ pending)", }) @@ -176,6 +178,7 @@ export class CompaniesController { } @Get("dashboard") + @PortalCustomer() @ApiOperation({ summary: "Get portal dashboard KPIs (delivered, spend, freight volume) for the current user", @@ -191,6 +194,7 @@ export class CompaniesController { } @Post("fetch-etrade-info") + @PortalCustomer() @ApiOperation({ summary: "Fetch company info from eTrade by TIN" }) async fetchETradeInfo( @CurrentUser() user: CurrentIamUser, @@ -211,6 +215,7 @@ export class CompaniesController { } @Patch("profile") + @PortalCustomer() @ApiOperation({ summary: "Update profile (flattened settings page)" }) async updateProfile( @CurrentUser() user: CurrentIamUser, @@ -220,6 +225,7 @@ export class CompaniesController { } @Post("company-profiles") + @PortalCustomer() @ApiOperation({ summary: "Add operational profile(s) (importer/exporter/forwarder) to the current user's company", @@ -236,6 +242,7 @@ export class CompaniesController { } @Post("onboarding/start") + @PortalCustomer() @ApiOperation({ summary: "Begin onboarding: create a draft company + profile + role(s) so later steps can save incrementally", @@ -261,6 +268,7 @@ export class CompaniesController { } @Post("company-profile") + @PortalCustomer() @ApiOperation({ summary: "Create a single operational profile for the current user's company. The role starts pending and does not become the active mode", @@ -278,6 +286,7 @@ export class CompaniesController { } @Post("company-profiles/:profileId/license") + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ @@ -298,6 +307,7 @@ export class CompaniesController { } @Post("company-profiles/:profileId/license/:fileId/replace") + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ @@ -324,6 +334,7 @@ export class CompaniesController { } @Delete("company-profiles/:profileId/license/:fileId") + @PortalCustomer() @ApiOperation({ summary: "Remove a business-license file (staged for review on an approved company).", @@ -341,6 +352,7 @@ export class CompaniesController { } @Get("company-profiles/:profileId/license") + @PortalCustomer() @ApiOperation({ summary: "List business-license documents (with review state) for a profile", }) @@ -352,6 +364,7 @@ export class CompaniesController { } @Get("poa-delegation") + @PortalCustomer() @ApiOperation({ summary: "List the Power of Attorney delegation letter (with review state) for the current user's company", @@ -363,6 +376,7 @@ export class CompaniesController { } @Post("poa-delegation") + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ @@ -383,6 +397,7 @@ export class CompaniesController { } @Delete("poa-delegation/:fileId") + @PortalCustomer() @ApiOperation({ summary: "Remove the Power of Attorney delegation letter (staged for review on an approved company).", @@ -395,6 +410,7 @@ export class CompaniesController { } @Post("identity/fayda/complete") + @PortalCustomer() @ApiOperation({ summary: "Bind a completed Fayda verification to the company's owner or Power of Attorney. " + @@ -409,6 +425,7 @@ export class CompaniesController { } @Post("identity/gm/same-as-owner") + @PortalCustomer() @ApiOperation({ summary: "Declare the General Manager is the company's owner, copying the owner's verified identity across. " + @@ -421,6 +438,7 @@ export class CompaniesController { } @Delete("identity/gm") + @PortalCustomer() @ApiOperation({ summary: "Clear the General Manager's identity — the \"same as owner\" declaration or a verification, and the details either wrote. " + @@ -433,6 +451,7 @@ export class CompaniesController { } @Delete("identity/fayda/poa") + @PortalCustomer() @ApiOperation({ summary: "Remove the company's Power of Attorney — the verified identity, its details and the delegation paper together. " + @@ -445,6 +464,7 @@ export class CompaniesController { } @Patch("onboarding-step") + @PortalCustomer() @ApiOperation({ summary: "Persist the user's current onboarding wizard step" }) @HttpCode(HttpStatus.NO_CONTENT) async setOnboardingStep( @@ -455,6 +475,7 @@ export class CompaniesController { } @Get("onboarding/requirements") + @PortalCustomer() @ApiOperation({ summary: "What the current user's company still needs to finish onboarding (server-driven documents + outstanding items)", @@ -466,6 +487,7 @@ export class CompaniesController { } @Post("onboarding/complete") + @PortalCustomer() @ApiOperation({ summary: "Mark the current user's onboarding as complete" }) async completeOnboarding( @CurrentUser() user: CurrentIamUser, @@ -477,6 +499,7 @@ export class CompaniesController { // Used by portal @Post("create") + @PortalCustomer() @ApiOperation({ summary: "Create a company with its associated external profile (onboarding)", @@ -591,7 +614,11 @@ export class CompaniesController { * permission still needs the applicant's documents. */ @Get(":companyId/documents") - @UseGuards(JwtGuard) + @MixedAudience([ + FREIGHT_PERMS.customers.view, + FREIGHT_PERMS.contracts.view, + FREIGHT_PERMS.bookings.view, + ]) @ApiOperation({ summary: "List documents uploaded for a company" }) async listDocuments( @Param("companyId", ParseUUIDPipe) companyId: string, @@ -661,6 +688,7 @@ export class CompaniesController { } @Post(":companyId/documents") + @MixedAudience(FREIGHT_PERMS.customers.update) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes("multipart/form-data") @ApiOperation({ summary: "Upload documents for a company (onboarding)" }) diff --git a/apps/edr-freight-api/src/modules/companies/companies.service.ts b/apps/edr-freight-api/src/modules/companies/companies.service.ts index b5c953cac..eb6b28b44 100644 --- a/apps/edr-freight-api/src/modules/companies/companies.service.ts +++ b/apps/edr-freight-api/src/modules/companies/companies.service.ts @@ -2057,6 +2057,11 @@ export class CompaniesService { // replace it before the application counts as complete. const flaggedDelegation = delegationDue && delegation.flagged; + // Mirrors `poaProven` in buildCompanyIdentityState — see the note there. + const poaProven = identity.faydaRequired + ? identity.poa.verified + : identity.poa.verified || Boolean(identity.poa.name?.trim()); + const outstanding = [ ...missingInfo.map((f) => `Add your ${f.label.toLowerCase()}`), ...missingDocs.map((d) => `Upload your ${d.fileLabel}`), @@ -2074,8 +2079,19 @@ export class CompaniesService { ...(identity.faydaRequired && !identity.owner.verified ? ["Verify the company owner's identity with Fayda"] : []), - ...((poaRequired || poaProvided) && !identity.poa.verified - ? ["Verify your Power of Attorney's identity with Fayda"] + // Nationality-aware, exactly like `poaProven` in + // buildCompanyIdentityState and the check in `assertIdentityVerified`: + // Fayda is an Ethiopian national ID, so a foreign company's typed + // representative has to count. Demanding a verification here regardless + // made this list disagree with the rule actually enforced, and left a + // foreign freight forwarder unable to submit — asked for a Fayda + // verification its representative may have no way to obtain. + ...((poaRequired || poaProvided) && !poaProven + ? [ + identity.faydaRequired + ? "Verify your Power of Attorney's identity with Fayda" + : "Name your Power of Attorney, or verify them with Fayda", + ] : []), ...(identity.passportRequired && !identity.owner.passportNumber ? ["Add the company owner's passport number"] @@ -2089,7 +2105,10 @@ export class CompaniesService { const poaItemCount = delegationDue ? 1 : 0; // One item per identity credential the company has to prove: the owner // always (Fayda for Ethiopian, passport for foreign), plus the PoA once - // there is one — that one is Fayda whatever the nationality. + // there is one — Fayda for an Ethiopian company, a named representative + // for a foreign one, same rule as `poaProven` above. Counting a foreign + // company's typed PoA as unproven here left the progress bar permanently + // short of 100% on an item it had already satisfied. const ownerCredentialDue = identity.faydaRequired || identity.passportRequired; const ownerCredentialProven = identity.faydaRequired @@ -2099,7 +2118,7 @@ export class CompaniesService { (ownerCredentialDue ? 1 : 0) + (delegationDue ? 1 : 0); const missingIdentityCount = (ownerCredentialDue && !ownerCredentialProven ? 1 : 0) + - (delegationDue && !identity.poa.verified ? 1 : 0); + (delegationDue && !poaProven ? 1 : 0); const total = requiredInfo.length + requiredDocCount + @@ -2767,7 +2786,13 @@ export class CompaniesService { // The verified payload owns the person's details from here on. ...(result.fullName ? { [`${prefix}Name`]: result.fullName } : {}), ...(result.email ? { [`${prefix}Email`]: result.email } : {}), - ...(result.phoneNumber ? { [`${prefix}Phone`]: result.phoneNumber } : {}), + // Fayda returns whatever the national registry holds, which is routinely a + // local number ("0911223344"). Every typed phone in this service is stored + // E.164, and `@IsValidPhone()` rejects anything else — so a raw claim here + // becomes a value the portal reads back and cannot resubmit. + ...(result.phoneNumber + ? { [`${prefix}Phone`]: normalizeE164(result.phoneNumber) } + : {}), ...(result.address ? { [`${prefix}Address`]: result.address } : {}), }; diff --git a/apps/edr-freight-api/src/modules/companies/dto/update-profile.dto.ts b/apps/edr-freight-api/src/modules/companies/dto/update-profile.dto.ts index 596644fab..dc7729479 100644 --- a/apps/edr-freight-api/src/modules/companies/dto/update-profile.dto.ts +++ b/apps/edr-freight-api/src/modules/companies/dto/update-profile.dto.ts @@ -1,4 +1,12 @@ -import { IsString, IsOptional, IsEmail, MaxLength, IsEnum, IsIn } from 'class-validator'; +import { + IsString, + IsOptional, + IsEmail, + MaxLength, + IsEnum, + IsIn, + Matches, +} from 'class-validator'; import { ETHIOPIAN_REGIONS, type EthiopianRegion } from '@edr/types'; import { CompanyNationality } from '../entities/company.entity'; import { IsValidPhone } from '../../../common/validators/is-phone-number.validator'; @@ -39,9 +47,13 @@ export class UpdateProfileDto { @IsTin({ message: 'TIN must be exactly 10 digits' }) tin?: string; + // Ethiopian VAT registration numbers are 10 digits, the same shape as the + // TIN. Both portal forms enforce that; without it here the API happily stored + // whatever a stale client sent, and the two layers disagreed about what the + // column may hold. @IsOptional() @IsString() - @MaxLength(50) + @Matches(/^\d{10}$/, { message: 'VAT number must be exactly 10 digits' }) vatNumber?: string; // `fanNumber` is deliberately absent: the FAN is the Fayda number of the diff --git a/apps/edr-freight-api/src/modules/compliance/compliance.controller.ts b/apps/edr-freight-api/src/modules/compliance/compliance.controller.ts index 2a5715647..0e5949300 100644 --- a/apps/edr-freight-api/src/modules/compliance/compliance.controller.ts +++ b/apps/edr-freight-api/src/modules/compliance/compliance.controller.ts @@ -1,5 +1,7 @@ import { Controller, Post, Get, Patch, Delete, Body, Param, Query } from '@nestjs/common'; import { ApiTags, ApiOperation } from '@nestjs/swagger'; +import { BookingStaff } from '../../common/booking-guards'; +import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; import { ComplianceService } from './compliance.service'; import { CreateComplianceRecordDto, @@ -9,10 +11,12 @@ import { ComplianceType } from './entities/compliance-record.entity'; @ApiTags('Vehicle Compliance') @Controller('compliance') +@BookingStaff(FREIGHT_PERMS.compliance.view) export class ComplianceController { constructor(private readonly complianceService: ComplianceService) {} @Post() + @BookingStaff(FREIGHT_PERMS.compliance.manage) @ApiOperation({ summary: 'Create a compliance record' }) create(@Body() dto: CreateComplianceRecordDto) { return this.complianceService.create(dto); @@ -40,12 +44,14 @@ export class ComplianceController { } @Patch(':id') + @BookingStaff(FREIGHT_PERMS.compliance.manage) @ApiOperation({ summary: 'Update a compliance record' }) update(@Param('id') id: string, @Body() dto: UpdateComplianceRecordDto) { return this.complianceService.update(id, dto); } @Delete(':id') + @BookingStaff(FREIGHT_PERMS.compliance.manage) @ApiOperation({ summary: 'Soft-delete a compliance record' }) remove(@Param('id') id: string) { return this.complianceService.remove(id); diff --git a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts index 8cf1c5671..6cba17f61 100644 --- a/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts +++ b/apps/edr-freight-api/src/modules/contract-templates/contract-templates.controller.ts @@ -10,7 +10,8 @@ import { } from "@nestjs/common"; import { ApiOperation, ApiTags } from "@nestjs/swagger"; -import { FreightAdmin } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { ContractTemplatesService } from "./contract-templates.service"; import { CreateArticleDto, @@ -25,29 +26,44 @@ import { export class ContractTemplatesController { constructor(private readonly service: ContractTemplatesService) {} - // Reads stay open to authenticated staff (the backoffice Templates tab); + // Reads are staff-only (the backoffice Templates tab is the only consumer); // writes are admin-guarded like other freight configuration resources. @Get() + @BookingStaff([ + FREIGHT_PERMS.settings.contractTemplates.view, + FREIGHT_PERMS.settings.contractTemplates.manage, + FREIGHT_PERMS.admin, + ]) @ApiOperation({ summary: "List the six contract document templates" }) list() { return this.service.list(); } @Get(":code") + @BookingStaff([ + FREIGHT_PERMS.settings.contractTemplates.view, + FREIGHT_PERMS.settings.contractTemplates.manage, + FREIGHT_PERMS.admin, + ]) @ApiOperation({ summary: "Get one contract template by code" }) getByCode(@Param("code") code: string) { return this.service.getByCode(code); } @Patch(":code") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.contractTemplates.manage, FREIGHT_PERMS.admin]) @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") + @BookingStaff([ + FREIGHT_PERMS.settings.contractTemplates.view, + FREIGHT_PERMS.settings.contractTemplates.manage, + FREIGHT_PERMS.admin, + ]) @ApiOperation({ summary: "Render an HTML preview of the template against mock contract data", }) @@ -61,21 +77,21 @@ export class ContractTemplatesController { /* ------------------------- article routes ------------------------- */ @Put(":code/articles") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.contractTemplates.manage, FREIGHT_PERMS.admin]) @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() + @BookingStaff([FREIGHT_PERMS.settings.contractTemplates.manage, FREIGHT_PERMS.admin]) @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() + @BookingStaff([FREIGHT_PERMS.settings.contractTemplates.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Update an article's title or body" }) updateArticle( @Param("code") code: string, @@ -86,7 +102,7 @@ export class ContractTemplatesController { } @Delete(":code/articles/:articleId") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.contractTemplates.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Remove an article from the template" }) removeArticle( @Param("code") code: string, diff --git a/apps/edr-freight-api/src/modules/contracts/contract-booking.resubmit-cargo.spec.ts b/apps/edr-freight-api/src/modules/contracts/contract-booking.resubmit-cargo.spec.ts new file mode 100644 index 000000000..d5d15d73d --- /dev/null +++ b/apps/edr-freight-api/src/modules/contracts/contract-booking.resubmit-cargo.spec.ts @@ -0,0 +1,115 @@ +import { ContractBookingService } from './contract-booking.service'; + +/** + * OPERATION_CHANGES_REQUESTED resubmit with restated cargo. Operations can ask + * for the cargo itself to change, so a completion payload that restates + * containers must cancel the unpaid invoice, wipe the persisted cargo and + * re-run the fresh-completion path (re-persist, re-price, re-invoice). A + * payload without cargo keeps the day-only resubmit behavior. + */ +describe('ContractBookingService — changes-requested resubmit restating cargo', () => { + const CONTRACT = { + id: 'c-1', + reference: 'CTR-1', + contractKind: 'GENERAL', + freightType: 'CONTAINER', + tradeDirection: 'IMPORT', + customsClearingEnabled: false, + contractValidUntil: null, + cargoScope: [], + }; + + const bookingWithCargo = () => ({ + id: 'b-1', + contractId: 'c-1', + reference: 'BKG-1', + status: 'OPERATION_CHANGES_REQUESTED', + bookingContainers: [{ containerSize: '20FT', quantity: 4 }], + cargoTotalWeightVgm: 80, + originYardId: 'y-o', + destinationYardId: 'y-d', + }); + + function makeService() { + const bookingsRepository = { + findByIdWithFiles: jest.fn().mockResolvedValue(bookingWithCargo()), + deleteContainers: jest.fn().mockResolvedValue(undefined), + update: jest.fn().mockResolvedValue(undefined), + }; + const invoiceService = { + cancelUnpaidInvoiceForBooking: jest.fn().mockResolvedValue(undefined), + }; + const trainSchedulingService = { + assertBookingWindowOpen: jest.fn().mockResolvedValue(undefined), + }; + const contractsRepository = { + findByIdWithRelations: jest.fn().mockResolvedValue(CONTRACT), + }; + const service = new ContractBookingService( + contractsRepository as never, + bookingsRepository as never, + {} as never, // bookingPricingService + {} as never, // consolidationService + {} as never, // containerTypesService + {} as never, // ruleEngineService + {} as never, // milestoneService + invoiceService as never, + {} as never, // bookingNotifier + {} as never, // dataSource + trainSchedulingService as never, + {} as never, // bookingBatchService + {} as never, // bookingTransitionService + ); + return { service, bookingsRepository, invoiceService }; + } + + // Both paths dead-end into a downstream private assert we replace with a + // sentinel — which path threw tells us which branch the resubmit took. + const SENTINEL = new Error('reached-branch'); + + it('restated cargo cancels the invoice, wipes cargo and re-runs fresh completion', async () => { + const { service, bookingsRepository, invoiceService } = makeService(); + // First gate inside the fresh-completion (!hasCargo) path. + jest + .spyOn( + service as never as { assertWithinQuantityCap: () => Promise }, + 'assertWithinQuantityCap', + ) + .mockRejectedValue(SENTINEL); + + await expect( + service.completeUnderContract('c-1', 'b-1', { + scheduledDate: new Date().toISOString(), + containers: [{ containerSize: '20FT', quantity: 2 }], + } as never), + ).rejects.toBe(SENTINEL); + + expect(invoiceService.cancelUnpaidInvoiceForBooking).toHaveBeenCalledWith('b-1'); + expect(bookingsRepository.deleteContainers).toHaveBeenCalledWith('b-1'); + expect(bookingsRepository.update).toHaveBeenCalledWith('b-1', { + cargoTotalWeightVgm: 0, + }); + }); + + it('a day-only resubmit keeps the persisted cargo and invoice untouched', async () => { + const { service, bookingsRepository, invoiceService } = makeService(); + // First call inside the day-only (hasCargo) resubmit path. + jest + .spyOn( + service as never as { + assertPersistedContainersAvailable: () => Promise; + }, + 'assertPersistedContainersAvailable', + ) + .mockRejectedValue(SENTINEL); + + await expect( + service.completeUnderContract('c-1', 'b-1', { + scheduledDate: new Date().toISOString(), + } as never), + ).rejects.toBe(SENTINEL); + + expect(invoiceService.cancelUnpaidInvoiceForBooking).not.toHaveBeenCalled(); + expect(bookingsRepository.deleteContainers).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/edr-freight-api/src/modules/contracts/contract-booking.service.ts b/apps/edr-freight-api/src/modules/contracts/contract-booking.service.ts index 7e0a23e3f..59afdb585 100644 --- a/apps/edr-freight-api/src/modules/contracts/contract-booking.service.ts +++ b/apps/edr-freight-api/src/modules/contracts/contract-booking.service.ts @@ -98,6 +98,9 @@ export class ContractBookingService { private readonly containerTypesService: ContainerTypesService, private readonly ruleEngineService: RuleEngineService, private readonly milestoneService: ClearanceMilestoneService, + // forwardRef: part of the booking-invoice ⇄ wagon-cancellation ⇄ contracts + // require cycle (see BookingTransitionService). + @Inject(forwardRef(() => BookingInvoiceService)) private readonly invoiceService: BookingInvoiceService, private readonly bookingNotifier: BookingLifecycleNotifierService, private readonly dataSource: DataSource, @@ -692,11 +695,30 @@ export class ContractBookingService { }); const freightType = contract.freightType; - const hasCargo = + let hasCargo = (booking.bookingContainers?.length ?? 0) > 0 || Number(booking.cargoTotalWeightVgm) > 0; const warnings: string[] = []; + // Operations may return a booking asking for the CARGO to change (fewer or + // more containers), not just the day. A resubmit whose payload restates the + // cargo therefore starts the completion over: cancel the unpaid invoice + // first (it throws if money is already recorded — cargo must not change + // under a paid invoice), then wipe the persisted cargo so the fresh- + // completion path below re-persists, re-prices and re-invoices from the + // payload. A resubmit without cargo keeps today's day-only behavior. + const restatesCargo = Boolean( + dto.containers?.length || dto.bulkLines?.length, + ); + if (hasCargo && restatesCargo) { + await this.invoiceService.cancelUnpaidInvoiceForBooking(booking.id); + await this.bookingsRepository.deleteContainers(booking.id); + await this.bookingsRepository.update(booking.id, { + cargoTotalWeightVgm: 0, + } as never); + hasCargo = false; + } + // EXPORT rides whole or not at all (no split concept): the chosen day must // have a single open train that carries the whole booking. First completion // sizes from the dto's cargo; a changes-requested resubmit (cargo already @@ -1863,6 +1885,9 @@ export class ContractBookingService { async validateShipment( contractId: string, dto: CreateBookingUnderContractDto, + // Completion/resubmit preview: the booking being completed must not clash + // with its own persisted containers. + excludeBookingId?: string, ): Promise<{ overweightLines: Array<{ containerTypeCode: string; @@ -2024,6 +2049,7 @@ export class ContractBookingService { originYardId: route?.originYardId, destinationYardId: route?.destinationYardId, }, + excludeBookingId, ); containerClashErrors = clashes.map( (c) => diff --git a/apps/edr-freight-api/src/modules/contracts/contracts.controller.ts b/apps/edr-freight-api/src/modules/contracts/contracts.controller.ts index ec61fdd4a..6273be365 100644 --- a/apps/edr-freight-api/src/modules/contracts/contracts.controller.ts +++ b/apps/edr-freight-api/src/modules/contracts/contracts.controller.ts @@ -14,12 +14,10 @@ import { UnauthorizedException, UploadedFiles, UploadedFile, - UseGuards, UseInterceptors, } from '@nestjs/common'; import { CurrentUser } from '@edr/api-common'; import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type'; -import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; import { AnyFilesInterceptor, FileInterceptor } from '@nestjs/platform-express'; import type { Response } from 'express'; import { @@ -32,7 +30,7 @@ import { } from '@nestjs/swagger'; import { actorLabel } from '../warehouses/current-actor.util'; -import { BookingStaff } from '../../common/booking-guards'; +import { BookingStaff, MixedAudience, PortalCustomer } from '../../common/booking-guards'; import { ContractDocumentHistoryService } from './contract-document-history.service'; import { FREIGHT_PERMS, @@ -127,6 +125,7 @@ export class ContractsController { } @Get('booking-requests/:reqId') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'A single shipment request' }) getBookingRequest(@Param('reqId', ParseUUIDPipe) reqId: string) { return this.bookingRequestService.findOne(reqId); @@ -159,6 +158,7 @@ export class ContractsController { } @Post('booking-requests/:reqId/cancel') + @PortalCustomer() @ApiOperation({ summary: 'Customer cancels their own pending shipment request' }) cancelBookingRequest( @Param('reqId', ParseUUIDPipe) reqId: string, @@ -168,6 +168,7 @@ export class ContractsController { } @Post(':id/booking-requests') + @PortalCustomer() @ApiOperation({ summary: 'Customer submits a shipment request on a GENERAL customs contract' }) submitBookingRequest( @Param('id', ParseUUIDPipe) id: string, @@ -178,12 +179,14 @@ export class ContractsController { } @Get(':id/booking-requests') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'List the shipment requests on a contract' }) listBookingRequests(@Param('id', ParseUUIDPipe) id: string) { return this.bookingRequestService.listForContract(id); } @Post() + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Create a new contract (DRAFT) with routes + cargo scope' }) @@ -203,6 +206,7 @@ export class ContractsController { } @Get() + @MixedAudience([]) @ApiOperation({ summary: 'List contracts (paginated)' }) async findAll( @Query() filter: FilterContractDto, @@ -247,6 +251,7 @@ export class ContractsController { } @Get('my') + @PortalCustomer() @ApiOperation({ summary: "List the current customer's contracts" }) async findMy( @CurrentUser() user: AuthUserPayload, @@ -301,6 +306,7 @@ export class ContractsController { } @Get(':id') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Get contract by ID (routes, cargo scope, unit rates)' }) async findOne( @Param('id', ParseUUIDPipe) id: string, @@ -319,6 +325,7 @@ export class ContractsController { } @Patch(':id') + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes('multipart/form-data') @ApiOperation({ @@ -337,6 +344,7 @@ export class ContractsController { } @Delete(':id') + @MixedAudience([]) @HttpCode(204) @ApiOperation({ summary: 'Soft-delete DRAFT contract' }) remove(@Param('id', ParseUUIDPipe) id: string) { @@ -344,6 +352,7 @@ export class ContractsController { } @Post(':id/documents') + @MixedAudience([]) @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Upload intake documents for a contract (DRAFT only)' }) @@ -355,18 +364,21 @@ export class ContractsController { } @Post(':id/generate-price') + @MixedAudience([]) @ApiOperation({ summary: 'Generate unit-rate breakdown (no totals at contract phase)' }) generatePrice(@Param('id', ParseUUIDPipe) id: string) { return this.pricingService.generatePrice(id); } @Post(':id/submit') + @MixedAudience([]) @ApiOperation({ summary: 'Customer submit contract (freezes contract_rate_snapshots)' }) submit(@Param('id', ParseUUIDPipe) id: string) { return this.transitionService.submit(id); } @Post(':id/confirm-submit') + @MixedAudience([]) @ApiOperation({ summary: 'Confirm submit after a price change' }) confirmSubmit(@Param('id', ParseUUIDPipe) id: string) { return this.transitionService.confirmSubmit(id); @@ -427,10 +439,7 @@ export class ContractsController { // real boundary: it admits only the approver whose step is currently pending // (edit rights hand off down the chain on each approval). @Put(':id/document/articles') - @BookingStaff([ - FREIGHT_PERMS.contracts.view, - ...bothFreightTypes(FREIGHT_PERMS.contracts.staffAccept), - ]) + @BookingStaff(FREIGHT_PERMS.contracts.editDocument) @ApiOperation({ summary: 'Edit this contract\'s document articles only (per-contract; never touches the six shared templates)', @@ -515,6 +524,7 @@ export class ContractsController { } @Post(':id/cancel') + @PortalCustomer() @ApiOperation({ summary: 'Customer cancels their own contract (blocked while a booking is live)', }) @@ -591,6 +601,7 @@ export class ContractsController { } @Get(':id/contract/view') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Contract PDF view-model + rendered HTML for signing' }) async getContractView( @Param('id', ParseUUIDPipe) id: string, @@ -630,6 +641,7 @@ export class ContractsController { } @Get(':id/contract/document') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Download contract PDF' }) async downloadContractDocument( @Param('id', ParseUUIDPipe) id: string, @@ -653,7 +665,7 @@ export class ContractsController { } @Post(':id/contract/send-signing-otp') - @UseGuards(JwtGuard) + @MixedAudience(bothFreightTypes(FREIGHT_PERMS.contracts.signStaff)) @ApiOperation({ summary: "Send the sudo-mode signing OTP to the contract company's registered phone (server picks the number)", @@ -666,7 +678,7 @@ export class ContractsController { } @Post(':id/contract/sign') - @UseGuards(JwtGuard) + @MixedAudience(bothFreightTypes(FREIGHT_PERMS.contracts.signStaff)) @ApiOperation({ summary: 'Apply digital signature (customer or staff/director/ceo)' }) async signContract( @Param('id', ParseUUIDPipe) id: string, @@ -691,6 +703,7 @@ export class ContractsController { } @Post(':id/renew') + @PortalCustomer() @ApiOperation({ summary: 'Create a renewal draft linked via renewalOfId' }) async renew( @Param('id', ParseUUIDPipe) id: string, @@ -712,12 +725,14 @@ export class ContractsController { // ── Pre-booking clearance (Path B, doc §15.2.1) ──────────────────────────── @Get(':id/clearance') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Pre-booking clearance document grid on the contract' }) getClearance(@Param('id', ParseUUIDPipe) id: string) { return this.clearanceService.getClearanceView(id); } @Post(':id/clearance/documents') + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer uploads clearance documents (fieldname = document key)' }) @@ -901,6 +916,7 @@ export class ContractsController { } @Post(':id/clearance/duty/dispute') + @PortalCustomer() @ApiOperation({ summary: 'Customer disputes the advised duty/tax with a reason — reopens the step so GL Ethiopia can re-advise (repeatable)', @@ -914,6 +930,7 @@ export class ContractsController { } @Post(':id/clearance/duty-slip') + @PortalCustomer() @UseInterceptors(FileInterceptor('file')) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer uploads duty/tax payment slip on contract' }) @@ -1057,6 +1074,7 @@ export class ContractsController { // ── Booking under contract (Path A customer / Path B GL ET) ──────────────── @Post(':id/bookings') + @BookingStaff(FREIGHT_PERMS.contracts.createBooking) @ApiOperation({ summary: 'Create a shipment booking under a contract — Path A (customer) or Path B (GL Ethiopia).', @@ -1078,6 +1096,7 @@ export class ContractsController { } @Post(':id/bookings/initiate') + @BookingStaff(FREIGHT_PERMS.contracts.createBooking) @ApiOperation({ summary: 'Initiate a bare booking instance under an import/export contract (ONE_TIME or GENERAL) — no cargo, no date; enters per-booking clearance (AWAITING_DOCUMENTS). ONE_TIME customs instances are opened by the customer (or GL); GENERAL customs comes from a shipment request.', @@ -1096,6 +1115,7 @@ export class ContractsController { } @Post(':id/bookings/:bookingId/complete') + @BookingStaff(FREIGHT_PERMS.contracts.createBooking) @ApiOperation({ summary: 'Complete an initiated booking after Operations finalized its clearance — cargo + binding day, window and departure checks, pricing and invoicing.', @@ -1117,6 +1137,7 @@ export class ContractsController { } @Post(':id/validate-shipment') + @MixedAudience([FREIGHT_PERMS.contracts.createBooking, FREIGHT_PERMS.contracts.view]) @ApiOperation({ summary: 'Pre-create validation + authoritative price preview: full booking price breakdown (rail, first/last mile, surcharges), overweight lines and 20ft weight-pairing errors for a shipment payload (no booking created).', @@ -1124,11 +1145,15 @@ export class ContractsController { validateShipment( @Param('id', ParseUUIDPipe) id: string, @Body() dto: CreateBookingUnderContractDto, + // Completion/resubmit preview: exclude this booking's own persisted + // containers from the same-train clash check. + @Query('bookingId') bookingId?: string, ) { - return this.contractBookingService.validateShipment(id, dto); + return this.contractBookingService.validateShipment(id, dto, bookingId); } @Get(':id/capacity') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Remaining bookable quantity per cargo line (GENERAL draw-down cap, or the outstanding remainder of a split ONE_TIME contract)', @@ -1141,12 +1166,14 @@ export class ContractsController { // ── Clearance milestones (doc §11.3, §12.2) ──────────────────────────────── @Get(':id/milestones') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Pre-booking clearance milestones for a contract cycle' }) listContractMilestones(@Param('id', ParseUUIDPipe) id: string) { return this.milestoneService.listForContract(id); } @Get('bookings/:bookingId/milestones') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'Post-booking clearance milestones for a shipment booking' }) listBookingMilestones(@Param('bookingId', ParseUUIDPipe) bookingId: string) { return this.milestoneService.listForBooking(bookingId); @@ -1280,7 +1307,7 @@ export class ContractsController { } @Post('bookings/:bookingId/final-invoice') - @BookingStaff(FREIGHT_PERMS.contracts.clearanceDjActions) + @BookingStaff(FREIGHT_PERMS.contracts.finalInvoiceRaise) @UseInterceptors(FileInterceptor('file')) @ApiConsumes('multipart/form-data') @ApiOperation({ @@ -1307,6 +1334,7 @@ export class ContractsController { } @Post('bookings/:bookingId/final-invoice/approve') + @PortalCustomer() @ApiOperation({ summary: 'Customer approves the drafted final invoice — unlocks the payment slip', }) @@ -1321,6 +1349,7 @@ export class ContractsController { } @Post('bookings/:bookingId/final-invoice-slip') + @PortalCustomer() @UseInterceptors(FileInterceptor('file')) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer attaches the payment slip for the final invoice' }) @@ -1332,10 +1361,7 @@ export class ContractsController { } @Post('bookings/:bookingId/final-invoice/confirm') - @BookingStaff([ - FREIGHT_PERMS.contracts.clearanceDjActions, - FREIGHT_PERMS.contracts.clearanceEtActions, - ]) + @BookingStaff(FREIGHT_PERMS.contracts.finalInvoiceConfirm) @ApiOperation({ summary: 'GL (ET or DJ) confirms the payment slip — settles the final invoice' }) confirmFinalInvoicePaid( @Param('bookingId', ParseUUIDPipe) bookingId: string, @@ -1378,6 +1404,7 @@ export class ContractsController { } @Post('bookings/:bookingId/second-duty-slip') + @PortalCustomer() @UseInterceptors(FileInterceptor('file')) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer attaches the additional duty/tax payment slip' }) @@ -1403,6 +1430,7 @@ export class ContractsController { } @Post('bookings/:bookingId/duty-slip') + @PortalCustomer() @UseInterceptors(AnyFilesInterceptor()) @ApiConsumes('multipart/form-data') @ApiOperation({ summary: 'Customer uploads the duty/tax payment slip' }) @@ -1419,6 +1447,7 @@ export class ContractsController { } @Get('bookings/:bookingId/incidents') + @MixedAudience(FREIGHT_PERMS.contracts.view) @ApiOperation({ summary: 'List cargo exception/damage reports for a shipment' }) listIncidents(@Param('bookingId', ParseUUIDPipe) bookingId: string) { return this.glOperationsService.listIncidents(bookingId); diff --git a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts deleted file mode 100644 index 6f425e1bb..000000000 --- a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Controller, Get, UseGuards } from "@nestjs/common"; -import { ApiOperation, ApiTags } from "@nestjs/swagger"; - -import { PermissionGuard } from "@tria-plc/api-common/modules/auth/services/permission.guard"; - -@ApiTags("demo-permissions") -@Controller() -export class DemoPermissionsController { - @Get("test_user1") - @ApiOperation({ summary: "Permission demo (can:demo:user1)" }) - @UseGuards(PermissionGuard(["can:demo:user1"])) - testUser1() { - return { ok: true, permission: "can:demo:user1" }; - } - - @Get("test_user2") - @ApiOperation({ summary: "Permission demo (can:demo:user2)" }) - @UseGuards(PermissionGuard(["can:demo:user2"])) - testUser2() { - return { ok: true, permission: "can:demo:user2" }; - } -} diff --git a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts deleted file mode 100644 index db73ed728..000000000 --- a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Module } from "@nestjs/common"; - -import { DemoPermissionsController } from "./demo-permissions.controller"; - -@Module({ - controllers: [DemoPermissionsController], -}) -export class DemoPermissionsModule {} diff --git a/apps/edr-freight-api/src/modules/dropdown-settings/dropdown-settings.controller.ts b/apps/edr-freight-api/src/modules/dropdown-settings/dropdown-settings.controller.ts index aad904557..aaf552f40 100644 --- a/apps/edr-freight-api/src/modules/dropdown-settings/dropdown-settings.controller.ts +++ b/apps/edr-freight-api/src/modules/dropdown-settings/dropdown-settings.controller.ts @@ -14,7 +14,8 @@ import { } from "@nestjs/common"; import { ApiOperation, ApiTags } from "@nestjs/swagger"; -import { FreightAdmin } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { CreateDropdownOptionDto } from "./dto/create-dropdown-option.dto"; import { CreateDropdownSettingDto } from "./dto/create-dropdown-setting.dto"; import { ListDropdownSettingsQueryDto } from "./dto/list-dropdown-settings-query.dto"; @@ -58,14 +59,14 @@ export class DropdownSettingsController { } @Post() - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Create a new dropdown setting" }) create(@Body() dto: CreateDropdownSettingDto) { return this.service.create(dto); } @Patch(":id") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Update a dropdown setting's metadata" }) update( @Param("id", ParseUUIDPipe) id: string, @@ -75,7 +76,7 @@ export class DropdownSettingsController { } @Delete(":id") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Soft-delete a dropdown setting" }) @HttpCode(HttpStatus.NO_CONTENT) remove(@Param("id", ParseUUIDPipe) id: string) { @@ -85,7 +86,7 @@ export class DropdownSettingsController { /* ------------------------- option routes ------------------------- */ @Put(":id/options") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Replace the full option list for a setting" }) replaceOptions( @Param("id", ParseUUIDPipe) id: string, @@ -95,7 +96,7 @@ export class DropdownSettingsController { } @Post(":id/options") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Append a single option to a setting" }) addOption( @Param("id", ParseUUIDPipe) id: string, @@ -105,7 +106,7 @@ export class DropdownSettingsController { } @Patch("options/:optionId") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Update a single option" }) updateOption( @Param("optionId", ParseUUIDPipe) optionId: string, @@ -115,7 +116,7 @@ export class DropdownSettingsController { } @Delete("options/:optionId") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.dropdown.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Soft-delete a single option" }) @HttpCode(HttpStatus.NO_CONTENT) removeOption(@Param("optionId", ParseUUIDPipe) optionId: string) { diff --git a/apps/edr-freight-api/src/modules/exchange-settings/exchange-settings.controller.ts b/apps/edr-freight-api/src/modules/exchange-settings/exchange-settings.controller.ts index a6c08a317..001fc90d2 100644 --- a/apps/edr-freight-api/src/modules/exchange-settings/exchange-settings.controller.ts +++ b/apps/edr-freight-api/src/modules/exchange-settings/exchange-settings.controller.ts @@ -3,7 +3,8 @@ import { ApiBearerAuth, 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 { FreightAdmin } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { UpdateExchangeSettingDto } from "./dto/update-exchange-setting.dto"; import { ExchangeSettingsService } from "./exchange-settings.service"; @@ -14,7 +15,7 @@ export class ExchangeSettingsController { constructor(private readonly service: ExchangeSettingsService) {} @Get() - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.exchangeRate.view, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Current USD→ETB fallback rate and CBE feed health", }) @@ -32,7 +33,7 @@ export class ExchangeSettingsController { } @Patch() - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.exchangeRate.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Set the USD→ETB fallback by hand (used only while CBE is unreachable)", diff --git a/apps/edr-freight-api/src/modules/facilities/facilities.controller.ts b/apps/edr-freight-api/src/modules/facilities/facilities.controller.ts index 25fbbc365..451c4d03b 100644 --- a/apps/edr-freight-api/src/modules/facilities/facilities.controller.ts +++ b/apps/edr-freight-api/src/modules/facilities/facilities.controller.ts @@ -1,6 +1,8 @@ import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post } from '@nestjs/common'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; +import { BookingStaff } from '../../common/booking-guards'; +import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry'; import { CreateFacilityDto } from './dto/create-facility.dto'; import { UpdateFacilityDto } from './dto/update-facility.dto'; import { Facility } from './entities/facility.entity'; @@ -8,10 +10,12 @@ import { FacilitiesService } from './facilities.service'; @ApiTags('Facilities') @Controller('facilities') +@BookingStaff(FREIGHT_PERMS.facilities.view) export class FacilitiesController { constructor(private readonly facilitiesService: FacilitiesService) {} @Post() + @BookingStaff(FREIGHT_PERMS.facilities.manage) @ApiOperation({ summary: 'Create a new facility' }) async create(@Body() createFacilityDto: CreateFacilityDto): Promise { return this.facilitiesService.create(createFacilityDto); @@ -30,6 +34,7 @@ export class FacilitiesController { } @Patch(':id') + @BookingStaff(FREIGHT_PERMS.facilities.manage) @ApiOperation({ summary: 'Update a facility' }) async update(@Param('id') id: string, @Body() updateFacilityDto: UpdateFacilityDto): Promise { return this.facilitiesService.update(id, updateFacilityDto); @@ -37,6 +42,7 @@ export class FacilitiesController { @Delete(':id') @HttpCode(204) + @BookingStaff(FREIGHT_PERMS.facilities.manage) @ApiOperation({ summary: 'Delete a facility (soft delete)' }) async remove(@Param('id') id: string): Promise { return this.facilitiesService.remove(id); diff --git a/apps/edr-freight-api/src/modules/file-upload-settings/file-upload-settings.controller.ts b/apps/edr-freight-api/src/modules/file-upload-settings/file-upload-settings.controller.ts index 661339902..ab4ae98f0 100644 --- a/apps/edr-freight-api/src/modules/file-upload-settings/file-upload-settings.controller.ts +++ b/apps/edr-freight-api/src/modules/file-upload-settings/file-upload-settings.controller.ts @@ -13,7 +13,8 @@ import { } from "@nestjs/common"; import { ApiOperation, ApiTags } from "@nestjs/swagger"; -import { FreightAdmin } from "../../common/booking-guards"; +import { BookingStaff } from "../../common/booking-guards"; +import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry"; import { CreateFileUploadFieldDto } from "./dto/create-file-upload-field.dto"; import { CreateFileUploadSettingDto } from "./dto/create-file-upload-setting.dto"; import { UpdateFileUploadFieldDto } from "./dto/update-file-upload-field.dto"; @@ -53,14 +54,14 @@ export class FileUploadSettingsController { } @Post() - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Create a new file upload setting" }) create(@Body() dto: CreateFileUploadSettingDto) { return this.service.create(dto); } @Patch(":id") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Update a file upload setting's metadata" }) update( @Param("id", ParseUUIDPipe) id: string, @@ -70,7 +71,7 @@ export class FileUploadSettingsController { } @Delete(":id") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Soft-delete a file upload setting" }) @HttpCode(HttpStatus.NO_CONTENT) remove(@Param("id", ParseUUIDPipe) id: string) { @@ -80,7 +81,7 @@ export class FileUploadSettingsController { /* ------------------------- field routes ------------------------- */ @Put(":id/fields") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Replace the full field list for a setting" }) replaceFields( @Param("id", ParseUUIDPipe) id: string, @@ -90,7 +91,7 @@ export class FileUploadSettingsController { } @Post(":id/fields") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Append a single field to a setting" }) addField( @Param("id", ParseUUIDPipe) id: string, @@ -100,7 +101,7 @@ export class FileUploadSettingsController { } @Patch("fields/:fieldId") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Update a single field" }) updateField( @Param("fieldId", ParseUUIDPipe) fieldId: string, @@ -110,7 +111,7 @@ export class FileUploadSettingsController { } @Delete("fields/:fieldId") - @FreightAdmin() + @BookingStaff([FREIGHT_PERMS.settings.fileUpload.manage, FREIGHT_PERMS.admin]) @ApiOperation({ summary: "Soft-delete a single field" }) @HttpCode(HttpStatus.NO_CONTENT) removeField(@Param("fieldId", ParseUUIDPipe) fieldId: string) { diff --git a/apps/edr-freight-api/src/modules/files/files.controller.ts b/apps/edr-freight-api/src/modules/files/files.controller.ts index fc58a731c..139da9fbd 100644 --- a/apps/edr-freight-api/src/modules/files/files.controller.ts +++ b/apps/edr-freight-api/src/modules/files/files.controller.ts @@ -16,6 +16,7 @@ import { } from "@nestjs/swagger"; import { Response } from "express"; +import { MixedAudience } from "../../common/booking-guards"; import { FilesService } from "./files.service"; @ApiTags("files") @@ -25,6 +26,7 @@ export class FilesController { constructor(private readonly filesService: FilesService) {} @Get(":fileId") + @MixedAudience([]) // Authenticated: no @Public, so the global JwtGuard applies. Unguessable file // UUIDs are obscurity, not authorization — raw byte streams must require auth. // Browser inline previews (/