Skip to main content

Bank8:Branch - Detailed Design Document

1. Scope & Context​

Bank8:Branch owns: the branch schema (schema-per-service - domain tables + branch.outbox / branch.audit_journal producer tables), the office hierarchy, staff records, tellers, cashier sessions, cash allocation and settlement, denomination counts, the shift summary, the vault position, cash in transit, and the bank8:branch:* event family.

It does NOT own: money movement or balances (Bank8:Ledger), the book of account (Bank8:Accounting), customer records (Bank8:Ledger), the teller UI (apps/eteller), staff credentials or sign-in (Sentin8:Auth), or delegation journeys (Sentin8:BFF / Sentin8:Auth).

2. Runtime Architecture​

Boot is shell-owned; this service spawns no embedded worker. It is a synchronous, request-driven service: the terminal drives sessions, counts, and movements, and each movement is one ledger posting.

Cash is a ledger position. The service holds no cash balance. Every allocation, settlement, or counter cash movement builds a posting batch and submits it to POST /v1/postings against the seeded internal accounts (cash_deposit, cheque_clearing, clearing, suspense, liquidity).

2.1 Posting mapping (normative)​

The ledger classifies an instruction by its type (debits_source() in bank8-ledger/src/handlers/postings.rs) and applies debit -= amount, credit += amount. Cash movements are all debit-direction:

Business eventBatch legs
Vault → teller floatWITHDRAWAL: vault account → teller drawer account
Teller → vault settlementWITHDRAWAL: teller drawer → vault account
Teller → teller transferWITHDRAWAL: source drawer → destination drawer
Counter cash depositWITHDRAWAL: teller drawer → customer account
Counter cash withdrawalWITHDRAWAL: customer account → teller drawer
Cash in transit outWITHDRAWAL: source → suspense account
Cash in transit receiptWITHDRAWAL: suspense → destination

The shift summary is computed from cash_transactions recorded during the session - never from a client-supplied total. A client count is input to the variance, not to the expected figure.

3. Data Model​

TablePurposeRLS tier
officesHierarchy: code, name, dot-path hierarchy, parent, activeenv
staffStaff bound to an office (business record; no credentials)env
tellersCash-handling positions with per-transaction and per-shift limitsenv
cashier_sessionsOpen/close with expected, counted, and varianceenv
cash_transactionsEvery movement with its ledger_posting_id and denomination breakdownenv
denominationsThe currency's note/coin catalogue per environmentenv
denomination_countsPer-session physical counts by denominationenv
vaultsThe branch's vault position objectenv
vault_transfersVault↔vault and vault↔logistics movementsenv
cash_in_transitIn-flight movements with source, destination, and receiptenv
branch.outbox / branch.audit_journalProducer tablesFORCE

Hierarchy querying. offices.hierarchy stores the dot-path (e.g. .0001.0007.). A subtree is a prefix scan, so "all offices under this branch" is an indexed range query rather than a recursive walk.

Money precision: all amounts NUMERIC(28,10); counted denominations are integers times the denomination value.

4. API Surface​

AudienceRoutesAuth gateEvents emitted
OfficesGET/POST /v1/offices, GET/PUT /v1/offices/{id}, POST …/{id}/deactivatebank8:branch:offices:read / :writeoffice:created, office:updated
StaffGET/POST /v1/staff, GET/PUT /v1/staff/{id}bank8:branch:staff:read / :writestaff:created, staff:updated
TellersGET/POST /v1/tellers, GET/PUT /v1/tellers/{id}bank8:branch:tellers:read / :writeteller:created, teller:updated
SessionsPOST /v1/cashiers/{id}/open, POST /v1/cashiers/{id}/close, GET /v1/cashiers/{id}/shift-summary, GET /v1/cashiersbank8:branch:cashiers:read / :writecashier:opened, cashier:closed, cash:variance
CashPOST /v1/cash-transactions, GET /v1/cash-transactions, POST /v1/cashiers/{id}/allocate, POST /v1/cashiers/{id}/settlebank8:branch:cash:read / :writecash:allocated, cash:settled
VaultGET /v1/vault/position, POST /v1/vault/transfers, POST /v1/vault/transfers/{id}/receivebank8:branch:vault:read / :writevault:transferred
DenominationsGET/POST /v1/denominationsbank8:branch:offices:read / :write-
Admin/SDUIGET /v1/admin/ui/{page}, GET /v1/admin/overviewbank8:branch:admin-

Shift summary contract (server-generated, immutable after close):

GET /v1/cashiers/{id}/shift-summary

200 { "session_id": "...", "teller_id": "...", "office_id": "...",
"opened_at": "...", "closed_at": "...",
"movements": [ { "kind": "cash_deposit", "amount": "…",
"denomination": "CAD",
"ledger_posting_id": "…" } ],
"expected_cash": "…", "counted_cash": "…",
"variance": "0.00", "variance_explained": false }

variance is always present: a zero is an explicit assertion that the drawer balanced. variance_explained flips only when an audited adjustment referencing the session is recorded.

Admin/SDUI pages: overview, offices, staff, tellers, sessions, vault, denominations.

5. Cross-Cutting Concerns​

  • Auth: platform token pipeline; Shield is the only gate. Staff identity is the platform's; Branch holds only the business record.
  • Tenant + RLS: set_tenant_context on the same connection as the query; explicit WHERE env_id = $N; every table ENABLE + FORCE ROW LEVEL SECURITY.
  • Ledger interaction: posting via POST /v1/postings; internal account reads via the public account API (staff-realm, internal-account scoped). No grant on ledger.*.
  • Idempotency: every cash movement carries branch:{session}:{kind}:{sequence} as its ledger idempotency key, so a retried terminal submission cannot double-move cash. Session open and close are unique per teller while open, and close is unique per session.
  • Event emission: outbox row in the same transaction as the domain write → relay → Bus. A variance emits on close only.
  • Audit: branch.audit_journal in the same transaction plus Sys audit push. Session close, adjustment, transfer receipt, and limit changes all record an actor.
  • TLS: PQ-TLS via sentin8-tls.

6. Failure Modes & Recovery​

FailureBehaviour
Movement without an open session409 with an explicit reason; nothing written.
Limit exceeded422; the movement is refused before any posting.
Ledger rejectsBranch surfaces the ledger's reason verbatim; no local cash record is created.
Local commit fails after ledger acceptCompensating reversal posting plus alert, mirroring the lending pattern.
Terminal crash mid-shiftExpected cash is recomputed from recorded movements on reload - the client's cached total is never authoritative.
Double-submitted movementAbsorbed by the deterministic ledger idempotency key.
Cash in transit never receivedVisible as open in-transit with age; never silently landed.

7. Concurrency & Performance Model​

Pool capped (3–5). The hot path is a single cash movement: one ledger posting plus one local row. Session rows are row-locked on write so two terminals cannot close the same shift concurrently; the ledger's balance-row serialization handles the money side.

Shift summary is computed from indexed reads scoped by session_id; the vault position is derived from movements, not maintained as a mutable counter.

8. Invariants​

  1. No session, no cash. A movement requires an open session at both source and destination where applicable.
  2. Every movement is a posting. cash_transactions.ledger_posting_id is mandatory.
  3. Limits are enforced pre-posting, not reported afterwards.
  4. Closed summaries are immutable. Corrections are new audited adjustment records referencing the session.
  5. Variance is always recorded, including zero.
  6. In-transit lands only on receipt.
  7. Offices with open work cannot be deactivated.
  8. No cross-service table access.

9. Testing Strategy​

  • Policy suite (tests/policy.rs) - seeded scope-mirror text with the handler-action parity matrix.
  • DB invariants (tests/db_invariants.rs, live bank8 DB): FORCE-RLS rejection; a single open session per teller; movement without a session rejected; closed summary immutability (UPDATE rejected); variance persisted including zero; in-transit cannot be marked received twice; offices.hierarchy prefix query returns the correct subtree; no branch view references ledger.*.
  • Shift arithmetic tests - expected cash equals the sum of recorded movements across deposit, withdrawal, allocation, and settlement mixes; variance computed from a counted breakdown.
  • OpenAPI drift (tests/openapi_drift.rs).
  • E2E - UI-only through the BFF, driven by eTeller: open shift, deposit, withdraw, close with a count, assert the summary and variance.

10. Open Questions​

  • Whether the vault is modelled as a teller with special limits or as a distinct object. Current design: distinct, so drawer and vault reconcile independently.
  • Multi-currency drawers: a drawer per denomination vs. one drawer with a cross-denomination count.
  • Whether cash-in-transit includes external logistics providers or stays internal to the branch network.

Architecture & Design: bank8:branch and its underlying concepts were designed by Hamid Jahanzad.