billing: store each subscription's yearly amount
billing.Subscription gains Annual, AnnualKnown and FreshRead. The Stripe read expands discounts, re-reads each coupon (applies_to expanded) and computes the next year's charge after discounts, before tax (annualOf); a failed coupon read leaves the amount unknown and is logged, never failing the read. Write answers mapped through subscriptionOf carry no FreshRead. billing_accounts gains annual_amount (-1 unknown) and facts_read_at. The sync stores the amount from fresh reads only and stamps facts_read_at when a fresh read is saved; failed reads, problem decisions and write answers leave both. The fake marks its reads FreshRead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+489
−28
internal/billing/billing.go+8 −0internal/billing/billingtest/fake.go+1 −0internal/billingstripe/adapter.go+31 −3internal/billingstripe/adapter_test.go+1 −0internal/billingstripe/annual.go+59 −0internal/billingstripe/annual_test.go+170 −0internal/billingstripe/catalog.go+10 −5internal/billingstripe/client.go+67 −7internal/billingstripe/prepared_test.go+3 −2internal/console/billingcheckout.go+1 −1internal/console/billingcustomer.go+1 −1internal/console/billingstore.go+24 −8internal/console/billingstore_test.go+19 −0internal/console/billingsync.go+12 −1internal/console/billingsync_test.go+82 −0
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index a154e6a60..7e0196d04 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -68,6 +68,14 @@ type Subscription struct { |
| // ProviderTime is the read's Date header; zero when the response had |
| // none. |
| ProviderTime time.Time |
| + // Annual is what the next year will charge: after discounts, before |
| + // tax, in minor units of Currency. AnnualKnown is false when the |
| + // adapter could not tell, and Annual is then 0. |
| + Annual int64 |
| + AnnualKnown bool |
| + // FreshRead is true only on a Provider.Subscription read. A write's |
| + // answer leaves it false, and the sync then keeps the stored Annual. |
| + FreshRead bool |
| } |
| // Renewing is a live subscription that will renew at its period end. |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index ab4766e20..fc8654b47 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -583,6 +583,7 @@ func (f *Fake) Subscription(ctx context.Context, id string) (*billing.Subscripti |
| } |
| c := snapshot(s) |
| c.ProviderTime = d |
| + c.FreshRead = true // a read, as the real adapter marks it; write answers stay false |
| return c, nil |
| } |
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go| index 437249fac..30ad8dc0d 100644 |
| --- a/internal/billingstripe/adapter.go |
| +++ b/internal/billingstripe/adapter.go |
| @@ -5,6 +5,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "log" |
| "net/http" |
| "strings" |
| "time" |
| @@ -206,7 +207,11 @@ func notFound(err error) bool { |
| return errors.As(err, &e) && e.Code == CodeAPIError && e.HTTPStatus == http.StatusNotFound |
| } |
| -// Subscription reads one subscription. |
| +// Subscription reads one subscription. Each discount's coupon is read |
| +// again on its own, as only that read carries the products the coupon is |
| +// limited to. A coupon read that fails leaves the yearly amount unknown and |
| +// is logged; the subscription read still succeeds, so entitlement never |
| +// waits on a coupon. |
| func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscription, error) { |
| s, date, err := p.client.getSubscription(ctx, id) |
| if notFound(err) { |
| @@ -215,11 +220,33 @@ func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscr |
| if err != nil { |
| return nil, err |
| } |
| - return subscriptionOf(s, date), nil |
| + couponsRead := true |
| + read := map[string]*Coupon{} |
| + for i := range s.Discounts { |
| + cid := s.Discounts[i].Coupon.ID |
| + cp, ok := read[cid] |
| + if !ok { |
| + cp, err = p.client.GetCoupon(ctx, cid) |
| + if err != nil { |
| + log.Printf("billingstripe: subscription %s: reading coupon %q: %v; its yearly amount is unknown", s.ID, cid, err) |
| + couponsRead = false |
| + break |
| + } |
| + read[cid] = cp |
| + } |
| + s.Discounts[i].Coupon = *cp |
| + } |
| + out := subscriptionOf(s, date) |
| + if !couponsRead { |
| + out.Annual, out.AnnualKnown = 0, false |
| + } |
| + out.FreshRead = true |
| + return out, nil |
| } |
| // subscriptionOf maps a Stripe subscription, read at provider time date, |
| -// onto the neutral one. |
| +// onto the neutral one. It is a mapping only: a write's answer goes through |
| +// it too, so it never sets FreshRead. |
| func subscriptionOf(s *Subscription, date time.Time) *billing.Subscription { |
| out := &billing.Subscription{ |
| ID: s.ID, |
| @@ -241,6 +268,7 @@ func subscriptionOf(s *Subscription, date time.Time) *billing.Subscription { |
| for _, it := range s.Items { |
| out.Items = append(out.Items, billing.Item{ItemID: it.ID, PriceID: it.PriceID, Quantity: it.Quantity, Currency: it.PriceCurrency}) |
| } |
| + out.Annual, out.AnnualKnown = annualOf(s) |
| return out |
| } |
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go| index 44f2cec66..544785b67 100644 |
| --- a/internal/billingstripe/adapter_test.go |
| +++ b/internal/billingstripe/adapter_test.go |
| @@ -205,6 +205,7 @@ func TestSubscriptionMapsFields(t *testing.T) { |
| 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 |
| } |
| if sub.ProviderTime.IsZero() { |
| t.Error("ProviderTime not set from the response's Date") |
diff --git a/internal/billingstripe/annual.go b/internal/billingstripe/annual.go| new file mode 100644 |
| index 000000000..d054f6a6e |
| --- /dev/null |
| +++ b/internal/billingstripe/annual.go |
| @@ -0,0 +1,59 @@ |
| +package billingstripe |
| + |
| +import "math" |
| + |
| +// annualOf is what the subscription will charge for its next year: every |
| +// item's unit amount times its quantity, less each subscription discount |
| +// that still applies at the next renewal, before tax, in minor units of the |
| +// subscription's currency, never below 0. Prices here are yearly, so one |
| +// renewal is one year. |
| +// |
| +// known is false, and amount 0, whenever the read does not show the whole |
| +// answer: more items than were sent, an item with no unit amount or with |
| +// discounts of its own, a coupon limited to some products, a fixed amount |
| +// off in another currency, or a coupon whose amount is not known. |
| +func annualOf(s *Subscription) (amount int64, known bool) { |
| + if s.ItemsHasMore { |
| + return 0, false |
| + } |
| + var gross int64 |
| + for _, it := range s.Items { |
| + if it.UnitAmount == nil || it.HasDiscounts { |
| + return 0, false |
| + } |
| + gross += *it.UnitAmount * it.Quantity |
| + } |
| + total := gross |
| + for _, d := range s.Discounts { |
| + c := d.Coupon |
| + switch c.Duration { |
| + case "forever": |
| + case "repeating": |
| + if d.End.IsZero() { |
| + return 0, false // a repeating discount always has an end |
| + } |
| + if !d.End.After(s.CurrentPeriodEnd) { |
| + continue // over before the next renewal |
| + } |
| + case "once": |
| + continue // spent on the first invoice |
| + default: |
| + return 0, false |
| + } |
| + if len(c.AppliesToProducts) > 0 { |
| + return 0, false |
| + } |
| + switch { |
| + case c.PercentOff != nil: |
| + total -= int64(math.Round(float64(gross) * *c.PercentOff / 100)) |
| + case c.AmountOff != nil: |
| + if c.Currency != s.Currency { |
| + return 0, false |
| + } |
| + total -= *c.AmountOff |
| + default: |
| + return 0, false |
| + } |
| + } |
| + return max(total, 0), true |
| +} |
diff --git a/internal/billingstripe/annual_test.go b/internal/billingstripe/annual_test.go| new file mode 100644 |
| index 000000000..d0382c212 |
| --- /dev/null |
| +++ b/internal/billingstripe/annual_test.go |
| @@ -0,0 +1,170 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "reflect" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestAnnualOf(t *testing.T) { |
| + periodEnd := time.Date(2027, 10, 25, 0, 0, 0, 0, time.UTC) |
| + i64 := func(v int64) *int64 { return &v } |
| + f64 := func(v float64) *float64 { return &v } |
| + personal := SubscriptionItem{ID: "si_1", PriceID: "price_p", Quantity: 1, PriceCurrency: "usd", UnitAmount: i64(2800)} |
| + pack := SubscriptionItem{ID: "si_2", PriceID: "price_a", Quantity: 2, PriceCurrency: "usd", UnitAmount: i64(1200)} |
| + sub := func(items []SubscriptionItem, discounts ...Discount) *Subscription { |
| + return &Subscription{ID: "sub_1", Currency: "usd", CurrentPeriodEnd: periodEnd, Items: items, Discounts: discounts} |
| + } |
| + pct := func(p float64, duration string, end time.Time) Discount { |
| + return Discount{Coupon: Coupon{ID: "c", PercentOff: f64(p), Duration: duration}, End: end} |
| + } |
| + off := func(amount int64, currency string) Discount { |
| + return Discount{Coupon: Coupon{ID: "c", AmountOff: i64(amount), Currency: currency, Duration: "forever"}} |
| + } |
| + cases := []struct { |
| + name string |
| + sub *Subscription |
| + want int64 |
| + known bool |
| + }{ |
| + {"one item", sub([]SubscriptionItem{personal}), 2800, true}, |
| + {"with a pack", sub([]SubscriptionItem{personal, pack}), 5200, true}, |
| + {"100% forever", sub([]SubscriptionItem{personal}, pct(100, "forever", time.Time{})), 0, true}, |
| + {"50% forever", sub([]SubscriptionItem{personal}, pct(50, "forever", time.Time{})), 1400, true}, |
| + {"amount off", sub([]SubscriptionItem{personal}, off(500, "usd")), 2300, true}, |
| + {"amount off over the total", sub([]SubscriptionItem{personal}, off(5000, "usd")), 0, true}, |
| + {"once", sub([]SubscriptionItem{personal}, pct(50, "once", time.Time{})), 2800, true}, |
| + {"repeating past the renewal", sub([]SubscriptionItem{personal}, pct(50, "repeating", periodEnd.AddDate(0, 1, 0))), 1400, true}, |
| + {"repeating ends before the renewal", sub([]SubscriptionItem{personal}, pct(50, "repeating", periodEnd.AddDate(0, -1, 0))), 2800, true}, |
| + {"amount off in another currency", sub([]SubscriptionItem{personal}, off(500, "eur")), 0, false}, |
| + {"product-limited coupon", sub([]SubscriptionItem{personal}, |
| + Discount{Coupon: Coupon{ID: "c", PercentOff: f64(50), Duration: "forever", AppliesToProducts: []string{"prod_x"}}}), 0, false}, |
| + {"no unit amount", sub([]SubscriptionItem{{ID: "si_1", PriceID: "price_p", Quantity: 1}}), 0, false}, |
| + {"item discount", sub([]SubscriptionItem{{ID: "si_1", PriceID: "price_p", Quantity: 1, UnitAmount: i64(2800), HasDiscounts: true}}), 0, false}, |
| + } |
| + for _, tc := range cases { |
| + got, known := annualOf(tc.sub) |
| + if got != tc.want || known != tc.known { |
| + t.Errorf("%s: annualOf = %d, %v; want %d, %v", tc.name, got, known, tc.want, tc.known) |
| + } |
| + } |
| + more := sub([]SubscriptionItem{personal}) |
| + more.ItemsHasMore = true |
| + if got, known := annualOf(more); got != 0 || known { |
| + t.Errorf("items has more: annualOf = %d, %v; want 0, false", got, known) |
| + } |
| +} |
| + |
| +func TestSubscriptionDecodesDiscounts(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if got := r.URL.Query()["expand[]"]; !reflect.DeepEqual(got, []string{"latest_invoice", "discounts"}) { |
| + t.Errorf("expand = %q", got) |
| + } |
| + fmt.Fprint(w, `{"id":"sub_1","customer":"cus_1","status":"active","livemode":false,"currency":"usd", |
| + "current_period_end":1824422400, |
| + "discounts":[{"id":"di_1","coupon":{"id":"half","valid":true,"livemode":false,"percent_off":50,"duration":"repeating"},"end":1830000000}, |
| + {"id":"di_2","coupon":{"id":"five","valid":true,"livemode":false,"amount_off":500,"currency":"usd","duration":"forever"},"end":null}], |
| + "items":{"has_more":false,"data":[{"id":"si_1","quantity":1,"price":{"id":"price_p","currency":"usd","unit_amount":2800}}, |
| + {"id":"si_2","quantity":2,"discounts":["di_3"],"price":{"id":"price_a","currency":"usd","unit_amount":null}}]}}`) |
| + })) |
| + defer srv.Close() |
| + c, err := NewClient("rk_test_abc", WithBaseURL(srv.URL)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err := c.GetSubscription(context.Background(), "sub_1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(s.Discounts) != 2 { |
| + t.Fatalf("discounts = %+v", s.Discounts) |
| + } |
| + d0, d1 := s.Discounts[0], s.Discounts[1] |
| + if d0.Coupon.ID != "half" || d0.Coupon.PercentOff == nil || *d0.Coupon.PercentOff != 50 || d0.Coupon.Duration != "repeating" || |
| + !d0.End.Equal(time.Unix(1830000000, 0).UTC()) { |
| + t.Errorf("discount 0 = %+v", d0) |
| + } |
| + if d1.Coupon.ID != "five" || d1.Coupon.AmountOff == nil || *d1.Coupon.AmountOff != 500 || d1.Coupon.Currency != "usd" || !d1.End.IsZero() { |
| + t.Errorf("discount 1 = %+v", d1) |
| + } |
| + if len(s.Items) != 2 { |
| + t.Fatalf("items = %+v", s.Items) |
| + } |
| + if it := s.Items[0]; it.UnitAmount == nil || *it.UnitAmount != 2800 || it.HasDiscounts { |
| + t.Errorf("item 0 = %+v", it) |
| + } |
| + if it := s.Items[1]; it.UnitAmount != nil || !it.HasDiscounts { |
| + t.Errorf("item 1 = %+v", it) |
| + } |
| +} |
| + |
| +func TestSubscriptionAnnualReadsCoupons(t *testing.T) { |
| + const subBody = `{"id":"sub_1","customer":"cus_1","status":"active","livemode":false,"currency":"usd", |
| + "current_period_end":1824422400,"metadata":{"account_sqid":"bab"}, |
| + "discounts":[{"id":"di_1","coupon":{"id":"half","valid":true,"livemode":false,"percent_off":50,"duration":"forever"},"end":null}], |
| + "items":{"has_more":false,"data":[{"id":"si_1","quantity":1,"price":{"id":"price_p","currency":"usd","unit_amount":2800}}]}}` |
| + run := func(name string, coupon func(w http.ResponseWriter)) (*Provider, func()) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case r.URL.Path == "/v1/subscriptions/sub_1": |
| + fmt.Fprint(w, subBody) |
| + case r.URL.Path == "/v1/coupons/half": |
| + if got := r.URL.Query()["expand[]"]; !reflect.DeepEqual(got, []string{"applies_to"}) { |
| + t.Errorf("%s: coupon expand = %q", name, got) |
| + } |
| + coupon(w) |
| + default: |
| + t.Errorf("%s: unexpected %s %s", name, r.Method, r.URL.Path) |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + return prepProvider(t, srv.URL, nil), srv.Close |
| + } |
| + |
| + p, done := run("half", func(w http.ResponseWriter) { |
| + fmt.Fprint(w, `{"id":"half","valid":true,"livemode":false,"percent_off":50,"duration":"forever"}`) |
| + }) |
| + sub, err := p.Subscription(context.Background(), "sub_1") |
| + done() |
| + if err != nil || sub.Annual != 1400 || !sub.AnnualKnown || !sub.FreshRead { |
| + t.Errorf("half: %+v, %v", sub, err) |
| + } |
| + |
| + p, done = run("product-limited", func(w http.ResponseWriter) { |
| + fmt.Fprint(w, `{"id":"half","valid":true,"livemode":false,"percent_off":50,"duration":"forever","applies_to":{"products":["prod_x"]}}`) |
| + }) |
| + sub, err = p.Subscription(context.Background(), "sub_1") |
| + done() |
| + if err != nil || sub.AnnualKnown || sub.Annual != 0 || !sub.FreshRead { |
| + t.Errorf("product-limited: %+v, %v", sub, err) |
| + } |
| + |
| + p, done = run("coupon fails", func(w http.ResponseWriter) { |
| + w.WriteHeader(http.StatusInternalServerError) |
| + fmt.Fprint(w, `{"error":{"type":"api_error"}}`) |
| + }) |
| + sub, err = p.Subscription(context.Background(), "sub_1") |
| + done() |
| + if err != nil { |
| + t.Fatalf("coupon fails: the subscription read failed: %v", err) |
| + } |
| + if sub.AnnualKnown || sub.Annual != 0 || !sub.FreshRead { |
| + t.Errorf("coupon fails: %+v", sub) |
| + } |
| + if sub.ID != "sub_1" || sub.Customer != "cus_1" || sub.Account != "bab" || sub.Currency != "usd" || sub.ProviderStatus != "active" || |
| + len(sub.Items) != 1 || sub.Items[0].PriceID != "price_p" || !sub.PeriodEnd.Equal(time.Unix(1824422400, 0).UTC()) { |
| + t.Errorf("coupon fails: other fields not mapped: %+v", sub) |
| + } |
| +} |
| + |
| +// A write's answer is not a read: mapped through subscriptionOf it carries |
| +// no FreshRead. |
| +func TestSubscriptionOfIsNotAFreshRead(t *testing.T) { |
| + if sub := subscriptionOf(&Subscription{ID: "sub_1", Currency: "usd"}, providerDate); sub.FreshRead { |
| + t.Errorf("subscriptionOf set FreshRead: %+v", sub) |
| + } |
| +} |
diff --git a/internal/billingstripe/catalog.go b/internal/billingstripe/catalog.go| index 4531da63e..8c05329cf 100644 |
| --- a/internal/billingstripe/catalog.go |
| +++ b/internal/billingstripe/catalog.go |
| @@ -228,11 +228,14 @@ func (c *Client) ActiveTaxRegistrations(ctx context.Context) ([]TaxRegistration, |
| // the house account at renewal (a "once" duration, or a percent below 100) |
| // slip through unnoticed. |
| type Coupon struct { |
| - ID string |
| - Valid bool |
| - LiveMode bool |
| - PercentOff *float64 |
| - AmountOff *int64 |
| + ID string |
| + Valid bool |
| + LiveMode bool |
| + PercentOff *float64 |
| + AmountOff *int64 |
| + // Currency is AmountOff's currency, lower case ("" for a percent-off |
| + // coupon). |
| + Currency string |
| Duration string |
| AppliesToProducts []string |
| // MaxRedemptions and RedeemBy are limits after which the coupon stops |
| @@ -248,6 +251,7 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| LiveMode *bool `json:"livemode"` |
| PercentOff *float64 `json:"percent_off"` |
| AmountOff *int64 `json:"amount_off"` |
| + Currency string `json:"currency"` |
| Duration string `json:"duration"` |
| MaxRedeem *int64 `json:"max_redemptions"` |
| RedeemBy *int64 `json:"redeem_by"` |
| @@ -270,6 +274,7 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| cp.LiveMode = *raw.LiveMode |
| cp.PercentOff = raw.PercentOff |
| cp.AmountOff = raw.AmountOff |
| + cp.Currency = raw.Currency |
| cp.Duration = raw.Duration |
| cp.MaxRedemptions = raw.MaxRedeem |
| cp.RedeemBy = raw.RedeemBy |
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go| index 78ed6299d..07f2bf222 100644 |
| --- a/internal/billingstripe/client.go |
| +++ b/internal/billingstripe/client.go |
| @@ -463,15 +463,22 @@ type SubscriptionItem struct { |
| // PriceCurrency is the currency of the item's price, lower case, as |
| // Stripe reports it ("" when the response carried none). |
| PriceCurrency string |
| + // UnitAmount is the price's unit_amount, nil when the response carried |
| + // none (a tiered or decimal price). |
| + UnitAmount *int64 |
| + // HasDiscounts is the item carrying discounts of its own. |
| + HasDiscounts bool |
| } |
| func (it *SubscriptionItem) UnmarshalJSON(b []byte) error { |
| var raw struct { |
| - ID string `json:"id"` |
| - Quantity int64 `json:"quantity"` |
| - Price struct { |
| - ID string `json:"id"` |
| - Currency string `json:"currency"` |
| + ID string `json:"id"` |
| + Quantity int64 `json:"quantity"` |
| + Discounts []json.RawMessage `json:"discounts"` |
| + Price struct { |
| + ID string `json:"id"` |
| + Currency string `json:"currency"` |
| + UnitAmount *int64 `json:"unit_amount"` |
| } `json:"price"` |
| } |
| if err := json.Unmarshal(b, &raw); err != nil { |
| @@ -481,6 +488,52 @@ func (it *SubscriptionItem) UnmarshalJSON(b []byte) error { |
| it.Quantity = raw.Quantity |
| it.PriceID = raw.Price.ID |
| it.PriceCurrency = raw.Price.Currency |
| + it.UnitAmount = raw.Price.UnitAmount |
| + it.HasDiscounts = len(raw.Discounts) > 0 |
| + return nil |
| +} |
| + |
| +// Discount is one discount on a subscription: its coupon and when it stops |
| +// applying (zero End: it has no end). |
| +type Discount struct { |
| + Coupon Coupon |
| + End time.Time |
| +} |
| + |
| +// UnmarshalJSON decodes an expanded discount or a bare discount id. A bare |
| +// id, or a coupon that does not decode, leaves a Coupon with no amount: |
| +// whatever reads it cannot tell what it takes off, and must say so rather |
| +// than fail the subscription it came with. |
| +func (d *Discount) UnmarshalJSON(b []byte) error { |
| + var v idOrExpanded |
| + if err := json.Unmarshal(b, &v); err != nil { |
| + return err |
| + } |
| + *d = Discount{} |
| + if v.Object == nil { |
| + return nil |
| + } |
| + var raw struct { |
| + Coupon json.RawMessage `json:"coupon"` |
| + End *int64 `json:"end"` |
| + } |
| + if err := json.Unmarshal(v.Object, &raw); err != nil { |
| + return err |
| + } |
| + if raw.End != nil && *raw.End > 0 { |
| + d.End = time.Unix(*raw.End, 0).UTC() |
| + } |
| + var cp Coupon |
| + if err := json.Unmarshal(raw.Coupon, &cp); err == nil { |
| + d.Coupon = cp |
| + return nil |
| + } |
| + var id struct { |
| + ID string `json:"id"` |
| + } |
| + if json.Unmarshal(raw.Coupon, &id) == nil { |
| + d.Coupon.ID = id.ID |
| + } |
| return nil |
| } |
| @@ -507,6 +560,10 @@ type Subscription struct { |
| // LatestInvoiceStatus is the latest invoice's status ("open", "paid", |
| // ...), "" unless the read expanded latest_invoice. |
| LatestInvoiceStatus string |
| + // Discounts are the subscription's own discounts, in the order Stripe |
| + // lists them. Each carries its coupon only when the read expanded |
| + // discounts. |
| + Discounts []Discount |
| } |
| // UnmarshalJSON decodes a Subscription strictly enough that a null response |
| @@ -534,6 +591,7 @@ func (s *Subscription) UnmarshalJSON(b []byte) error { |
| ExpiresAt int64 `json:"expires_at"` |
| } `json:"pending_update"` |
| LatestInvoice idOrExpanded `json:"latest_invoice"` |
| + Discounts []Discount `json:"discounts"` |
| } |
| if err := json.Unmarshal(b, &raw); err != nil { |
| return err |
| @@ -556,6 +614,7 @@ func (s *Subscription) UnmarshalJSON(b []byte) error { |
| s.Items = raw.Items.Data |
| s.LiveMode, s.ItemsHasMore = *raw.LiveMode, raw.Items.HasMore |
| s.Currency = raw.Currency |
| + s.Discounts = raw.Discounts |
| if raw.PendingUpdate != nil { |
| s.PendingUpdate = true |
| if raw.PendingUpdate.ExpiresAt > 0 { |
| @@ -782,7 +841,8 @@ func (c *Client) CreatePortal(ctx context.Context, customerID, returnURL, config |
| } |
| // GetSubscription reads one subscription, with its latest invoice |
| -// expanded so whether it is still being collected is in the same read. |
| +// expanded so whether it is still being collected is in the same read, and |
| +// its discounts expanded so their coupons are too. |
| func (c *Client) GetSubscription(ctx context.Context, id string) (*Subscription, error) { |
| sub, _, err := c.getSubscription(ctx, id) |
| return sub, err |
| @@ -794,7 +854,7 @@ func (c *Client) getSubscription(ctx context.Context, id string) (*Subscription, |
| return nil, time.Time{}, &Error{Code: CodeInvalidID} |
| } |
| var sub Subscription |
| - meta, err := c.call(ctx, http.MethodGet, "/v1/subscriptions/"+id, url.Values{"expand[]": {"latest_invoice"}}, "", &sub) |
| + meta, err := c.call(ctx, http.MethodGet, "/v1/subscriptions/"+id, url.Values{"expand[]": {"latest_invoice", "discounts"}}, "", &sub) |
| if err != nil { |
| return nil, meta.Date, err |
| } |
diff --git a/internal/billingstripe/prepared_test.go b/internal/billingstripe/prepared_test.go| index 3b4622f7c..343c0a89c 100644 |
| --- a/internal/billingstripe/prepared_test.go |
| +++ b/internal/billingstripe/prepared_test.go |
| @@ -936,9 +936,10 @@ func TestCollectingOf(t *testing.T) { |
| t.Errorf("collectingOf(%q, %q, %v) = %v, want %v", tc.status, tc.invoice, tc.pending, got, tc.want) |
| } |
| } |
| - // End to end: the read expands latest_invoice and maps pending_update. |
| + // End to end: the read expands latest_invoice and discounts, and maps |
| + // pending_update. |
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - if r.URL.Query().Get("expand[]") != "latest_invoice" { |
| + if got := r.URL.Query()["expand[]"]; len(got) != 2 || got[0] != "latest_invoice" || got[1] != "discounts" { |
| t.Errorf("read query %q", r.URL.RawQuery) |
| } |
| fmt.Fprint(w, `{"id":"sub_1","customer":"cus_1","status":"active","livemode":false,"currency":"usd", |
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index 0f4b3e77b..8882b0e8b 100644 |
| --- a/internal/console/billingcheckout.go |
| +++ b/internal/console/billingcheckout.go |
| @@ -451,7 +451,7 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| return "", err |
| } |
| if b == nil { |
| - b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}} |
| + b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}, Annual: -1} |
| } |
| if b.Customer != "" { |
| if currency != "" { |
diff --git a/internal/console/billingcustomer.go b/internal/console/billingcustomer.go| index 462c01497..12be69a3d 100644 |
| --- a/internal/console/billingcustomer.go |
| +++ b/internal/console/billingcustomer.go |
| @@ -25,7 +25,7 @@ func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct |
| return nil, err |
| } |
| if b == nil { |
| - b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}} |
| + b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}, Annual: -1} |
| } |
| currency := b.Currency |
| if fixCurrency && currency == "" { |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index 178f88c00..a2b2fafad 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -144,6 +144,10 @@ func (s *Store) migrateBilling6b() error { |
| `customer_attempt INTEGER NOT NULL DEFAULT 0`, |
| `customer_prepared BLOB`, |
| `customer_first_sent_at INTEGER NOT NULL DEFAULT 0`, |
| + // The billing dashboard: the subscription's yearly amount (-1 |
| + // unknown) and when a subscription read last succeeded. |
| + `annual_amount INTEGER NOT NULL DEFAULT -1`, |
| + `facts_read_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 |
| @@ -287,6 +291,14 @@ type billingAccount struct { |
| CustomerAttempt int |
| CustomerPrepared *billing.Prepared |
| CustomerFirstSentAt time.Time |
| + |
| + // The billing dashboard. Annual is what the subscription will charge |
| + // for its next year, after discounts and before tax, in minor units of |
| + // Currency; -1 when unknown. FactsReadAt is when a subscription read |
| + // last succeeded and was saved: a write's answer, a failed read and a |
| + // read that opened a problem instead leave it. |
| + Annual int64 |
| + FactsReadAt time.Time |
| } |
| // billingRenewing is a subscription the provider will charge again at its |
| @@ -297,18 +309,20 @@ func billingRenewing(b *billingAccount) bool { return b.Live && !b.CancelAtPerio |
| 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.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.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` |
| func scanBillingAccount(sc interface{ Scan(...any) error }) (*billingAccount, error) { |
| var b billingAccount |
| var state, packs string |
| - var periodEnd, paidEnd, synced, pendingExpires, checked, drift, firstSent int64 |
| + var periodEnd, paidEnd, synced, pendingExpires, checked, drift, firstSent, factsRead 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, |
| &b.Plan, &b.Seats, &b.PaidSeats, &live, &collecting, &pending, &pendingExpires, |
| - &checked, &drift, &b.SeatDriftMembers, &b.CustomerAttempt, &prepared, &firstSent); err != nil { |
| + &checked, &drift, &b.SeatDriftMembers, &b.CustomerAttempt, &prepared, &firstSent, |
| + &b.Annual, &factsRead); err != nil { |
| return nil, err |
| } |
| b.State = billing.State(state) |
| @@ -316,7 +330,7 @@ func scanBillingAccount(sc interface{ Scan(...any) error }) (*billingAccount, er |
| 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) |
| + b.CustomerFirstSentAt, b.FactsReadAt = timeOrZero(firstSent), timeOrZero(factsRead) |
| if err := json.Unmarshal([]byte(packs), &b.PaidPacks); err != nil { |
| return nil, err |
| } |
| @@ -440,8 +454,9 @@ func putBillingState(e sqlExecer, b billingAccount) error { |
| _, 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, |
| 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + seats_checked_at, seat_drift_at, seat_drift_members, customer_attempt, customer_prepared, customer_first_sent_at, |
| + annual_amount, facts_read_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, |
| @@ -450,12 +465,13 @@ func putBillingState(e sqlExecer, b billingAccount) error { |
| 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`, |
| + 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`, |
| 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)) |
| + unixOrZero(b.CustomerFirstSentAt), b.Annual, unixOrZero(b.FactsReadAt)) |
| return err |
| } |
diff --git a/internal/console/billingstore_test.go b/internal/console/billingstore_test.go| index ff83076a6..6931209e0 100644 |
| --- a/internal/console/billingstore_test.go |
| +++ b/internal/console/billingstore_test.go |
| @@ -100,6 +100,25 @@ func TestBillingStateRoundTrips(t *testing.T) { |
| } |
| } |
| +func TestBillingAccountAnnualRoundTrip(t *testing.T) { |
| + st, ids := planStore(t, "bab") |
| + if err := st.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := st.BillingAccount(ids["bab"]) |
| + 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 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) { |
| + t.Fatalf("after put = %+v, %v; want Annual 2400 read at %v", got, err, billingNow) |
| + } |
| +} |
| + |
| func TestLiveBillingAccountsPagesAndSkipsDeleted(t *testing.T) { |
| st, ids := planStore(t, "bab", "bdk", "bdm") |
| for i, sqid := range []string{"bab", "bdk", "bdm"} { |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index a48103c89..e8091976e 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -63,7 +63,9 @@ func liveState(s billing.State) bool { return s == billing.StatePaid || s == bil |
| // default plan, packs and team fields cleared. |
| // |
| // Every saved decision carries the read's provider facts (Live, |
| -// Collecting, PendingUpdate, PendingExpires). |
| +// Collecting, PendingUpdate, PendingExpires) and, from a fresh read only, |
| +// its yearly amount (-1 when the read could not tell); a write's answer |
| +// keeps the stored amount. |
| func decideBilling(in billingInput) billingDecision { |
| sub, prev := in.Sub, in.Prev |
| if sub.LiveMode != in.LiveMode { |
| @@ -94,6 +96,12 @@ func decideBilling(in billingInput) billingDecision { |
| // 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 sub.FreshRead { |
| + next.Annual = -1 |
| + if sub.AnnualKnown { |
| + next.Annual = sub.Annual |
| + } |
| + } |
| if other { |
| // A new subscription after the old one ended: nothing of the old |
| // period carries over, its seats included. |
| @@ -362,6 +370,9 @@ func (s *Server) applyBillingRead(ctx context.Context, acct *Account, prev *bill |
| var next *billingAccount |
| if d.Save { |
| d.Next.SyncedAt = now |
| + if sub.FreshRead { |
| + d.Next.FactsReadAt = now |
| + } |
| next = &d.Next |
| } |
| _, owned, err := s.applyBillingPlan(ctx, acct, next, d.Plan, now) |
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go| index 2c7b1017d..214164ca6 100644 |
| --- a/internal/console/billingsync_test.go |
| +++ b/internal/console/billingsync_test.go |
| @@ -514,6 +514,88 @@ func TestDecideSavesFacts(t *testing.T) { |
| } |
| } |
| +func TestDecideBillingStoresAnnual(t *testing.T) { |
| + prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid, PaidPacks: map[string]int{}, |
| + Annual: 5200} |
| + read := paidSub("sub_1", "active", nil) |
| + read.FreshRead, read.Annual, read.AnnualKnown = true, 2400, true |
| + if d := decideBilling(decideIn(prev, read, nil)); !d.Save || d.Next.Annual != 2400 { |
| + t.Errorf("known read: Annual = %d, want 2400", d.Next.Annual) |
| + } |
| + unknown := paidSub("sub_1", "active", nil) |
| + unknown.FreshRead = true |
| + if d := decideBilling(decideIn(prev, unknown, nil)); !d.Save || d.Next.Annual != -1 { |
| + t.Errorf("unknown read: Annual = %d, want -1", d.Next.Annual) |
| + } |
| + answer := paidSub("sub_1", "active", nil) |
| + answer.Annual, answer.AnnualKnown = 2400, true // a write's answer: FreshRead false |
| + if d := decideBilling(decideIn(prev, answer, nil)); !d.Save || d.Next.Annual != 5200 { |
| + t.Errorf("write answer: Annual = %d, want the stored 5200", d.Next.Annual) |
| + } |
| +} |
| + |
| +func TestFactsReadAt(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + ctx := context.Background() |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.srv.syncSubscription(ctx, "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + factsReadAt := func() time.Time { |
| + t.Helper() |
| + b, err := bf.st.BillingAccount(bf.acct.ID) |
| + if err != nil || b == nil { |
| + t.Fatalf("billing row = %+v, %v", b, err) |
| + } |
| + return b.FactsReadAt |
| + } |
| + if got := factsReadAt(); !got.Equal(billingNow) { |
| + t.Fatalf("after a sync: FactsReadAt = %v, want %v", got, billingNow) |
| + } |
| + |
| + // A failed read leaves it. |
| + bf.fake.Lock() |
| + bf.fake.SubErr = map[string]error{"sub_1": errors.New("network down")} |
| + bf.fake.Unlock() |
| + if err := bf.srv.syncSubscription(ctx, "sub_1", billingNow.Add(time.Hour)); err == nil { |
| + t.Fatal("failed read: no error") |
| + } |
| + if got := factsReadAt(); !got.Equal(billingNow) { |
| + t.Errorf("after a failed read: FactsReadAt = %v, want %v", got, billingNow) |
| + } |
| + bf.fake.Lock() |
| + bf.fake.SubErr = nil |
| + bf.fake.Unlock() |
| + |
| + // A read whose decision opens a problem instead of saving leaves it. |
| + other := bf.personalSub("sub_1", "active", nil) |
| + other.Account = "zzzzzz" |
| + bf.put(other) |
| + if err := bf.srv.syncSubscription(ctx, "sub_1", billingNow.Add(2*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if open, _ := bf.st.BillingProblems(false); len(open) != 1 || open[0].Reason != problemAccountMismatch { |
| + t.Fatalf("problems = %+v", open) |
| + } |
| + if got := factsReadAt(); !got.Equal(billingNow) { |
| + t.Errorf("after an account mismatch: FactsReadAt = %v, want %v", got, billingNow) |
| + } |
| + |
| + // A write's answer applied through applyBillingRead leaves it. |
| + prev, err := bf.st.BillingAccount(bf.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + answer := bf.personalSub("sub_1", "active", nil) // FreshRead false |
| + if err := bf.srv.applyBillingRead(ctx, bf.acct, prev, answer, billingNow.Add(3*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + if !b.SyncedAt.Equal(billingNow.Add(3*time.Hour)) || !b.FactsReadAt.Equal(billingNow) { |
| + t.Errorf("after a write answer: SyncedAt %v FactsReadAt %v; want the answer saved and FactsReadAt %v", b.SyncedAt, b.FactsReadAt, billingNow) |
| + } |
| +} |
| + |
| func TestBillingRenewingUsesFacts(t *testing.T) { |
| cases := []struct { |
| b billingAccount |