billing: provider-neutral subscription types, price map and item-set recognition (plans 6a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+730
−0
internal/billing/billing.go+92 −0internal/billing/billingtest/fake.go+99 −0internal/billing/helpers_test.go+59 −0internal/billing/prices.go+196 −0internal/billing/prices_test.go+95 −0internal/billing/recognise.go+87 −0internal/billing/recognise_test.go+102 −0
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| new file mode 100644 |
| index 000000000..4cfc58dee |
| --- /dev/null |
| +++ b/internal/billing/billing.go |
| @@ -0,0 +1,92 @@ |
| +// Package billing is the provider-neutral boundary between the console and |
| +// a billing provider (spec 2026-10-20-plans-caps-packs-design.md §10). |
| +// The console imports only this package; an adapter (internal/billingstripe) |
| +// implements Provider. |
| +// |
| +// A subscription is what the provider says when asked, never what an event |
| +// body claims: an event only names which subscription to read. |
| +package billing |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// State is a subscription's provider status mapped onto what the plan |
| +// does with it. |
| +type State string |
| + |
| +const ( |
| + // StatePaid keeps paid limits: active, trialing and past due (spec |
| + // §9.2: paid limits while the provider retries). |
| + StatePaid State = "paid" |
| + // StatePending changes nothing: a subscription not yet paid for. |
| + StatePending State = "pending" |
| + // StateEnded drops the account to the default plan. |
| + StateEnded State = "ended" |
| +) |
| + |
| +// Item is one line of a subscription: a price and its quantity. |
| +type Item struct { |
| + PriceID string |
| + Quantity int64 |
| + Currency string |
| +} |
| + |
| +// Subscription is a fresh read of one subscription at the provider. |
| +type Subscription struct { |
| + ID, Customer string |
| + Account string // the account sqid the purchase metadata names |
| + ProviderStatus string // the provider's own word, for operators |
| + State State // the adapter's mapping |
| + 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 |
| +} |
| + |
| +// EventKind says what an event asks the console to re-read. |
| +type EventKind string |
| + |
| +const ( |
| + EventSubscription EventKind = "subscription" |
| + EventCheckout EventKind = "checkout" |
| + EventIgnored EventKind = "ignored" |
| +) |
| + |
| +// Event is a verified provider event, reduced to what to read next. |
| +type Event struct { |
| + ID string |
| + Kind EventKind |
| + Object string // the subscription or checkout id |
| + LiveMode bool |
| +} |
| + |
| +var ( |
| + // ErrBadEvent is any signature or shape failure on an event. |
| + ErrBadEvent = errors.New("billing: event refused") |
| + // ErrNotFound is the provider saying the object does not exist. |
| + ErrNotFound = errors.New("billing: not found") |
| +) |
| + |
| +// Provider is a billing provider as the console uses it. |
| +type Provider interface { |
| + // ParseEvent verifies and reduces a webhook delivery. Any signature |
| + // or shape failure is ErrBadEvent. |
| + ParseEvent(raw []byte, header http.Header, now time.Time) (Event, error) |
| + // Subscription reads one subscription. ErrNotFound when the provider |
| + // has none; any other error is transient. |
| + Subscription(ctx context.Context, id string) (*Subscription, error) |
| + // CheckoutSubscription is the subscription a checkout made, "" when it |
| + // made none. |
| + CheckoutSubscription(ctx context.Context, checkoutID string) (string, error) |
| + // Check is the readiness check: the provider account and every price |
| + // of the book agree with the configuration. |
| + Check(ctx context.Context, book *plans.PriceBook, prices PriceMap) error |
| +} |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| new file mode 100644 |
| index 000000000..2c8b000c9 |
| --- /dev/null |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -0,0 +1,99 @@ |
| +// Package billingtest is an in-memory billing.Provider for tests. |
| +package billingtest |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// Fake is an in-memory billing.Provider. Set Subs and Checkouts to what the |
| +// provider would say; set Err to make every call fail, CheckErr to fail |
| +// only the readiness check. Calls counts every call but ParseEvent. |
| +type Fake struct { |
| + mu sync.Mutex |
| + Subs map[string]*billing.Subscription |
| + Checkouts map[string]string |
| + Err error |
| + CheckErr error |
| + Calls int |
| +} |
| + |
| +// New is an empty Fake. |
| +func New() *Fake { |
| + return &Fake{Subs: map[string]*billing.Subscription{}, Checkouts: map[string]string{}} |
| +} |
| + |
| +// Lock and Unlock guard a test's edits to the maps while the code under |
| +// test may be reading them. |
| +func (f *Fake) Lock() { f.mu.Lock() } |
| +func (f *Fake) Unlock() { f.mu.Unlock() } |
| + |
| +// ParseEvent accepts a JSON {"id","kind","object","live"} body under the |
| +// header Fake-Signature: ok. |
| +func (f *Fake) ParseEvent(raw []byte, header http.Header, _ time.Time) (billing.Event, error) { |
| + if header.Get("Fake-Signature") != "ok" { |
| + return billing.Event{}, billing.ErrBadEvent |
| + } |
| + var e struct { |
| + ID string `json:"id"` |
| + Kind string `json:"kind"` |
| + Object string `json:"object"` |
| + Live bool `json:"live"` |
| + } |
| + if err := json.Unmarshal(raw, &e); err != nil || e.ID == "" { |
| + return billing.Event{}, billing.ErrBadEvent |
| + } |
| + switch billing.EventKind(e.Kind) { |
| + case billing.EventSubscription, billing.EventCheckout, billing.EventIgnored: |
| + default: |
| + return billing.Event{}, billing.ErrBadEvent |
| + } |
| + return billing.Event{ID: e.ID, Kind: billing.EventKind(e.Kind), Object: e.Object, LiveMode: e.Live}, nil |
| +} |
| + |
| +// Subscription returns a copy of Subs[id], or billing.ErrNotFound. |
| +func (f *Fake) Subscription(_ context.Context, id string) (*billing.Subscription, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.Calls++ |
| + if f.Err != nil { |
| + return nil, f.Err |
| + } |
| + s, ok := f.Subs[id] |
| + if !ok { |
| + return nil, billing.ErrNotFound |
| + } |
| + c := *s |
| + c.Items = append([]billing.Item(nil), s.Items...) |
| + return &c, nil |
| +} |
| + |
| +// CheckoutSubscription returns Checkouts[id], "" when absent. |
| +func (f *Fake) CheckoutSubscription(_ context.Context, id string) (string, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.Calls++ |
| + if f.Err != nil { |
| + return "", f.Err |
| + } |
| + return f.Checkouts[id], nil |
| +} |
| + |
| +// Check returns Err, then CheckErr. |
| +func (f *Fake) Check(context.Context, *plans.PriceBook, billing.PriceMap) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.Calls++ |
| + if f.Err != nil { |
| + return f.Err |
| + } |
| + return f.CheckErr |
| +} |
| + |
| +var _ billing.Provider = (*Fake)(nil) |
diff --git a/internal/billing/helpers_test.go b/internal/billing/helpers_test.go| new file mode 100644 |
| index 000000000..92c438cc5 |
| --- /dev/null |
| +++ b/internal/billing/helpers_test.go |
| @@ -0,0 +1,59 @@ |
| +package billing |
| + |
| +import ( |
| + "encoding/json" |
| + "regexp" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +func exampleCatalog(t *testing.T) *plans.Catalog { |
| + t.Helper() |
| + c, err := plans.LoadCatalog("../plans/testdata/example-catalog.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +func exampleBook(t *testing.T, c *plans.Catalog) *plans.PriceBook { |
| + t.Helper() |
| + b, err := plans.LoadPriceBook("../plans/testdata/example-pricebook.json", c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +var nonAlnum = regexp.MustCompile(`[^A-Za-z0-9]`) |
| + |
| +// priceIDFor is the fake provider price id the tests give a key. |
| +func priceIDFor(key string) string { return "price_" + nonAlnum.ReplaceAllString(key, "") } |
| + |
| +// fullPrices is every key the book needs, each with its fake id. |
| +func fullPrices(b *plans.PriceBook) map[string]string { |
| + m := map[string]string{} |
| + for plan := range b.Plans { |
| + for _, cur := range b.Currencies { |
| + k := PriceRef{Book: b.Version, Kind: KindPlan, Name: plan, Currency: cur}.Key() |
| + m[k] = priceIDFor(k) |
| + } |
| + } |
| + for pack := range b.Packs { |
| + for _, cur := range b.Currencies { |
| + k := PriceRef{Book: b.Version, Kind: KindPack, Name: pack, Currency: cur}.Key() |
| + m[k] = priceIDFor(k) |
| + } |
| + } |
| + return m |
| +} |
| + |
| +func rawPrices(t *testing.T, m map[string]string) string { |
| + t.Helper() |
| + b, err := json.Marshal(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
diff --git a/internal/billing/prices.go b/internal/billing/prices.go| new file mode 100644 |
| index 000000000..84b3747e2 |
| --- /dev/null |
| +++ b/internal/billing/prices.go |
| @@ -0,0 +1,196 @@ |
| +package billing |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// The kinds of thing a price is for. |
| +const ( |
| + KindPlan = "plan" |
| + KindPack = "pack" |
| +) |
| + |
| +// maxPriceMapBytes bounds the configured price map. |
| +const maxPriceMapBytes = 64 << 10 |
| + |
| +var priceIDPattern = regexp.MustCompile(`^price_[A-Za-z0-9]{1,250}$`) |
| + |
| +// PriceRef names one price by what it is for: a book, a plan or pack, and |
| +// a currency. Its Key is how the configuration and the provider's |
| +// metadata[price_key] name it. |
| +type PriceRef struct { |
| + Book, Kind, Name, Currency string |
| +} |
| + |
| +// Key is "<book>/<plan>/<currency>" for a plan and |
| +// "<book>/pack/<pack>/<currency>" for a pack. |
| +func (r PriceRef) Key() string { |
| + if r.Kind == KindPack { |
| + return r.Book + "/pack/" + r.Name + "/" + r.Currency |
| + } |
| + return r.Book + "/" + r.Name + "/" + r.Currency |
| +} |
| + |
| +// parsePriceKey is Key's inverse. |
| +func parsePriceKey(key string) (PriceRef, error) { |
| + parts := strings.Split(key, "/") |
| + var r PriceRef |
| + switch { |
| + case len(parts) == 3 && parts[1] != KindPack: |
| + r = PriceRef{Book: parts[0], Kind: KindPlan, Name: parts[1], Currency: parts[2]} |
| + case len(parts) == 4 && parts[1] == KindPack: |
| + r = PriceRef{Book: parts[0], Kind: KindPack, Name: parts[2], Currency: parts[3]} |
| + default: |
| + return PriceRef{}, fmt.Errorf("price key %q is neither <book>/<plan>/<currency> nor <book>/pack/<name>/<currency>", key) |
| + } |
| + if r.Book == "" || r.Name == "" { |
| + return PriceRef{}, fmt.Errorf("price key %q has an empty part", key) |
| + } |
| + if !slices.Contains(plans.SoldCurrencies, r.Currency) { |
| + return PriceRef{}, fmt.Errorf("price key %q: currency %q is not one of %v", key, r.Currency, plans.SoldCurrencies) |
| + } |
| + return r, nil |
| +} |
| + |
| +// PriceMap is the configured map from price keys to provider price ids, |
| +// both ways. Provider ids live only here, never in the book. |
| +type PriceMap struct { |
| + byKey map[string]string |
| + byID map[string]PriceRef |
| +} |
| + |
| +// ParsePriceMap parses the configured JSON object of price key to provider |
| +// price id. Every price the book needs must be present. Keys of other book |
| +// versions are allowed: a subscription bought under an earlier book keeps |
| +// it for life, and its prices must still be recognised. A key under the |
| +// configured book's version must be one the book prices. |
| +func ParsePriceMap(raw string, book *plans.PriceBook) (PriceMap, error) { |
| + if len(raw) > maxPriceMapBytes { |
| + return PriceMap{}, fmt.Errorf("price map is larger than %d bytes", maxPriceMapBytes) |
| + } |
| + var obj map[string]string |
| + dec := json.NewDecoder(strings.NewReader(raw)) |
| + if err := dec.Decode(&obj); err != nil { |
| + return PriceMap{}, fmt.Errorf("price map: %w", err) |
| + } |
| + if err := dec.Decode(new(json.RawMessage)); err != io.EOF { |
| + return PriceMap{}, errors.New("price map: trailing content") |
| + } |
| + if obj == nil { |
| + return PriceMap{}, errors.New("price map: not an object") |
| + } |
| + if err := rejectDuplicateKeys([]byte(raw)); err != nil { |
| + return PriceMap{}, fmt.Errorf("price map: %w", err) |
| + } |
| + m := PriceMap{byKey: map[string]string{}, byID: map[string]PriceRef{}} |
| + for key, id := range obj { |
| + ref, err := parsePriceKey(key) |
| + if err != nil { |
| + return PriceMap{}, err |
| + } |
| + if !priceIDPattern.MatchString(id) { |
| + return PriceMap{}, fmt.Errorf("price key %q: the value is not a price id", key) |
| + } |
| + if other, dup := m.byID[id]; dup { |
| + return PriceMap{}, fmt.Errorf("price keys %q and %q name the same price", other.Key(), key) |
| + } |
| + if ref.Book == book.Version && !bookPrices(book, ref) { |
| + return PriceMap{}, fmt.Errorf("price key %q is under book %s, which does not price it", key, book.Version) |
| + } |
| + m.byKey[key] = id |
| + m.byID[id] = ref |
| + } |
| + for _, ref := range bookRefs(book) { |
| + if _, ok := m.byKey[ref.Key()]; !ok { |
| + return PriceMap{}, fmt.Errorf("price map has no price for %q", ref.Key()) |
| + } |
| + } |
| + return m, nil |
| +} |
| + |
| +func bookPrices(book *plans.PriceBook, r PriceRef) bool { |
| + switch r.Kind { |
| + case KindPlan: |
| + _, ok := book.PlanPrice(r.Name, r.Currency) |
| + return ok |
| + case KindPack: |
| + _, ok := book.PackPrice(r.Name, r.Currency) |
| + return ok |
| + } |
| + return false |
| +} |
| + |
| +// bookRefs is every price the book needs. |
| +func bookRefs(book *plans.PriceBook) []PriceRef { |
| + var out []PriceRef |
| + for name := range book.Plans { |
| + for _, c := range book.Currencies { |
| + out = append(out, PriceRef{Book: book.Version, Kind: KindPlan, Name: name, Currency: c}) |
| + } |
| + } |
| + for name := range book.Packs { |
| + for _, c := range book.Currencies { |
| + out = append(out, PriceRef{Book: book.Version, Kind: KindPack, Name: name, Currency: c}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Lookup is what a provider price id is for. |
| +func (m PriceMap) Lookup(priceID string) (PriceRef, bool) { |
| + r, ok := m.byID[priceID] |
| + return r, ok |
| +} |
| + |
| +// ID is the provider price id for r. |
| +func (m PriceMap) ID(r PriceRef) (string, bool) { |
| + id, ok := m.byKey[r.Key()] |
| + return id, ok |
| +} |
| + |
| +// Refs is every price in the map under book, sorted by key. |
| +func (m PriceMap) Refs(book string) []PriceRef { |
| + var out []PriceRef |
| + for _, r := range m.byID { |
| + if r.Book == book { |
| + out = append(out, r) |
| + } |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].Key() < out[j].Key() }) |
| + return out |
| +} |
| + |
| +// rejectDuplicateKeys refuses a JSON object with the same key twice: |
| +// encoding/json would keep the last and say nothing. |
| +func rejectDuplicateKeys(data []byte) error { |
| + dec := json.NewDecoder(bytes.NewReader(data)) |
| + if _, err := dec.Token(); err != nil { |
| + return err |
| + } |
| + seen := map[string]bool{} |
| + for dec.More() { |
| + tok, err := dec.Token() |
| + if err != nil { |
| + return err |
| + } |
| + key, _ := tok.(string) |
| + if seen[key] { |
| + return fmt.Errorf("the key %q appears twice", key) |
| + } |
| + seen[key] = true |
| + if _, err := dec.Token(); err != nil { // the value: a string |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/billing/prices_test.go b/internal/billing/prices_test.go| new file mode 100644 |
| index 000000000..88daf97e3 |
| --- /dev/null |
| +++ b/internal/billing/prices_test.go |
| @@ -0,0 +1,95 @@ |
| +package billing |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestParsePriceMap(t *testing.T) { |
| + cat := exampleCatalog(t) |
| + book := exampleBook(t, cat) |
| + |
| + full := fullPrices(book) |
| + if len(full) != 15 { |
| + t.Fatalf("example book needs %d prices, want 15", len(full)) |
| + } |
| + m, err := ParsePriceMap(rawPrices(t, full), book) |
| + if err != nil { |
| + t.Fatalf("full set: %v", err) |
| + } |
| + ref, ok := m.Lookup(priceIDFor("example-v1/pack/apps/gbp")) |
| + if !ok || ref != (PriceRef{Book: "example-v1", Kind: KindPack, Name: "apps", Currency: "gbp"}) { |
| + t.Errorf("Lookup(apps gbp) = %+v, %v", ref, ok) |
| + } |
| + if id, ok := m.ID(PriceRef{Book: "example-v1", Kind: KindPlan, Name: "personal", Currency: "usd"}); !ok || id != priceIDFor("example-v1/personal/usd") { |
| + t.Errorf("ID(personal usd) = %q, %v", id, ok) |
| + } |
| + refs := m.Refs("example-v1") |
| + if len(refs) != 15 { |
| + t.Errorf("Refs = %d entries", len(refs)) |
| + } |
| + for i := 1; i < len(refs); i++ { |
| + if refs[i-1].Key() >= refs[i].Key() { |
| + t.Errorf("Refs not sorted at %d: %q then %q", i, refs[i-1].Key(), refs[i].Key()) |
| + } |
| + } |
| + |
| + with := func(edit func(m map[string]string)) string { |
| + c := map[string]string{} |
| + for k, v := range full { |
| + c[k] = v |
| + } |
| + edit(c) |
| + return rawPrices(t, c) |
| + } |
| + |
| + // An earlier book's key recognises subscriptions bought under it. |
| + old, err := ParsePriceMap(with(func(m map[string]string) { m["example-v0/personal/usd"] = "price_old1" }), book) |
| + if err != nil { |
| + t.Fatalf("earlier book key: %v", err) |
| + } |
| + if ref, ok := old.Lookup("price_old1"); !ok || ref.Book != "example-v0" || ref.Kind != KindPlan || ref.Name != "personal" { |
| + t.Errorf("Lookup(old) = %+v, %v", ref, ok) |
| + } |
| + if got := old.Refs("example-v1"); len(got) != 15 { |
| + t.Errorf("Refs(current) with an old key = %d", len(got)) |
| + } |
| + |
| + for name, raw := range map[string]string{ |
| + "missing key": with(func(m map[string]string) { delete(m, "example-v1/pack/email/eur") }), |
| + "duplicate id": with(func(m map[string]string) { m["example-v0/personal/usd"] = full["example-v1/personal/usd"] }), |
| + "unsold currency": with(func(m map[string]string) { m["x/personal/jpy"] = "price_jpy" }), |
| + "pack with no cur": with(func(m map[string]string) { m["x/pack/apps"] = "price_noc" }), |
| + "five parts": with(func(m map[string]string) { m["x/pack/apps/usd/more"] = "price_five" }), |
| + "empty book": with(func(m map[string]string) { m["/personal/usd"] = "price_empty" }), |
| + "upper currency": with(func(m map[string]string) { m["x/personal/USD"] = "price_upper" }), |
| + "product id value": with(func(m map[string]string) { m["x/personal/usd"] = "prod_x" }), |
| + "current book extra": with(func(m map[string]string) { m["example-v1/business/usd"] = "price_biz" }), |
| + "current pack extra": with(func(m map[string]string) { m["example-v1/pack/seats/usd"] = "price_seats" }), |
| + "not json": "{", |
| + "not an object": `["price_x"]`, |
| + "over 64 KiB": `{"x/personal/usd": "price_` + strings.Repeat("a", 64*1024) + `"}`, |
| + } { |
| + if _, err := ParsePriceMap(raw, book); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| +} |
| + |
| +// The size limit is on the raw value, checked before parsing. |
| +func TestParsePriceMapSizeLimit(t *testing.T) { |
| + cat := exampleCatalog(t) |
| + book := exampleBook(t, cat) |
| + raw := rawPrices(t, fullPrices(book)) |
| + pad := 64*1024 - len(raw) |
| + at := strings.Replace(raw, "{", "{"+strings.Repeat(" ", pad), 1) |
| + if len(at) != 64*1024 { |
| + t.Fatalf("len = %d", len(at)) |
| + } |
| + if _, err := ParsePriceMap(at, book); err != nil { |
| + t.Errorf("exactly 64 KiB: %v", err) |
| + } |
| + if _, err := ParsePriceMap(" "+at, book); err == nil { |
| + t.Error("64 KiB + 1 accepted") |
| + } |
| +} |
diff --git a/internal/billing/recognise.go b/internal/billing/recognise.go| new file mode 100644 |
| index 000000000..07212a3e4 |
| --- /dev/null |
| +++ b/internal/billing/recognise.go |
| @@ -0,0 +1,87 @@ |
| +package billing |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "slices" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// Purchase is what a subscription bought: one paid plan and the packs on |
| +// it, under one book, in one currency. |
| +type Purchase struct { |
| + Book, Currency, Plan string |
| + Packs map[string]int |
| +} |
| + |
| +// ErrUnrecognised is a subscription whose items are not a purchase the |
| +// console sells. Each error wraps it with the reason. |
| +var ErrUnrecognised = errors.New("billing: subscription not recognised") |
| + |
| +func unrecognised(format string, a ...any) error { |
| + return fmt.Errorf("%w: %s", ErrUnrecognised, fmt.Sprintf(format, a...)) |
| +} |
| + |
| +// Recognise turns a subscription's items into a purchase: exactly one paid |
| +// plan at quantity 1, and at most one item per pack that plan offers, each |
| +// within its quantity bounds, all under one book and in the subscription's |
| +// currency. A subscription under an earlier book is read from its keys |
| +// alone; the current book is not consulted. |
| +func Recognise(sub *Subscription, prices PriceMap, cat *plans.Catalog) (Purchase, error) { |
| + if !sub.ItemsComplete { |
| + return Purchase{}, unrecognised("the provider did not send every item") |
| + } |
| + p := Purchase{Currency: sub.Currency, Packs: map[string]int{}} |
| + var packItems []PriceRef |
| + var packQty []int64 |
| + for _, it := range sub.Items { |
| + ref, ok := prices.Lookup(it.PriceID) |
| + if !ok { |
| + return Purchase{}, unrecognised("price %s is not in the price map", it.PriceID) |
| + } |
| + if ref.Currency != sub.Currency || it.Currency != sub.Currency { |
| + return Purchase{}, unrecognised("item %s is in %s, the subscription in %s", ref.Key(), it.Currency, sub.Currency) |
| + } |
| + if p.Book == "" { |
| + p.Book = ref.Book |
| + } else if p.Book != ref.Book { |
| + return Purchase{}, unrecognised("items from books %s and %s", p.Book, ref.Book) |
| + } |
| + switch ref.Kind { |
| + case KindPlan: |
| + if p.Plan != "" { |
| + return Purchase{}, unrecognised("more than one plan item") |
| + } |
| + if it.Quantity != 1 { |
| + return Purchase{}, unrecognised("plan %s has quantity %d", ref.Name, it.Quantity) |
| + } |
| + plan, ok := cat.Plans[ref.Name] |
| + if !ok || !plan.Paid { |
| + return Purchase{}, unrecognised("plan %q is not a paid plan in the catalog", ref.Name) |
| + } |
| + p.Plan = ref.Name |
| + case KindPack: |
| + packItems = append(packItems, ref) |
| + packQty = append(packQty, it.Quantity) |
| + } |
| + } |
| + if p.Plan == "" { |
| + return Purchase{}, unrecognised("no plan item") |
| + } |
| + offered := cat.Plans[p.Plan].Packs |
| + for i, ref := range packItems { |
| + if _, dup := p.Packs[ref.Name]; dup { |
| + return Purchase{}, unrecognised("pack %s appears twice", ref.Name) |
| + } |
| + pk, ok := cat.Packs[ref.Name] |
| + if !ok || !slices.Contains(offered, ref.Name) { |
| + return Purchase{}, unrecognised("plan %s does not offer pack %q", p.Plan, ref.Name) |
| + } |
| + if packQty[i] < 1 || packQty[i] > int64(pk.MaxQuantity) { |
| + return Purchase{}, unrecognised("pack %s has quantity %d, allowed 1 to %d", ref.Name, packQty[i], pk.MaxQuantity) |
| + } |
| + p.Packs[ref.Name] = int(packQty[i]) |
| + } |
| + return p, nil |
| +} |
diff --git a/internal/billing/recognise_test.go b/internal/billing/recognise_test.go| new file mode 100644 |
| index 000000000..21aa7cf8a |
| --- /dev/null |
| +++ b/internal/billing/recognise_test.go |
| @@ -0,0 +1,102 @@ |
| +package billing |
| + |
| +import ( |
| + "errors" |
| + "reflect" |
| + "testing" |
| +) |
| + |
| +func recogniseFixture(t *testing.T, extra map[string]string) (PriceMap, func(key string, qty int64, cur string) Item) { |
| + t.Helper() |
| + cat := exampleCatalog(t) |
| + book := exampleBook(t, cat) |
| + full := fullPrices(book) |
| + for k, v := range extra { |
| + full[k] = v |
| + } |
| + m, err := ParsePriceMap(rawPrices(t, full), book) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + item := func(key string, qty int64, cur string) Item { |
| + id, ok := full[key] |
| + if !ok { |
| + id = "price_unknown" |
| + } |
| + return Item{PriceID: id, Quantity: qty, Currency: cur} |
| + } |
| + return m, item |
| +} |
| + |
| +func TestRecognisePersonalWithPacks(t *testing.T) { |
| + m, item := recogniseFixture(t, nil) |
| + sub := &Subscription{ |
| + ID: "sub_1", Currency: "usd", State: StatePaid, ItemsComplete: true, |
| + Items: []Item{ |
| + item("example-v1/personal/usd", 1, "usd"), |
| + item("example-v1/pack/apps/usd", 2, "usd"), |
| + item("example-v1/pack/email/usd", 1, "usd"), |
| + }, |
| + } |
| + got, err := Recognise(sub, m, exampleCatalog(t)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := Purchase{Book: "example-v1", Currency: "usd", Plan: "personal", Packs: map[string]int{"apps": 2, "email": 1}} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Errorf("Recognise = %+v, want %+v", got, want) |
| + } |
| + |
| + // Personal alone has an empty, non-nil pack map. |
| + sub.Items = sub.Items[:1] |
| + got, err = Recognise(sub, m, exampleCatalog(t)) |
| + if err != nil || got.Packs == nil || len(got.Packs) != 0 { |
| + t.Errorf("personal alone = %+v, %v", got, err) |
| + } |
| +} |
| + |
| +// A subscription bought under an earlier book keeps it: its keys alone say |
| +// what was bought. |
| +func TestRecogniseEarlierBook(t *testing.T) { |
| + m, item := recogniseFixture(t, map[string]string{ |
| + "example-v0/personal/eur": "price_v0personaleur", |
| + "example-v0/pack/apps/eur": "price_v0appseur", |
| + }) |
| + sub := &Subscription{ID: "sub_1", Currency: "eur", ItemsComplete: true, Items: []Item{ |
| + item("example-v0/personal/eur", 1, "eur"), item("example-v0/pack/apps/eur", 3, "eur"), |
| + }} |
| + got, err := Recognise(sub, m, exampleCatalog(t)) |
| + if err != nil || got.Book != "example-v0" || got.Packs["apps"] != 3 { |
| + t.Errorf("Recognise = %+v, %v", got, err) |
| + } |
| +} |
| + |
| +func TestRecogniseRefuses(t *testing.T) { |
| + m, item := recogniseFixture(t, map[string]string{ |
| + "example-v0/personal/usd": "price_v0personalusd", |
| + "example-v0/free/usd": "price_v0freeusd", |
| + }) |
| + personal := item("example-v1/personal/usd", 1, "usd") |
| + apps := func(q int64) Item { return item("example-v1/pack/apps/usd", q, "usd") } |
| + cases := map[string]*Subscription{ |
| + "items incomplete": {Currency: "usd", ItemsComplete: false, Items: []Item{personal}}, |
| + "unknown price": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, {PriceID: "price_nope", Quantity: 1, Currency: "usd"}}}, |
| + "plan qty 2": {Currency: "usd", ItemsComplete: true, Items: []Item{item("example-v1/personal/usd", 2, "usd")}}, |
| + "no plan item": {Currency: "usd", ItemsComplete: true, Items: []Item{apps(1)}}, |
| + "no items": {Currency: "usd", ItemsComplete: true}, |
| + "two plan items": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, personal}}, |
| + "apps twice": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, apps(1), apps(2)}}, |
| + "apps qty 0": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, apps(0)}}, |
| + "apps qty 21": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, apps(21)}}, |
| + "eur pack on usd": {Currency: "usd", ItemsComplete: true, Items: []Item{personal, item("example-v1/pack/apps/eur", 1, "eur")}}, |
| + "sub currency eur": {Currency: "eur", ItemsComplete: true, Items: []Item{personal}}, |
| + "item currency off": {Currency: "usd", ItemsComplete: true, Items: []Item{{PriceID: personal.PriceID, Quantity: 1, Currency: "eur"}}}, |
| + "two books": {Currency: "usd", ItemsComplete: true, Items: []Item{item("example-v0/personal/usd", 1, "usd"), apps(1)}}, |
| + "free plan priced": {Currency: "usd", ItemsComplete: true, Items: []Item{item("example-v0/free/usd", 1, "usd")}}, |
| + } |
| + for name, sub := range cases { |
| + if _, err := Recognise(sub, m, exampleCatalog(t)); !errors.Is(err, ErrUnrecognised) { |
| + t.Errorf("%s: err = %v, want ErrUnrecognised", name, err) |
| + } |
| + } |
| +} |