console: billing keeps team seats, provider facts and prepared requests through 6a's one transaction; intents, house and retirement rows (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+982
−16
internal/console/billingstore.go+405 −11internal/console/billingstore_test.go+205 −0internal/console/billingsync.go+22 −5internal/console/billingsync_test.go+344 −0internal/console/store_gate.go+6 −0
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index bb776de20..179427c9e 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -1,9 +1,12 @@ |
| package console |
| import ( |
| + "bytes" |
| "database/sql" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| @@ -94,6 +97,82 @@ CREATE TABLE IF NOT EXISTS billing_problems ( |
| 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;`) |
| + if err != nil { |
| + return err |
| + } |
| + return s.migrateBilling6b() |
| +} |
| + |
| +// migrateBilling6b adds plans 6b's billing state: team seats and provider |
| +// facts on the billing row, the customer create's prepared request, and the |
| +// Checkout intent, house, retirement and restore-check tables. The ALTERs |
| +// are guarded like the store's ALTER list: a second start finds each column |
| +// and carries on. |
| +func (s *Store) migrateBilling6b() error { |
| + for _, col := range []string{ |
| + `plan TEXT NOT NULL DEFAULT ''`, |
| + `seats INTEGER NOT NULL DEFAULT 0`, |
| + `paid_seats INTEGER NOT NULL DEFAULT 0`, |
| + `live INTEGER NOT NULL DEFAULT 0`, |
| + `collecting INTEGER NOT NULL DEFAULT 0`, |
| + `pending_update INTEGER NOT NULL DEFAULT 0`, |
| + `pending_expires INTEGER NOT NULL DEFAULT 0`, |
| + `seats_checked_at INTEGER NOT NULL DEFAULT 0`, |
| + `seat_drift_at INTEGER NOT NULL DEFAULT 0`, |
| + `seat_drift_members INTEGER NOT NULL DEFAULT 0`, |
| + `customer_attempt INTEGER NOT NULL DEFAULT 0`, |
| + `customer_prepared BLOB`, |
| + `customer_first_sent_at INTEGER NOT NULL DEFAULT 0`, |
| + } { |
| + if _, err := s.db.Exec(`ALTER TABLE billing_accounts ADD COLUMN ` + col); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + } |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_checkout_intents ( |
| + account_id INTEGER PRIMARY KEY, |
| + intent_id TEXT NOT NULL UNIQUE, |
| + session TEXT NOT NULL DEFAULT '', |
| + url TEXT NOT NULL DEFAULT '', |
| + book TEXT NOT NULL, |
| + plan TEXT NOT NULL, |
| + currency TEXT NOT NULL, |
| + seats INTEGER NOT NULL DEFAULT 0, |
| + packs TEXT NOT NULL DEFAULT '{}', |
| + prepared BLOB NOT NULL, |
| + expire_prepared BLOB, |
| + state TEXT NOT NULL, |
| + created_at INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL, |
| + first_sent_at INTEGER NOT NULL DEFAULT 0, |
| + returned_at INTEGER NOT NULL DEFAULT 0, |
| + resolved_at INTEGER NOT NULL DEFAULT 0 |
| +); |
| +CREATE UNIQUE INDEX IF NOT EXISTS billing_checkout_intents_session ON billing_checkout_intents(session) WHERE session != ''; |
| +CREATE TABLE IF NOT EXISTS billing_house ( |
| + account_id INTEGER PRIMARY KEY, |
| + set_by TEXT NOT NULL, |
| + note TEXT NOT NULL, |
| + set_at INTEGER NOT NULL |
| +); |
| +CREATE TABLE IF NOT EXISTS billing_retirements ( |
| + account_id INTEGER PRIMARY KEY, |
| + started_by TEXT NOT NULL, |
| + started_at INTEGER NOT NULL |
| +); |
| +CREATE TABLE IF NOT EXISTS billing_restore_checks ( |
| + op_id TEXT PRIMARY KEY, |
| + account_id INTEGER NOT NULL, |
| + subscription TEXT NOT NULL, |
| + period_end INTEGER NOT NULL, |
| + price TEXT NOT NULL, |
| + target INTEGER NOT NULL, |
| + state TEXT NOT NULL, |
| + baseline TEXT NOT NULL DEFAULT '', |
| + attempts INTEGER NOT NULL DEFAULT 0, |
| + last_error TEXT NOT NULL DEFAULT '', |
| + created_at INTEGER NOT NULL, |
| + checked_at INTEGER NOT NULL DEFAULT 0 |
| +);`) |
| return err |
| } |
| @@ -110,32 +189,98 @@ type billingAccount struct { |
| PaidPacks map[string]int // highest quantity per pack paid for in the period ending PaidPeriodEnd |
| PaidPeriodEnd time.Time |
| SyncedAt time.Time |
| + |
| + // Plans 6b. Plan is the recognised plan of the subscription, "" when |
| + // none; Seats is a team plan's current quantity and PaidSeats the |
| + // highest paid for in the period ending PaidPeriodEnd (0 off team plans). |
| + Plan string |
| + Seats, PaidSeats int |
| + // The provider facts of the last read (billing.Subscription): Live is |
| + // settlement, Collecting an open invoice still being collected, |
| + // PendingUpdate a charged change waiting for payment until |
| + // PendingExpires. |
| + Live, Collecting, PendingUpdate bool |
| + PendingExpires time.Time |
| + // The seat drift check's console-local clocks and the member count it |
| + // last saw over the paid seats. |
| + SeatsCheckedAt, SeatDriftAt time.Time |
| + SeatDriftMembers int |
| + // The customer create in flight: its attempt (each attempt has its own |
| + // idempotency key), its prepared request exactly as sent, and the |
| + // provider time stamped just before its first send (Invariant 9). |
| + CustomerAttempt int |
| + CustomerPrepared *billing.Prepared |
| + CustomerFirstSentAt time.Time |
| } |
| +// billingRenewing is a subscription the provider will charge again at its |
| +// period end: live and not set to cancel. It reads the stored facts, never |
| +// the entitlement state. |
| +func billingRenewing(b *billingAccount) bool { return b.Live && !b.CancelAtPeriodEnd } |
| + |
| 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` |
| + b.period_end, b.cancel_at_period_end, b.paid_packs, b.paid_period_end, b.synced_at, |
| + b.plan, b.seats, b.paid_seats, b.live, b.collecting, b.pending_update, b.pending_expires, |
| + b.seats_checked_at, b.seat_drift_at, b.seat_drift_members, b.customer_attempt, b.customer_prepared, b.customer_first_sent_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 |
| + var periodEnd, paidEnd, synced, pendingExpires, checked, drift, firstSent int64 |
| + var cancel, live, collecting, pending int |
| + var prepared []byte |
| if err := sc.Scan(&b.AccountID, &b.Customer, &b.Subscription, &b.ProviderStatus, &state, &b.Book, &b.Currency, |
| - &periodEnd, &cancel, &packs, &paidEnd, &synced); err != nil { |
| + &periodEnd, &cancel, &packs, &paidEnd, &synced, |
| + &b.Plan, &b.Seats, &b.PaidSeats, &live, &collecting, &pending, &pendingExpires, |
| + &checked, &drift, &b.SeatDriftMembers, &b.CustomerAttempt, &prepared, &firstSent); 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 |
| + b.Live, b.Collecting, b.PendingUpdate = live != 0, collecting != 0, pending != 0 |
| + b.PendingExpires, b.SeatsCheckedAt, b.SeatDriftAt = timeOrZero(pendingExpires), timeOrZero(checked), timeOrZero(drift) |
| + b.CustomerFirstSentAt = timeOrZero(firstSent) |
| if err := json.Unmarshal([]byte(packs), &b.PaidPacks); err != nil { |
| return nil, err |
| } |
| if b.PaidPacks == nil { |
| b.PaidPacks = map[string]int{} |
| } |
| + var err error |
| + if b.CustomerPrepared, err = decodePrepared(prepared); err != nil { |
| + return nil, err |
| + } |
| return &b, nil |
| } |
| +// encodePrepared is a prepared request as stored: JSON, whose Body (bytes) |
| +// is base64 and so round-trips exactly. nil is SQL NULL. |
| +func encodePrepared(p *billing.Prepared) (any, error) { |
| + if p == nil { |
| + return nil, nil |
| + } |
| + return json.Marshal(p) |
| +} |
| + |
| +func decodePrepared(raw []byte) (*billing.Prepared, error) { |
| + if raw == nil { |
| + return nil, nil |
| + } |
| + var p billing.Prepared |
| + if err := json.Unmarshal(raw, &p); err != nil { |
| + return nil, err |
| + } |
| + return &p, nil |
| +} |
| + |
| +func boolInt(b bool) int { |
| + if b { |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| 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) { |
| @@ -200,19 +345,29 @@ func putBillingState(e sqlExecer, b billingAccount) error { |
| if err != nil { |
| return err |
| } |
| - cancel := 0 |
| - if b.CancelAtPeriodEnd { |
| - cancel = 1 |
| + prepared, err := encodePrepared(b.CustomerPrepared) |
| + if err != nil { |
| + return err |
| } |
| _, err = e.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + (account_id, subscription, provider_status, state, book, currency, period_end, cancel_at_period_end, paid_packs, paid_period_end, synced_at, |
| + plan, seats, paid_seats, live, collecting, pending_update, pending_expires, |
| + seats_checked_at, seat_drift_at, seat_drift_members, customer_attempt, customer_prepared, customer_first_sent_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`, |
| + paid_period_end = excluded.paid_period_end, synced_at = excluded.synced_at, |
| + plan = excluded.plan, seats = excluded.seats, paid_seats = excluded.paid_seats, live = excluded.live, |
| + collecting = excluded.collecting, pending_update = excluded.pending_update, pending_expires = excluded.pending_expires, |
| + seats_checked_at = excluded.seats_checked_at, seat_drift_at = excluded.seat_drift_at, |
| + seat_drift_members = excluded.seat_drift_members, customer_attempt = excluded.customer_attempt, |
| + customer_prepared = excluded.customer_prepared, customer_first_sent_at = excluded.customer_first_sent_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)) |
| + boolInt(b.CancelAtPeriodEnd), packs, unixOrZero(b.PaidPeriodEnd), unixOrZero(b.SyncedAt), |
| + b.Plan, b.Seats, b.PaidSeats, boolInt(b.Live), boolInt(b.Collecting), boolInt(b.PendingUpdate), unixOrZero(b.PendingExpires), |
| + unixOrZero(b.SeatsCheckedAt), unixOrZero(b.SeatDriftAt), b.SeatDriftMembers, b.CustomerAttempt, prepared, |
| + unixOrZero(b.CustomerFirstSentAt)) |
| return err |
| } |
| @@ -447,3 +602,242 @@ func (s *Store) EndBillingDiscovery(accountID int64, failed bool, now time.Time) |
| RETURNING discover_failures`, accountID).Scan(&n) |
| return n, err |
| } |
| + |
| +// The states of a Checkout intent. creating: the create is prepared and |
| +// may have been sent; open: the provider has the session; then one of the |
| +// terminal states, which are history (Invariant 6). |
| +const ( |
| + intentCreating = "creating" |
| + intentOpen = "open" |
| + intentCompleted = "completed" |
| + intentExpired = "expired" |
| + intentAbandoned = "abandoned" |
| +) |
| + |
| +// checkoutIntent is an account's Checkout: what it asked to buy, the |
| +// create exactly as prepared (and sent), the session the provider made and, |
| +// once one is prepared, the session's expiry. ExpiresAt and FirstSentAt |
| +// are provider times (Invariant 9). An account has at most one intent; a |
| +// terminal one is replaced by the next. |
| +type checkoutIntent struct { |
| + AccountID int64 |
| + ID, Session, URL string |
| + Book, Plan, Currency string |
| + Seats int |
| + Packs map[string]int |
| + Prepared billing.Prepared // the create, exactly as sent |
| + ExpirePrepared *billing.Prepared // set when an expiry is prepared |
| + State string |
| + CreatedAt, ExpiresAt, FirstSentAt, ReturnedAt, ResolvedAt time.Time |
| +} |
| + |
| +// intentTerminal is an intent nothing more will happen to: completed, |
| +// expired or abandoned. |
| +func intentTerminal(ci *checkoutIntent) bool { |
| + switch ci.State { |
| + case intentCompleted, intentExpired, intentAbandoned: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +const checkoutIntentColumns = `account_id, intent_id, session, url, book, plan, currency, seats, packs, prepared, expire_prepared, |
| + state, created_at, expires_at, first_sent_at, returned_at, resolved_at` |
| + |
| +func scanCheckoutIntent(sc interface{ Scan(...any) error }) (*checkoutIntent, error) { |
| + var ci checkoutIntent |
| + var packs string |
| + var prepared, expire []byte |
| + var created, expires, firstSent, returned, resolved int64 |
| + if err := sc.Scan(&ci.AccountID, &ci.ID, &ci.Session, &ci.URL, &ci.Book, &ci.Plan, &ci.Currency, &ci.Seats, &packs, |
| + &prepared, &expire, &ci.State, &created, &expires, &firstSent, &returned, &resolved); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(packs), &ci.Packs); err != nil { |
| + return nil, err |
| + } |
| + if ci.Packs == nil { |
| + ci.Packs = map[string]int{} |
| + } |
| + if err := json.Unmarshal(prepared, &ci.Prepared); err != nil { |
| + return nil, err |
| + } |
| + var err error |
| + if ci.ExpirePrepared, err = decodePrepared(expire); err != nil { |
| + return nil, err |
| + } |
| + ci.CreatedAt, ci.ExpiresAt, ci.FirstSentAt = timeOrZero(created), timeOrZero(expires), timeOrZero(firstSent) |
| + ci.ReturnedAt, ci.ResolvedAt = timeOrZero(returned), timeOrZero(resolved) |
| + return &ci, nil |
| +} |
| + |
| +// PutCheckoutIntent writes the account's intent. The same intent is |
| +// updated in place, but its prepared requests are never edited (Invariant |
| +// 1): a create whose bytes differ, or an expiry other than the one already |
| +// stored, is refused. Another intent replaces the account's only when the |
| +// stored one is terminal, so an outstanding create is never lost. |
| +func (s *Store) PutCheckoutIntent(ci checkoutIntent) error { |
| + if ci.ID == "" { |
| + return errors.New("billing: checkout intent without an id") |
| + } |
| + packs, err := canonicalPacks(ci.Packs) |
| + if err != nil { |
| + return err |
| + } |
| + prepared, err := json.Marshal(ci.Prepared) |
| + if err != nil { |
| + return err |
| + } |
| + expire, err := encodePrepared(ci.ExpirePrepared) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + cur, err := scanCheckoutIntent(tx.QueryRow(`SELECT `+checkoutIntentColumns+` FROM billing_checkout_intents WHERE account_id = ?`, ci.AccountID)) |
| + switch { |
| + case errors.Is(err, sql.ErrNoRows): |
| + case err != nil: |
| + return err |
| + case cur.ID != ci.ID: |
| + if !intentTerminal(cur) { |
| + return fmt.Errorf("billing: account %d's checkout intent %s is still %s", ci.AccountID, cur.ID, cur.State) |
| + } |
| + default: |
| + if !samePrepared(&cur.Prepared, &ci.Prepared) { |
| + return fmt.Errorf("billing: checkout intent %s: the prepared create cannot change", ci.ID) |
| + } |
| + if cur.ExpirePrepared != nil && !samePrepared(cur.ExpirePrepared, ci.ExpirePrepared) { |
| + return fmt.Errorf("billing: checkout intent %s: the prepared expiry cannot change", ci.ID) |
| + } |
| + } |
| + if _, err := tx.Exec(`INSERT INTO billing_checkout_intents (`+checkoutIntentColumns+`) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + ON CONFLICT(account_id) DO UPDATE SET intent_id = excluded.intent_id, session = excluded.session, url = excluded.url, |
| + book = excluded.book, plan = excluded.plan, currency = excluded.currency, seats = excluded.seats, packs = excluded.packs, |
| + prepared = excluded.prepared, expire_prepared = excluded.expire_prepared, state = excluded.state, |
| + created_at = excluded.created_at, expires_at = excluded.expires_at, first_sent_at = excluded.first_sent_at, |
| + returned_at = excluded.returned_at, resolved_at = excluded.resolved_at`, |
| + ci.AccountID, ci.ID, ci.Session, ci.URL, ci.Book, ci.Plan, ci.Currency, ci.Seats, packs, prepared, expire, |
| + ci.State, unixOrZero(ci.CreatedAt), unixOrZero(ci.ExpiresAt), unixOrZero(ci.FirstSentAt), |
| + unixOrZero(ci.ReturnedAt), unixOrZero(ci.ResolvedAt)); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// samePrepared is two prepared requests that send the same bytes. |
| +func samePrepared(a, b *billing.Prepared) bool { |
| + if a == nil || b == nil { |
| + return a == b |
| + } |
| + return a.Kind == b.Kind && a.Method == b.Method && a.Path == b.Path && a.Key == b.Key && bytes.Equal(a.Body, b.Body) |
| +} |
| + |
| +func (s *Store) checkoutIntentWhere(where string, arg any) (*checkoutIntent, error) { |
| + ci, err := scanCheckoutIntent(s.db.QueryRow(`SELECT `+checkoutIntentColumns+` FROM billing_checkout_intents WHERE `+where, arg)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + return ci, err |
| +} |
| + |
| +// CheckoutIntent is the account's intent, nil when it has none. |
| +func (s *Store) CheckoutIntent(accountID int64) (*checkoutIntent, error) { |
| + return s.checkoutIntentWhere(`account_id = ?`, accountID) |
| +} |
| + |
| +// CheckoutIntentBySession is the intent whose session is session, nil |
| +// when none is. |
| +func (s *Store) CheckoutIntentBySession(session string) (*checkoutIntent, error) { |
| + if session == "" { |
| + return nil, nil |
| + } |
| + return s.checkoutIntentWhere(`session = ?`, session) |
| +} |
| + |
| +// NonTerminalCheckoutIntents is up to limit intents still creating or |
| +// open, oldest first: the pass's observation list. |
| +func (s *Store) NonTerminalCheckoutIntents(limit int) ([]checkoutIntent, error) { |
| + rows, err := s.db.Query(`SELECT `+checkoutIntentColumns+` FROM billing_checkout_intents |
| + WHERE state IN (?, ?) ORDER BY created_at, account_id LIMIT ?`, intentCreating, intentOpen, limit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []checkoutIntent |
| + for rows.Next() { |
| + ci, err := scanCheckoutIntent(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, *ci) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// SetBillingHouse marks the account as a house account (on), recording who |
| +// set it and why, or clears the mark (off; clearing an unmarked account is |
| +// not an error). |
| +func (s *Store) SetBillingHouse(accountID int64, on bool, by, note string, now time.Time) error { |
| + if !on { |
| + _, err := s.db.Exec(`DELETE FROM billing_house WHERE account_id = ?`, accountID) |
| + return err |
| + } |
| + _, err := s.db.Exec(`INSERT INTO billing_house (account_id, set_by, note, set_at) VALUES (?, ?, ?, ?) |
| + ON CONFLICT(account_id) DO UPDATE SET set_by = excluded.set_by, note = excluded.note, set_at = excluded.set_at`, |
| + accountID, by, note, now.Unix()) |
| + return err |
| +} |
| + |
| +// BillingHouse is whether the account is a house account. |
| +func (s *Store) BillingHouse(accountID int64) (bool, error) { |
| + var n int |
| + err := s.db.QueryRow(`SELECT COUNT(*) FROM billing_house WHERE account_id = ?`, accountID).Scan(&n) |
| + return n > 0, err |
| +} |
| + |
| +// retirementTTL is how long a retirement row holds. It is measured on the |
| +// console's clock from the console-written started_at (Invariant 9's |
| +// console-local timers), so a crash mid-deletion frees the account after |
| +// an hour. |
| +const retirementTTL = time.Hour |
| + |
| +// BeginBillingRetirement marks the account as being deleted, restarting |
| +// the clock of any mark already there. (The plan's BeginRetirement, |
| +// EndRetirement and Retiring carry Billing in their names because the |
| +// instance lifetimes code already has a Store.BeginRetirement.) |
| +func (s *Store) BeginBillingRetirement(accountID int64, by string, now time.Time) error { |
| + _, err := s.db.Exec(`INSERT INTO billing_retirements (account_id, started_by, started_at) VALUES (?, ?, ?) |
| + ON CONFLICT(account_id) DO UPDATE SET started_by = excluded.started_by, started_at = excluded.started_at`, |
| + accountID, by, now.Unix()) |
| + return err |
| +} |
| + |
| +// EndBillingRetirement clears the account's retirement mark, if any. |
| +func (s *Store) EndBillingRetirement(accountID int64) error { |
| + _, err := s.db.Exec(`DELETE FROM billing_retirements WHERE account_id = ?`, accountID) |
| + return err |
| +} |
| + |
| +// BillingRetiring is whether the account is being deleted. A mark |
| +// retirementTTL old or older is stale: it is cleared and the account is not |
| +// retiring. |
| +func (s *Store) BillingRetiring(accountID int64, now time.Time) (bool, error) { |
| + var started int64 |
| + err := s.db.QueryRow(`SELECT started_at FROM billing_retirements WHERE account_id = ?`, accountID).Scan(&started) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + if now.Before(time.Unix(started, 0).Add(retirementTTL)) { |
| + return true, nil |
| + } |
| + _, err = s.db.Exec(`DELETE FROM billing_retirements WHERE account_id = ? AND started_at = ?`, accountID, started) |
| + return false, err |
| +} |
diff --git a/internal/console/billingstore_test.go b/internal/console/billingstore_test.go| index c913f4777..ff83076a6 100644 |
| --- a/internal/console/billingstore_test.go |
| +++ b/internal/console/billingstore_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "bytes" |
| "errors" |
| "reflect" |
| "testing" |
| @@ -67,6 +68,12 @@ func TestBillingStateRoundTrips(t *testing.T) { |
| 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, |
| + Plan: "community", Seats: 11, PaidSeats: 14, Live: true, Collecting: true, PendingUpdate: true, |
| + PendingExpires: billingNow.Add(23 * time.Hour), SeatsCheckedAt: billingNow.Add(-time.Hour), |
| + SeatDriftAt: billingNow.Add(-2 * time.Hour), SeatDriftMembers: 9, CustomerAttempt: 2, |
| + CustomerPrepared: &billing.Prepared{Kind: billing.PreparedCustomer, Method: "POST", Path: "/v1/customers", |
| + Body: []byte("metadata[account]=bab&\x00\xff"), Key: "customer:bab:2"}, |
| + CustomerFirstSentAt: billingNow.Add(-3 * time.Minute), |
| } |
| put := want |
| put.Customer = "cus_ignored" // PutBillingState writes every column but the customer |
| @@ -159,3 +166,201 @@ func TestOneOpenProblemPerReason(t *testing.T) { |
| t.Errorf("unknown problem = %+v, %v", p, err) |
| } |
| } |
| + |
| +func testIntent(accountID int64, id string) checkoutIntent { |
| + return checkoutIntent{ |
| + AccountID: accountID, ID: id, Book: "example-v1", Plan: "community", Currency: "usd", Seats: 12, |
| + Packs: map[string]int{"apps": 2, "email": 1}, |
| + Prepared: billing.Prepared{Kind: billing.PreparedCheckout, Method: "POST", Path: "/v1/checkout/sessions", |
| + Body: []byte("line_items[0][quantity]=12&metadata[intent]=" + id + "&\x00\xfe\xff\r\n"), Key: "checkout:" + id}, |
| + State: intentCreating, CreatedAt: billingNow, ExpiresAt: billingNow.Add(time.Hour), FirstSentAt: billingNow.Add(time.Second), |
| + } |
| +} |
| + |
| +func TestCheckoutIntentRoundTrip(t *testing.T) { |
| + st, ids := planStore(t, "bab", "bdk") |
| + want := testIntent(ids["bab"], "ci_1") |
| + if err := st.PutCheckoutIntent(want); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := st.CheckoutIntent(ids["bab"]) |
| + if err != nil || got == nil { |
| + t.Fatalf("CheckoutIntent = %v, %v", got, err) |
| + } |
| + if !reflect.DeepEqual(*got, want) { |
| + t.Fatalf("round trip:\n got %+v\nwant %+v", *got, want) |
| + } |
| + if !bytes.Equal(got.Prepared.Body, want.Prepared.Body) { |
| + t.Fatalf("prepared body changed: %q", got.Prepared.Body) |
| + } |
| + // The create answered: open, with a session; then an expiry is prepared. |
| + want.Session, want.URL, want.State = "cs_1", "https://pay.example.com/cs_1", intentOpen |
| + if err := st.PutCheckoutIntent(want); err != nil { |
| + t.Fatal(err) |
| + } |
| + want.ExpirePrepared = &billing.Prepared{Kind: billing.PreparedExpire, Method: "POST", Path: "/v1/checkout/sessions/cs_1/expire", |
| + Body: []byte{}, Key: "expire:ci_1"} |
| + want.ReturnedAt = billingNow.Add(10 * time.Minute) |
| + if err := st.PutCheckoutIntent(want); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err = st.CheckoutIntentBySession("cs_1") |
| + if err != nil || got == nil || !reflect.DeepEqual(*got, want) { |
| + t.Fatalf("CheckoutIntentBySession = %+v, %v\nwant %+v", got, err, want) |
| + } |
| + if !bytes.Equal(got.Prepared.Body, want.Prepared.Body) || got.ExpirePrepared == nil || got.ExpirePrepared.Key != "expire:ci_1" { |
| + t.Fatalf("prepared requests changed: %+v %+v", got.Prepared, got.ExpirePrepared) |
| + } |
| + for _, s := range []string{"", "cs_none"} { |
| + if got, err := st.CheckoutIntentBySession(s); got != nil || err != nil { |
| + t.Errorf("session %q = %+v, %v", s, got, err) |
| + } |
| + } |
| + if got, err := st.CheckoutIntent(ids["bdk"]); got != nil || err != nil { |
| + t.Errorf("no intent = %+v, %v", got, err) |
| + } |
| + |
| + // A prepared request is never edited, and an outstanding intent is |
| + // never replaced. |
| + edited := want |
| + edited.Prepared.Body = append([]byte(nil), want.Prepared.Body...) |
| + edited.Prepared.Body[0] = 'X' |
| + if err := st.PutCheckoutIntent(edited); err == nil { |
| + t.Error("the create's prepared bytes were edited") |
| + } |
| + edited = want |
| + edited.ExpirePrepared = &billing.Prepared{Kind: billing.PreparedExpire, Method: "POST", Path: "/v1/checkout/sessions/cs_1/expire", Key: "expire:other"} |
| + if err := st.PutCheckoutIntent(edited); err == nil { |
| + t.Error("the expiry's prepared request was edited") |
| + } |
| + if err := st.PutCheckoutIntent(testIntent(ids["bab"], "ci_2")); err == nil { |
| + t.Error("an open intent was replaced") |
| + } |
| + // The session belongs to one intent. |
| + other := testIntent(ids["bdk"], "ci_3") |
| + other.Session = "cs_1" |
| + if err := st.PutCheckoutIntent(other); err == nil { |
| + t.Error("two intents share a session") |
| + } |
| + other.Session = "" |
| + if err := st.PutCheckoutIntent(other); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + list, err := st.NonTerminalCheckoutIntents(10) |
| + if err != nil || len(list) != 2 { |
| + t.Fatalf("NonTerminalCheckoutIntents = %+v, %v", list, err) |
| + } |
| + if list, err := st.NonTerminalCheckoutIntents(1); err != nil || len(list) != 1 { |
| + t.Fatalf("limit 1: %d, %v", len(list), err) |
| + } |
| + // Terminal: history, so a new intent may take its place. |
| + want.State, want.ResolvedAt = intentExpired, billingNow.Add(20*time.Minute) |
| + if err := st.PutCheckoutIntent(want); err != nil { |
| + t.Fatal(err) |
| + } |
| + list, _ = st.NonTerminalCheckoutIntents(10) |
| + if len(list) != 1 || list[0].ID != "ci_3" { |
| + t.Fatalf("after expiry: %+v", list) |
| + } |
| + next := testIntent(ids["bab"], "ci_4") |
| + if err := st.PutCheckoutIntent(next); err != nil { |
| + t.Fatalf("new intent after a terminal one: %v", err) |
| + } |
| + if got, _ := st.CheckoutIntent(ids["bab"]); got == nil || got.ID != "ci_4" || got.Session != "" { |
| + t.Fatalf("replacement = %+v", got) |
| + } |
| + if got, _ := st.CheckoutIntentBySession("cs_1"); got != nil { |
| + t.Fatalf("the replaced intent's session still resolves: %+v", got) |
| + } |
| +} |
| + |
| +func TestIntentTerminal(t *testing.T) { |
| + for state, want := range map[string]bool{ |
| + intentCreating: false, intentOpen: false, |
| + intentCompleted: true, intentExpired: true, intentAbandoned: true, |
| + } { |
| + if got := intentTerminal(&checkoutIntent{State: state}); got != want { |
| + t.Errorf("intentTerminal(%q) = %v, want %v", state, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestBillingHouseOnOff(t *testing.T) { |
| + st, ids := planStore(t, "bab", "bdk") |
| + if on, err := st.BillingHouse(ids["bab"]); on || err != nil { |
| + t.Fatalf("initially = %v, %v", on, err) |
| + } |
| + if err := st.SetBillingHouse(ids["bab"], true, "ops@example.com", "staff account", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if on, err := st.BillingHouse(ids["bab"]); !on || err != nil { |
| + t.Fatalf("on = %v, %v", on, err) |
| + } |
| + if on, _ := st.BillingHouse(ids["bdk"]); on { |
| + t.Fatal("house leaked to another account") |
| + } |
| + // Setting it again records who set it last. |
| + if err := st.SetBillingHouse(ids["bab"], true, "lead@example.com", "still staff", billingNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var by, note string |
| + var at int64 |
| + if err := st.db.QueryRow(`SELECT set_by, note, set_at FROM billing_house WHERE account_id = ?`, ids["bab"]).Scan(&by, ¬e, &at); err != nil { |
| + t.Fatal(err) |
| + } |
| + if by != "lead@example.com" || note != "still staff" || at != billingNow.Add(time.Hour).Unix() { |
| + t.Fatalf("row = %q %q %d", by, note, at) |
| + } |
| + if err := st.SetBillingHouse(ids["bab"], false, "ops@example.com", "left", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if on, err := st.BillingHouse(ids["bab"]); on || err != nil { |
| + t.Fatalf("off = %v, %v", on, err) |
| + } |
| + if err := st.SetBillingHouse(ids["bab"], false, "ops@example.com", "again", billingNow); err != nil { |
| + t.Fatalf("off twice: %v", err) |
| + } |
| +} |
| + |
| +func TestRetirementRowsExpire(t *testing.T) { |
| + st, ids := planStore(t, "bab", "bdk") |
| + if r, err := st.BillingRetiring(ids["bab"], billingNow); r || err != nil { |
| + t.Fatalf("initially = %v, %v", r, err) |
| + } |
| + if err := st.BeginBillingRetirement(ids["bab"], "owner@example.com", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, err := st.BillingRetiring(ids["bab"], billingNow.Add(retirementTTL-time.Second)); !r || err != nil { |
| + t.Fatalf("within the hour = %v, %v", r, err) |
| + } |
| + if r, _ := st.BillingRetiring(ids["bdk"], billingNow); r { |
| + t.Fatal("retirement leaked to another account") |
| + } |
| + if r, err := st.BillingRetiring(ids["bab"], billingNow.Add(retirementTTL)); r || err != nil { |
| + t.Fatalf("after an hour = %v, %v", r, err) |
| + } |
| + var n int |
| + if err := st.db.QueryRow(`SELECT COUNT(*) FROM billing_retirements WHERE account_id = ?`, ids["bab"]).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("stale row not cleared: %d, %v", n, err) |
| + } |
| + // Begin again restarts the clock; End clears it. |
| + if err := st.BeginBillingRetirement(ids["bab"], "owner@example.com", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.BeginBillingRetirement(ids["bab"], "owner@example.com", billingNow.Add(50*time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := st.BillingRetiring(ids["bab"], billingNow.Add(80*time.Minute)); !r { |
| + t.Fatal("a second begin did not restart the clock") |
| + } |
| + if err := st.EndBillingRetirement(ids["bab"]); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := st.BillingRetiring(ids["bab"], billingNow); r { |
| + t.Fatal("ended retirement still retiring") |
| + } |
| + if err := st.EndBillingRetirement(ids["bab"]); err != nil { |
| + t.Fatalf("end twice: %v", err) |
| + } |
| +} |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index 11d76ce7c..e06754ce4 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -31,7 +31,7 @@ type billingInput struct { |
| type planChange struct { |
| Plan string |
| Packs map[string]int |
| - Seats int // the paid seat count (plans 6b); 0 counts the members |
| + Seats int // the paid seat count (plans 6b): PaidSeats, 0 for non-team plans |
| Reason string |
| } |
| @@ -58,9 +58,12 @@ func liveState(s billing.State) bool { return s == billing.StatePaid || s == bil |
| // - pending: adopt it, change no plan; |
| // - paid but not recognised: adopt it, open a problem, change no plan; |
| // - paid and recognised: adopt it and write the plan with the period's |
| -// highest paid pack quantities; |
| +// highest paid pack quantities and, on a team plan, seats (PaidSeats); |
| // - ended, and it is the current subscription (or none is recorded): the |
| -// default plan, packs cleared. |
| +// default plan, packs and team fields cleared. |
| +// |
| +// Every saved decision carries the read's provider facts (Live, |
| +// Collecting, PendingUpdate, PendingExpires). |
| func decideBilling(in billingInput) billingDecision { |
| sub, prev := in.Sub, in.Prev |
| if sub.LiveMode != in.LiveMode { |
| @@ -88,10 +91,14 @@ func decideBilling(in billingInput) billingDecision { |
| next.Currency = sub.Currency |
| next.PeriodEnd = sub.PeriodEnd |
| next.CancelAtPeriodEnd = sub.CancelAtPeriodEnd |
| + // The provider facts of this read (plans 6b), whatever its state. |
| + next.Live, next.Collecting = sub.Live, sub.Collecting |
| + next.PendingUpdate, next.PendingExpires = sub.PendingUpdate, sub.PendingExpires |
| if other { |
| // A new subscription after the old one ended: nothing of the old |
| - // period carries over. |
| + // period carries over, its seats included. |
| next.PaidPacks, next.PaidPeriodEnd, next.Book = map[string]int{}, time.Time{}, "" |
| + next.Plan, next.Seats, next.PaidSeats = "", 0, 0 |
| } |
| d := billingDecision{Save: true, Next: next} |
| // Adopting a replacement for a subscription that has ended (a fresh |
| @@ -117,6 +124,15 @@ func decideBilling(in billingInput) billingDecision { |
| return d |
| } |
| d.Next.Book = in.Purchase.Book |
| + // Seats (plans 6b): a new period, plan or subscription starts the |
| + // paid count again at the billed quantity; within one, the highest |
| + // paid for holds until renewal, as packs do. |
| + if !d.Next.PaidPeriodEnd.Equal(sub.PeriodEnd) || prev.Plan != in.Purchase.Plan || prev.Subscription != sub.ID { |
| + d.Next.PaidSeats = in.Purchase.Seats |
| + } else { |
| + d.Next.PaidSeats = max(d.Next.PaidSeats, in.Purchase.Seats) |
| + } |
| + d.Next.Plan, d.Next.Seats = in.Purchase.Plan, in.Purchase.Seats |
| if !d.Next.PaidPeriodEnd.Equal(sub.PeriodEnd) { |
| // A new period: reductions made in the last one take effect. |
| d.Next.PaidPacks = maps.Clone(in.Purchase.Packs) |
| @@ -131,11 +147,12 @@ func decideBilling(in billingInput) billingDecision { |
| d.Next.PaidPacks[name] = max(d.Next.PaidPacks[name], q) |
| } |
| } |
| - d.Plan = &planChange{Plan: in.Purchase.Plan, Packs: maps.Clone(d.Next.PaidPacks), |
| + d.Plan = &planChange{Plan: in.Purchase.Plan, Packs: maps.Clone(d.Next.PaidPacks), Seats: d.Next.PaidSeats, |
| Reason: fmt.Sprintf("subscription %s %s", sub.ID, sub.ProviderStatus)} |
| return d |
| default: // ended, and it is the current subscription or none is recorded |
| d.Next.PaidPacks, d.Next.PaidPeriodEnd = map[string]int{}, time.Time{} |
| + d.Next.Plan, d.Next.Seats, d.Next.PaidSeats = "", 0, 0 |
| d.Plan = &planChange{Plan: in.DefaultPlan, Reason: fmt.Sprintf("subscription %s ended (%s)", sub.ID, sub.ProviderStatus)} |
| return d |
| } |
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go| index a5810edc1..a52b1f45f 100644 |
| --- a/internal/console/billingsync_test.go |
| +++ b/internal/console/billingsync_test.go |
| @@ -4,8 +4,10 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "net/http" |
| "reflect" |
| "regexp" |
| + "sync" |
| "testing" |
| "time" |
| @@ -395,3 +397,345 @@ func TestSyncEndedDropsToDefault(t *testing.T) { |
| t.Fatalf("row = %+v", row) |
| } |
| } |
| + |
| +// ---- plans 6b: team seats and provider facts ---- |
| + |
| +// teamIn is decideIn for a team plan bought at seats. |
| +func teamIn(prev *billingAccount, sub *billing.Subscription, plan string, seats int) billingInput { |
| + in := decideIn(prev, sub, nil) |
| + in.Purchase.Plan, in.Purchase.Seats = plan, seats |
| + return in |
| +} |
| + |
| +func TestDecideTeamSeatsHoldUntilRenewal(t *testing.T) { |
| + sub := paidSub("sub_1", "active", nil) |
| + d := decideBilling(teamIn(nil, sub, "community", 14)) |
| + if d.Plan == nil || d.Plan.Plan != "community" || d.Plan.Seats != 14 || d.Next.PaidSeats != 14 || d.Next.Seats != 14 || d.Next.Plan != "community" { |
| + t.Fatalf("first: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + prev := d.Next |
| + d = decideBilling(teamIn(&prev, sub, "community", 11)) |
| + if d.Plan.Seats != 14 || d.Next.PaidSeats != 14 || d.Next.Seats != 11 { |
| + t.Fatalf("reduced in period: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + prev = d.Next |
| + d = decideBilling(teamIn(&prev, sub, "community", 12)) |
| + if d.Plan.Seats != 14 || d.Next.PaidSeats != 14 || d.Next.Seats != 12 { |
| + t.Fatalf("raised back within: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + prev = d.Next |
| + renewed := paidSub("sub_1", "active", nil) |
| + renewed.PeriodEnd = periodEnd.AddDate(1, 0, 0) |
| + d = decideBilling(teamIn(&prev, renewed, "community", 11)) |
| + if d.Plan.Seats != 11 || d.Next.PaidSeats != 11 || d.Next.Seats != 11 { |
| + t.Fatalf("renewal: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| +} |
| + |
| +func TestDecideUpgradeResetsSeats(t *testing.T) { |
| + sub := paidSub("sub_1", "active", nil) |
| + d := decideBilling(decideIn(nil, sub, nil)) |
| + if d.Plan.Seats != 0 || d.Next.PaidSeats != 0 || d.Next.Plan != "personal" { |
| + t.Fatalf("personal: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + prev := d.Next |
| + d = decideBilling(teamIn(&prev, sub, "business", 10)) |
| + if d.Plan.Plan != "business" || d.Plan.Seats != 10 || d.Next.PaidSeats != 10 || d.Next.Plan != "business" { |
| + t.Fatalf("upgrade in period: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + // A plan change in the period starts the seat count again rather than |
| + // keeping the old plan's higher one. |
| + prev = d.Next |
| + prev.PaidSeats, prev.Seats = 20, 20 |
| + d = decideBilling(teamIn(&prev, sub, "community", 12)) |
| + if d.Plan.Seats != 12 || d.Next.PaidSeats != 12 || d.Next.Plan != "community" { |
| + t.Fatalf("business x 20 -> community x 12: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| +} |
| + |
| +func TestDecideNewSubscriptionClearsSeats(t *testing.T) { |
| + // The ended subscription is still the account's: its end clears the team fields. |
| + prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_a", State: billing.StatePaid, Plan: "community", |
| + Seats: 20, PaidSeats: 20, PaidPacks: map[string]int{}, PaidPeriodEnd: periodEnd} |
| + d := decideBilling(teamIn(prev, paidSub("sub_a", "canceled", nil), "community", 20)) |
| + if d.Plan == nil || d.Plan.Plan != "free" || d.Plan.Seats != 0 || d.Next.Plan != "" || d.Next.Seats != 0 || d.Next.PaidSeats != 0 { |
| + t.Fatalf("ended: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| + // A row that still carries the old subscription's seats (recorded |
| + // ended), and a new one in the same period: nothing carries over. |
| + prev = &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_a", State: billing.StateEnded, Plan: "community", |
| + Seats: 20, PaidSeats: 20, PaidPacks: map[string]int{}, PaidPeriodEnd: periodEnd} |
| + d = decideBilling(teamIn(prev, paidSub("sub_b", "active", nil), "community", 10)) |
| + if d.Plan == nil || d.Plan.Seats != 10 || d.Next.PaidSeats != 10 || d.Next.Seats != 10 || d.Next.Subscription != "sub_b" { |
| + t.Fatalf("new subscription: plan %+v next %+v", d.Plan, d.Next) |
| + } |
| +} |
| + |
| +func TestDecideSavesFacts(t *testing.T) { |
| + expires := periodEnd.Add(-48 * time.Hour) |
| + prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid, PaidPacks: map[string]int{}, |
| + Live: true, Collecting: true, PendingUpdate: true, PendingExpires: expires} |
| + sub := paidSub("sub_1", "active", nil) |
| + sub.Live = true |
| + d := decideBilling(decideIn(prev, sub, nil)) |
| + if !d.Save || !d.Next.Live || d.Next.Collecting || d.Next.PendingUpdate || !d.Next.PendingExpires.IsZero() { |
| + t.Fatalf("cleared facts not saved: %+v", d.Next) |
| + } |
| + sub.Collecting, sub.PendingUpdate, sub.PendingExpires = true, true, expires |
| + sub.ProviderStatus, sub.State = "past_due", billing.StatePaid |
| + d = decideBilling(decideIn(prev, sub, nil)) |
| + if !d.Next.Live || !d.Next.Collecting || !d.Next.PendingUpdate || !d.Next.PendingExpires.Equal(expires) { |
| + t.Fatalf("paid facts: %+v", d.Next) |
| + } |
| + // Pending and ended reads save their facts too. |
| + pending := paidSub("sub_1", "incomplete", nil) |
| + pending.Live, pending.Collecting = true, true |
| + d = decideBilling(decideIn(prev, pending, nil)) |
| + if !d.Save || !d.Next.Live || !d.Next.Collecting { |
| + t.Fatalf("pending facts: %+v", d.Next) |
| + } |
| + unpaid := paidSub("sub_1", "unpaid", nil) |
| + unpaid.Live, unpaid.Collecting = true, true |
| + d = decideBilling(decideIn(prev, unpaid, nil)) |
| + if !d.Save || !d.Next.Live || !d.Next.Collecting || d.Next.State != billing.StateEnded { |
| + t.Fatalf("unpaid facts: %+v", d.Next) |
| + } |
| + ended := paidSub("sub_1", "canceled", nil) |
| + d = decideBilling(decideIn(prev, ended, nil)) |
| + if d.Next.Live || d.Next.Collecting || d.Next.PendingUpdate { |
| + t.Fatalf("canceled facts: %+v", d.Next) |
| + } |
| +} |
| + |
| +func TestBillingRenewingUsesFacts(t *testing.T) { |
| + cases := []struct { |
| + b billingAccount |
| + want bool |
| + }{ |
| + {billingAccount{State: billing.StatePaid, Live: true}, true}, |
| + {billingAccount{State: billing.StatePaid, Live: true, CancelAtPeriodEnd: true}, false}, |
| + {billingAccount{State: billing.StatePaid, Live: false}, false}, // the state alone is not settlement |
| + {billingAccount{State: billing.StateEnded, Live: true}, true}, // unpaid: still charged at the provider |
| + {billingAccount{State: billing.StatePending, Live: true}, true}, // incomplete |
| + {billingAccount{State: billing.StateEnded, Live: false}, false}, |
| + } |
| + for i, c := range cases { |
| + if got := billingRenewing(&c.b); got != c.want { |
| + t.Errorf("case %d %+v: billingRenewing = %v, want %v", i, c.b, got, c.want) |
| + } |
| + } |
| + // Through a sync's decision: the read's facts decide. |
| + unpaid := paidSub("sub_1", "unpaid", nil) |
| + unpaid.Live = true |
| + d := decideBilling(decideIn(nil, unpaid, nil)) |
| + if !billingRenewing(&d.Next) { |
| + t.Fatalf("unpaid read: not renewing: %+v", d.Next) |
| + } |
| + stopped := paidSub("sub_1", "active", nil) |
| + stopped.Live, stopped.CancelAtPeriodEnd = true, true |
| + d = decideBilling(decideIn(nil, stopped, nil)) |
| + if billingRenewing(&d.Next) { |
| + t.Fatalf("renewal stopped: still renewing: %+v", d.Next) |
| + } |
| +} |
| + |
| +// testTeamSub is a team plan subscription at seats on customer for |
| +// account sqid, in usd. |
| +func testTeamSub(id, customer, sqid, plan, status string, seats int64) *billing.Subscription { |
| + items := []billing.Item{{ItemID: "si_" + id, PriceID: testPriceID("example-v1/" + plan + "/usd"), Quantity: seats, Currency: "usd"}} |
| + return &billing.Subscription{ID: id, Customer: customer, Account: sqid, ProviderStatus: status, State: billingStateFor(status), |
| + Live: billingLiveFor(status), Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items} |
| +} |
| + |
| +func (bf *billingFixture) teamSub(id, plan, status string, seats int64) *billing.Subscription { |
| + return testTeamSub(id, "cus_1", bf.acct.Sqid, plan, status, seats) |
| +} |
| + |
| +// seats is the account's plan row and billing row as (plan, plan row |
| +// seats, billing PaidSeats, billing Seats). |
| +func (bf *billingFixture) seats(t *testing.T) (string, int, int, int) { |
| + t.Helper() |
| + row, err := bf.st.AccountPlan(bf.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := bf.st.BillingAccount(bf.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if row == nil || b == nil { |
| + t.Fatalf("plan row %+v billing row %+v", row, b) |
| + } |
| + return row.Plan, row.Seats, b.PaidSeats, b.Seats |
| +} |
| + |
| +func TestSyncSeatsGoThroughOneTransaction(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.teamSub("sub_1", "community", "active", 12)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 12 || paid != 12 || cur != 12 { |
| + t.Fatalf("first sync: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| + if _, err := bf.st.db.Exec(`CREATE TRIGGER fail_plan BEFORE UPDATE ON account_plans BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.put(bf.teamSub("sub_1", "community", "active", 14)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Hour)); err == nil { |
| + t.Fatal("a failed plan write was reported as success") |
| + } |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 12 || paid != 12 || cur != 12 { |
| + t.Fatalf("seats committed without the plan write: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| + if b, _ := bf.st.BillingAccount(bf.acct.ID); !b.SyncedAt.Equal(billingNow) { |
| + t.Fatalf("billing row committed without the plan write: %+v", b) |
| + } |
| + if _, err := bf.st.db.Exec(`DROP TRIGGER fail_plan`); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(2*time.Hour)) |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 14 || paid != 14 || cur != 14 { |
| + t.Fatalf("the next pass did not finish the change: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| +} |
| + |
| +func TestDiscoveryThenSeats(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.teamSub("sub_1", "community", "active", 12)) |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 12 || paid != 12 || cur != 12 { |
| + t.Fatalf("discovered: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| + if b, _ := bf.st.BillingAccount(bf.acct.ID); b.Plan != "community" || !b.Live { |
| + t.Fatalf("billing row = %+v", b) |
| + } |
| + // A member leaves and the quantity comes down in the period: the paid |
| + // seats hold until renewal. |
| + bf.put(bf.teamSub("sub_1", "community", "active", 10)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(2*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 12 || paid != 12 || cur != 10 { |
| + t.Fatalf("reduced in period: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| +} |
| + |
| +func TestPendingReplacementThenPayment(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.teamSub("sub_1", "community", "active", 15)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.put(bf.teamSub("sub_1", "community", "canceled", 15)) |
| + bf.put(bf.teamSub("sub_2", "community", "incomplete", 10)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_2", billingNow.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + if b.Subscription != "sub_2" || b.State != billing.StatePending || b.Plan != "" || b.Seats != 0 || b.PaidSeats != 0 { |
| + t.Fatalf("pending replacement kept the old seats: %+v", b) |
| + } |
| + if plan, rowSeats, _, _ := bf.seats(t); plan != "free" || rowSeats != 0 { |
| + t.Fatalf("pending replacement: plan %q row seats %d", plan, rowSeats) |
| + } |
| + bf.put(bf.teamSub("sub_2", "community", "active", 10)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_2", billingNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if plan, rowSeats, paid, cur := bf.seats(t); plan != "community" || rowSeats != 10 || paid != 10 || cur != 10 { |
| + t.Fatalf("paid replacement: plan %q row seats %d paid %d cur %d", plan, rowSeats, paid, cur) |
| + } |
| +} |
| + |
| +// A missing-subscription close and a sync that writes seats, in both |
| +// orders: the billing row's plan and paid seats always agree with the plan |
| +// row, and a close never ends a subscription a newer read found. |
| +func TestMissingClosureRacesSeatWrite(t *testing.T) { |
| + setup := func(t *testing.T) (*billingFixture, int64) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.teamSub("sub_1", "community", "active", 12)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.fake.Lock() |
| + delete(bf.fake.Subs, "sub_1") |
| + bf.fake.Unlock() |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ := bf.st.BillingProblems(false) |
| + if len(open) != 1 || open[0].Reason != problemSubscriptionMissing { |
| + t.Fatalf("problems = %+v", open) |
| + } |
| + return bf, open[0].ID |
| + } |
| + consistent := func(t *testing.T, bf *billingFixture, wantPlan string, wantSeats int) { |
| + t.Helper() |
| + row, _ := bf.st.AccountPlan(bf.acct.ID) |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + billingPlan := b.Plan |
| + if billingPlan == "" { |
| + billingPlan = "free" |
| + } |
| + if row.Plan != wantPlan || row.Seats != wantSeats || billingPlan != row.Plan || b.PaidSeats != row.Seats { |
| + t.Fatalf("inconsistent: plan row %q seats %d; billing plan %q paid seats %d state %s; want %q x %d", |
| + row.Plan, row.Seats, b.Plan, b.PaidSeats, b.State, wantPlan, wantSeats) |
| + } |
| + } |
| + |
| + t.Run("sync between the close's steps", func(t *testing.T) { |
| + bf, id := setup(t) |
| + bf.put(bf.teamSub("sub_1", "community", "active", 14)) |
| + var once sync.Once |
| + bf.fake.Lock() |
| + bf.fake.BeforeSubscription = func(string) error { |
| + var fire bool |
| + once.Do(func() { fire = true }) |
| + if !fire { |
| + return nil |
| + } |
| + // The close's first read answers not found; meanwhile a sync |
| + // reads the subscription with 14 seats and commits. |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + _ = bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Minute)) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(15 * time.Second): |
| + t.Error("the racing sync did not finish") |
| + } |
| + return billing.ErrNotFound |
| + } |
| + bf.fake.Unlock() |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-seat-race") |
| + if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, id), map[string]any{"note": "gone"}, op); status == http.StatusOK { |
| + t.Fatalf("close succeeded over a newer sync: %v", out) |
| + } |
| + consistent(t, bf, "community", 14) |
| + if b, _ := bf.st.BillingAccount(bf.acct.ID); b.State != billing.StatePaid || b.Seats != 14 { |
| + t.Fatalf("billing row = %+v", b) |
| + } |
| + }) |
| + |
| + t.Run("close then sync", func(t *testing.T) { |
| + bf, id := setup(t) |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-seat-close") |
| + if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, id), map[string]any{"note": "gone"}, op); status != http.StatusOK { |
| + t.Fatalf("close: %d %v", status, out) |
| + } |
| + consistent(t, bf, "free", 0) |
| + // The provider has it again, now at 14: the sync adopts it afresh. |
| + bf.put(bf.teamSub("sub_1", "community", "active", 14)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + consistent(t, bf, "community", 14) |
| + }) |
| +} |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 51e4323bc..24b1858f3 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -239,6 +239,12 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "claim_sql_receipts": {NonApp: "private SQL effect receipts and fences"}, |
| "email_challenges": {NonApp: "emailed sign-in and step-up links and codes in flight, keyed by id hash; carries no app column"}, |
| "pending_actions": {NonApp: "replay-by-token actions, keyed by token hash; carries no app column and re-enters the ordinary handlers"}, |
| + |
| + // Plans 6b's billing tables. |
| + "billing_checkout_intents": {NonApp: "an account's Checkout intent and its prepared provider requests, keyed by account; names no app"}, |
| + "billing_house": {NonApp: "house accounts an operator marked, keyed by account; names no app"}, |
| + "billing_retirements": {NonApp: "accounts whose deletion is in progress, keyed by account; names no app"}, |
| + "billing_restore_checks": {NonApp: "an account's late-restore verification obligations; names no app"}, |
| } |
| // claimSQLReservedName is the TEMP permit table. A main-schema table by that |