| 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) |
| + } |
| +} |