carlos / platform Public

console: billing sync decides the plan from a fresh subscription read; pack reductions hold until renewal (plans 6a)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 8c397394e9e45cf7bc74d51ca0602a8843953bfa parent 75e53c4
2 files changed, +606 −0
  • internal/console/billingsync.go +236 −0
  • internal/console/billingsync_test.go +370 −0
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go
new file mode 100644
index 000000000..c6ed14bf8
--- /dev/null
+++ b/internal/console/billingsync.go
@@ -0,0 +1,236 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "maps"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// Plan sync (plans 6a). Every webhook and the hourly pass end here: the
+// subscription is read fresh from the provider, under the account's lock,
+// and a pure decision turns that read and the stored billing row into what
+// to save, what plan to write and what problem to open. An event body is
+// never trusted: it only names the subscription to read.
+
+// billingInput is everything decideBilling looks at.
+type billingInput struct {
+ Prev *billingAccount // the row for the subscription's customer; never nil here
+ Sub *billing.Subscription
+ Purchase billing.Purchase
+ Unrecognised error // from Recognise; nil when Purchase is good
+ AccountSqid string
+ LiveMode bool
+ DefaultPlan string
+}
+
+type planChange struct {
+ Plan string
+ Packs map[string]int
+ Reason string
+}
+
+type problemNote struct{ Reason, Detail string }
+
+// billingDecision is what one fresh read changes.
+type billingDecision struct {
+ Save bool
+ Next billingAccount
+ Plan *planChange
+ Problem *problemNote
+}
+
+func liveState(s billing.State) bool { return s == billing.StatePaid || s == billing.StatePending }
+
+// decideBilling is the sync's whole policy, first match wins:
+//
+// - the subscription is in the other mode, or names another account: a
+// problem, nothing saved (an identity contradiction never moves a plan);
+// - another subscription of this account is still live and this one is
+// too: a second subscription, a problem, nothing saved;
+// - another subscription is recorded and this one has ended: an old
+// subscription ending, nothing to do;
+// - 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;
+// - ended, and it is the current subscription (or none is recorded): the
+// default plan, packs cleared.
+func decideBilling(in billingInput) billingDecision {
+ sub, prev := in.Sub, in.Prev
+ if sub.LiveMode != in.LiveMode {
+ return billingDecision{Problem: &problemNote{problemModeMismatch, fmt.Sprintf("subscription live mode is %v", sub.LiveMode)}}
+ }
+ if sub.Account != in.AccountSqid {
+ return billingDecision{Problem: &problemNote{problemAccountMismatch, fmt.Sprintf("subscription metadata names account %q", sub.Account)}}
+ }
+ other := prev.Subscription != "" && prev.Subscription != sub.ID
+ if other && liveState(prev.State) && liveState(sub.State) {
+ return billingDecision{Problem: &problemNote{problemSecondSubscription, fmt.Sprintf("subscription %s is still %s", prev.Subscription, prev.ProviderStatus)}}
+ }
+ if other && sub.State == billing.StateEnded {
+ return billingDecision{}
+ }
+
+ next := *prev
+ next.PaidPacks = maps.Clone(prev.PaidPacks)
+ if next.PaidPacks == nil {
+ next.PaidPacks = map[string]int{}
+ }
+ next.Subscription = sub.ID
+ next.ProviderStatus = sub.ProviderStatus
+ next.State = sub.State
+ next.Currency = sub.Currency
+ next.PeriodEnd = sub.PeriodEnd
+ next.CancelAtPeriodEnd = sub.CancelAtPeriodEnd
+ if other {
+ // A new subscription after the old one ended: nothing of the old
+ // period carries over.
+ next.PaidPacks, next.PaidPeriodEnd, next.Book = map[string]int{}, time.Time{}, ""
+ }
+ d := billingDecision{Save: true, Next: next}
+
+ switch sub.State {
+ case billing.StatePending:
+ return d
+ case billing.StatePaid:
+ if in.Unrecognised != nil {
+ d.Problem = &problemNote{problemUnrecognised, in.Unrecognised.Error()}
+ return d
+ }
+ d.Next.Book = in.Purchase.Book
+ 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)
+ if d.Next.PaidPacks == nil {
+ d.Next.PaidPacks = map[string]int{}
+ }
+ d.Next.PaidPeriodEnd = sub.PeriodEnd
+ } else {
+ // The same period: keep the highest quantity paid for. A pack
+ // whose item was removed keeps its stored quantity.
+ for name, q := range in.Purchase.Packs {
+ d.Next.PaidPacks[name] = max(d.Next.PaidPacks[name], q)
+ }
+ }
+ d.Plan = &planChange{Plan: in.Purchase.Plan, Packs: maps.Clone(d.Next.PaidPacks),
+ 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.Plan = &planChange{Plan: in.DefaultPlan, Reason: fmt.Sprintf("subscription %s ended (%s)", sub.ID, sub.ProviderStatus)}
+ return d
+ }
+}
+
+// syncSubscription reads one subscription and applies the decision. It
+// returns nil when a problem was opened, when the provider has no such
+// subscription, and when the account is gone; a transient provider or
+// store error is returned so the caller can retry (the webhook answers
+// 503 and the provider redelivers).
+func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, now time.Time) error {
+ if s.billing == nil {
+ return nil
+ }
+ cfg := s.billing.cfg
+ first, err := cfg.Provider.Subscription(ctx, subscriptionID)
+ if errors.Is(err, billing.ErrNotFound) {
+ log.Printf("console: billing: subscription %s not found at the provider; nothing changed", subscriptionID)
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
+ }
+ bound, err := s.store.BillingAccountByCustomer(first.Customer)
+ if err != nil {
+ return err
+ }
+ if bound == nil {
+ var accountID int64
+ if first.Account != "" {
+ if a, err := s.store.AccountBySqid(first.Account); err != nil {
+ return err
+ } else if a != nil {
+ accountID = a.ID
+ }
+ }
+ return s.openBillingProblem(accountID, first.Account, subscriptionID, problemUnknownCustomer,
+ fmt.Sprintf("customer %s is not bound to any account", first.Customer), now)
+ }
+ acct, err := s.store.AccountByID(bound.AccountID)
+ if err != nil {
+ return err
+ }
+ if acct == nil {
+ log.Printf("console: billing: subscription %s belongs to deleted account %d; nothing changed", subscriptionID, bound.AccountID)
+ return nil
+ }
+
+ defer s.billing.locks.lock(acct.Sqid)()
+ // Re-read under the lock: the read that decides is the latest one.
+ sub, err := cfg.Provider.Subscription(ctx, subscriptionID)
+ if errors.Is(err, billing.ErrNotFound) {
+ log.Printf("console: billing: subscription %s not found at the provider; nothing changed", subscriptionID)
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
+ }
+ prev, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return err
+ }
+ if prev == nil || prev.Customer != sub.Customer {
+ // The customer changed between the two reads: settle it next time.
+ return fmt.Errorf("billing: subscription %s changed customer during the sync", subscriptionID)
+ }
+ purchase, unrecognised := billing.Recognise(sub, cfg.Prices, s.cfg.PlanCatalog)
+ d := decideBilling(billingInput{
+ Prev: prev, Sub: sub, Purchase: purchase, Unrecognised: unrecognised,
+ AccountSqid: acct.Sqid, LiveMode: cfg.LiveMode, DefaultPlan: s.cfg.PlanCatalog.DefaultPlan,
+ })
+ if d.Save {
+ d.Next.SyncedAt = now
+ if err := s.store.PutBillingState(d.Next); err != nil {
+ return err
+ }
+ }
+ if d.Plan != nil {
+ written, owned, err := s.store.SetBillingPlan(acct.ID, d.Plan.Plan, d.Plan.Packs, d.Plan.Reason, now)
+ if errors.Is(err, ErrAccountGone) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if written {
+ s.publishPlanNow(ctx, acct.ID, now)
+ }
+ if !owned && sub.State == billing.StatePaid {
+ if err := s.openBillingProblem(acct.ID, acct.Sqid, sub.ID, problemNotBillingOwned,
+ "the account's plan was set by an operator; billing leaves it alone", now); err != nil {
+ return err
+ }
+ }
+ }
+ if d.Problem != nil {
+ return s.openBillingProblem(acct.ID, acct.Sqid, sub.ID, d.Problem.Reason, d.Problem.Detail, now)
+ }
+ return nil
+}
+
+// openBillingProblem opens a problem and logs it once, when it opens.
+func (s *Server) openBillingProblem(accountID int64, sqid, subscription, reason, detail string, now time.Time) error {
+ opened, err := s.store.OpenBillingProblem(accountID, subscription, reason, detail, now)
+ if err != nil {
+ return err
+ }
+ if opened {
+ log.Printf("console: billing problem opened: account %q subscription %s reason %s", sqid, subscription, reason)
+ }
+ return nil
+}
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
new file mode 100644
index 000000000..742ee4ecc
--- /dev/null
+++ b/internal/console/billingsync_test.go
@@ -0,0 +1,370 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "reflect"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/billing/billingtest"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+var periodEnd = time.Date(2027, 10, 25, 0, 0, 0, 0, time.UTC)
+
+func paidSub(id, status string, packs map[string]int64) *billing.Subscription {
+ return &billing.Subscription{ID: id, Customer: "cus_1", Account: "bab", ProviderStatus: status, State: billingStateFor(status),
+ Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true}
+}
+
+// billingStateFor mirrors the Stripe adapter's mapping for test fixtures.
+func billingStateFor(status string) billing.State {
+ switch status {
+ case "active", "trialing", "past_due":
+ return billing.StatePaid
+ case "incomplete":
+ return billing.StatePending
+ }
+ return billing.StateEnded
+}
+
+func decideIn(prev *billingAccount, sub *billing.Subscription, packs map[string]int) billingInput {
+ if prev == nil {
+ prev = &billingAccount{AccountID: 7, Customer: "cus_1", PaidPacks: map[string]int{}}
+ }
+ if packs == nil {
+ packs = map[string]int{}
+ }
+ return billingInput{
+ Prev: prev, Sub: sub, AccountSqid: "bab", LiveMode: false, DefaultPlan: "free",
+ Purchase: billing.Purchase{Book: "example-v1", Currency: "usd", Plan: "personal", Packs: packs},
+ }
+}
+
+func TestDecidePaidRecognised(t *testing.T) {
+ d := decideBilling(decideIn(nil, paidSub("sub_1", "active", nil), map[string]int{"apps": 2}))
+ if !d.Save || d.Problem != nil || d.Plan == nil {
+ t.Fatalf("decision = %+v", d)
+ }
+ if d.Plan.Plan != "personal" || !reflect.DeepEqual(d.Plan.Packs, map[string]int{"apps": 2}) || d.Plan.Reason != "subscription sub_1 active" {
+ t.Errorf("plan = %+v", d.Plan)
+ }
+ n := d.Next
+ if n.Subscription != "sub_1" || n.State != billing.StatePaid || n.ProviderStatus != "active" || !n.PaidPeriodEnd.Equal(periodEnd) ||
+ !n.PeriodEnd.Equal(periodEnd) || n.Book != "example-v1" || n.Currency != "usd" || n.Customer != "cus_1" || n.AccountID != 7 {
+ t.Errorf("next = %+v", n)
+ }
+}
+
+func TestDecidePastDueKeepsPaid(t *testing.T) {
+ a := decideBilling(decideIn(nil, paidSub("sub_1", "active", nil), map[string]int{"apps": 1}))
+ b := decideBilling(decideIn(nil, paidSub("sub_1", "past_due", nil), map[string]int{"apps": 1}))
+ if b.Plan == nil || a.Plan.Plan != b.Plan.Plan || !reflect.DeepEqual(a.Plan.Packs, b.Plan.Packs) || b.Next.State != billing.StatePaid {
+ t.Fatalf("past_due = %+v, active = %+v", b, a)
+ }
+}
+
+func TestDecidePendingChangesNothing(t *testing.T) {
+ d := decideBilling(decideIn(nil, paidSub("sub_1", "incomplete", nil), nil))
+ if !d.Save || d.Plan != nil || d.Problem != nil || d.Next.Subscription != "sub_1" || d.Next.State != billing.StatePending {
+ t.Fatalf("decision = %+v", d)
+ }
+}
+
+func TestDecideEndedDropsToDefault(t *testing.T) {
+ prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid,
+ PaidPacks: map[string]int{"apps": 3}, PaidPeriodEnd: periodEnd}
+ for _, status := range []string{"canceled", "unpaid"} {
+ d := decideBilling(decideIn(prev, paidSub("sub_1", status, nil), nil))
+ if !d.Save || d.Plan == nil || d.Plan.Plan != "free" || d.Plan.Packs != nil || d.Problem != nil {
+ t.Fatalf("%s: decision = %+v", status, d)
+ }
+ if d.Plan.Reason != "subscription sub_1 ended ("+status+")" || len(d.Next.PaidPacks) != 0 || d.Next.State != billing.StateEnded {
+ t.Errorf("%s: plan %+v next %+v", status, d.Plan, d.Next)
+ }
+ }
+ pending := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_1", State: billing.StatePending, PaidPacks: map[string]int{}}
+ d := decideBilling(decideIn(pending, paidSub("sub_1", "incomplete_expired", nil), nil))
+ if d.Plan == nil || d.Plan.Plan != "free" {
+ t.Fatalf("incomplete_expired after pending: %+v", d)
+ }
+ // No subscription recorded yet: an ended one is still the account's.
+ d = decideBilling(decideIn(nil, paidSub("sub_9", "canceled", nil), nil))
+ if d.Plan == nil || d.Plan.Plan != "free" || d.Next.Subscription != "sub_9" {
+ t.Fatalf("ended with none recorded: %+v", d)
+ }
+}
+
+func TestDecideOldSubscriptionEndedIsIgnored(t *testing.T) {
+ prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_new", State: billing.StatePaid, PaidPacks: map[string]int{}}
+ d := decideBilling(decideIn(prev, paidSub("sub_old", "canceled", nil), nil))
+ if d.Save || d.Plan != nil || d.Problem != nil {
+ t.Fatalf("decision = %+v", d)
+ }
+}
+
+func TestDecideSecondSubscription(t *testing.T) {
+ prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_a", State: billing.StatePaid, PaidPacks: map[string]int{}}
+ for _, status := range []string{"active", "incomplete"} {
+ d := decideBilling(decideIn(prev, paidSub("sub_b", status, nil), nil))
+ if d.Save || d.Plan != nil || d.Problem == nil || d.Problem.Reason != problemSecondSubscription {
+ t.Fatalf("%s: decision = %+v", status, d)
+ }
+ }
+}
+
+func TestDecideAdoptsAfterEnded(t *testing.T) {
+ prev := &billingAccount{AccountID: 7, Customer: "cus_1", Subscription: "sub_a", State: billing.StateEnded, PaidPacks: map[string]int{}}
+ d := decideBilling(decideIn(prev, paidSub("sub_b", "active", nil), nil))
+ if !d.Save || d.Next.Subscription != "sub_b" || d.Plan == nil || d.Plan.Plan != "personal" || d.Problem != nil {
+ t.Fatalf("decision = %+v", d)
+ }
+}
+
+func TestDecideIdentityProblems(t *testing.T) {
+ sub := paidSub("sub_1", "active", nil)
+ sub.Account = "zzz"
+ d := decideBilling(decideIn(nil, sub, nil))
+ if d.Save || d.Plan != nil || d.Problem == nil || d.Problem.Reason != problemAccountMismatch {
+ t.Fatalf("account mismatch: %+v", d)
+ }
+ sub = paidSub("sub_1", "active", nil)
+ sub.LiveMode = true
+ d = decideBilling(decideIn(nil, sub, nil))
+ if d.Save || d.Plan != nil || d.Problem == nil || d.Problem.Reason != problemModeMismatch {
+ t.Fatalf("mode mismatch: %+v", d)
+ }
+}
+
+func TestDecideUnrecognisedOpensAProblem(t *testing.T) {
+ in := decideIn(nil, paidSub("sub_1", "active", nil), nil)
+ in.Unrecognised = errors.Join(billing.ErrUnrecognised, errors.New("price price_x is not in the price map"))
+ d := decideBilling(in)
+ if !d.Save || d.Plan != nil || d.Problem == nil || d.Problem.Reason != problemUnrecognised || d.Problem.Detail == "" {
+ t.Fatalf("decision = %+v", d)
+ }
+ if d.Next.Subscription != "sub_1" || d.Next.State != billing.StatePaid {
+ t.Errorf("next = %+v", d.Next)
+ }
+}
+
+func TestPackReductionHoldsUntilRenewal(t *testing.T) {
+ sub := paidSub("sub_1", "active", nil)
+ d := decideBilling(decideIn(nil, sub, map[string]int{"apps": 3}))
+ prev := d.Next
+ d = decideBilling(decideIn(&prev, sub, map[string]int{"apps": 1}))
+ if !reflect.DeepEqual(d.Plan.Packs, map[string]int{"apps": 3}) {
+ t.Fatalf("reduced in period: %+v", d.Plan.Packs)
+ }
+ prev = d.Next
+ d = decideBilling(decideIn(&prev, sub, map[string]int{"apps": 2}))
+ if !reflect.DeepEqual(d.Plan.Packs, map[string]int{"apps": 3}) {
+ t.Fatalf("raised back within: %+v", d.Plan.Packs)
+ }
+ // A pack item removed in the period keeps its quantity too.
+ prev = d.Next
+ prev.PaidPacks = map[string]int{"apps": 3, "email": 1}
+ d = decideBilling(decideIn(&prev, sub, map[string]int{"apps": 2}))
+ if !reflect.DeepEqual(d.Plan.Packs, map[string]int{"apps": 3, "email": 1}) {
+ t.Fatalf("removed item: %+v", d.Plan.Packs)
+ }
+ prev = d.Next
+ renewed := paidSub("sub_1", "active", nil)
+ renewed.PeriodEnd = periodEnd.AddDate(1, 0, 0)
+ d = decideBilling(decideIn(&prev, renewed, map[string]int{"apps": 1}))
+ if !reflect.DeepEqual(d.Plan.Packs, map[string]int{"apps": 1}) || !d.Next.PaidPeriodEnd.Equal(renewed.PeriodEnd) {
+ t.Fatalf("renewal: %+v next %+v", d.Plan.Packs, d.Next)
+ }
+}
+
+// ---- store-backed sync ----
+
+var billingKeyChars = regexp.MustCompile(`[^A-Za-z0-9]`)
+
+func testPriceID(key string) string { return "price_" + billingKeyChars.ReplaceAllString(key, "") }
+
+type billingFixture struct {
+ *consoleFixture
+ fake *billingtest.Fake
+ acct *Account
+}
+
+// newBillingFixture is a console with the example catalog, the example
+// book, a full price map and a Fake provider, and one account bound to
+// customer cus_1.
+func newBillingFixture(t *testing.T) *billingFixture {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ cat := examplePlanCatalog(t)
+ book, err := plans.LoadPriceBook("../plans/testdata/example-pricebook.json", cat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw := map[string]string{}
+ for name := range book.Plans {
+ for _, c := range book.Currencies {
+ k := billing.PriceRef{Book: book.Version, Kind: billing.KindPlan, Name: name, Currency: c}.Key()
+ raw[k] = testPriceID(k)
+ }
+ }
+ for name := range book.Packs {
+ for _, c := range book.Currencies {
+ k := billing.PriceRef{Book: book.Version, Kind: billing.KindPack, Name: name, Currency: c}.Key()
+ raw[k] = testPriceID(k)
+ }
+ }
+ b, _ := json.Marshal(raw)
+ prices, err := billing.ParsePriceMap(string(b), book)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fake := billingtest.New()
+ cfg := &BillingConfig{Book: book, Prices: prices, Provider: fake}
+ fx.srv.cfg.PlanCatalog = cat
+ fx.srv.cfg.Billing = cfg
+ fx.srv.billing = newBillingRuntime(cfg)
+ acct := planAccount(t, fx, 501)
+ if err := fx.st.SetBillingCustomer(acct.ID, "cus_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ return &billingFixture{consoleFixture: fx, fake: fake, acct: acct}
+}
+
+// personalSub is an active Personal subscription on cus_1 for the
+// fixture's account, with the given packs.
+func (bf *billingFixture) personalSub(id, status string, packs map[string]int64) *billing.Subscription {
+ items := []billing.Item{{PriceID: testPriceID("example-v1/personal/usd"), Quantity: 1, Currency: "usd"}}
+ for name, q := range packs {
+ items = append(items, billing.Item{PriceID: testPriceID("example-v1/pack/" + name + "/usd"), Quantity: q, Currency: "usd"})
+ }
+ return &billing.Subscription{ID: id, Customer: "cus_1", Account: bf.acct.Sqid, ProviderStatus: status, State: billingStateFor(status),
+ Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items}
+}
+
+func (bf *billingFixture) put(sub *billing.Subscription) {
+ bf.fake.Lock()
+ bf.fake.Subs[sub.ID] = sub
+ bf.fake.Unlock()
+}
+
+func TestSyncWritesThePlanRow(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_1", "active", map[string]int64{"apps": 2}))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ row, _ := bf.st.AccountPlan(bf.acct.ID)
+ if row == nil || row.Plan != "personal" || row.Source != PlanSourceBilling || row.Packs["apps"] != 2 {
+ t.Fatalf("plan row = %+v", row)
+ }
+ r, _ := readLimits(t, bf.consoleFixture, bf.acct.Sqid)
+ if r == nil || r.Plan != "personal" || r.Limits.RunningThings != 35 {
+ t.Fatalf("limits record = %+v", r)
+ }
+ b, _ := bf.st.BillingAccount(bf.acct.ID)
+ if b.Subscription != "sub_1" || b.State != billing.StatePaid || !b.SyncedAt.Equal(billingNow) {
+ t.Errorf("billing row = %+v", b)
+ }
+}
+
+func TestSyncUnchangedKeepsThrottle(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := bf.st.SetAccountThrottle(bf.acct.ID, &plans.Throttle{Awake: true, Until: billingNow.Add(48 * time.Hour)}, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := bf.st.AccountPlan(bf.acct.ID)
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ after, _ := bf.st.AccountPlan(bf.acct.ID)
+ if after.Revision != before.Revision || after.Throttle == nil || !after.Throttle.Awake {
+ t.Fatalf("unchanged sync wrote: before %+v after %+v", before, after)
+ }
+}
+
+func TestPaidSubscriptionOnSponsoredAccountOpensProblem(t *testing.T) {
+ bf := newBillingFixture(t)
+ if _, err := bf.st.SetAccountPlan(bf.acct.ID, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: 40}, "friend", "op@example.com", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := bf.st.AccountPlan(bf.acct.ID)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ after, _ := bf.st.AccountPlan(bf.acct.ID)
+ if !reflect.DeepEqual(before, after) {
+ t.Fatalf("sponsored row changed:\n%+v\n%+v", before, after)
+ }
+ open, _ := bf.st.BillingProblems(false)
+ if len(open) != 1 || open[0].Reason != problemNotBillingOwned || open[0].AccountID != bf.acct.ID || open[0].Subscription != "sub_1" {
+ t.Fatalf("problems = %+v", open)
+ }
+}
+
+func TestSyncUnknownCustomerOpensProblem(t *testing.T) {
+ bf := newBillingFixture(t)
+ sub := bf.personalSub("sub_1", "active", nil)
+ sub.Customer = "cus_stranger"
+ bf.put(sub)
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatalf("err = %v, want nil", err)
+ }
+ if row, _ := bf.st.AccountPlan(bf.acct.ID); row != nil {
+ t.Fatalf("plan row written: %+v", row)
+ }
+ open, _ := bf.st.BillingProblems(false)
+ // The metadata names the fixture's account, which exists: the problem is filed under it.
+ if len(open) != 1 || open[0].Reason != problemUnknownCustomer || open[0].AccountID != bf.acct.ID {
+ t.Fatalf("problems = %+v", open)
+ }
+ sub.Account = "zzzzzz"
+ sub.ID = "sub_2"
+ bf.put(sub)
+ if err := bf.srv.syncSubscription(context.Background(), "sub_2", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ open, _ = bf.st.BillingProblems(false)
+ if len(open) != 2 || open[0].AccountID != 0 {
+ t.Fatalf("unknown account: problems = %+v", open)
+ }
+}
+
+func TestSyncTransientErrorIsReturned(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ bf.fake.Err = errors.New("network down")
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err == nil {
+ t.Fatal("transient error swallowed")
+ }
+ if row, _ := bf.st.AccountPlan(bf.acct.ID); row != nil {
+ t.Fatalf("plan row written: %+v", row)
+ }
+ if b, _ := bf.st.BillingAccount(bf.acct.ID); b.Subscription != "" {
+ t.Fatalf("billing row written: %+v", b)
+ }
+}
+
+func TestSyncEndedDropsToDefault(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_1", "active", map[string]int64{"apps": 1}))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ bf.put(bf.personalSub("sub_1", "canceled", map[string]int64{"apps": 1}))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ row, _ := bf.st.AccountPlan(bf.acct.ID)
+ if row.Plan != "free" || len(row.Packs) != 0 || row.Source != PlanSourceBilling {
+ t.Fatalf("row = %+v", row)
+ }
+}