← Case study

POSTGRESQL REFERENCE · WORKING SOURCE

tests/integration_test.ts

This file ships in the runnable source archive. Synthetic fixtures and demonstration policies are identified in the README.

Download the complete project ↓
import assert from "node:assert/strict";
import {
  Api,
  book,
  capacity,
  clock,
  createHarness,
  DECLARATION,
  END,
  type Harness,
  type Json,
  palletList,
  quote,
  receive,
  rejected,
  release,
  START,
  success,
} from "./harness.ts";
import {
  adversarialRegressions,
  appendOnlyAdjustments,
  arrivalAndAmendmentEdges,
  blocksAndRelocation,
  cancelWithCustody,
  competingHolds,
  daylightSaving,
  expireWithCustody,
  expiryRace,
  idempotencyConflicts,
  incompatibleAndVariance,
  midnightBoundaries,
  overstayThreat,
  secondWarehouse,
  tariffSnapshot,
  tenantIsolation,
} from "./scenarios.ts";

async function mainWorkflow(h: Harness) {
  await h.reset();
  const empty = await capacity(h.cedar);
  assert.equal(empty.totalPositions, 8);
  assert.equal(empty.projected.minimumAvailable, 8);

  const q = await quote(h.cedar);
  assert.equal(q.totalCents, 7800, "Six pallets × three estimated days plus handling = $78");
  assert.equal((await capacity(h.cedar)).projected.minimumAvailable, 8, "A quote consumes no capacity");
  const hold = await h.cedar.post("/api/holds", { quoteId: q.id });
  assert.equal((await capacity(h.cedar)).projected.minimumAvailable, 2);

  const confirmationKey = crypto.randomUUID();
  const reservation = await h.cedar.post(`/api/holds/${hold.id}/confirm`, {}, confirmationKey);
  const replay = await h.cedar.post(`/api/holds/${hold.id}/confirm`, {}, confirmationKey);
  assert.deepEqual(replay, reservation, "Confirmation replay returns the original outcome");
  assert.equal((await h.cedar.get("/api/bootstrap")).reservations.length, 1);

  await clock(h, START);
  const receiveKey = crypto.randomUUID();
  const receiptBody = { pallets: palletList(5, "CORE") };
  const receipt = await h.operator.post(
    `/api/reservations/${reservation.id}/receive`,
    receiptBody,
    receiveKey,
  );
  assert.deepEqual(
    await h.operator.post(`/api/reservations/${reservation.id}/receive`, receiptBody, receiveKey),
    receipt,
  );
  assert.equal(receipt.pallets.length, 5);
  assert.equal(receipt.reservation.inCustody, 5);
  assert.equal(receipt.reservation.unreceived, 1);
  const afterReceipt = await capacity(h.operator);
  assert.equal(afterReceipt.physical.occupied, 5);
  const nowBucket = afterReceipt.timeline.find((bucket: Json) =>
    new Date(bucket.at).getTime() === new Date(START).getTime()
  );
  assert.ok(nowBucket, "Capacity includes the current hour");
  assert.equal(nowBucket.occupied, 5);
  assert.equal(nowBucket.committed, 1);
  assert.equal(nowBucket.available, 2, "Five occupied plus one unreceived consumes exactly six positions");

  const closed = await h.operator.post(`/api/reservations/${reservation.id}/close-receiving`, {
    disposition: "release",
    reason: "Five pallets arrived; release unused sixth position",
  });
  assert.equal(closed.unreceived, 0);
  assert.equal(closed.inCustody, 5);
  assert.equal((await capacity(h.operator)).projected.minimumAvailable, 3);
  const ids = receipt.pallets.map((p: Json) => p.id);
  assert.equal(new Set(ids).size, 5, "Every pallet has a stable unique internal identity");

  const request = await h.cedar.post(`/api/reservations/${reservation.id}/release-requests`, {
    palletIds: ids.slice(0, 2),
    reason: "Synthetic customer requests first two pallets",
  });
  assert.equal(
    (await h.cedar.get(`/api/reservations/${reservation.id}`)).inCustody,
    5,
    "A release request is not a physical departure",
  );
  await clock(h, "2026-10-27T22:00:00Z"); // October 27, 16:00 MDT.
  const releaseKey = crypto.randomUUID();
  const firstDepartureBody = {
    palletIds: ids.slice(0, 2),
    reason: "Two pallets collected",
    releaseRequestId: request.id,
  };
  const firstDeparture = await h.operator.post(
    `/api/reservations/${reservation.id}/release`,
    firstDepartureBody,
    releaseKey,
  );
  assert.deepEqual(
    await h.operator.post(`/api/reservations/${reservation.id}/release`, firstDepartureBody, releaseKey),
    firstDeparture,
  );
  assert.equal(firstDeparture.reservation.inCustody, 3);
  assert.equal(firstDeparture.reservation.released, 2);
  assert.equal((await capacity(h.operator, "2026-10-27T22:00:00Z", END)).physical.free, 5);

  await clock(h, "2026-10-28T16:00:00Z"); // October 28, 10:00 MDT.
  const final = await release(h, reservation.id, ids.slice(2));
  assert.equal(final.reservation.inCustody, 0);
  assert.equal(final.reservation.released, 5);
  assert.equal(final.reservation.status, "completed");
  const invoice = await h.cedar.get(`/api/reservations/${reservation.id}/invoice`);
  assert.deepEqual(invoice.summary, {
    palletDays: 13,
    storageCents: 2600,
    receivingCents: 2000,
    releaseCents: 1500,
    adjustmentCents: 0,
    totalCents: 6100,
  });
  assert.equal(invoice.quoteEstimateCents, 7800);
  assert.equal(invoice.currency, "USD");
  assert.equal(invoice.rateVersion, q.rateVersion);
  assert.equal(invoice.lines.length, 23, "Thirteen daily storage lines plus five receives and five releases");
  assert.equal(new Set(invoice.lines.map((line: Json) => line.id)).size, invoice.lines.length);
  assert.ok(
    invoice.lines.every((line: Json) =>
      Number.isInteger(line.totalCents) && line.rateVersion === invoice.rateVersion
    ),
  );
  const movementIds = new Set(invoice.events.map((event: Json) => event.id));
  assert.ok(
    invoice.lines.every((line: Json) =>
      line.movementIds.length > 0 && line.movementIds.every((id: string) => movementIds.has(id))
    ),
  );
  assert.ok(
    invoice.events.every((event: Json) =>
      event.actorName && event.ownerOrgId && event.occurredAt && event.recordedAt && event.reason
    ),
  );
  const storage = invoice.lines.filter((line: Json) => line.kind === "storage");
  const daysByPallet = ids.map((id: string) => storage.filter((line: Json) => line.palletId === id).length);
  assert.deepEqual(daysByPallet, [2, 2, 3, 3, 3], "Two pallets overlap Oct 26–27; three overlap Oct 26–28");
  assert.deepEqual(
    await h.cedar.get(`/api/reservations/${reservation.id}/invoice`),
    invoice,
    "Preview recalculation is reproducible",
  );
  assert.equal((await capacity(h.operator, "2026-10-28T16:00:00Z", END)).physical.free, 8);
  return { reservation, invoice, ids };
}

Deno.test({
  name: "svc_warehouse actual PostgreSQL acceptance",
  sanitizeResources: false,
  sanitizeOps: false,
  async fn(t) {
    const h = await createHarness();
    try {
      const gatePassed = await t.step(
        "GATE: customer booking → five-of-six receipt → partial/final release → USD 61 evidence",
        async () => {
          await mainWorkflow(h);
        },
      );
      assert.ok(gatePassed, "The complete customer/operator workflow is the first acceptance gate");
      if (Deno.env.get("TEST_SCOPE") === "core") return;
      const scenarios: [string, (h: Harness) => Promise<void>][] = [
        [
          "Adversarial input, precise early-receipt amendment, block union, and elapsed-start regressions",
          adversarialRegressions,
        ],
        ["Two concurrent customers compete for the final two positions", competingHolds],
        ["Hold expiry occurs while confirmation waits for the PostgreSQL warehouse lock", expiryRace],
        ["Concurrent idempotent receives/releases and changed-payload conflicts", idempotencyConflicts],
        ["Incompatible pallets and explicit capacity-checked excess delivery", incompatibleAndVariance],
        ["Partial departure then cancellation preserves remaining physical custody", cancelWithCustody],
        ["Expiry releases only unreceived commitment, never physical custody", expireWithCustody],
        ["Overstay exposes threatened booking and preserves custody after failed extension", overstayThreat],
        [
          "Blocked promised capacity creates deficit; relocation preserves position exclusivity",
          blocksAndRelocation,
        ],
        [
          "Early and late receiving, retained balance, and atomic reservation amendments",
          arrivalAndAmendmentEdges,
        ],
        ["Exact midnight exclusion and two-minute midnight overlap billing", midnightBoundaries],
        ["25-hour fall-back and 23-hour spring-forward days each bill one calendar day", daylightSaving],
        ["Accepted quote tariff survives later rate version; expired quote cannot be held", tariffSnapshot],
        ["Cross-tenant identifier tampering, customer role, session, and CSRF enforcement", tenantIsolation],
        ["Immutable movement evidence is corrected with a linked adjustment", appendOnlyAdjustments],
        ["Second warehouse fixture and lower-capability zone (after core gate)", secondWarehouse],
      ];
      for (const [name, scenario] of scenarios) {
        await t.step(name, async () => await scenario(h));
      }
    } finally {
      await h.close();
    }
  },
});