# CASES implementation

## Delivery order

1. Preserve one director, directory, ledger, evidence matching, follow-up clock and the director screen.
2. WhatsApp Business intake: verified signed events, deduplication, contact/reference matching and human filing.
3. Gmail archive: separate OAuth read-only connection, exact archive check, bounded recent reads and intentional yearly pagination.
4. Manual WhatsApp replies and simple approved text templates, opt-in and server-side window checks.
5. Configure and validate one enterprise pilot before repeating the case kit.

## Trust and data flow

The Next.js interface calls the same-origin `/api` paths. FastAPI owns authentication and every business mutation. The server never trusts client-supplied owner IDs or identity headers. A Google OIDC login is restricted to `DIRECTOR_EMAIL`; its random opaque session credential is HttpOnly, SameSite=Lax and Secure on HTTPS. Only the credential hash is stored in the SQL sessions table. OAuth states use Authlib and short-lived signed cookies. Gmail tokens are encrypted with a separately configured Fernet key and never returned to the frontend.

WhatsApp events enter a public route that verifies the exact raw-body HMAC, business account and phone ID. Provider IDs deduplicate intake. The rest of the API requires the director session, and mutations require the configured origin. A public webhook does not grant access to the evidence inbox or ledger.

## Invoice invariants

- The client row's atomic sequence update and draft insert share one SQL transaction.
- Submitted invoices require a PO or WO and an account manager.
- Monetary amounts use integer minor units. Currencies are kept separate.
- Payments use a client lock on Postgres, a stale-balance condition and the FIFO older-invoice predicate. The payment and audit event commit together.
- Disputes retain the balance. Activity notes reset the silence clock.
- The screen ages from the invoice date; donor project end risk is independent of the silence clock.

## Evidence invariants

Both channels use the same Python matcher. Exact verified sender and exact client code/invoice/PO/WO references determine candidate clients. More than one candidate stays unfiled. A place name or similar-looking amount cannot choose a client. Manual corrections require a reason; an invoice selected for filing must belong to the chosen client. Repeated provider events preserve an existing manual correction.

The browser receives up to 500 short evidence records, not a whole mailbox. Gmail reads 50 IDs per page, then bounded metadata reads with concurrency five; it stores only headers, timestamp and a 600-character snippet. Recent reads cover 30 days. Historical reads use one selected UTC calendar year and provider pagination.

## Sending invariants

A reply is addressed to the verified contact from an inbound, filed WhatsApp message. Opt-in is required. The latest inbound timestamp is checked on the server. An expired window needs a currently approved template; unsupported media/button/named-parameter templates are rejected. The unique outbox request is committed before the Meta call. Failure or timeout after dispatch retains an unconfirmed claim. Receipt updates advance monotonically to prevent an old sent event from replacing read.

## Current checks and limits

Seventeen Python tests exercise authentication, origin checks, rules gate, submission, independent sequences, payment ordering, payment races, donor rules, owner isolation, filing corrections, webhook verification/deduplication, delivery order, encryption, opt-in/window refusal, uncertain-send replay prevention and templates. Six frontend tests cover matching and collection presentation. The Next.js production build passes.

Provider activation, hosted Postgres, deployed browser QA and live authorized sends remain unverified until hosting/configuration. The first schema uses explicit initial installation; future upgrades need versioned migrations. No real client records or provider credentials are seeded. Sample data exists only in browser memory.
