feat(payments): wallet pay, waive and settle groundwork (#30) #97

Merged
amiryahaya merged 13 commits from feat/30-payments into main 2026-10-26 03:30:37 +01:00
Owner

Closes #30.

What

  • payments table (migration 0018): append-only record of money that arrived or was waived. One succeeded row per sale (partial unique index), (provider, reference) unique, refund_due for money that cannot buy tickets (#36 will refund it; refund_due -> refunded is the only allowed update). A guard trigger refuses delete/truncate and any other change.
  • Wallet pay: POST /v1/me/transactions/{id}/pay. Wallet debit, sale completion and payment row in one transaction; a sale that turns out cancelled returns ErrSaleCancelled and the debit is rolled back. Idempotency-Key required.
  • Waive: POST /v1/admin/transactions/{id}/waive with a written reason (1..500). New permission admin_portal.payments.waive, held by Finance Manager and Super Admin through a platform-scope grant only (handler checks HasInOrganization(p, "")). Finance Executive and Park Management cannot waive.
  • Gateway groundwork for #31-#33: Provider interface and Service.Settle. Wrong amount/currency, cancelled/released sale, or a second payment for a completed sale becomes a refund_due row and the caller still commits. No gateway, callback route or M-Pesa job in this PR.
  • Supporting changes: sales.Completer.Lock/Sale, CompleteRequest.Actor/Reason, rest.DecodeBodyKeep, rbac.ContextWithAccess; OpenAPI + live contract test; ADR 0012, CLAUDE.md Payments section, spec R-TXN-2/R-PAY.

Lock order: sale -> wallet -> seats -> tickets.

Rulings (author's call, no design round)

  • Waiving a Processing sale is refused (revisit with #31 reconciliation).
  • Repeat of (provider, reference) is a replay; it ignores the new event's amount, wallet id and waive reason. A repeat under another provider is 409.
  • No "started attempt" record yet, so ADR 0011's "check reference against what we started" is not enforced; consider an attempts table with #31.
  • Adapters must reject unknown currencies in Parse; references must be unique per charge.

Known gaps

  • No live HTTP test with a Finance Manager token; the role split is pinned by a role test and fake-guard handler tests (listed in ADR 0012).
  • Provider.Name() has no non-test reader yet (kept for #31). DecodeBodyKeep restores a partial body on decode failure (harmless, undocumented).
  • 503 mapping is unit-tested only.

Deploy notes

  • New migration 0018 (KWS_MODE=migrate).
  • The worker (KWS_MODE=worker) must be running before checkout goes live (unchanged from #26/#29).
  • The app DB role must be neither owner nor superuser (the guard triggers can be disabled otherwise).

Verification

  • make cover: 90.1% total (minimum 80%)
  • make lint: 0 issues; make contract: ok
  • go test -race ./...: 42 packages pass; new concurrency tests also pass with -count=5
  • Dual-pass review (ponytail complexity, then correctness): no Must fix and no Critical/Important left; fixes after Pass 2 re-checked by both passes.

🤖 Generated with Claude Code

Closes #30. ## What - **`payments` table (migration 0018):** append-only record of money that arrived or was waived. One `succeeded` row per sale (partial unique index), `(provider, reference)` unique, `refund_due` for money that cannot buy tickets (#36 will refund it; `refund_due` -> `refunded` is the only allowed update). A guard trigger refuses delete/truncate and any other change. - **Wallet pay:** `POST /v1/me/transactions/{id}/pay`. Wallet debit, sale completion and payment row in one transaction; a sale that turns out cancelled returns `ErrSaleCancelled` and the debit is rolled back. Idempotency-Key required. - **Waive:** `POST /v1/admin/transactions/{id}/waive` with a written reason (1..500). New permission `admin_portal.payments.waive`, held by Finance Manager and Super Admin through a platform-scope grant only (handler checks `HasInOrganization(p, "")`). Finance Executive and Park Management cannot waive. - **Gateway groundwork for #31-#33:** `Provider` interface and `Service.Settle`. Wrong amount/currency, cancelled/released sale, or a second payment for a completed sale becomes a `refund_due` row and the caller still commits. No gateway, callback route or M-Pesa job in this PR. - Supporting changes: `sales.Completer.Lock/Sale`, `CompleteRequest.Actor/Reason`, `rest.DecodeBodyKeep`, `rbac.ContextWithAccess`; OpenAPI + live contract test; ADR 0012, CLAUDE.md Payments section, spec R-TXN-2/R-PAY. Lock order: sale -> wallet -> seats -> tickets. ## Rulings (author's call, no design round) - Waiving a **Processing** sale is refused (revisit with #31 reconciliation). - Repeat of `(provider, reference)` is a replay; it ignores the new event's amount, wallet id and waive reason. A repeat under another provider is 409. - No "started attempt" record yet, so ADR 0011's "check reference against what we started" is not enforced; consider an attempts table with #31. - Adapters must reject unknown currencies in `Parse`; references must be unique per charge. ## Known gaps - No live HTTP test with a Finance Manager token; the role split is pinned by a role test and fake-guard handler tests (listed in ADR 0012). - `Provider.Name()` has no non-test reader yet (kept for #31). `DecodeBodyKeep` restores a partial body on decode failure (harmless, undocumented). - 503 mapping is unit-tested only. ## Deploy notes - New migration 0018 (`KWS_MODE=migrate`). - The worker (`KWS_MODE=worker`) must be running before checkout goes live (unchanged from #26/#29). - The app DB role must be neither owner nor superuser (the guard triggers can be disabled otherwise). ## Verification - `make cover`: **90.1%** total (minimum 80%) - `make lint`: 0 issues; `make contract`: ok - `go test -race ./...`: 42 packages pass; new concurrency tests also pass with `-count=5` - Dual-pass review (ponytail complexity, then correctness): no Must fix and no Critical/Important left; fixes after Pass 2 re-checked by both passes. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
payments.Service pays a pending sale from the buyer's own wallet (lock
sale -> owner/status/method/expiry -> WalletOwnedBy -> Ledger.Apply with
key payment:<sale id> -> Complete -> payment row) and waives any
customer's pending sale with a reason. A cancelled result is
ErrSaleCancelled so the caller rolls back the debit; a completed sale
with a succeeded payment by the same provider is a replay.

sales: Completer.Lock, LockedSale gains UserID/CurrencyID/PaymentMethod,
CompleteRequest.Actor records who completed (waive).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Settle locks the sale, replays a known (provider, reference), and records
the money that arrived: succeeded when it completes the sale, refund_due
when the amount or currency differs, the sale is final, or Complete
cancels it. The Provider interface moves to provider.go.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
An organization-scoped grant of admin_portal.payments.waive no longer
waives any customer's sale; rbac.ContextWithAccess lets rbactest carry
the grant's scope.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
An upper-case currency id on an exact payment no longer becomes
refund_due, and an upper-case resend replays. Adds the parked Settle
tests: concurrent different references on a pending or processing
sale, overpayment, payment past expires_at, non-uuid currency.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
CompleteRequest.Reason sets the completion log's reason, so a waived
sale no longer reads "paid, reference waived". Tests: wallet pay of a
guest sale is not found, pay or waive of a processing sale is refused,
wallet pay racing a waive completes once and debits only if it won.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Migration 0018 is not deployed, so it is edited in place: the guard
also runs before INSERT and refuses status refunded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
replay reads the sale with Completer.Sale; WalletOwnedBy becomes
OwnsWallet (SELECT 1); the unused ErrAmountMismatch alias goes;
sales.Owned and rest.DecodeBodyKeep are shared by checkout, pay and
waive (the dead 401 branch in waive is gone).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
docs(payments): waive holders and scope, replay and lock-order notes (#30)
All checks were successful
ci / changes (pull_request) Successful in 18s
ci / clients (pull_request) Successful in 1m19s
ci / api (pull_request) Successful in 19m7s
ci / ci-gate (pull_request) Successful in 13s
3b1b201164
Finance Manager (and Super Admin) through a platform-scope grant only;
a waive replay ignores a new reason; a wallet-first path would
deadlock against wallet pay via the wallet_ledger foreign key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!97
No description provided.