carlos / platform Public

billing: neutral billable and renewal-failing subscription facts

billing.Subscription gains Billable (the provider counts it as running and
charging) and RenewalFailing (a renewal charge failing while it retries),
so the console can tell paying from trials without the provider's status
words. The Stripe adapter maps them from the status (active or past_due;
past_due), the Fake keeps them on its own transitions, and the sync saves
them on every read that saves, as billing_accounts billable and
renewal_failing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 588dab2b5241af56b56cbbb6479cb79c994501f3 parent bd66229
8 files changed, +84 −24
  • internal/billing/billing.go +13 −7
  • internal/billing/billingtest/fake.go +4 −1
  • internal/billingstripe/adapter.go +7 −0
  • internal/billingstripe/adapter_test.go +23 −3
  • internal/console/billingstore.go +17 −7
  • internal/console/billingstore_test.go +5 −2
  • internal/console/billingsync.go +1 −0
  • internal/console/billingsync_test.go +14 −4
diff --git a/internal/billing/billing.go b/internal/billing/billing.go
index 6584dda76..1512c5db0 100644
--- a/internal/billing/billing.go
+++ b/internal/billing/billing.go
@@ -50,13 +50,19 @@ type Subscription struct {
// trialing, past due, incomplete, unpaid). An unpaid subscription has
// lost paid limits (State ended) but is still live, so a billing problem
// on it cannot be closed until it is cancelled at the provider.
- Live bool
- Currency string
- LiveMode bool
- PeriodEnd time.Time
- CancelAtPeriodEnd bool
- Items []Item
- ItemsComplete bool // false when the provider said there are more items than it sent
+ Live bool
+ // Billable is the provider counting the subscription as running and
+ // charging (the billing dashboard's paying, with a payment received):
+ // not a trial, not waiting for its first payment, not ended.
+ // RenewalFailing is a renewal charge failing while the provider
+ // retries; the subscription stays Billable meanwhile.
+ Billable, RenewalFailing bool
+ Currency string
+ LiveMode bool
+ PeriodEnd time.Time
+ CancelAtPeriodEnd bool
+ Items []Item
+ ItemsComplete bool // false when the provider said there are more items than it sent
// PendingUpdate is a charged change waiting for its payment (provider
// fact 8): its items are not applied, and it is dropped at
// PendingExpires unless paid first.
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go
index 011a8fbc3..88cd03c0e 100644
--- a/internal/billing/billingtest/fake.go
+++ b/internal/billing/billingtest/fake.go
@@ -115,6 +115,8 @@ type Fake struct {
// Subs is the provider's subscriptions by id. Reads return copies.
// Items seeded without an ItemID get a stable one when first served.
+ // Tests set every fact, Billable and RenewalFailing included; the Fake
+ // keeps them on its own transitions (a checkout runs, a cancel ends).
Subs map[string]*billing.Subscription
// Checkouts maps a checkout id to the subscription it made (6a's
// CheckoutSubscription); Sessions is consulted when absent.
@@ -1356,6 +1358,7 @@ func (f *Fake) Renew(subscription string) error {
}
if s.CancelAtPeriodEnd {
s.Live, s.State, s.ProviderStatus = false, billing.StateEnded, "canceled"
+ s.Billable, s.RenewalFailing = false, false
} else {
old := s.PeriodEnd
s.PeriodEnd = old.AddDate(1, 0, 0)
@@ -1422,7 +1425,7 @@ func (f *Fake) CompleteCheckout(sessionID string) (string, error) {
}
sub := &billing.Subscription{
ID: f.nextID("sub"), Customer: s.Customer, Account: s.Request.AccountSqid, ProviderStatus: "active",
- State: billing.StatePaid, Live: true, Currency: s.Request.Currency, PeriodEnd: f.ProviderClock.AddDate(1, 0, 0),
+ State: billing.StatePaid, Live: true, Billable: true, Currency: s.Request.Currency, PeriodEnd: f.ProviderClock.AddDate(1, 0, 0),
ItemsComplete: true,
}
for _, it := range s.Request.Items {
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go
index 4cae5acda..e807a8fa9 100644
--- a/internal/billingstripe/adapter.go
+++ b/internal/billingstripe/adapter.go
@@ -146,6 +146,11 @@ func liveOf(status string) bool {
}
}
+// billableOf is whether Stripe counts a subscription in this status as
+// running and charging: active, or past due while it retries a renewal.
+// A trial, an incomplete first payment and every ended status are not.
+func billableOf(status string) bool { return status == "active" || status == "past_due" }
+
// collectingOf is whether Stripe is still trying to collect money on a
// subscription: it is past due, unpaid or incomplete (an open invoice it
// retries or awaits), its latest invoice is open, or a charged change is
@@ -261,6 +266,8 @@ func subscriptionOf(s *Subscription, date time.Time) *billing.Subscription {
ProviderStatus: s.Status,
State: stateOf(s.Status),
Live: liveOf(s.Status),
+ Billable: billableOf(s.Status),
+ RenewalFailing: s.Status == "past_due",
Currency: s.Currency,
LiveMode: s.LiveMode,
PeriodEnd: s.CurrentPeriodEnd,
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go
index 1b4e33141..dbbfe7911 100644
--- a/internal/billingstripe/adapter_test.go
+++ b/internal/billingstripe/adapter_test.go
@@ -43,6 +43,24 @@ func TestLiveOf(t *testing.T) {
}
}
+// Billable is running and charging: a trial, an incomplete first payment
+// and every ended status are not. RenewalFailing is past due alone.
+func TestBillableAndRenewalFailing(t *testing.T) {
+ for status, want := range map[string][2]bool{
+ "active": {true, false}, "past_due": {true, true},
+ "trialing": {false, false}, "incomplete": {false, false}, "unpaid": {false, false},
+ "canceled": {false, false}, "incomplete_expired": {false, false}, "paused": {false, false}, "weird": {false, false},
+ } {
+ sub := subscriptionOf(&Subscription{ID: "sub_1", Status: status, Currency: "usd"}, time.Time{})
+ if got := [2]bool{sub.Billable, sub.RenewalFailing}; got != want {
+ t.Errorf("%q: Billable, RenewalFailing = %v, want %v", status, got, want)
+ }
+ if billableOf(status) != want[0] {
+ t.Errorf("billableOf(%q) = %v, want %v", status, !want[0], want[0])
+ }
+ }
+}
+
func testProvider(t *testing.T, base string, live bool, secrets ...string) *Provider {
t.Helper()
key := "rk_test_abc"
@@ -212,9 +230,11 @@ func TestSubscriptionMapsFields(t *testing.T) {
want := billing.Subscription{
ID: "sub_1", Customer: "cus_1", Account: "bab", ProviderStatus: "past_due", State: billing.StatePaid, Live: true,
Currency: "usd", LiveMode: false, PeriodEnd: end, CancelAtPeriodEnd: true, ItemsComplete: true,
- Items: []billing.Item{{ItemID: "si_1", PriceID: "price_p", Quantity: 1, Currency: "usd"}, {ItemID: "si_2", PriceID: "price_a", Quantity: 3, Currency: "usd"}},
- Collecting: true, // past due: still collecting
- FreshRead: true, // a read; the prices carry no unit_amount, so Annual is unknown
+ Items: []billing.Item{{ItemID: "si_1", PriceID: "price_p", Quantity: 1, Currency: "usd"}, {ItemID: "si_2", PriceID: "price_a", Quantity: 3, Currency: "usd"}},
+ Collecting: true, // past due: still collecting
+ Billable: true, // past due: still running and charging
+ RenewalFailing: true, // past due: the renewal is failing
+ FreshRead: true, // a read; the prices carry no unit_amount, so Annual is unknown
}
if sub.ProviderTime.IsZero() {
t.Error("ProviderTime not set from the response's Date")
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 6fc0dc8bd..d2b174475 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -148,6 +148,10 @@ func (s *Store) migrateBilling6b() error {
// unknown) and when a subscription read last succeeded.
`annual_amount INTEGER NOT NULL DEFAULT -1`,
`facts_read_at INTEGER NOT NULL DEFAULT 0`,
+ // The provider's neutral running facts (billing.Subscription):
+ // counted as running and charging, and a renewal failing.
+ `billable INTEGER NOT NULL DEFAULT 0`,
+ `renewal_failing 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
@@ -299,6 +303,9 @@ type billingAccount struct {
// read that opened a problem instead leave it.
Annual int64
FactsReadAt time.Time
+ // Billable and RenewalFailing are the last read's
+ // billing.Subscription facts of the same names.
+ Billable, RenewalFailing bool
}
// billingRenewing is a subscription the provider will charge again at its
@@ -310,19 +317,19 @@ const billingAccountColumns = `b.account_id, b.customer, b.subscription, b.provi
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,
- b.annual_amount, b.facts_read_at`
+ b.annual_amount, b.facts_read_at, b.billable, b.renewal_failing`
func scanBillingAccount(sc interface{ Scan(...any) error }) (*billingAccount, error) {
var b billingAccount
var state, packs string
var periodEnd, paidEnd, synced, pendingExpires, checked, drift, firstSent, factsRead int64
- var cancel, live, collecting, pending int
+ var cancel, live, collecting, pending, billable, failing 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,
&b.Plan, &b.Seats, &b.PaidSeats, &live, &collecting, &pending, &pendingExpires,
&checked, &drift, &b.SeatDriftMembers, &b.CustomerAttempt, &prepared, &firstSent,
- &b.Annual, &factsRead); err != nil {
+ &b.Annual, &factsRead, &billable, &failing); err != nil {
return nil, err
}
b.State = billing.State(state)
@@ -331,6 +338,7 @@ func scanBillingAccount(sc interface{ Scan(...any) error }) (*billingAccount, er
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, b.FactsReadAt = timeOrZero(firstSent), timeOrZero(factsRead)
+ b.Billable, b.RenewalFailing = billable != 0, failing != 0
if err := json.Unmarshal([]byte(packs), &b.PaidPacks); err != nil {
return nil, err
}
@@ -455,8 +463,8 @@ func putBillingState(e sqlExecer, b billingAccount) error {
(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,
- annual_amount, facts_read_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ annual_amount, facts_read_at, billable, renewal_failing)
+ 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,
@@ -466,12 +474,14 @@ func putBillingState(e sqlExecer, b billingAccount) error {
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,
- annual_amount = excluded.annual_amount, facts_read_at = excluded.facts_read_at`,
+ annual_amount = excluded.annual_amount, facts_read_at = excluded.facts_read_at,
+ billable = excluded.billable, renewal_failing = excluded.renewal_failing`,
b.AccountID, b.Subscription, b.ProviderStatus, string(b.State), b.Book, b.Currency, unixOrZero(b.PeriodEnd),
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), b.Annual, unixOrZero(b.FactsReadAt))
+ unixOrZero(b.CustomerFirstSentAt), b.Annual, unixOrZero(b.FactsReadAt),
+ boolInt(b.Billable), boolInt(b.RenewalFailing))
return err
}
diff --git a/internal/console/billingstore_test.go b/internal/console/billingstore_test.go
index 6931209e0..bbbb2f06e 100644
--- a/internal/console/billingstore_test.go
+++ b/internal/console/billingstore_test.go
@@ -109,12 +109,15 @@ func TestBillingAccountAnnualRoundTrip(t *testing.T) {
if err != nil || b == nil || b.Annual != -1 || !b.FactsReadAt.IsZero() {
t.Fatalf("fresh row = %+v, %v; want Annual -1 and no facts read", b, err)
}
- b.Annual, b.FactsReadAt = 2400, billingNow
+ if b.Billable || b.RenewalFailing {
+ t.Fatalf("fresh row = %+v; want not billable, no failing renewal", b)
+ }
+ b.Annual, b.FactsReadAt, b.Billable, b.RenewalFailing = 2400, billingNow, true, true
if err := st.PutBillingState(*b); err != nil {
t.Fatal(err)
}
got, err := st.BillingAccount(ids["bab"])
- if err != nil || got.Annual != 2400 || !got.FactsReadAt.Equal(billingNow) {
+ if err != nil || got.Annual != 2400 || !got.FactsReadAt.Equal(billingNow) || !got.Billable || !got.RenewalFailing {
t.Fatalf("after put = %+v, %v; want Annual 2400 read at %v", got, err, billingNow)
}
}
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go
index e8091976e..2214dc1ef 100644
--- a/internal/console/billingsync.go
+++ b/internal/console/billingsync.go
@@ -95,6 +95,7 @@ func decideBilling(in billingInput) billingDecision {
next.CancelAtPeriodEnd = sub.CancelAtPeriodEnd
// The provider facts of this read (plans 6b), whatever its state.
next.Live, next.Collecting = sub.Live, sub.Collecting
+ next.Billable, next.RenewalFailing = sub.Billable, sub.RenewalFailing
next.PendingUpdate, next.PendingExpires = sub.PendingUpdate, sub.PendingExpires
if sub.FreshRead {
next.Annual = -1
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
index 214164ca6..2034d6017 100644
--- a/internal/console/billingsync_test.go
+++ b/internal/console/billingsync_test.go
@@ -32,6 +32,10 @@ func billingLiveFor(status string) bool {
return false
}
+// billingBillableFor mirrors the Stripe adapter's billableOf for test
+// fixtures.
+func billingBillableFor(status string) bool { return status == "active" || status == "past_due" }
+
// billingStateFor mirrors the Stripe adapter's mapping for test fixtures.
func billingStateFor(status string) billing.State {
switch status {
@@ -253,7 +257,7 @@ func testPersonalSub(id, customer, sqid, status string, packs map[string]int64)
items = append(items, billing.Item{PriceID: testPriceID("example-v1/pack/" + name + "/usd"), Quantity: q, 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}
+ Live: billingLiveFor(status), Billable: billingBillableFor(status), RenewalFailing: status == "past_due", Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items}
}
// newBillingFixture is a console with billing on (enableBilling) and one
@@ -482,16 +486,22 @@ 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}
+ prev.Billable, prev.RenewalFailing = true, true
sub := paidSub("sub_1", "active", nil)
- sub.Live = true
+ sub.Live, sub.Billable = true, true
d := decideBilling(decideIn(prev, sub, nil))
+ if !d.Next.Billable || d.Next.RenewalFailing {
+ t.Fatalf("running facts not saved: %+v", d.Next)
+ }
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
+ sub.RenewalFailing = true
d = decideBilling(decideIn(prev, sub, nil))
- if !d.Next.Live || !d.Next.Collecting || !d.Next.PendingUpdate || !d.Next.PendingExpires.Equal(expires) {
+ if !d.Next.Live || !d.Next.Collecting || !d.Next.PendingUpdate || !d.Next.PendingExpires.Equal(expires) ||
+ !d.Next.Billable || !d.Next.RenewalFailing {
t.Fatalf("paid facts: %+v", d.Next)
}
// Pending and ended reads save their facts too.
@@ -509,7 +519,7 @@ func TestDecideSavesFacts(t *testing.T) {
}
ended := paidSub("sub_1", "canceled", nil)
d = decideBilling(decideIn(prev, ended, nil))
- if d.Next.Live || d.Next.Collecting || d.Next.PendingUpdate {
+ if d.Next.Live || d.Next.Collecting || d.Next.PendingUpdate || d.Next.Billable || d.Next.RenewalFailing {
t.Fatalf("canceled facts: %+v", d.Next)
}
}