Ledger

Payment-data migration 025

Deploy migration 025 together with the corresponding API, worker, CLI and site builds while payment workers are paused. It replaces invoice payment_method with nullable ach_payment_method_xid / card_payment_method_xid, renames vendor and customer parent identifiers to ach_profile_xid / card_profile_xid, and converts ACH account type and preferred payout rail columns to enum names. Existing payment/work status columns are already strings. Queued payment JSON keeps its existing wire format and frozen provider identifiers.

Public API responses emit invoice payment method, ACH account type and preferred payout rail as enum names. The frontend API client binds those names to the numeric constants in Site/enums.js, like invoice display status. Form requests still submit numeric enum values; stored outbox payloads are unchanged.

The conventional 025_Seed.sql backfills method references from retained original charge requests matched to the invoice's current provider charge. Missing or conflicting evidence aborts the transaction before the old discriminator is removed. For charges without retained requests, obtain the actual method from the provider record using payment_xid, review it, and add the static rows in the seed before deployment. Never use the customer's current saved method as a historical substitute. Migration execution performs no API calls.

Read-only verification on 2026-11-06 found 99 live invoices requiring references. The seed includes 65 original Stripe card methods and nine ModT ACH bank-account references, matched by invoice ID, provider payment ID and method. All ten retained charge requests agree with those provider results. The remaining 25 older Stripe payment intents returned resource_missing under the configured account. Those exact invoice/payment pairs receive legacy:stripe:unknown in the card-method column until the old account's method IDs are recovered. Existing evidence takes precedence over the marker. It preserves card classification but cannot be queued or executed as a new charge; autopay treats it as unavailable.

A production-backup rehearsal is required before deployment. Missing methods outside the approved 25 historical payments still abort migration. Follow up with an old-account backfill to replace the markers, matching both invoice and payment IDs. Invoice payment_xid is unique (multiple nulls allowed); reusable payment method IDs are deliberately not unique. Charge-amount/fee storage, payout disposition and outbox priorities are excluded.

Local rehearsal on 2026-11-06 passed against backup 20261106T222705Z in rehearsal_025_20261106 at 127.0.0.1:10074. All 16 source table counts matched on restore. Migration 025 preserved application row counts and ledger balances, backfilled nine ACH and 65 known card methods, and marked exactly 25 old-account card methods. The other 21 invoices have no selected method. A second migration run reported no pending migrations. PgLite restoration required disabling parallel maintenance workers for index creation; production and local prod_tb were untouched.

Purpose

The ledger records the lifecycle of submitted money movements, regardless of source. Financial facts are immutable; only status can change, with trigger-written history:

Invoice and payout statuses remain user-facing projections. The ledger is the durable record used for reconciliation, balances, transaction history, and future reporting.

Scope

The implementation uses ledger for financial facts and current status, and append-only ledger_history for initial status and every status change. It is not a full double-entry accounting system. A later posting/account model may project from these entries if formal accounting requirements demand it.

Financial facts are immutable. No ledger entry is deleted, and its kind, amount, parties, source, and references cannot be changed. Corrections are new entries that reference the original entry.

Payout provider acceptance creates a Pending entry, in the same transaction that records submission. Queued intent and payouts awaiting bank setup create no ledger entry. Customer collections are tracked on invoices, not in this ledger. Their posted bank receipts create Completed BankDeposit entries exactly once. Payout settlement changes status to Completed. Failed and Canceled submitted movements remain visible without contributing to settled balances. An ambiguous submission has no entry until the existing retry/reconciliation path recovers a confirmed provider reference; it must not invent movement or a new payment.

Storage

ledger
- id                 text primary key
- kind               text not null
- amount             bigint not null
- status             text not null
- invoice_id         text null references invoice(id)
- vendor_id          text null references vendor(id)
- customer_id        text null references customer(id)
- source             text not null
- source_reference   text not null
- idempotency_key    text not null unique
- reversal_of_id     text null references ledger(id)
- memo               text null
- occurred_at        timestamptz not null
- created_at         timestamptz not null

amount is signed and stored in cents. Positive amounts move money into Tendr.me; negative amounts move money out. Zero is invalid except if a future, explicitly defined entry kind requires it.

Kind is a caller-defined string throughout the request, outbox payload, and ledger. There is no enum, registry, or database allowlist. New handlers supply their own nonblank kind without changing Core. Source is likewise a provider-owned string.

Entry Semantics

kind says what the event is. Existing conventions include (not an exhaustive list):

BankDeposit
CollectionReturn
ProcessingFee
VendorPayout
ReferralBonus
ReferralActivationFirst
ReferralActivationSecond
BusinessWithdrawal
CapitalContribution
Refund
Adjustment
Reversal

Balance queries return settled Amount (Completed only) and separate PendingAmount, within the requested account/date/kind scope. Failed/Canceled entries contribute to neither. Listing entries includes every status.

A reversal is a new entry with the opposite amount and reversal_of_id set to the original entry. The original entry remains unchanged. A refund, return, or chargeback is likewise a new entry, not a mutation of an original payment.

Business Withdrawals

Set WITHDRAWAL_ACCOUNT_ID in the CLI environment configuration to the destination ModT external account ID (not a counterparty ID). The CLI reads its name directly from ModT using the existing ModT API configuration. If the display name is empty, it uses the account-holder name (party_name); lookup failures or missing names stop the command without queueing. No account-name config or IGateway extension is needed. Then use the admin CLI:

dotnet run --project Cli -- withdraw 250.00 --env Prod

The command previews the configured destination account ID, amount, available float, and projected remaining float, then requires explicit confirmation (default no). It pins the destination in the request and queues BusinessWithdrawal through the shared payout service with no vendor, invoice, or customer association. It uses the normal automatic rail ladder (RTP, same-day ACH, ACH), falling back only on a definitive unsupported-rail response. The worker handles the float check, hourly insufficient-float deferral, provider submission, and negative Pending ledger entry. Business withdrawals do not send confirmation emails; the CLI reports the queued work. The ledger memo is generated automatically, e.g. Business withdrawal to Tendr Me LLC ••••da4b. The suffix is the last four characters of the ModT account ID, not the bank account number. The memo is pinned with the request and preserved on settlement; there is no free-text memo argument. Normal polling settles the ledger entry; no invoice status or RT reward is affected. No new table, migration, or public API endpoint is involved.

The printed request key can be supplied as --request-key <key> when recovering an interrupted command. Review existing work first: the request-key lookup lasts only as long as the outbox entry is retained. A new key requests another withdrawal. Ledger tracking and status polling do not depend on retaining that outbox entry.

Available float is not a calculation of withdrawable profit or reserved future obligations. The preview excludes unsubmitted jobs, and the worker uses the configured account pinned at queue time; later config changes do not redirect queued work. The existing float gate is a snapshot check, not an atomic reservation across concurrent payouts. Dashboard-created withdrawals are not automatically discovered by bank-deposit polling; use this command instead.

Sources and Idempotency

source identifies the origin of a financial event. It is a nonblank, case-sensitive string supplied by IGateway.Source for provider transactions. An independent gateway supplies its own stable name without changing Core or the database schema. These are examples, not a predefined list:

Stripe
ModT
Manual
System

source_reference is the stable source event identifier: a Stripe charge ID, a ModT payment-order ID, a bank wire reference, or an internal record ID for a system-generated reversal.

Callers supply a stable, generated 10-character lowercase alphanumeric idempotency_key, validated by UniqueId. They retain it across retries rather than generating a fresh key for each insert attempt. A duplicate key returns the already-recorded entry rather than inserting another one. It must match the source, source reference, kind, amount, invoice/vendor/customer scope, reversal reference, memo, and event timestamp; conflicting facts throw instead of silently succeeding. Timestamp comparisons use PostgreSQL's microsecond precision.

Payout reconciliation uses the original operation ID as this ledger key: one movement lifecycle per payout operation. The ledger entry retains this identity independently of outbox retention. This is distinct from the provider request's idempotency key. Other callers must persist their generated ledger keys before retryable execution; multiple movements need separate keys. A unique index on (source, source_reference, kind) independently prevents the same provider movement from being recorded twice under different keys.

Replaying creation returns the entry's current status without resetting it or adding history. Status changes preserve the original submission timestamp and facts.

Core API

ILedgerStore owns storage, idempotency-key validation, and the small set of ledger-specific invariants. A separate ledger service is not needed yet.

public interface ILedgerStore
{
    Task<ILedgerEntry> CreateAsync(LedgerEntryCreateOptions options);
    Task<ILedgerEntry?> GetByIdAsync(string id);
    Task<LedgerPage> ListAsync(LedgerQuery query);
    Task<LedgerBalance> GetBalanceAsync(LedgerBalanceQuery query);
    Task SetStatusAsync(string idempotencyKey, PaymentStatus status, string eventId);
    Task<IReadOnlyList<LedgerHistory>> GetHistoryAsync(string id);
}

CreateAsync inserts a financial entry with an explicit status using the shared patch writer's insert-only path, never an upsert that updates existing facts. It participates in a caller's transaction when present, or commit their own transaction otherwise. Returned records are hydrated from PostgreSQL, including database-generated created_at timestamps.

Historical timestamp repair (020)

Migration 020 corrects the old timezone-stripping created_at defaults. Its Prod-only seed also repairs historical values with set-based predicates, under the owner's confirmation that production application sessions used America/Los_Angeles and no manual corrections were made. Keep writers stopped and retain the pre-cutover backup. The migration must not be run as standalone SQL.

Normal vendor, customer, and vendor/customer-link inserts used the default; the two vendors explicitly timestamped in 001_Seed.sql are excluded. ACH rows before March 12, 2026 UTC are repaired. The reviewed inventory contains no ACH rows in the March 12-17 deployment transition window; the migration rejects any such rows rather than guessing which application version created them. Later ACH rows, invoices, card accounts, and ledger rows remain unchanged.

The correction uses explicit Los Angeles/UTC conversions, not a fixed offset. Spring-forward timestamps with an ambiguous inverse fail review. Migration version tracking prevents a second application, and production rollback is blocked to preserve that protection. Development history is deliberately not changed: it used a different timezone and already has individual repairs. The repair is a marked section of 020_Seed.Prod.sql; the backfill generator preserves it in production migration output. Schema, ledger backfill, timestamp repair, and the single 020 version record commit or roll back together.

Owner column permissions reject accidental changes to financial facts, deletes, and truncates. The database rejects zero amounts, invalid statuses, and invalid idempotency-key formats. The store rejects blank kinds, but accepts caller-defined values. The store additionally requires a reversal to negate an existing settled entry's amount in the same invoice/vendor/customer scope.

ListAsync supports UI transaction history with vendor, customer, invoice, kind, date range, and paging filters. Its page contains ILedgerEntry records directly. GetBalanceAsync returns settled and pending totals in cents for the requested scope.

List pages and their counts share one database snapshot and use event time plus ID for stable ordering (newest first by default, OldestFirst for catch-up). Null kind filters mean unrestricted; empty filters match nothing. Date bounds are inclusive and filter the financial entry's event time.

CLI Bank Balance

dotnet run --project Cli -- ledger balance --env Development

This read-only command uses ILedgerStore.GetBankBalanceAsync to report:

The query sums every Completed row, without filtering kind or source: select sum(amount) from ledger where status='Completed'; InvoicePayment and ManualCollection are prohibited ledger kinds, not hidden balance exclusions. Pending incoming funds and Failed/Canceled movements do not contribute. All figures use one database snapshot. This is a ledger-based USD estimate, not a live bank balance or profit calculation. Unsubmitted payout jobs are excluded. No operating reserve threshold is enforced. Only database configuration is required, not payment gateways or Worker.

Production's migration baseline is 019. Consolidated 020_WorkProcessingAndLedger.cs (version 202610280020) creates the final ledger, lifecycle/permissions, invoice, and work schema directly, then applies embedded 020_Seed.Prod.sql through the shared seed loader for ENVIRONMENT=Prod. Schema, data, and migration version commit atomically. There is no provider allowlist. Previously migrated development databases with the retired 020-024 chain need a separately reviewed rebaseline or disposable rebuild; no local data is automatically erased. Queue/outbox infrastructure, local payment handlers, and file-backed gateway simulation use separate work.outbox and work.job_queue tables. Migration 022 removes duplicate collection-order ledger rows and their history, preserving verified bank receipts. Take a backup before applying; it creates no payment/RT tables or ledger columns. The only added invoice columns are payment_created_at and payout_created_at, recording provider submission times. Before cleanup, matching ACH ledger order dates populate payment_created_at; matching payout movements populate payout_created_at. Production seed data supplies 57 verified Stripe charge dates and the approved invoice-date fallback for 25 older Stripe references whose account is unavailable. No provider calls run in migrations. Invoice fields track collections; payout ledger entries track disbursements. ReferralBonus, ReferralActivationFirst, and ReferralActivationSecond ledger entries are RT payout evidence, including Pending entries. Activation awards are attributed to the referred child through invoice_id; vendor_id identifies the paid referrer. Zero-award calculations create no ledger entry and may be recalculated after work retention. Invoice and RT payouts share IPayoutService, the same execution handler, polling, and ledger recording; see Local durable work. API charges and CLI payouts now always enqueue through the shared payment pipeline. The worker owns ledger/projection updates; there is no synchronous bypass mode. The API Function App now hosts the shared engine via Azure timers (work pickup every two seconds, recurring invoice discovery every minute, deposits every four hours). Provider status checks use handler-owned outbox backoff: two seconds for the first minute, one minute until age one day, and four hours thereafter. The local migration rehearsal against a production snapshot passed on October 28; see the historical rehearsal results below. Incoming bank-deposit discovery and outbox recording are implemented; the initial deposit history must be backfilled before discovery can run. Submission receipt emails are implemented. Automatic failure recovery, failure emails and webhooks remain deferred. Email delivery now uses the durable outbox; existing post-commit receipt callbacks still enqueue after business commit.

Implementation and Rollout Tracking

The pre-deployment checklist has been retired following production rollout. Outstanding work is tracked in tasks.txt. Rehearsal results below remain historical evidence, not a live production balance or instructions to rerun migration 020 or regenerate historical backfill.

Implementation includes the pure RT calculator and three-tier/three-year defaults (with LiveForever retained), shared worker/timer routing and checkpoints, daily return discovery, bank-deposit polling, buffered work traces, and operator alerts. The CLI vendor rail sets preferred rails; invoice pay retries definitively failed/canceled invoice payouts without recharging the customer. It does not cover RT retries or completed-then-returned payouts.

Production smoke-test implementation and the flat referral activation reward are tracked in the central backlog. Reward requirements remain in program notes.

Retained Invoice Funds

invoice.payout_status = 'Retained' means the operator intentionally kept the funds as float and no vendor payout is owed. It uses PaymentStatus.Retained = 8; there is no separate disposition column or autopay discriminator. Retained is valid only for the invoice payout status, not customer payment, ledger, or provider-result statuses. It has no payout provider reference and does not create a ledger cash movement. Application scheduling and reconciliation enforce payout behavior. Database CHECK constraints also enforce the closed, Core-owned invoice status values and prohibit payout references for Unknown or Retained. Migration 026 extends these checks using SQL in the migration class because FluentMigrator has no CHECK builder. This does not introduce a global allowlist for extensible work types.

Automatic invoice settlement skips vendor payout scheduling for Retained invoices. Explicit payout and retry commands also refuse to schedule them. Pending-payment polling excludes them. The API returns the payout status name Retained, while the invoice remains displayed as Paid, not Disbursed. Referral eligibility is unchanged.

Migration 026 reclassifies 28 exact operator-approved Abe @Tendr invoices: 14 from the original retained-float backfill and 14 confirmed on November 9, 2026. It validates their vendor, totals, prior statuses, and absence of payout references, timestamps, vendor-payout ledger entries and payout work before changing only payout_status. The original collection-ledger memos were removed with the collection-ledger cleanup; this status now records the decision directly on each invoice.

Deploy the application and migration with workers paused and a fresh backup. This is not a cancellation mechanism for already-queued/submitted payments: review those separately instead of manually changing their invoice status to Retained.

Migration Rehearsal (2026-10-28)

Passed using an actual production baseline-019 dump, restored into file-backed PgLite on 127.0.0.1:10074, database prod_tb. Source reads and pg_dump shared one exported, repeatable-read, read-only snapshot. All 8 source tables (312 rows) restored with matching counts. Local ownership was assigned to prod_tb_user, without superuser or CREATEROLE; source ACLs were not imported.

The actual Migrations entry point ran with ENVIRONMENT=Prod and an explicit local ConnectionStrings:Migrations command-line override. Production credentials and configuration were not changed. Migration 020 and its embedded production seed committed together. Verification confirmed:

This rehearsal predates the addition of the diagnostic work.log table to unreleased migration 020. The persistent copy has not been updated with that table; the updated migration and log writes are covered by disposable-database tests.

Private dump, logs, and verification output are under ~/.tendrme/rehearsal-ledger-20261028-10074/; the persistent cluster is its pglite/ subdirectory. This copy contains production data and must not be committed. Startup remains through the standard script:

PGLITE_WAIT=1 PGLITE_PORT=10074 \
  PGLITE_DATA_DIR="$HOME/.tendrme/rehearsal-ledger-20261028-10074/pglite" \
  PGLITE_LOG_FILE="$HOME/.tendrme/rehearsal-ledger-20261028-10074/pglite.log" \
  ./scripts/ensure-pglite.sh

PGLITE_WAIT=1 keeps a newly started server attached to the calling session; the normal default still detaches. Existing healthy servers are reused. Production was PostgreSQL 16.15; PgLite was PostgreSQL 18.3. This is not an engine-version-identical or Azure deployment rehearsal. As data grows, use an isolated server-side clone/restored backup, ideally matching production's engine, instead of downloading a full local copy. Backfill generation and bank reconciliation were cutover requirements, not instructions to repeat the completed migration.

The optional tendr ledger balance convenience command implements the bank-balance accounting rule; it is not a release blocker. Timers (including daily payout-return discovery), receipt emails, bank-deposit polling, and RT catch-up are implemented. Historical RT catch-up execution is tracked in tasks.txt.

Reconciliation and Backfill

Unreleased migrations 020-024 are flattened into migration 020, starting from production's 019 baseline. It embeds the reviewed, deterministic one-time ledger backfill from provider history, including ModT history. Migrations must not call Stripe, ModT, or any other external API at runtime.

Before refreshing its embedded data:

  1. Inventory production invoices, payment fields, and current statuses.
  2. Reconcile recorded Stripe and ModT external IDs against their providers.
  3. Identify submitted movements and their verified status. Keep unsubmitted intent and unresolved ambiguous attempts in operational tracking.
  4. Review the resulting event set and exact amounts.
  5. Encode only the approved rows as migration inserts with fixed values and pre-generated, fixed idempotency keys.

The ad hoc backfill generator reads production's 019 invoices and provider history without database writes, then emits reviewed SQL for the updated schema. Rerun it with --format migration immediately before cutover, review and replace 020_Seed.Prod.sql, then rebuild. Generation is read-only; running migration 020 applies schema and data together. Unresolved evidence blocks SQL generation rather than inventing financial history.

Scheduled status checking queries known provider payment IDs and durably queues deduplicated terminal observations through the same publication entry point intended for future authenticated webhooks. It does not write financial state. The worker's reconciliation handler updates ledger status and the invoice; other event handlers schedule invoice and RT payouts. Those changes and event completion share one transaction. Duplicate observations cannot repeat these effects. Polling will remain active as the backstop for missed webhooks; ambiguous submissions without a saved provider reference still require provider-specific recovery.

Stripe-to-Tendr bank settlement is a separate reconciliation flow, not covered by polling known customer charges or vendor payouts. BankDepositPoller discovers posted bank credits at ModT every four hours, starting one day before the latest Completed BankDeposit ledger date, regardless of source. It queues observations; BankDepositHandler records them through the normal transaction machinery. A bank receipt moves existing Stripe-held funds; it must not count as new revenue or trigger another invoice/RT payout. The bank description's Originator field identifies the source (STRIPE normalizes to Stripe; other values retain their original spelling), while the ModT transaction id is the ledger's source_reference. Reporting provider, bank reference and metadata remain in the outbox payload; no association to an individual Stripe payout is guessed. See the incoming-transfer design.

History and Permissions

ledger_history uses (id, version) as its primary key: id references ledger.id, and version starts at 1 for each entry and increments only on a status change. The ledger row's update lock serializes version allocation. There is no independent history-row ID or global sequence. The table stores previous/new status, database timestamp, originating outbox event ID, and database actor. Inserts record the original operation ID. Status updates carry the observation event ID using transaction-local context; direct admin SQL without that context records a null event ID, not a fabricated cause. Repeated unchanged status creates no history. History rolls back with the ledger transaction. Terminal statuses cannot transition again; refunds/reversals are compensating entries.

The application keeps its existing non-superuser database-owner login. The migration sets permissions immediately after creating the ledger/history and trigger, in the same transaction: SELECT/INSERT on ledger, UPDATE(status) only, and SELECT/INSERT on history. It revokes table-wide mutation privileges and checks that inherited grants do not bypass those restrictions. No table-grant loop or permission maintenance is required for unrelated application tables, including future tables created by the owner.

This protects against accidental DML, not a malicious owner. The owner can explicitly restore privileges, change schema, or disable triggers. Superusers bypass these checks and must not be the production application login.

The history trigger runs with the caller's permissions, with a pinned search path and qualified table names. History INSERT is intentionally allowed for the existing owner; UPDATE, DELETE, and TRUNCATE are denied. Application code leaves history insertion to the trigger, but the database does not prohibit direct history inserts. No extra role, CREATEROLE privilege, admin provisioning, or connection-string change is required. Migration and rollback run as the existing database owner.

Local API/CLI/Worker and migrations use dev_tb_user; Worker reads the selected Bill database config. The former dev_tb_runtime login and broad-grant provisioning scripts are retired. Production uses the existing database owner without switching to a separate application login.