console: billing payment table and account matching
billing_payments keeps one row per provider balance movement, recorded once (ON CONFLICT(movement_id) DO NOTHING). RecordPayment matches the account in the same transaction: a domain purchase's payment intent (reason domain, detail the domain, tax derived above the quoted price), then the bound customer, then a recorded charge row. A refund or reversal recorded with no tax inherits its charge's share. Rows survive account deletion. Adds RematchPayments, Payments with its filter, and the reconcile cursor; both tables are classified NonApp in the gate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+721
−1
internal/console/billingpayments_store.go+366 −0internal/console/billingpayments_store_test.go+350 −0internal/console/billingstore.go+1 −1internal/console/store_gate.go+4 −0
diff --git a/internal/console/billingpayments_store.go b/internal/console/billingpayments_store.go| new file mode 100644 |
| index 000000000..be5392cf3 |
| --- /dev/null |
| +++ b/internal/console/billingpayments_store.go |
| @@ -0,0 +1,366 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// migrateBillingMoney adds the billing dashboard's money record: one row |
| +// per provider balance movement, and the reconcile's cursor. Account |
| +// deletion leaves payment rows alone: they are the money record. |
| +func (s *Store) migrateBillingMoney() error { |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_payments ( |
| + movement_id TEXT PRIMARY KEY, |
| + source_id TEXT NOT NULL, |
| + kind TEXT NOT NULL, |
| + reason TEXT NOT NULL, |
| + account_id INTEGER NOT NULL DEFAULT 0, |
| + customer TEXT NOT NULL DEFAULT '', |
| + subscription TEXT NOT NULL DEFAULT '', |
| + payment_intent TEXT NOT NULL DEFAULT '', |
| + charge TEXT NOT NULL DEFAULT '', |
| + amount INTEGER NOT NULL, |
| + tax INTEGER NOT NULL, |
| + currency TEXT NOT NULL, |
| + settled INTEGER NOT NULL, |
| + fee INTEGER NOT NULL, |
| + settled_tax INTEGER NOT NULL, |
| + settled_currency TEXT NOT NULL, |
| + detail TEXT NOT NULL DEFAULT '', |
| + at INTEGER NOT NULL, |
| + live INTEGER NOT NULL, |
| + recorded_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX IF NOT EXISTS billing_payments_at ON billing_payments(at); |
| +CREATE INDEX IF NOT EXISTS billing_payments_account_at ON billing_payments(account_id, at); |
| +CREATE INDEX IF NOT EXISTS billing_payments_subscription ON billing_payments(subscription); |
| +CREATE TABLE IF NOT EXISTS billing_payment_cursor ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + through INTEGER NOT NULL, |
| + succeeded_at INTEGER NOT NULL DEFAULT 0 |
| +);`) |
| + return err |
| +} |
| + |
| +// paymentRow is a recorded payment with what the console added: the |
| +// account it matched (0: unmatched), a detail (a domain purchase's domain) |
| +// and when it was recorded. |
| +type paymentRow struct { |
| + billing.Payment |
| + AccountID int64 |
| + Detail string |
| + RecordedAt time.Time |
| +} |
| + |
| +// sqlQueryer is a store handle or a transaction. |
| +type sqlQueryer interface { |
| + QueryRow(query string, args ...any) *sql.Row |
| +} |
| + |
| +// matchPayment finds a payment's account, first hit wins: its payment |
| +// intent is a domain purchase's (the reason becomes domain, the detail the |
| +// domain, and a charge with no tax above the quoted price carries the |
| +// difference as tax); its customer is an account's; its charge is a |
| +// recorded charge row's (whose subscription it takes when it has none). |
| +// Unmatched leaves AccountID 0. |
| +func matchPayment(q sqlQueryer, r *paymentRow) error { |
| + p := &r.Payment |
| + if p.PaymentIntent != "" { |
| + var account, amount int64 |
| + var domain, currency string |
| + err := q.QueryRow(`SELECT account_id, domain, currency, amount FROM domain_purchases |
| + WHERE payment_intent = ? ORDER BY created_at, id LIMIT 1`, p.PaymentIntent).Scan(&account, &domain, ¤cy, &amount) |
| + switch { |
| + case err == nil: |
| + r.AccountID, r.Detail = account, domain |
| + // A refund keeps its own reason: a reversal stays reversed. |
| + if p.Kind != billing.PaymentRefund { |
| + p.Reason = billing.ReasonDomain |
| + } |
| + if p.Tax == 0 && strings.EqualFold(currency, p.Currency) && p.Amount > amount { |
| + p.Tax = p.Amount - amount |
| + p.SettledTax = billing.SettledShare(p.Tax, p.Amount, p.Settled) |
| + } |
| + return nil |
| + case !errors.Is(err, sql.ErrNoRows): |
| + return err |
| + } |
| + } |
| + if p.Customer != "" { |
| + var account int64 |
| + err := q.QueryRow(`SELECT account_id FROM billing_accounts WHERE customer = ?`, p.Customer).Scan(&account) |
| + switch { |
| + case err == nil: |
| + r.AccountID = account |
| + return nil |
| + case !errors.Is(err, sql.ErrNoRows): |
| + return err |
| + } |
| + } |
| + if p.Charge != "" { |
| + var account int64 |
| + var subscription string |
| + err := q.QueryRow(`SELECT account_id, subscription FROM billing_payments |
| + WHERE source_id = ? AND kind IN ('subscription', 'once_off') AND account_id != 0 |
| + ORDER BY at, movement_id LIMIT 1`, p.Charge).Scan(&account, &subscription) |
| + switch { |
| + case err == nil: |
| + r.AccountID = account |
| + if p.Subscription == "" { |
| + p.Subscription = subscription |
| + } |
| + return nil |
| + case !errors.Is(err, sql.ErrNoRows): |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// inheritRefundTax gives a refund or reversal recorded with no tax the |
| +// share of tax its charge carried, so a refund leaves the same share of tax |
| +// as its charge: a domain charge's tax is derived on record, and the |
| +// provider's refund of it arrives with none. |
| +func inheritRefundTax(q sqlQueryer, p *billing.Payment) error { |
| + if p.Kind != billing.PaymentRefund || p.Tax != 0 || p.Charge == "" { |
| + return nil |
| + } |
| + var tax, amount int64 |
| + err := q.QueryRow(`SELECT tax, amount FROM billing_payments |
| + WHERE source_id = ? AND kind IN ('subscription', 'once_off') ORDER BY at, movement_id LIMIT 1`, p.Charge).Scan(&tax, &amount) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil || tax == 0 { |
| + return err |
| + } |
| + p.Tax = billing.SettledShare(tax, amount, p.Amount) |
| + p.SettledTax = billing.SettledShare(p.Tax, p.Amount, p.Settled) |
| + return nil |
| +} |
| + |
| +// RecordPayment records one balance movement, once: in one transaction it |
| +// matches the account, inherits a refund's tax, and inserts unless the |
| +// movement is already recorded. True when a row was written; a movement |
| +// recorded before keeps its first row. |
| +func (s *Store) RecordPayment(p billing.Payment, now time.Time) (bool, error) { |
| + if p.Movement == "" { |
| + return false, errors.New("billing: a payment with no movement") |
| + } |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return false, err |
| + } |
| + defer tx.Rollback() |
| + var seen bool |
| + if err := tx.QueryRow(`SELECT EXISTS(SELECT 1 FROM billing_payments WHERE movement_id = ?)`, p.Movement).Scan(&seen); err != nil || seen { |
| + return false, err |
| + } |
| + r := paymentRow{Payment: p} |
| + if err := matchPayment(tx, &r); err != nil { |
| + return false, err |
| + } |
| + if err := inheritRefundTax(tx, &r.Payment); err != nil { |
| + return false, err |
| + } |
| + res, err := tx.Exec(`INSERT INTO billing_payments (`+paymentColumns+`, recorded_at) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + ON CONFLICT(movement_id) DO NOTHING`, |
| + r.Movement, r.Source, string(r.Kind), r.Reason, r.AccountID, r.Customer, r.Subscription, r.PaymentIntent, r.Charge, |
| + r.Amount, r.Tax, r.Currency, r.Settled, r.Fee, r.SettledTax, r.SettledCurrency, r.Detail, |
| + r.At.Unix(), r.LiveMode, now.Unix()) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return false, err |
| + } |
| + return n == 1, tx.Commit() |
| +} |
| + |
| +// HasPayment reports whether a balance movement is recorded. |
| +func (s *Store) HasPayment(movement string) (bool, error) { |
| + var ok bool |
| + err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM billing_payments WHERE movement_id = ?)`, movement).Scan(&ok) |
| + return ok, err |
| +} |
| + |
| +// RematchPayments runs the account match again for unmatched rows (a |
| +// customer bound, or a charge recorded, after them) and returns how many |
| +// now have an account. Fees name no customer and stay unmatched. |
| +func (s *Store) RematchPayments() (int, error) { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return 0, err |
| + } |
| + defer tx.Rollback() |
| + rows, err := tx.Query(`SELECT ` + paymentColumns + `, recorded_at FROM billing_payments |
| + WHERE account_id = 0 AND kind != 'fee' ORDER BY at, movement_id`) |
| + if err != nil { |
| + return 0, err |
| + } |
| + var unmatched []paymentRow |
| + for rows.Next() { |
| + r, err := scanPaymentRow(rows) |
| + if err != nil { |
| + rows.Close() |
| + return 0, err |
| + } |
| + unmatched = append(unmatched, r) |
| + } |
| + if err := rows.Close(); err != nil { |
| + return 0, err |
| + } |
| + if err := rows.Err(); err != nil { |
| + return 0, err |
| + } |
| + matched := 0 |
| + for _, r := range unmatched { |
| + if err := matchPayment(tx, &r); err != nil { |
| + return 0, err |
| + } |
| + if r.AccountID == 0 { |
| + continue |
| + } |
| + if _, err := tx.Exec(`UPDATE billing_payments SET account_id = ?, reason = ?, detail = ?, subscription = ?, |
| + tax = ?, settled_tax = ? WHERE movement_id = ? AND account_id = 0`, |
| + r.AccountID, r.Reason, r.Detail, r.Subscription, r.Tax, r.SettledTax, r.Movement); err != nil { |
| + return 0, err |
| + } |
| + matched++ |
| + } |
| + return matched, tx.Commit() |
| +} |
| + |
| +const paymentColumns = `movement_id, source_id, kind, reason, account_id, customer, subscription, payment_intent, charge, |
| + amount, tax, currency, settled, fee, settled_tax, settled_currency, detail, at, live` |
| + |
| +func scanPaymentRow(sc interface{ Scan(...any) error }) (paymentRow, error) { |
| + var r paymentRow |
| + var kind string |
| + var at, recorded int64 |
| + if err := sc.Scan(&r.Movement, &r.Source, &kind, &r.Reason, &r.AccountID, &r.Customer, &r.Subscription, |
| + &r.PaymentIntent, &r.Charge, &r.Amount, &r.Tax, &r.Currency, &r.Settled, &r.Fee, &r.SettledTax, |
| + &r.SettledCurrency, &r.Detail, &at, &r.LiveMode, &recorded); err != nil { |
| + return paymentRow{}, err |
| + } |
| + r.Kind = billing.PaymentKind(kind) |
| + r.At, r.RecordedAt = time.Unix(at, 0).UTC(), time.Unix(recorded, 0).UTC() |
| + return r, nil |
| +} |
| + |
| +// paymentFilter selects recorded payments. From and To bound at (From |
| +// inclusive, To exclusive; zero is open). Kind "" is every kind but fee |
| +// (the payment lists), "all" every row with fees (the money sums), a |
| +// payment kind that kind, and "unmatched" rows with no account, fees |
| +// excluded. AccountID 0 is every account; Limit 0 is no limit. |
| +type paymentFilter struct { |
| + From, To time.Time |
| + Kind string |
| + AccountID int64 |
| + Offset, Limit int |
| +} |
| + |
| +// Payments lists recorded payments newest first (by at, then movement) |
| +// and how many match the filter. |
| +func (s *Store) Payments(f paymentFilter) ([]paymentRow, int, error) { |
| + var where []string |
| + var args []any |
| + switch f.Kind { |
| + case "": |
| + where = append(where, `kind != 'fee'`) |
| + case "all": |
| + case string(billing.PaymentSubscription), string(billing.PaymentOnceOff), string(billing.PaymentRefund), string(billing.PaymentFee): |
| + where, args = append(where, `kind = ?`), append(args, f.Kind) |
| + case "unmatched": |
| + where = append(where, `account_id = 0 AND kind != 'fee'`) |
| + default: |
| + return nil, 0, fmt.Errorf("billing: unknown payment kind %q", f.Kind) |
| + } |
| + if !f.From.IsZero() { |
| + where, args = append(where, `at >= ?`), append(args, f.From.Unix()) |
| + } |
| + if !f.To.IsZero() { |
| + where, args = append(where, `at < ?`), append(args, f.To.Unix()) |
| + } |
| + if f.AccountID != 0 { |
| + where, args = append(where, `account_id = ?`), append(args, f.AccountID) |
| + } |
| + cond := "" |
| + if len(where) > 0 { |
| + cond = ` WHERE ` + strings.Join(where, ` AND `) |
| + } |
| + var total int |
| + if err := s.db.QueryRow(`SELECT COUNT(*) FROM billing_payments`+cond, args...).Scan(&total); err != nil { |
| + return nil, 0, err |
| + } |
| + limit := -1 |
| + if f.Limit > 0 { |
| + limit = f.Limit |
| + } |
| + offset := max(f.Offset, 0) |
| + rows, err := s.db.Query(`SELECT `+paymentColumns+`, recorded_at FROM billing_payments`+cond+ |
| + ` ORDER BY at DESC, movement_id DESC LIMIT ? OFFSET ?`, append(args, limit, offset)...) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + defer rows.Close() |
| + var out []paymentRow |
| + for rows.Next() { |
| + r, err := scanPaymentRow(rows) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + out = append(out, r) |
| + } |
| + return out, total, rows.Err() |
| +} |
| + |
| +// PaymentCursor is how far the payment reconcile has read; ok is false |
| +// before its first read. |
| +func (s *Store) PaymentCursor() (through time.Time, ok bool, err error) { |
| + var unix int64 |
| + err = s.db.QueryRow(`SELECT through FROM billing_payment_cursor WHERE id = 1`).Scan(&unix) |
| + if errors.Is(err, sql.ErrNoRows) || (err == nil && unix == 0) { |
| + return time.Time{}, false, nil |
| + } |
| + if err != nil { |
| + return time.Time{}, false, err |
| + } |
| + return time.Unix(unix, 0).UTC(), true, nil |
| +} |
| + |
| +// SetPaymentCursor records how far the payment reconcile has read. |
| +func (s *Store) SetPaymentCursor(through time.Time) error { |
| + _, err := s.db.Exec(`INSERT INTO billing_payment_cursor (id, through) VALUES (1, ?) |
| + ON CONFLICT(id) DO UPDATE SET through = excluded.through`, through.Unix()) |
| + return err |
| +} |
| + |
| +// PaymentsReconciledAt is when the payment reconcile last succeeded; zero |
| +// when it never has. |
| +func (s *Store) PaymentsReconciledAt() (time.Time, error) { |
| + var unix int64 |
| + err := s.db.QueryRow(`SELECT succeeded_at FROM billing_payment_cursor WHERE id = 1`).Scan(&unix) |
| + if errors.Is(err, sql.ErrNoRows) || (err == nil && unix == 0) { |
| + return time.Time{}, nil |
| + } |
| + if err != nil { |
| + return time.Time{}, err |
| + } |
| + return time.Unix(unix, 0).UTC(), nil |
| +} |
| + |
| +// SetPaymentsReconciled records a successful payment reconcile. Before |
| +// any cursor the row's through is 0, which PaymentCursor reads as none. |
| +func (s *Store) SetPaymentsReconciled(at time.Time) error { |
| + _, err := s.db.Exec(`INSERT INTO billing_payment_cursor (id, through, succeeded_at) VALUES (1, 0, ?) |
| + ON CONFLICT(id) DO UPDATE SET succeeded_at = excluded.succeeded_at`, at.Unix()) |
| + return err |
| +} |
diff --git a/internal/console/billingpayments_store_test.go b/internal/console/billingpayments_store_test.go| new file mode 100644 |
| index 000000000..11c7540f5 |
| --- /dev/null |
| +++ b/internal/console/billingpayments_store_test.go |
| @@ -0,0 +1,350 @@ |
| +package console |
| + |
| +import ( |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +var paymentAt = time.Date(2026, 10, 15, 9, 0, 0, 0, time.UTC) |
| + |
| +// testCharge is a subscription charge on cus_1 of 1200 eur with 200 tax, |
| +// settled 1200 eur. |
| +func testCharge(movement, charge string) billing.Payment { |
| + return billing.Payment{ |
| + Movement: movement, Source: charge, Kind: billing.PaymentSubscription, Reason: billing.ReasonRenewal, |
| + Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_" + charge, Charge: charge, |
| + Amount: 1200, Tax: 200, Currency: "eur", |
| + Settled: 1200, Fee: 40, SettledTax: 200, SettledCurrency: "eur", |
| + At: paymentAt, LiveMode: true, |
| + } |
| +} |
| + |
| +func recordPayment(t *testing.T, s *Store, p billing.Payment) { |
| + t.Helper() |
| + wrote, err := s.RecordPayment(p, billingNow) |
| + if err != nil || !wrote { |
| + t.Fatalf("RecordPayment(%s) = %v, %v; want true, nil", p.Movement, wrote, err) |
| + } |
| +} |
| + |
| +func paymentByMovement(t *testing.T, s *Store, movement string) paymentRow { |
| + t.Helper() |
| + rows, _, err := s.Payments(paymentFilter{Kind: "all"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range rows { |
| + if r.Movement == movement { |
| + return r |
| + } |
| + } |
| + t.Fatalf("no row for %s", movement) |
| + return paymentRow{} |
| +} |
| + |
| +func TestRecordPaymentIdempotent(t *testing.T) { |
| + s, _ := planStore(t, "bab") |
| + p := testCharge("mv_1", "ch_1") |
| + if wrote, err := s.RecordPayment(p, billingNow); err != nil || !wrote { |
| + t.Fatalf("first = %v, %v; want true", wrote, err) |
| + } |
| + if wrote, err := s.RecordPayment(p, billingNow); err != nil || wrote { |
| + t.Fatalf("second = %v, %v; want false", wrote, err) |
| + } |
| + other := p |
| + other.Amount, other.Settled, other.Tax = 9999, 9999, 0 |
| + if wrote, err := s.RecordPayment(other, billingNow.Add(time.Hour)); err != nil || wrote { |
| + t.Fatalf("other amounts = %v, %v; want false", wrote, err) |
| + } |
| + rows, total, err := s.Payments(paymentFilter{Kind: "all"}) |
| + if err != nil || total != 1 || len(rows) != 1 { |
| + t.Fatalf("rows %d total %d err %v; want one", len(rows), total, err) |
| + } |
| + got := rows[0] |
| + if got.Payment.Amount != 1200 || got.Settled != 1200 || got.Tax != 200 || !got.RecordedAt.Equal(billingNow) { |
| + t.Errorf("row changed: %+v", got) |
| + } |
| + if !got.At.Equal(p.At) || got.Customer != "cus_1" || got.Subscription != "sub_1" || got.Fee != 40 || |
| + got.SettledTax != 200 || got.SettledCurrency != "eur" || !got.LiveMode || got.Source != "ch_1" || |
| + got.Kind != billing.PaymentSubscription || got.Reason != billing.ReasonRenewal || got.PaymentIntent != "pi_ch_1" { |
| + t.Errorf("row does not round trip: %+v", got) |
| + } |
| + if ok, err := s.HasPayment("mv_1"); err != nil || !ok { |
| + t.Errorf("HasPayment(mv_1) = %v, %v", ok, err) |
| + } |
| + if ok, err := s.HasPayment("mv_2"); err != nil || ok { |
| + t.Errorf("HasPayment(mv_2) = %v, %v", ok, err) |
| + } |
| +} |
| + |
| +func TestRecordPaymentMatchesCustomer(t *testing.T) { |
| + s, ids := planStore(t, "bab", "shop") |
| + if err := s.SetBillingCustomer(ids["shop"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + recordPayment(t, s, testCharge("mv_1", "ch_1")) |
| + if got := paymentByMovement(t, s, "mv_1"); got.AccountID != ids["shop"] { |
| + t.Errorf("account = %d, want shop %d", got.AccountID, ids["shop"]) |
| + } |
| +} |
| + |
| +func TestRecordPaymentMatchesDomainPurchase(t *testing.T) { |
| + s, ids := planStore(t, "bab", "shop") |
| + if err := s.CreateDomainPurchase(DomainPurchase{AccountID: ids["shop"], Domain: "shop.example.com", App: "web", |
| + Currency: "usd", Amount: 1500, PaymentIntent: "pi_dom"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := billing.Payment{ |
| + Movement: "mv_dom", Source: "ch_dom", Kind: billing.PaymentOnceOff, Reason: billing.ReasonOther, |
| + Customer: "cus_other", PaymentIntent: "pi_dom", Charge: "ch_dom", |
| + Amount: 1800, Currency: "usd", Settled: 1700, Fee: 50, SettledCurrency: "eur", At: paymentAt, |
| + } |
| + recordPayment(t, s, p) |
| + got := paymentByMovement(t, s, "mv_dom") |
| + if got.AccountID != ids["shop"] || got.Reason != billing.ReasonDomain || got.Detail != "shop.example.com" { |
| + t.Errorf("got account %d reason %q detail %q; want shop, domain, shop.example.com", got.AccountID, got.Reason, got.Detail) |
| + } |
| + if got.Tax != 300 || got.SettledTax != billing.SettledShare(300, 1800, 1700) { |
| + t.Errorf("tax %d settled tax %d; want 300, %d", got.Tax, got.SettledTax, billing.SettledShare(300, 1800, 1700)) |
| + } |
| +} |
| + |
| +func TestRecordPaymentRefundFollowsCharge(t *testing.T) { |
| + s, ids := planStore(t, "bab", "shop") |
| + if err := s.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + recordPayment(t, s, testCharge("mv_1", "ch_1")) |
| + refund := billing.Payment{ |
| + Movement: "mv_re", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonOther, |
| + Charge: "ch_1", Amount: -600, Tax: -100, Currency: "eur", |
| + Settled: -600, SettledTax: -100, SettledCurrency: "eur", At: paymentAt.Add(time.Hour), |
| + } |
| + recordPayment(t, s, refund) |
| + got := paymentByMovement(t, s, "mv_re") |
| + if got.AccountID != ids["bab"] || got.Subscription != "sub_1" { |
| + t.Errorf("refund account %d subscription %q; want bab, sub_1", got.AccountID, got.Subscription) |
| + } |
| + if got.Tax != -100 || got.SettledTax != -100 { |
| + t.Errorf("refund tax %d/%d changed; want -100/-100", got.Tax, got.SettledTax) |
| + } |
| +} |
| + |
| +func TestRecordPaymentDomainRefundInheritsTax(t *testing.T) { |
| + s, ids := planStore(t, "bab") |
| + if err := s.CreateDomainPurchase(DomainPurchase{AccountID: ids["bab"], Domain: "shop.example.com", App: "web", |
| + Currency: "eur", Amount: 10000, PaymentIntent: "pi_dom"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + charge := billing.Payment{ |
| + Movement: "mv_dom", Source: "ch_dom", Kind: billing.PaymentOnceOff, Reason: billing.ReasonOther, |
| + PaymentIntent: "pi_dom", Charge: "ch_dom", |
| + Amount: 12000, Currency: "eur", Settled: 13000, Fee: 400, SettledCurrency: "usd", At: paymentAt, |
| + } |
| + recordPayment(t, s, charge) |
| + refund := billing.Payment{ |
| + Movement: "mv_re", Source: "re_dom", Kind: billing.PaymentRefund, Reason: billing.ReasonOther, |
| + Charge: "ch_dom", Amount: -12000, Currency: "eur", Settled: -13000, SettledCurrency: "usd", |
| + At: paymentAt.Add(time.Hour), |
| + } |
| + recordPayment(t, s, refund) |
| + c, r := paymentByMovement(t, s, "mv_dom"), paymentByMovement(t, s, "mv_re") |
| + if c.Tax != 2000 { |
| + t.Fatalf("charge tax %d, want derived 2000", c.Tax) |
| + } |
| + if r.Tax != -2000 { |
| + t.Errorf("refund tax %d, want -2000", r.Tax) |
| + } |
| + if r.AccountID != ids["bab"] { |
| + t.Errorf("refund account %d, want bab", r.AccountID) |
| + } |
| + if sum := (c.Settled - c.SettledTax) + (r.Settled - r.SettledTax); sum != 0 { |
| + t.Errorf("charge %d-%d plus refund %d-%d = %d, want 0", c.Settled, c.SettledTax, r.Settled, r.SettledTax, sum) |
| + } |
| + |
| + // A failed refund's reversal inherits the opposite share and keeps its |
| + // reason. |
| + reversal := refund |
| + reversal.Movement, reversal.Reason, reversal.Amount, reversal.Settled = "mv_rv", billing.ReasonReversed, 12000, 13000 |
| + recordPayment(t, s, reversal) |
| + v := paymentByMovement(t, s, "mv_rv") |
| + if v.Tax != 2000 || v.SettledTax != -r.SettledTax || v.Reason != billing.ReasonReversed { |
| + t.Errorf("reversal tax %d settled tax %d reason %q; want 2000, %d, reversed", v.Tax, v.SettledTax, v.Reason, -r.SettledTax) |
| + } |
| +} |
| + |
| +func TestRecordPaymentUnmatched(t *testing.T) { |
| + s, _ := planStore(t, "bab") |
| + p := testCharge("mv_1", "ch_1") |
| + p.Customer = "cus_nobody" |
| + recordPayment(t, s, p) |
| + if got := paymentByMovement(t, s, "mv_1"); got.AccountID != 0 { |
| + t.Errorf("account = %d, want 0", got.AccountID) |
| + } |
| + rows, total, err := s.Payments(paymentFilter{Kind: "unmatched"}) |
| + if err != nil || total != 1 || len(rows) != 1 || rows[0].Movement != "mv_1" { |
| + t.Errorf("unmatched = %+v, %d, %v; want mv_1", rows, total, err) |
| + } |
| +} |
| + |
| +func TestRematchPayments(t *testing.T) { |
| + s, ids := planStore(t, "bab") |
| + recordPayment(t, s, testCharge("mv_1", "ch_1")) |
| + fee := billing.Payment{Movement: "mv_fee", Kind: billing.PaymentFee, Settled: -100, SettledCurrency: "eur", At: paymentAt} |
| + recordPayment(t, s, fee) |
| + if n, err := s.RematchPayments(); err != nil || n != 0 { |
| + t.Fatalf("rematch before binding = %d, %v; want 0", n, err) |
| + } |
| + if err := s.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, err := s.RematchPayments(); err != nil || n != 1 { |
| + t.Fatalf("rematch = %d, %v; want 1", n, err) |
| + } |
| + if got := paymentByMovement(t, s, "mv_1"); got.AccountID != ids["bab"] { |
| + t.Errorf("account = %d, want bab", got.AccountID) |
| + } |
| + if n, err := s.RematchPayments(); err != nil || n != 0 { |
| + t.Errorf("second rematch = %d, %v; want 0", n, err) |
| + } |
| +} |
| + |
| +func TestPaymentsFilter(t *testing.T) { |
| + s, ids := planStore(t, "bab", "shop") |
| + if err := s.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.SetBillingCustomer(ids["shop"], "cus_2", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + oct := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) |
| + nov := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) |
| + mk := func(mv string, kind billing.PaymentKind, customer string, at time.Time) billing.Payment { |
| + return billing.Payment{Movement: mv, Source: "src_" + mv, Kind: kind, Reason: billing.ReasonOther, Customer: customer, |
| + Amount: 100, Currency: "eur", Settled: 100, SettledCurrency: "eur", At: at} |
| + } |
| + for _, p := range []billing.Payment{ |
| + mk("mv_sep", billing.PaymentSubscription, "cus_1", oct.Add(-time.Hour)), // September |
| + mk("mv_a", billing.PaymentSubscription, "cus_1", oct), // first second of October |
| + mk("mv_b", billing.PaymentOnceOff, "cus_2", oct.Add(48*time.Hour)), // |
| + mk("mv_c", billing.PaymentRefund, "cus_1", oct.Add(72*time.Hour)), // |
| + mk("mv_d", billing.PaymentFee, "", oct.Add(96*time.Hour)), // a fee: no account |
| + mk("mv_e", billing.PaymentOnceOff, "cus_nobody", oct.Add(96*time.Hour)), // same instant as the fee |
| + mk("mv_f", billing.PaymentSubscription, "cus_2", nov.Add(-time.Second)), // last second of October |
| + mk("mv_nov", billing.PaymentSubscription, "cus_2", nov), // November |
| + } { |
| + recordPayment(t, s, p) |
| + } |
| + movements := func(rows []paymentRow) []string { |
| + var out []string |
| + for _, r := range rows { |
| + out = append(out, r.Movement) |
| + } |
| + return out |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + f paymentFilter |
| + want []string |
| + n int |
| + }{ |
| + {"october", paymentFilter{From: oct, To: nov}, []string{"mv_f", "mv_e", "mv_c", "mv_b", "mv_a"}, 5}, |
| + {"october all", paymentFilter{From: oct, To: nov, Kind: "all"}, []string{"mv_f", "mv_e", "mv_d", "mv_c", "mv_b", "mv_a"}, 6}, |
| + {"every row", paymentFilter{Kind: "all"}, []string{"mv_nov", "mv_f", "mv_e", "mv_d", "mv_c", "mv_b", "mv_a", "mv_sep"}, 8}, |
| + {"open start", paymentFilter{To: oct}, []string{"mv_sep"}, 1}, |
| + {"open end", paymentFilter{From: nov}, []string{"mv_nov"}, 1}, |
| + {"subscription", paymentFilter{From: oct, To: nov, Kind: "subscription"}, []string{"mv_f", "mv_a"}, 2}, |
| + {"once off", paymentFilter{Kind: "once_off"}, []string{"mv_e", "mv_b"}, 2}, |
| + {"refund", paymentFilter{Kind: "refund"}, []string{"mv_c"}, 1}, |
| + {"fee", paymentFilter{Kind: "fee"}, []string{"mv_d"}, 1}, |
| + {"unmatched", paymentFilter{Kind: "unmatched"}, []string{"mv_e"}, 1}, |
| + {"account", paymentFilter{AccountID: ids["shop"]}, []string{"mv_nov", "mv_f", "mv_b"}, 3}, |
| + {"page", paymentFilter{Kind: "all", Offset: 2, Limit: 3}, []string{"mv_e", "mv_d", "mv_c"}, 8}, |
| + {"past the end", paymentFilter{Offset: 10, Limit: 3}, nil, 7}, |
| + } { |
| + rows, n, err := s.Payments(tc.f) |
| + if err != nil { |
| + t.Fatalf("%s: %v", tc.name, err) |
| + } |
| + if got := movements(rows); n != tc.n || !equalStrings(got, tc.want) { |
| + t.Errorf("%s: %v (count %d); want %v (count %d)", tc.name, got, n, tc.want, tc.n) |
| + } |
| + } |
| + if _, _, err := s.Payments(paymentFilter{Kind: "bogus"}); err == nil { |
| + t.Error("an unknown kind was accepted") |
| + } |
| +} |
| + |
| +func equalStrings(a, b []string) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for i := range a { |
| + if a[i] != b[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func TestPaymentCursorRoundTrip(t *testing.T) { |
| + // A reconcile recorded before any cursor leaves the cursor unset. |
| + early, _ := planStore(t, "bab") |
| + if err := early.SetPaymentsReconciled(billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok, err := early.PaymentCursor(); err != nil || ok { |
| + t.Fatalf("cursor after a reconcile alone ok=%v err=%v; want none", ok, err) |
| + } |
| + |
| + s, _ := planStore(t, "bab") |
| + if _, ok, err := s.PaymentCursor(); err != nil || ok { |
| + t.Fatalf("fresh cursor ok=%v err=%v; want none", ok, err) |
| + } |
| + if at, err := s.PaymentsReconciledAt(); err != nil || !at.IsZero() { |
| + t.Fatalf("fresh reconciled = %v, %v; want zero", at, err) |
| + } |
| + through := time.Date(2026, 11, 9, 10, 0, 0, 0, time.UTC) |
| + if err := s.SetPaymentCursor(through); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok, err := s.PaymentCursor(); err != nil || !ok || !got.Equal(through) { |
| + t.Fatalf("cursor = %v, %v, %v; want %v", got, ok, err, through) |
| + } |
| + if err := s.SetPaymentCursor(through.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _, _ := s.PaymentCursor(); !got.Equal(through.Add(time.Hour)) { |
| + t.Fatalf("cursor after move = %v", got) |
| + } |
| + if at, err := s.PaymentsReconciledAt(); err != nil || !at.IsZero() { |
| + t.Fatalf("reconciled after a cursor write = %v, %v; want zero", at, err) |
| + } |
| + done := through.Add(2 * time.Hour) |
| + if err := s.SetPaymentsReconciled(done); err != nil { |
| + t.Fatal(err) |
| + } |
| + if at, err := s.PaymentsReconciledAt(); err != nil || !at.Equal(done) { |
| + t.Fatalf("reconciled = %v, %v; want %v", at, err, done) |
| + } |
| + if got, ok, _ := s.PaymentCursor(); !ok || !got.Equal(through.Add(time.Hour)) { |
| + t.Errorf("cursor after reconcile = %v, %v", got, ok) |
| + } |
| +} |
| + |
| +func TestPaymentsSurviveAccountReap(t *testing.T) { |
| + s, ids := planStore(t, "bab") |
| + if err := s.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + recordPayment(t, s, testCharge("mv_1", "ch_1")) |
| + if err := s.ReapAccount(ids["bab"], billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, n, err := s.Payments(paymentFilter{AccountID: ids["bab"]}) |
| + if err != nil || n != 1 || len(rows) != 1 || rows[0].AccountID != ids["bab"] { |
| + t.Errorf("after reap: %+v, %d, %v; want the row kept", rows, n, err) |
| + } |
| +} |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index a2b2fafad..6fc0dc8bd 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -253,7 +253,7 @@ CREATE INDEX IF NOT EXISTS billing_operations_invite ON billing_operations(invit |
| if _, err := s.db.Exec(`ALTER TABLE billing_operations ADD COLUMN start_quantity INTEGER NOT NULL DEFAULT -1`); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| return err |
| } |
| - return nil |
| + return s.migrateBillingMoney() |
| } |
| // billingAccount is one account's billing state. |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index ff2d632f5..b89da653b 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -285,6 +285,10 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "managed_fleet_storage": {NonApp: "fleet storage and sealed credentials; no app identity"}, |
| "billing_operations": {NonApp: "an account's billing operations, each one prepared provider request and its outcome, keyed by subscription; names no app"}, |
| + // The billing dashboard's money record (billingpayments_store.go). |
| + "billing_payments": {NonApp: "money received, refunded or kept as fees, one row per provider balance movement, with the account; names no app"}, |
| + "billing_payment_cursor": {NonApp: "how far the payment reconcile has read; names no app"}, |
| + |
| "managed_fleet_delivered_keys": {NonApp: "fleet access key IDs ever delivered to boxes; no app identity"}, |
| // The alert engine's tables (alertstore.go). A scope is "fleet" or an |