carlos / platform Public

console: billing account state, billing problems, and a guarded plan write that skips unchanged rows (plans 6a)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 75e53c4b826cdacd12c2d3a4684bf23679a8b130 parent 9310761
6 files changed, +611 −15
  • internal/console/accountplans.go +90 −6
  • internal/console/accountplans_test.go +101 −0
  • internal/console/apiaccountplan.go +22 −8
  • internal/console/billingstore.go +264 −1
  • internal/console/billingstore_test.go +132 −0
  • internal/console/store_gate.go +2 −0
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index 5a3980c24..683e318e6 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -91,10 +91,20 @@ func (s *Store) AccountPlan(accountID int64) (*AccountPlanRow, error) {
// It validates nothing: callers check the plan against the catalog first.
func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, source string,
sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) {
- if packs == nil {
- packs = map[string]int{}
- }
- pj, err := json.Marshal(packs)
+ return upsertAccountPlan(s.db, accountID, plan, packs, source, sponsored, reason, by, now)
+}
+
+// rowQuerier is what upsertAccountPlan needs: the store's handle or a
+// transaction.
+type rowQuerier interface {
+ QueryRow(query string, args ...any) *sql.Row
+}
+
+// upsertAccountPlan is SetAccountPlan's write, shared with billing's
+// guarded write (SetBillingPlan) so both change a plan row the same way.
+func upsertAccountPlan(q rowQuerier, accountID int64, plan string, packs map[string]int, source string,
+ sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) {
+ pj, err := canonicalPacks(packs)
if err != nil {
return 0, err
}
@@ -107,7 +117,7 @@ func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]in
sj = string(b)
}
var rev int64
- err = s.db.QueryRow(`INSERT INTO account_plans
+ err = q.QueryRow(`INSERT INTO account_plans
(account_id, plan, packs, source, sponsored, reason, revision, updated_by, updated_at)
SELECT ?, ?, ?, ?, ?, ?, 1, ?, ? WHERE EXISTS (SELECT 1 FROM accounts WHERE id = ? AND deleted_at = 0)
ON CONFLICT(account_id) DO UPDATE SET plan = excluded.plan, packs = excluded.packs,
@@ -115,13 +125,87 @@ func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]in
updated_by = excluded.updated_by, updated_at = excluded.updated_at, revision = revision + 1,
throttle = ''
RETURNING revision`,
- accountID, plan, string(pj), source, sj, reason, by, now.Unix(), accountID).Scan(&rev)
+ accountID, plan, pj, source, sj, reason, by, now.Unix(), accountID).Scan(&rev)
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrAccountGone
}
return rev, err
}
+// canonicalPacks is the stored form of a pack map: JSON with sorted keys,
+// "{}" for none.
+func canonicalPacks(packs map[string]int) (string, error) {
+ if packs == nil {
+ packs = map[string]int{}
+ }
+ b, err := json.Marshal(packs) // map keys marshal sorted
+ return string(b), err
+}
+
+// planBilling is who billing's plan writes name as their writer.
+const planBilling = "billing"
+
+// SetBillingPlan is billing's plan write (plans 6a). In one transaction it
+// writes only a row billing owns, a missing row or one whose source is
+// default or billing, and only when the plan, packs or source would change:
+// an unchanged subscription writes nothing, so the hourly sync never bumps
+// the revision or clears the 4c throttle. An operator or sponsored row is
+// never touched (not written, not owned). A deleted account is
+// ErrAccountGone.
+func (s *Store) SetBillingPlan(accountID int64, plan string, packs map[string]int, reason string, now time.Time) (written, owned bool, err error) {
+ want, err := canonicalPacks(packs)
+ if err != nil {
+ return false, false, err
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, false, err
+ }
+ defer tx.Rollback()
+ var live int
+ if err := tx.QueryRow(`SELECT COUNT(*) FROM accounts WHERE id = ? AND deleted_at = 0`, accountID).Scan(&live); err != nil {
+ return false, false, err
+ }
+ if live == 0 {
+ return false, false, ErrAccountGone
+ }
+ var curPlan, curPacks, curSource string
+ err = tx.QueryRow(`SELECT plan, packs, source FROM account_plans WHERE account_id = ?`, accountID).Scan(&curPlan, &curPacks, &curSource)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ case err != nil:
+ return false, false, err
+ case curSource != PlanSourceDefault && curSource != PlanSourceBilling:
+ return false, false, nil
+ default:
+ var cur map[string]int
+ if err := json.Unmarshal([]byte(curPacks), &cur); err != nil {
+ return false, true, err
+ }
+ have, err := canonicalPacks(cur)
+ if err != nil {
+ return false, true, err
+ }
+ if curPlan == plan && have == want && curSource == PlanSourceBilling {
+ return false, true, nil
+ }
+ }
+ if err := billingSetPlan(tx, accountID, plan, packs, reason, now); err != nil {
+ return false, true, err
+ }
+ return true, true, tx.Commit()
+}
+
+// billingSetPlan is the one place billing changes a plan row. It switches
+// to Plan 4d-1's plan-change function when it lands (that function records
+// a lapse start); until then it is SetAccountPlan's own upsert, run inside
+// SetBillingPlan's transaction so the ownership guard and the write cannot
+// be split by an operator's write.
+func billingSetPlan(tx *sql.Tx, accountID int64, plan string, packs map[string]int, reason string, now time.Time) error {
+ _, err := upsertAccountPlan(tx, accountID, plan, packs, PlanSourceBilling, nil, reason, planBilling, now)
+ return err
+}
+
// EnsureDefaultPlans gives every live account without a plan row the
// default plan, and reports how many rows it inserted.
func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, error) {
diff --git a/internal/console/accountplans_test.go b/internal/console/accountplans_test.go
index 4b1553c22..aa374a21b 100644
--- a/internal/console/accountplans_test.go
+++ b/internal/console/accountplans_test.go
@@ -183,3 +183,104 @@ func TestSetAccountPlanRefusesADeletedAccount(t *testing.T) {
t.Fatalf("unknown account: err %v, want ErrAccountGone", err)
}
}
+
+func TestSetBillingPlanWritesOnlyChanges(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ id := ids["bab"]
+ written, owned, err := st.SetBillingPlan(id, "personal", nil, "subscription sub_1 active", planNow)
+ if err != nil || !written || !owned {
+ t.Fatalf("no row: written %v owned %v err %v", written, owned, err)
+ }
+ row, _ := st.AccountPlan(id)
+ if row.Revision != 1 || row.Source != PlanSourceBilling || row.Plan != "personal" || row.UpdatedBy != "billing" || len(row.Packs) != 0 {
+ t.Fatalf("row = %+v", row)
+ }
+ written, owned, err = st.SetBillingPlan(id, "personal", map[string]int{}, "subscription sub_1 active", planNow.Add(time.Hour))
+ if err != nil || written || !owned {
+ t.Fatalf("same again: written %v owned %v err %v", written, owned, err)
+ }
+ if row, _ := st.AccountPlan(id); row.Revision != 1 {
+ t.Fatalf("unchanged write bumped the revision: %+v", row)
+ }
+ written, _, err = st.SetBillingPlan(id, "personal", map[string]int{"apps": 1}, "subscription sub_1 active", planNow)
+ if err != nil || !written {
+ t.Fatalf("packs changed: written %v err %v", written, err)
+ }
+ if row, _ := st.AccountPlan(id); row.Revision != 2 || row.Packs["apps"] != 1 {
+ t.Fatalf("row = %+v", row)
+ }
+}
+
+func TestSetBillingPlanTakesDefaultRows(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ if _, err := st.EnsureDefaultPlans("free", planNow); err != nil {
+ t.Fatal(err)
+ }
+ written, owned, err := st.SetBillingPlan(ids["bab"], "personal", nil, "subscription sub_1 active", planNow)
+ if err != nil || !written || !owned {
+ t.Fatalf("written %v owned %v err %v", written, owned, err)
+ }
+ if row, _ := st.AccountPlan(ids["bab"]); row.Source != PlanSourceBilling || row.Plan != "personal" || row.Revision != 2 {
+ t.Fatalf("row = %+v", row)
+ }
+ // A default row that already says the default plan, written by
+ // billing as the default plan: the source still becomes billing.
+ st2, ids2 := planStore(t, "bdk")
+ if _, err := st2.EnsureDefaultPlans("free", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if written, _, err := st2.SetBillingPlan(ids2["bdk"], "free", nil, "subscription sub_1 ended", planNow); err != nil || !written {
+ t.Fatalf("default to billing-owned free: written %v err %v", written, err)
+ }
+}
+
+func TestSetBillingPlanLeavesSponsoredAndOperatorRows(t *testing.T) {
+ for _, source := range []string{PlanSourceSponsored, PlanSourceOperator} {
+ st, ids := planStore(t, "bab")
+ var sponsored *plans.Limits
+ if source == PlanSourceSponsored {
+ sponsored = &plans.Limits{RunningThings: 50}
+ }
+ if _, err := st.SetAccountPlan(ids["bab"], "free", nil, source, sponsored, "by hand", "op@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := st.AccountPlan(ids["bab"])
+ written, owned, err := st.SetBillingPlan(ids["bab"], "personal", map[string]int{"apps": 2}, "subscription sub_1 active", planNow.Add(time.Hour))
+ if err != nil || written || owned {
+ t.Fatalf("%s: written %v owned %v err %v", source, written, owned, err)
+ }
+ after, _ := st.AccountPlan(ids["bab"])
+ if !reflect.DeepEqual(before, after) {
+ t.Fatalf("%s row changed:\n%+v\n%+v", source, before, after)
+ }
+ }
+}
+
+func TestSetBillingPlanKeepsThrottleWhenUnchanged(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ if _, _, err := st.SetBillingPlan(ids["bab"], "personal", nil, "subscription sub_1 active", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.SetAccountThrottle(ids["bab"], &plans.Throttle{Bandwidth: true, Until: planNow.Add(24 * time.Hour)}, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if written, _, err := st.SetBillingPlan(ids["bab"], "personal", nil, "subscription sub_1 active", planNow.Add(time.Hour)); err != nil || written {
+ t.Fatalf("written %v err %v", written, err)
+ }
+ if row, _ := st.AccountPlan(ids["bab"]); row.Throttle == nil || !row.Throttle.Bandwidth {
+ t.Fatalf("throttle lost: %+v", row)
+ }
+}
+
+func TestSetBillingPlanRefusesADeletedAccount(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ if _, err := st.db.Exec(`UPDATE accounts SET deleted_at = 1 WHERE id = ?`, ids["bab"]); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := st.SetBillingPlan(ids["bab"], "personal", nil, "x", planNow); !errors.Is(err, ErrAccountGone) {
+ t.Fatalf("err = %v, want ErrAccountGone", err)
+ }
+ if _, _, err := st.SetBillingPlan(99999, "personal", nil, "x", planNow); !errors.Is(err, ErrAccountGone) {
+ t.Fatalf("missing account: err = %v, want ErrAccountGone", err)
+ }
+}
diff --git a/internal/console/apiaccountplan.go b/internal/console/apiaccountplan.go
index d21fceb2b..423f844af 100644
--- a/internal/console/apiaccountplan.go
+++ b/internal/console/apiaccountplan.go
@@ -1,6 +1,7 @@
package console
import (
+ "context"
"errors"
"fmt"
"log"
@@ -128,14 +129,7 @@ func (s *Server) handleAPIAccountPlanSet(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusInternalServerError, planCopySaveFailed)
return
}
- if row, err := s.store.AccountPlan(acct.ID); err != nil {
- log.Printf("console: api account plan %s: reread: %v", acct.Sqid, err)
- } else if row != nil && s.cfg.Releases != nil {
- // Best effort: the pass retries anything this misses.
- if err := s.publishAccountLimits(r.Context(), *row, now); err != nil {
- log.Printf("console: api account plan %s: publish: %v", acct.Sqid, err)
- }
- }
+ s.publishPlanNow(r.Context(), acct.ID, now)
reply, err := s.accountPlanReplyFor(acct)
if err != nil {
log.Printf("console: api account plan %s: %v", acct.Sqid, err)
@@ -195,3 +189,23 @@ func (s *Server) accountPlanReplyFor(acct *Account) (accountPlanReply, error) {
}
return reply, nil
}
+
+// publishPlanNow publishes the account's limits record at once, after a
+// plan write. Best effort, logged: the limits pass retries anything this
+// misses. A no-op without Releases.
+func (s *Server) publishPlanNow(ctx context.Context, accountID int64, now time.Time) {
+ if s.cfg.Releases == nil {
+ return
+ }
+ row, err := s.store.AccountPlan(accountID)
+ if err != nil {
+ log.Printf("console: publish plan of account %d: reread: %v", accountID, err)
+ return
+ }
+ if row == nil {
+ return
+ }
+ if err := s.publishAccountLimits(ctx, *row, now); err != nil {
+ log.Printf("console: publish plan of account %s: %v", row.Sqid, err)
+ }
+}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 3ba7e4c27..da04e24e9 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -2,8 +2,11 @@ package console
import (
"database/sql"
+ "encoding/json"
"errors"
"time"
+
+ "github.com/carlosframework/platform/internal/billing"
)
// ErrPriceBookEdited refuses a price book whose content changed under a
@@ -18,7 +21,10 @@ func (s *Store) migrateBilling() error {
status TEXT NOT NULL,
first_seen INTEGER NOT NULL
);`)
- return err
+ if err != nil {
+ return err
+ }
+ return s.migrateBillingAccounts()
}
// NotePriceBook records a book version's digest the first time the console
@@ -43,3 +49,260 @@ func (s *Store) NotePriceBook(version, digest, status string, now time.Time) err
}
return nil
}
+
+// The reasons a billing problem is opened for (plans 6a Calls 1 to 3, 11).
+const (
+ problemUnknownCustomer = "unknown_customer"
+ problemAccountMismatch = "account_mismatch"
+ problemModeMismatch = "mode_mismatch"
+ problemSecondSubscription = "second_subscription"
+ problemUnrecognised = "unrecognised"
+ problemNotBillingOwned = "not_billing_owned"
+)
+
+func (s *Store) migrateBillingAccounts() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_accounts (
+ account_id INTEGER PRIMARY KEY,
+ customer TEXT NOT NULL DEFAULT '',
+ subscription TEXT NOT NULL DEFAULT '',
+ provider_status TEXT NOT NULL DEFAULT '',
+ state TEXT NOT NULL DEFAULT '',
+ book TEXT NOT NULL DEFAULT '',
+ currency TEXT NOT NULL DEFAULT '',
+ period_end INTEGER NOT NULL DEFAULT 0,
+ cancel_at_period_end INTEGER NOT NULL DEFAULT 0,
+ paid_packs TEXT NOT NULL DEFAULT '{}',
+ paid_period_end INTEGER NOT NULL DEFAULT 0,
+ synced_at INTEGER NOT NULL DEFAULT 0
+);
+CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_customer ON billing_accounts(customer) WHERE customer != '';
+CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_subscription ON billing_accounts(subscription) WHERE subscription != '';
+CREATE TABLE IF NOT EXISTS billing_problems (
+ id INTEGER PRIMARY KEY,
+ account_id INTEGER NOT NULL,
+ subscription TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ detail TEXT NOT NULL,
+ opened_at INTEGER NOT NULL,
+ closed_at INTEGER NOT NULL DEFAULT 0,
+ closed_by TEXT NOT NULL DEFAULT '',
+ note TEXT NOT NULL DEFAULT ''
+);
+CREATE UNIQUE INDEX IF NOT EXISTS billing_problems_open ON billing_problems(account_id, subscription, reason) WHERE closed_at = 0;`)
+ return err
+}
+
+// billingAccount is one account's billing state.
+type billingAccount struct {
+ AccountID int64
+ Customer string
+ Subscription string
+ ProviderStatus string
+ State billing.State // "" before any subscription
+ Book, Currency string
+ PeriodEnd time.Time
+ CancelAtPeriodEnd bool
+ PaidPacks map[string]int // highest quantity per pack paid for in the period ending PaidPeriodEnd
+ PaidPeriodEnd time.Time
+ SyncedAt time.Time
+}
+
+const billingAccountColumns = `b.account_id, b.customer, b.subscription, b.provider_status, b.state, b.book, b.currency,
+ b.period_end, b.cancel_at_period_end, b.paid_packs, b.paid_period_end, b.synced_at`
+
+func scanBillingAccount(sc interface{ Scan(...any) error }) (*billingAccount, error) {
+ var b billingAccount
+ var state, packs string
+ var periodEnd, paidEnd, synced int64
+ var cancel int
+ if err := sc.Scan(&b.AccountID, &b.Customer, &b.Subscription, &b.ProviderStatus, &state, &b.Book, &b.Currency,
+ &periodEnd, &cancel, &packs, &paidEnd, &synced); err != nil {
+ return nil, err
+ }
+ b.State = billing.State(state)
+ b.PeriodEnd, b.PaidPeriodEnd, b.SyncedAt = timeOrZero(periodEnd), timeOrZero(paidEnd), timeOrZero(synced)
+ b.CancelAtPeriodEnd = cancel != 0
+ if err := json.Unmarshal([]byte(packs), &b.PaidPacks); err != nil {
+ return nil, err
+ }
+ if b.PaidPacks == nil {
+ b.PaidPacks = map[string]int{}
+ }
+ return &b, nil
+}
+
+func (s *Store) billingAccountWhere(where string, arg any) (*billingAccount, error) {
+ b, err := scanBillingAccount(s.db.QueryRow(`SELECT `+billingAccountColumns+` FROM billing_accounts b WHERE `+where, arg))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return b, err
+}
+
+// BillingAccount is the account's billing row, nil when it has none.
+func (s *Store) BillingAccount(accountID int64) (*billingAccount, error) {
+ return s.billingAccountWhere(`b.account_id = ?`, accountID)
+}
+
+// BillingAccountByCustomer is the row bound to a provider customer, nil
+// when none is.
+func (s *Store) BillingAccountByCustomer(customer string) (*billingAccount, error) {
+ if customer == "" {
+ return nil, nil
+ }
+ return s.billingAccountWhere(`b.customer = ?`, customer)
+}
+
+// SetBillingCustomer binds the account's provider customer. Binding the
+// same customer again is a no-op; a customer bound to another account, or
+// a second customer for this one, is an error.
+func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time) error {
+ if customer == "" {
+ return errors.New("billing: empty customer")
+ }
+ res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at) VALUES (?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer WHERE billing_accounts.customer = ''`,
+ accountID, customer, now.Unix())
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil || n == 1 {
+ return err
+ }
+ var bound string
+ if err := s.db.QueryRow(`SELECT customer FROM billing_accounts WHERE account_id = ?`, accountID).Scan(&bound); err != nil {
+ return err
+ }
+ if bound != customer {
+ return errors.New("billing: the account already has another customer")
+ }
+ return nil
+}
+
+// PutBillingState writes every column of the account's billing row but the
+// customer, creating the row if needed.
+func (s *Store) PutBillingState(b billingAccount) error {
+ packs, err := canonicalPacks(b.PaidPacks)
+ if err != nil {
+ return err
+ }
+ cancel := 0
+ if b.CancelAtPeriodEnd {
+ cancel = 1
+ }
+ _, err = s.db.Exec(`INSERT INTO billing_accounts
+ (account_id, subscription, provider_status, state, book, currency, period_end, cancel_at_period_end, paid_packs, paid_period_end, synced_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET subscription = excluded.subscription, provider_status = excluded.provider_status,
+ state = excluded.state, book = excluded.book, currency = excluded.currency, period_end = excluded.period_end,
+ cancel_at_period_end = excluded.cancel_at_period_end, paid_packs = excluded.paid_packs,
+ paid_period_end = excluded.paid_period_end, synced_at = excluded.synced_at`,
+ b.AccountID, b.Subscription, b.ProviderStatus, string(b.State), b.Book, b.Currency, unixOrZero(b.PeriodEnd),
+ cancel, packs, unixOrZero(b.PaidPeriodEnd), unixOrZero(b.SyncedAt))
+ return err
+}
+
+// LiveBillingAccounts pages, in account order after afterAccountID, the
+// live accounts whose subscription is paid or pending: the hourly sync's
+// work list.
+func (s *Store) LiveBillingAccounts(afterAccountID int64, limit int) ([]billingAccount, error) {
+ rows, err := s.db.Query(`SELECT `+billingAccountColumns+` FROM billing_accounts b JOIN accounts a ON a.id = b.account_id
+ WHERE a.deleted_at = 0 AND b.account_id > ? AND b.subscription != '' AND b.state IN (?, ?)
+ ORDER BY b.account_id LIMIT ?`, afterAccountID, string(billing.StatePaid), string(billing.StatePending), limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []billingAccount
+ for rows.Next() {
+ b, err := scanBillingAccount(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *b)
+ }
+ return out, rows.Err()
+}
+
+// billingProblem is one billing problem for an operator.
+type billingProblem struct {
+ ID, AccountID int64
+ Subscription, Reason string
+ Detail string
+ OpenedAt, ClosedAt time.Time
+ ClosedBy, Note string
+}
+
+const billingProblemColumns = `id, account_id, subscription, reason, detail, opened_at, closed_at, closed_by, note`
+
+func scanBillingProblem(sc interface{ Scan(...any) error }) (*billingProblem, error) {
+ var p billingProblem
+ var opened, closed int64
+ if err := sc.Scan(&p.ID, &p.AccountID, &p.Subscription, &p.Reason, &p.Detail, &opened, &closed, &p.ClosedBy, &p.Note); err != nil {
+ return nil, err
+ }
+ p.OpenedAt, p.ClosedAt = timeOrZero(opened), timeOrZero(closed)
+ return &p, nil
+}
+
+// OpenBillingProblem opens a problem unless one is already open for the
+// same account, subscription and reason, and reports whether it opened one.
+func (s *Store) OpenBillingProblem(accountID int64, subscription, reason, detail string, now time.Time) (bool, error) {
+ res, err := s.db.Exec(`INSERT INTO billing_problems (account_id, subscription, reason, detail, opened_at)
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(account_id, subscription, reason) WHERE closed_at = 0 DO NOTHING`,
+ accountID, subscription, reason, detail, now.Unix())
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n == 1, err
+}
+
+// BillingProblems lists problems newest first, open ones only unless
+// includeClosed.
+func (s *Store) BillingProblems(includeClosed bool) ([]billingProblem, error) {
+ q := `SELECT ` + billingProblemColumns + ` FROM billing_problems`
+ if !includeClosed {
+ q += ` WHERE closed_at = 0`
+ }
+ rows, err := s.db.Query(q + ` ORDER BY opened_at DESC, id DESC`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []billingProblem
+ for rows.Next() {
+ p, err := scanBillingProblem(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *p)
+ }
+ return out, rows.Err()
+}
+
+// BillingProblem is one problem, nil when there is none with that id.
+func (s *Store) BillingProblem(id int64) (*billingProblem, error) {
+ p, err := scanBillingProblem(s.db.QueryRow(`SELECT `+billingProblemColumns+` FROM billing_problems WHERE id = ?`, id))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return p, err
+}
+
+// errBillingProblemClosed refuses closing a problem twice.
+var errBillingProblemClosed = errors.New("billing problem already closed")
+
+// CloseBillingProblem closes an open problem with who closed it and their
+// note. An already closed or unknown problem is an error.
+func (s *Store) CloseBillingProblem(id int64, by, note string, now time.Time) error {
+ res, err := s.db.Exec(`UPDATE billing_problems SET closed_at = ?, closed_by = ?, note = ? WHERE id = ? AND closed_at = 0`,
+ now.Unix(), by, note, id)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil || n == 1 {
+ return err
+ }
+ return errBillingProblemClosed
+}
diff --git a/internal/console/billingstore_test.go b/internal/console/billingstore_test.go
index 83d115153..c913f4777 100644
--- a/internal/console/billingstore_test.go
+++ b/internal/console/billingstore_test.go
@@ -2,8 +2,11 @@ package console
import (
"errors"
+ "reflect"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/billing"
)
var billingNow = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
@@ -27,3 +30,132 @@ func TestNotePriceBook(t *testing.T) {
t.Errorf("first_seen = %d, %v; want the first start", first, err)
}
}
+
+func TestBillingCustomerIsUnique(t *testing.T) {
+ st, ids := planStore(t, "bab", "bdk")
+ if err := st.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil {
+ t.Errorf("same customer again: %v", err)
+ }
+ if err := st.SetBillingCustomer(ids["bdk"], "cus_1", billingNow); err == nil {
+ t.Error("cus_1 bound to a second account")
+ }
+ if err := st.SetBillingCustomer(ids["bab"], "cus_2", billingNow); err == nil {
+ t.Error("an account's customer replaced")
+ }
+ b, err := st.BillingAccountByCustomer("cus_1")
+ if err != nil || b == nil || b.AccountID != ids["bab"] {
+ t.Fatalf("BillingAccountByCustomer = %+v, %v", b, err)
+ }
+ if b, err := st.BillingAccountByCustomer("cus_none"); b != nil || err != nil {
+ t.Errorf("unknown customer = %+v, %v", b, err)
+ }
+ if b, err := st.BillingAccount(ids["bdk"]); b != nil || err != nil {
+ t.Errorf("account with no billing row = %+v, %v", b, err)
+ }
+}
+
+func TestBillingStateRoundTrips(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ if err := st.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ want := billingAccount{
+ AccountID: ids["bab"], Customer: "cus_1", Subscription: "sub_1", ProviderStatus: "past_due",
+ State: billing.StatePaid, Book: "example-v1", Currency: "usd",
+ PeriodEnd: billingNow.AddDate(1, 0, 0), CancelAtPeriodEnd: true,
+ PaidPacks: map[string]int{"apps": 3}, PaidPeriodEnd: billingNow.AddDate(1, 0, 0), SyncedAt: billingNow,
+ }
+ put := want
+ put.Customer = "cus_ignored" // PutBillingState writes every column but the customer
+ if err := st.PutBillingState(put); err != nil {
+ t.Fatal(err)
+ }
+ got, err := st.BillingAccount(ids["bab"])
+ if err != nil || got == nil {
+ t.Fatalf("BillingAccount = %v, %v", got, err)
+ }
+ if !reflect.DeepEqual(*got, want) {
+ t.Errorf("round trip:\n got %+v\nwant %+v", *got, want)
+ }
+ live, err := st.LiveBillingAccounts(0, 10)
+ if err != nil || len(live) != 1 || live[0].AccountID != ids["bab"] {
+ t.Errorf("LiveBillingAccounts = %+v, %v", live, err)
+ }
+ put.State = billing.StateEnded
+ if err := st.PutBillingState(put); err != nil {
+ t.Fatal(err)
+ }
+ if live, err := st.LiveBillingAccounts(0, 10); err != nil || len(live) != 0 {
+ t.Errorf("ended: LiveBillingAccounts = %+v, %v", live, err)
+ }
+}
+
+func TestLiveBillingAccountsPagesAndSkipsDeleted(t *testing.T) {
+ st, ids := planStore(t, "bab", "bdk", "bdm")
+ for i, sqid := range []string{"bab", "bdk", "bdm"} {
+ if err := st.SetBillingCustomer(ids[sqid], "cus_"+sqid, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.PutBillingState(billingAccount{AccountID: ids[sqid], Subscription: "sub_" + sqid, State: billing.StatePending, PaidPacks: map[string]int{}}); err != nil {
+ t.Fatal(err, i)
+ }
+ }
+ if _, err := st.db.Exec(`UPDATE accounts SET deleted_at = 1 WHERE id = ?`, ids["bdk"]); err != nil {
+ t.Fatal(err)
+ }
+ page, err := st.LiveBillingAccounts(0, 1)
+ if err != nil || len(page) != 1 || page[0].AccountID != ids["bab"] {
+ t.Fatalf("page 1 = %+v, %v", page, err)
+ }
+ page, err = st.LiveBillingAccounts(page[0].AccountID, 5)
+ if err != nil || len(page) != 1 || page[0].AccountID != ids["bdm"] {
+ t.Fatalf("page 2 = %+v, %v", page, err)
+ }
+}
+
+func TestOneOpenProblemPerReason(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ opened, err := st.OpenBillingProblem(ids["bab"], "sub_1", problemUnrecognised, "price x is not in the price map", billingNow)
+ if err != nil || !opened {
+ t.Fatalf("first open = %v, %v", opened, err)
+ }
+ if opened, err := st.OpenBillingProblem(ids["bab"], "sub_1", problemUnrecognised, "again", billingNow); err != nil || opened {
+ t.Fatalf("second open = %v, %v; want false", opened, err)
+ }
+ if opened, err := st.OpenBillingProblem(ids["bab"], "sub_1", problemSecondSubscription, "", billingNow); err != nil || !opened {
+ t.Fatalf("another reason = %v, %v", opened, err)
+ }
+ open, err := st.BillingProblems(false)
+ if err != nil || len(open) != 2 {
+ t.Fatalf("open problems = %+v, %v", open, err)
+ }
+ id := open[1].ID // newest first: the unrecognised one is second
+ if open[1].Reason != problemUnrecognised {
+ t.Fatalf("order = %+v", open)
+ }
+ if err := st.CloseBillingProblem(id, "op@example.com", "refunded and cancelled", billingNow.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.CloseBillingProblem(id, "op@example.com", "again", billingNow); err == nil {
+ t.Error("closed twice")
+ }
+ p, err := st.BillingProblem(id)
+ if err != nil || p == nil || p.ClosedBy != "op@example.com" || p.Note != "refunded and cancelled" || !p.ClosedAt.Equal(billingNow.Add(time.Hour)) {
+ t.Errorf("closed problem = %+v, %v", p, err)
+ }
+ if opened, err := st.OpenBillingProblem(ids["bab"], "sub_1", problemUnrecognised, "", billingNow); err != nil || !opened {
+ t.Fatalf("open after close = %v, %v", opened, err)
+ }
+ if open, _ := st.BillingProblems(false); len(open) != 2 {
+ t.Errorf("open problems = %d, want 2", len(open))
+ }
+ if all, _ := st.BillingProblems(true); len(all) != 3 {
+ t.Errorf("all problems = %d, want 3", len(all))
+ }
+ if p, err := st.BillingProblem(9999); p != nil || err != nil {
+ t.Errorf("unknown problem = %+v, %v", p, err)
+ }
+}
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index f28326dc2..bd750bbb9 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -211,6 +211,8 @@ var claimSQLTables = map[string]claimSQLTable{
"account_plans": {NonApp: "an account's plan and packs, keyed by account; names no app"},
"plan_cap_state": {NonApp: "an account's plan cap warnings and grace clocks, keyed by account; names no app"},
"billing_price_books": {NonApp: "price book versions and digests the console has started with; names no app"},
+ "billing_accounts": {NonApp: "an account's billing customer, subscription state and paid pack quantities; names no app"},
+ "billing_problems": {NonApp: "billing problems for an operator, keyed by account and subscription; names no app"},
"alert_seen": {NonApp: "operator alert memory, keyed by box, rule and address"},
"claim_loss_pages": {NonApp: "claim recovery page attempts per loss record and condition, and scan progress; no app state or lifecycle authority"},
"move_pages": {NonApp: "the move pass's last page attempt per finding (rule names the host and the move); no app column"},