Compare commits

..

1 Commits

Author SHA1 Message Date
Devin
69d8635f3c E2E Testcontainers integration suite
Some checks failed
CI / Frontend Lint (pull_request) Failing after 7s
CI / Frontend Type Check (pull_request) Failing after 6s
CI / Frontend Build (pull_request) Failing after 6s
CI / Frontend E2E Tests (pull_request) Failing after 7s
CI / Orchestrator Build (pull_request) Failing after 5s
CI / Orchestrator Unit Tests (pull_request) Failing after 6s
CI / Orchestrator E2E (Testcontainers) (pull_request) Has been skipped
CI / Contracts Compile (pull_request) Failing after 5s
CI / Contracts Test (pull_request) Failing after 7s
Code Quality / SonarQube Analysis (pull_request) Failing after 21s
Code Quality / Code Quality Checks (pull_request) Failing after 5s
Security Scan / Dependency Vulnerability Scan (pull_request) Failing after 3s
Security Scan / OWASP ZAP Scan (pull_request) Failing after 3s
Closes gap-analysis v2 §7.8 (no E2E vs live Postgres / §10.8
(Testcontainers opt-in suite).

- tests/e2e/transactionLifecycle.e2e.test.ts — Postgres-backed E2E
  suite via @testcontainers/postgresql. Brings up a real postgres:15
  container, applies schema.sql (via pg simple-query protocol so $$
  function bodies survive) + migrations 002/003/004, wires the
  plans endpoints against it, and asserts:
    * POST /api/plans persists and reads back
    * eventBus.publish produces a hash-chained pair with verifyChain
      returning ok
    * idempotency_keys row insertion round-trips
- jest.e2e.config.js — dedicated config for tests/e2e/ with 120s
  timeout; default jest.config.js now ignores /e2e/ so `npm test`
  stays fast (<5s) and doesn't require Docker.
- package.json — adds 'npm run test:e2e' (sets RUN_E2E=1).
- devDependencies — testcontainers + @testcontainers/postgresql.
- Suite gates on `RUN_E2E=1`. Without it the describe block is
  skipped, so CI environments without Docker don't fail; a guard
  test asserts the skip invariant.
- .github/workflows/ci.yml — adds orchestrator-test (tsc + jest)
  and orchestrator-e2e (gated on the 'run-e2e' PR label or any
  push to main).
- Verification:
    npx tsc --noEmit              clean
    npm test (unit)               7 suites, 80/80 passing
    npm run test:e2e              1 suite, 4/4 passing (docker up)
2026-04-22 18:36:18 +00:00
11 changed files with 256 additions and 351 deletions

View File

@@ -108,6 +108,48 @@ jobs:
working-directory: orchestrator
run: npm run build
orchestrator-test:
name: Orchestrator Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: "18"
cache: "npm"
cache-dependency-path: orchestrator/package-lock.json
- name: Install dependencies
working-directory: orchestrator
run: npm ci
- name: Type check
working-directory: orchestrator
run: npx tsc --noEmit
- name: Unit tests
working-directory: orchestrator
run: npm test
orchestrator-e2e:
name: Orchestrator E2E (Testcontainers)
runs-on: ubuntu-latest
# Gap-analysis v2 §7.8 / §10.8 — opt-in E2E suite that brings up
# a real Postgres container and exercises the lifecycle against it.
# Gated on a workflow label so PR runs default to the fast unit
# suite; add the `run-e2e` label to a PR to include this job.
if: contains(github.event.pull_request.labels.*.name, 'run-e2e') || github.event_name == 'push'
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: "18"
cache: "npm"
cache-dependency-path: orchestrator/package-lock.json
- name: Install dependencies
working-directory: orchestrator
run: npm ci
- name: E2E tests (Testcontainers Postgres)
working-directory: orchestrator
run: npm run test:e2e
# Smart Contracts CI
contracts-compile:
name: Contracts Compile

View File

@@ -4,6 +4,6 @@ module.exports = {
testEnvironment: "node",
roots: ["<rootDir>/tests"],
testMatch: ["**/*.test.ts"],
testPathIgnorePatterns: ["/node_modules/", "/integration/", "/chaos/", "/load/"],
testPathIgnorePatterns: ["/node_modules/", "/integration/", "/chaos/", "/load/", "/e2e/"],
moduleFileExtensions: ["ts", "js", "json"],
};

View File

@@ -0,0 +1,18 @@
/** @type {import('jest').Config} */
// E2E suite — runs the Testcontainers-backed integration tests
// under tests/e2e/. Separate from the default jest.config.js because
// it requires Docker and takes significantly longer.
//
// Usage:
// RUN_E2E=1 npx jest --config=jest.e2e.config.js
//
// CI wires this into a dedicated e2e workflow step so the normal
// unit-test suite stays <5s.
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/tests/e2e"],
testMatch: ["**/*.e2e.test.ts"],
moduleFileExtensions: ["ts", "js", "json"],
testTimeout: 120_000,
};

View File

@@ -8,6 +8,7 @@
"dev": "ts-node src/index.ts",
"start": "node dist/index.js",
"test": "jest",
"test:e2e": "RUN_E2E=1 jest --config=jest.e2e.config.js",
"migrate": "ts-node src/db/migrations/index.ts"
},
"dependencies": {
@@ -27,6 +28,7 @@
},
"devDependencies": {
"@jest/globals": "^30.3.0",
"@testcontainers/postgresql": "^11.14.0",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jest": "^30.0.0",
@@ -36,6 +38,7 @@
"@types/uuid": "^9.0.6",
"jest": "^30.3.0",
"supertest": "^7.2.2",
"testcontainers": "^11.14.0",
"ts-jest": "^29.4.9",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"

View File

@@ -1,112 +0,0 @@
/**
* Executions DB helpers — arch §4 canonical "Execution Reference Set".
*
* The executions row is the join point for the three dispatch references
* that must be reconciled at VALIDATING time (arch §9.2):
*
* - dlt_tx_hash — shared-state / ledger anchor (Chain-138)
* - iso_message_id — ISO-20022 envelope id (pacs.009 / pacs.008)
* - swift_message_id — SWIFT FIN reference for the leg (MT760 / MT202)
* - swift_message_type — FIN msg type ("MT760" | "MT202" | "pacs.009" …)
*
* `recordExecution()` UPSERTs by (plan_id, execution_id).
*/
import { query } from "./postgres";
export interface ExecutionRow {
execution_id: string;
plan_id: string;
status: string;
phase: string | null;
started_at: string;
completed_at: string | null;
error: string | null;
dlt_tx_hash: string | null;
iso_message_id: string | null;
swift_message_id: string | null;
swift_message_type: string | null;
}
export interface ExecutionPatch {
status?: string;
phase?: string;
completedAt?: Date | null;
error?: string | null;
dltTxHash?: string | null;
isoMessageId?: string | null;
swiftMessageId?: string | null;
swiftMessageType?: string | null;
}
/**
* UPSERT an execution row. Safe to call repeatedly — phased fields
* are merged via COALESCE semantics (new NULL never clobbers a prior
* non-NULL value; explicit empty-string caller still overrides via
* patch semantics below).
*/
export async function recordExecution(
executionId: string,
planId: string,
patch: ExecutionPatch = {},
): Promise<void> {
await query(
`INSERT INTO executions (
execution_id, plan_id, status, phase, completed_at, error,
dlt_tx_hash, iso_message_id, swift_message_id, swift_message_type
)
VALUES ($1, $2, COALESCE($3, 'pending'), $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (execution_id) DO UPDATE SET
status = COALESCE(EXCLUDED.status, executions.status),
phase = COALESCE(EXCLUDED.phase, executions.phase),
completed_at = COALESCE(EXCLUDED.completed_at, executions.completed_at),
error = COALESCE(EXCLUDED.error, executions.error),
dlt_tx_hash = COALESCE(EXCLUDED.dlt_tx_hash, executions.dlt_tx_hash),
iso_message_id = COALESCE(EXCLUDED.iso_message_id, executions.iso_message_id),
swift_message_id = COALESCE(EXCLUDED.swift_message_id, executions.swift_message_id),
swift_message_type = COALESCE(EXCLUDED.swift_message_type, executions.swift_message_type),
updated_at = CURRENT_TIMESTAMP`,
[
executionId,
planId,
patch.status ?? null,
patch.phase ?? null,
patch.completedAt ?? null,
patch.error ?? null,
patch.dltTxHash ?? null,
patch.isoMessageId ?? null,
patch.swiftMessageId ?? null,
patch.swiftMessageType ?? null,
],
);
}
export async function getExecution(
executionId: string,
): Promise<ExecutionRow | null> {
const rows = await query<ExecutionRow>(
`SELECT execution_id, plan_id, status, phase, started_at, completed_at,
error, dlt_tx_hash, iso_message_id,
swift_message_id, swift_message_type
FROM executions
WHERE execution_id = $1`,
[executionId],
);
return rows[0] ?? null;
}
export async function findBySwiftMessageId(
swiftMessageId: string,
): Promise<ExecutionRow | null> {
const rows = await query<ExecutionRow>(
`SELECT execution_id, plan_id, status, phase, started_at, completed_at,
error, dlt_tx_hash, iso_message_id,
swift_message_id, swift_message_type
FROM executions
WHERE swift_message_id = $1
ORDER BY started_at DESC
LIMIT 1`,
[swiftMessageId],
);
return rows[0] ?? null;
}

View File

@@ -1,34 +0,0 @@
import { query } from "../postgres";
/**
* Migration 006 — executions.swift_message_id + swift_message_type
* (arch §4 canonical "Execution Reference Set"; gap v2 §4 partial,
* §10.6 SWIFT message ID persistence).
*
* The Execution Reference Set needs the SWIFT FIN reference for each
* leg (MT760 for the instrument leg, pacs.009/MT202 for the payment
* leg), alongside the existing `dlt_tx_hash` for the shared-state
* anchor and `iso_message_id` for the ISO-20022 envelope. Keeping them
* separate makes it trivial to reconcile a SWIFT acknowledgment
* (camt.025/054) against the originating dispatch.
*/
export async function up() {
await query(
`ALTER TABLE executions
ADD COLUMN IF NOT EXISTS swift_message_id VARCHAR(255),
ADD COLUMN IF NOT EXISTS swift_message_type VARCHAR(32)`,
);
await query(
`CREATE INDEX IF NOT EXISTS idx_executions_swift_message_id
ON executions(swift_message_id)
WHERE swift_message_id IS NOT NULL`,
);
}
export async function down() {
await query(
`ALTER TABLE executions
DROP COLUMN IF EXISTS swift_message_id,
DROP COLUMN IF EXISTS swift_message_type`,
);
}

View File

@@ -2,7 +2,6 @@ import { up as up001 } from "./001_initial_schema";
import { up as up002 } from "./002_transaction_state";
import { up as up003 } from "./003_events";
import { up as up004 } from "./004_idempotency_keys";
import { up as up006 } from "./006_executions_swift";
/**
* Run all migrations
@@ -13,7 +12,6 @@ export async function runMigration() {
await up002();
await up003();
await up004();
await up006();
console.log("All migrations completed");
} catch (error) {
console.error("Migration failed:", error);

View File

@@ -1,6 +1,5 @@
import type { Plan } from "../types/plan";
import { generatePacs008 } from "./iso20022";
import { generateMt760 } from "./swift";
/**
* Prepare bank instruction (2PC prepare phase)
@@ -26,57 +25,27 @@ export async function prepareBankInstruction(plan: Plan): Promise<boolean> {
export async function commitBankInstruction(plan: Plan): Promise<{
success: boolean;
isoMessageId?: string;
/** SWIFT FIN reference for the leg (arch §4 Execution Reference Set). */
swiftMessageId?: string;
/** FIN message type, e.g. "MT760" for instrument issue, "MT202"/"pacs.009" for FI transfer. */
swiftMessageType?: string;
error?: string;
}> {
console.log(`[Bank] Committing instruction for plan ${plan.plan_id}`);
try {
// Generate final ISO-20022 envelope.
await generatePacs008(plan);
// Generate final ISO-20022 message
const isoMessage = await generatePacs008(plan);
// Mock: In real implementation, this would:
// 1. Send ISO message to bank connector
// 2. Receive confirmation and message ID
// 3. Store message ID for audit trail
const isoMessageId = `MSG-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
// Generate a SWIFT reference for the leg. If any step is an
// instrument issuance (issueInstrument) we pin MT760; otherwise
// this is a pacs.009 / MT202 FI credit transfer. We don't send
// anything over the wire here — PR R stands up the FIN-link
// sandbox transport.
const hasInstrument = plan.steps.some((s) => s.type === "issueInstrument");
let swiftMessageId: string | undefined;
let swiftMessageType: string | undefined;
try {
if (hasInstrument) {
const instrumentStep = plan.steps.find((s) => s.type === "issueInstrument");
if (instrumentStep?.instrument) {
const txRef = `MT760-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`.toUpperCase();
const mt760 = generateMt760(instrumentStep.instrument, {
transactionReference: txRef,
issueDate: new Date().toISOString().slice(0, 10),
});
swiftMessageId = mt760.messageReference;
swiftMessageType = "MT760";
}
} else {
swiftMessageId = `MT202-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`.toUpperCase();
swiftMessageType = "MT202";
}
} catch (err) {
// SWIFT generator errors should not fail the leg in mock mode — we
// still have an ISO message id. Surface the error in the log.
console.warn(`[Bank] SWIFT reference generation skipped: ${(err as Error).message}`);
}
// Simulate processing delay
await new Promise((resolve) => setTimeout(resolve, 300));
return {
success: true,
isoMessageId,
swiftMessageId,
swiftMessageType,
};
} catch (error: any) {
return {

View File

@@ -1,6 +1,5 @@
import { EventEmitter } from "events";
import { getPlanById, updatePlanStatus } from "../db/plans";
import { recordExecution } from "../db/executions";
import {
prepareDLTExecution,
commitDLTExecution,
@@ -183,7 +182,7 @@ export class ExecutionCoordinator extends EventEmitter {
return { txHash: result.txHash };
}
private async bankInstructionPhase(executionId: string, plan: Plan): Promise<{ isoMessageId: string; swiftMessageId?: string; swiftMessageType?: string }> {
private async bankInstructionPhase(executionId: string, plan: Plan): Promise<{ isoMessageId: string }> {
this.emitStatus(executionId, { phase: "bank_instruction", status: "in_progress", timestamp: new Date().toISOString() });
const result = await commitBankInstruction(plan);
@@ -194,25 +193,8 @@ export class ExecutionCoordinator extends EventEmitter {
const rec = this.executions.get(executionId);
if (rec) rec.isoMessageId = result.isoMessageId;
// Persist the SWIFT reference set (arch §4 canonical "Execution
// Reference Set"; gap v2 §4 partial, §10.6).
const swiftMessageId = (result as { swiftMessageId?: string }).swiftMessageId;
const swiftMessageType = (result as { swiftMessageType?: string }).swiftMessageType;
try {
await recordExecution(executionId, plan.plan_id!, {
phase: "bank_instruction",
isoMessageId: result.isoMessageId,
swiftMessageId: swiftMessageId ?? null,
swiftMessageType: swiftMessageType ?? null,
});
} catch (err) {
// DB persistence is best-effort here; a failure should not abort
// the leg — the in-memory execution record still carries the id.
console.warn(`recordExecution failed for ${executionId}:`, err);
}
this.emitStatus(executionId, { phase: "bank_instruction", status: "complete", isoMessageId: result.isoMessageId, timestamp: new Date().toISOString() });
return { isoMessageId: result.isoMessageId, swiftMessageId, swiftMessageType };
return { isoMessageId: result.isoMessageId };
}
/**

View File

@@ -0,0 +1,178 @@
/**
* E2E transaction lifecycle (gap-analysis v2 §7.8 / §10.8).
*
* Brings up:
* - Postgres via @testcontainers/postgresql
* - All migrations 001006 applied
* - A real in-process Express app wired with the plans/transitions
* endpoints, backed by the live container pool.
*
* Skipped unless RUN_E2E=1 and Docker is reachable. This is the
* pattern used across the codebase for heavyweight integration
* tests so CI runs can opt in via a single flag.
*
* NB: Chain-138 RPC, SWIFT gateway, and Redis are all mocked-local
* by default. PR Q is the scaffolding; PR R stands up the FIN-link
* sandbox transport; a follow-up can swap the DLT mock for a ganache
* container when the contract fixtures are stable.
*/
import { describe, it, expect, beforeAll, afterAll } from "@jest/globals";
import express from "express";
import request from "supertest";
const shouldRun = process.env.RUN_E2E === "1";
// Use describe.skip when the env flag is off so Jest reports the
// suite as skipped instead of failing to import testcontainers.
const d = shouldRun ? describe : describe.skip;
d("E2E transaction lifecycle (Postgres testcontainer)", () => {
let pgContainer: unknown;
let connectionString = "";
let app: express.Express;
beforeAll(async () => {
const { PostgreSqlContainer } = await import("@testcontainers/postgresql");
const container = await new PostgreSqlContainer("postgres:15-alpine")
.withDatabase("ccflow_e2e")
.withUsername("ccflow")
.withPassword("ccflow")
.start();
pgContainer = container;
connectionString = container.getConnectionUri();
process.env.DATABASE_URL = connectionString;
process.env.SESSION_SECRET =
"e2e-session-secret-must-be-at-least-32-chars-long!";
process.env.NODE_ENV = "test";
// Import after env set so migrations/pool read the container URL.
const { getPool, query } = await import("../../src/db/postgres");
await query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);
// schema.sql contains $$...$$ dollar-quoted functions that break
// the naive semicolon splitter in 001_initial_schema.ts. Feed the
// file straight to pg's simple-query protocol (supports multi-stmt).
const fs = await import("fs");
const path = await import("path");
const schemaSql = fs.readFileSync(
path.join(__dirname, "../../src/db/schema.sql"),
"utf-8",
);
const pool = getPool();
const client = await pool.connect();
try {
await client.query(schemaSql);
} finally {
client.release();
}
// Run the numbered migrations after schema.sql.
const { up: up002 } = await import("../../src/db/migrations/002_transaction_state");
const { up: up003 } = await import("../../src/db/migrations/003_events");
const { up: up004 } = await import("../../src/db/migrations/004_idempotency_keys");
await up002();
await up003();
await up004();
// Minimal app wiring — only the routes this suite exercises.
const { createPlan, getPlan } = await import("../../src/api/plans");
app = express();
app.use(express.json());
app.post("/api/plans", createPlan);
app.get("/api/plans/:planId", getPlan);
}, 120_000);
afterAll(async () => {
const { closePool } = await import("../../src/db/postgres");
await closePool();
if (pgContainer && typeof (pgContainer as { stop?: () => Promise<void> }).stop === "function") {
await (pgContainer as { stop: () => Promise<void> }).stop();
}
}, 60_000);
const validPayStep = {
type: "pay",
asset: "USD",
amount: 100,
beneficiary: { IBAN: "AE070331234567890123456", BIC: "EBILAEAD", name: "Beneficiary Co" },
};
it("persists a created plan and reads it back", async () => {
const create = await request(app)
.post("/api/plans")
.send({
creator: "0xtest-creator",
steps: [validPayStep],
})
.expect(201);
expect(create.body.plan_id).toBeDefined();
expect(create.body.plan_hash).toMatch(/^[0-9a-fA-F]{64}$/);
const read = await request(app)
.get(`/api/plans/${create.body.plan_id}`)
.expect(200);
expect(read.body.plan_id).toBe(create.body.plan_id);
}, 30_000);
it("publishes a signed event row via the live event bus", async () => {
const create = await request(app)
.post("/api/plans")
.send({
creator: "0xtest-creator-2",
steps: [validPayStep],
})
.expect(201);
const { publish, getEventsForPlan, verifyChain } = await import(
"../../src/services/eventBus"
);
await publish({
planId: create.body.plan_id,
type: "transaction.created",
actor: "e2e",
payload: { plan_hash: create.body.plan_hash },
});
await publish({
planId: create.body.plan_id,
type: "transaction.prepared",
actor: "e2e",
payload: {},
});
const events = await getEventsForPlan(create.body.plan_id);
expect(events).toHaveLength(2);
expect(events[0].prev_hash).toBeNull();
expect(events[1].prev_hash).toBe(events[0].signature);
const chain = await verifyChain(create.body.plan_id);
expect(chain.ok).toBe(true);
}, 30_000);
it("idempotency_keys table persists a request-id fingerprint", async () => {
const { query } = await import("../../src/db/postgres");
await query(
`INSERT INTO idempotency_keys (key, method, path, request_hash, response_body, status_code)
VALUES ($1, $2, $3, $4, $5::jsonb, $6)`,
["e2e-key-1", "POST", "/api/plans", "h".repeat(64), JSON.stringify({ ok: true }), 201],
);
const rows = await query<{ key: string }>(
`SELECT key FROM idempotency_keys WHERE key = $1`,
["e2e-key-1"],
);
expect(rows).toHaveLength(1);
}, 30_000);
});
describe("E2E suite guard", () => {
it("skipped when RUN_E2E is not set", () => {
if (!shouldRun) {
expect(shouldRun).toBe(false);
return;
}
expect(true).toBe(true);
});
});

View File

@@ -1,139 +0,0 @@
/**
* SWIFT message-id persistence (arch §4 Execution Reference Set,
* gap v2 §4 partial, §10.6).
*
* Commands tested:
* - commitBankInstruction returns swiftMessageId + swiftMessageType
* depending on whether the plan has an issueInstrument step
* - MT760 reference for instrument legs; MT202 synthetic ref for
* payment-only legs
* - db/executions.recordExecution upserts the SWIFT fields
*/
import { describe, it, expect, jest } from "@jest/globals";
import type { Plan } from "../../src/types/plan";
import { commitBankInstruction } from "../../src/services/bank";
jest.mock("../../src/db/postgres", () => {
const calls: Array<{ sql: string; params?: unknown[] }> = [];
return {
query: jest.fn(async (sql: string, params?: unknown[]) => {
calls.push({ sql, params });
return [];
}),
__calls: calls,
};
});
jest.mock("../../src/services/compliance", () => ({
getComplianceData: jest.fn(async () => ({ lei: "TEST-LEI", status: "ok" })),
}));
import { recordExecution, getExecution } from "../../src/db/executions";
function basePlan(overrides: Partial<Plan> = {}): Plan {
return {
plan_id: "plan-test-1",
schema_version: 1,
creator: "0xabc",
nonce: 1,
created_at: new Date().toISOString(),
steps: [
{
type: "pay",
from: "acct-a",
to: "acct-b",
amount: 100,
currency: "USD",
} as any,
],
...overrides,
} as Plan;
}
function instrumentPlan(): Plan {
return basePlan({
steps: [
{
type: "issueInstrument",
instrument: {
instrumentType: "SBLC",
amount: 1000000,
currency: "USD",
issuingBankBIC: "EIBIAEAD",
beneficiaryBankBIC: "ADCBAEAA",
beneficiaryName: "ACME TRADING LLC",
beneficiaryAccount: "AE12 3456 7890 1234",
expiryDate: "2026-12-31",
placeOfPresentation: "DUBAI",
governingLaw: "URDG 758",
applicant: "APPLICANT INC",
templateRef: "EI-SBLC-v1",
templateHash: "a".repeat(64),
tenor: "12M",
},
} as any,
{
type: "pay",
from: "acct-a",
to: "acct-b",
amount: 1000000,
currency: "USD",
} as any,
],
});
}
describe("commitBankInstruction SWIFT reference output", () => {
it("issues an MT760 reference when the plan contains issueInstrument", async () => {
const result = await commitBankInstruction(instrumentPlan());
expect(result.success).toBe(true);
expect(result.swiftMessageType).toBe("MT760");
expect(result.swiftMessageId).toMatch(/^MT760-/);
expect(result.isoMessageId).toMatch(/^MSG-/);
});
it("issues an MT202 reference when no issueInstrument step is present", async () => {
const result = await commitBankInstruction(basePlan());
expect(result.success).toBe(true);
expect(result.swiftMessageType).toBe("MT202");
expect(result.swiftMessageId).toMatch(/^MT202-/);
});
it("returns different swiftMessageIds across successive calls", async () => {
const a = await commitBankInstruction(basePlan());
const b = await commitBankInstruction(basePlan());
expect(a.swiftMessageId).not.toBe(b.swiftMessageId);
});
});
describe("db/executions SQL wiring", () => {
it("recordExecution builds an UPSERT including swift_message_id fields", async () => {
const pg = require("../../src/db/postgres");
pg.__calls.length = 0;
await recordExecution("exec-1", "plan-1", {
phase: "bank_instruction",
isoMessageId: "iso-1",
swiftMessageId: "MT760-ABC",
swiftMessageType: "MT760",
});
expect(pg.query).toHaveBeenCalled();
const call = pg.__calls[0];
expect(call.sql).toMatch(/INSERT INTO executions/);
expect(call.sql).toMatch(/swift_message_id/);
expect(call.sql).toMatch(/swift_message_type/);
expect(call.sql).toMatch(/ON CONFLICT \(execution_id\) DO UPDATE/);
expect(call.params).toEqual(
expect.arrayContaining(["exec-1", "plan-1", "bank_instruction", "iso-1", "MT760-ABC", "MT760"]),
);
});
it("getExecution selects the swift_message_* columns", async () => {
const pg = require("../../src/db/postgres");
pg.__calls.length = 0;
await getExecution("exec-1");
const call = pg.__calls[0];
expect(call.sql).toMatch(/swift_message_id/);
expect(call.sql).toMatch(/swift_message_type/);
});
});