carlos / platform Public

plans: price book with draft/approved status and currency choice, the public export (schema 2) and pricebook-export (plans 6a, shared with plans 7 task 1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1a778636c5dd7abb9651c260b33bae63a52de25d parent 9d1af95
10 files changed, +1,163 −0
  • cmd/pricebook-export/main.go +61 −0
  • cmd/pricebook-export/main_test.go +74 −0
  • docs/superpowers/specs/2026-10-25-public-price-export-schema-2.md +93 −0
  • internal/cgroup/cgroup_test.go +11 −0
  • internal/plans/export.go +142 −0
  • internal/plans/export_test.go +109 −0
  • internal/plans/pricebook.go +298 −0
  • internal/plans/pricebook_test.go +192 −0
  • internal/plans/testdata/example-pricebook.json +20 −0
  • internal/plans/testdata/example-public-pricebook.json +163 −0
diff --git a/cmd/pricebook-export/main.go b/cmd/pricebook-export/main.go
new file mode 100644
index 000000000..b3536c369
--- /dev/null
+++ b/cmd/pricebook-export/main.go
@@ -0,0 +1,61 @@
+// Command pricebook-export writes the public price export (schema 2) a
+// pricing page renders from: a plan catalog and the price book that prices
+// it, joined and byte-stable. The schema is
+// docs/superpowers/specs/2026-10-25-public-price-export-schema-2.md.
+//
+// pricebook-export -catalog <file> -book <file> [-o <file>]
+package main
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+func main() {
+ if err := run(os.Args[1:], os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, "pricebook-export:", err)
+ os.Exit(1)
+ }
+}
+
+func run(args []string, stdout io.Writer) error {
+ fs := flag.NewFlagSet("pricebook-export", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ catalogPath := fs.String("catalog", "", "plan catalog file")
+ bookPath := fs.String("book", "", "price book file")
+ outPath := fs.String("o", "", "write the export here instead of stdout")
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ if fs.NArg() != 0 {
+ return fmt.Errorf("unexpected argument %q", fs.Arg(0))
+ }
+ if *catalogPath == "" {
+ return errors.New("-catalog is required")
+ }
+ if *bookPath == "" {
+ return errors.New("-book is required")
+ }
+ cat, err := plans.LoadCatalog(*catalogPath)
+ if err != nil {
+ return err
+ }
+ book, err := plans.LoadPriceBook(*bookPath, cat)
+ if err != nil {
+ return err
+ }
+ out, err := plans.PublicExport(cat, book)
+ if err != nil {
+ return err
+ }
+ if *outPath == "" {
+ _, err = stdout.Write(out)
+ return err
+ }
+ return os.WriteFile(*outPath, out, 0o644)
+}
diff --git a/cmd/pricebook-export/main_test.go b/cmd/pricebook-export/main_test.go
new file mode 100644
index 000000000..07a33da70
--- /dev/null
+++ b/cmd/pricebook-export/main_test.go
@@ -0,0 +1,74 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+const (
+ catalogPath = "../../internal/plans/testdata/example-catalog.json"
+ bookPath = "../../internal/plans/testdata/example-pricebook.json"
+)
+
+func TestRunWritesExport(t *testing.T) {
+ out := filepath.Join(t.TempDir(), "public.json")
+ if err := run([]string{"-catalog", catalogPath, "-book", bookPath, "-o", out}, new(bytes.Buffer)); err != nil {
+ t.Fatal(err)
+ }
+ cat, err := plans.LoadCatalog(catalogPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ book, err := plans.LoadPriceBook(bookPath, cat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := plans.PublicExport(cat, book)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Error("written export differs from PublicExport")
+ }
+
+ var stdout bytes.Buffer
+ if err := run([]string{"-catalog", catalogPath, "-book", bookPath}, &stdout); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(stdout.Bytes(), want) {
+ t.Error("stdout export differs from PublicExport")
+ }
+}
+
+func TestRunRefusesMissingFlags(t *testing.T) {
+ for _, args := range [][]string{{"-book", bookPath}, {"-catalog", catalogPath}, {}} {
+ err := run(args, new(bytes.Buffer))
+ if err == nil || !(strings.Contains(err.Error(), "-catalog") || strings.Contains(err.Error(), "-book")) {
+ t.Errorf("run(%v) = %v, want an error naming -catalog or -book", args, err)
+ }
+ }
+}
+
+func TestRunRefusesABookForAnotherCatalog(t *testing.T) {
+ dir := t.TempDir()
+ b, err := os.ReadFile(bookPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := filepath.Join(dir, "book.json")
+ if err := os.WriteFile(other, bytes.Replace(b, []byte(`"2026-10-20-v1"`), []byte(`"2026-01-01-v0"`), 1), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := run([]string{"-catalog", catalogPath, "-book", other}, new(bytes.Buffer)); err == nil {
+ t.Fatal("a book over another catalog version was exported")
+ }
+}
diff --git a/docs/superpowers/specs/2026-10-25-public-price-export-schema-2.md b/docs/superpowers/specs/2026-10-25-public-price-export-schema-2.md
new file mode 100644
index 000000000..9ce15611f
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-public-price-export-schema-2.md
@@ -0,0 +1,93 @@
+# Public price export, schema 2
+
+The public export is what a pricing page renders from. It joins a plan
+catalog and the price book that prices it into one JSON file, so the page
+and the console can never quote different prices or limits. Schema 2
+replaces schema 1 (amadan discussion #198), which carried bands, country
+bands and metered overage rates. v1 dropped all three.
+
+## Making one
+
+```
+go run ./cmd/pricebook-export -catalog <catalog.json> -book <pricebook.json> [-o <file>]
+```
+
+Without `-o` the export goes to stdout. The command refuses a book that
+prices another catalog version, or that fails any of the book's checks
+(`internal/plans/pricebook.go`). It never refuses a draft: the site does
+that, so a draft export can be previewed but never published.
+
+The same inputs always give the same bytes. A changed export means a
+changed catalog or book.
+
+## What it never carries
+
+No billing provider's identifiers. Stripe price ids live only in the
+console's `CARLOS_BILLING_PRICES`, keyed by price key. The book has no
+field for them and neither does the export.
+
+## Shape
+
+Field order is fixed and part of the contract. Two-space indent, a
+trailing newline.
+
+```json
+{
+ "schema": 2,
+ "price_book": "example-v1",
+ "price_book_id": "example-v1@5abc547e3db4",
+ "status": "draft",
+ "catalog_version": "2026-10-20-v1",
+ "catalog_id": "2026-10-20-v1@7a9ba092f2c0",
+ "default_currency": "usd",
+ "currencies": [
+ {"code": "usd", "symbol": "$", "minor_per_major": 100},
+ {"code": "eur", "symbol": "€", "minor_per_major": 100},
+ {"code": "gbp", "symbol": "£", "minor_per_major": 100}
+ ],
+ "country_currency": {"AT": "eur", "GB": "gbp"},
+ "free_accounts_per_person": 1,
+ "plans": [
+ {"key": "free", "paid": false, "default": true, "annual_minor": {},
+ "memory_mb": 0, "limits": {"running_things": 3}, "packs": []},
+ {"key": "personal", "paid": true, "default": false,
+ "annual_minor": {"eur": 2400, "gbp": 2200, "usd": 2800},
+ "memory_mb": 512, "limits": {"running_things": 25},
+ "packs": ["apps", "bandwidth", "email", "storage"]}
+ ],
+ "packs": [
+ {"key": "apps", "adds": {"running_things": 5}, "max_quantity": 20,
+ "annual_minor": {"eur": 500, "gbp": 450, "usd": 600}}
+ ]
+}
+```
+
+`limits` and `adds` are abbreviated above. The full example, generated by
+the command, is `internal/plans/testdata/example-public-pricebook.json`.
+
+## Fields
+
+| Field | Meaning |
+| --- | --- |
+| `schema` | Always `2`. A page refuses any other number. |
+| `price_book`, `price_book_id` | The book's version, and its version plus a 12-hex content digest. |
+| `status` | `draft` or `approved`. A published page needs `approved`. |
+| `catalog_version`, `catalog_id` | The same pair for the catalog. |
+| `default_currency` | The currency for a country the map does not list. |
+| `currencies` | The currencies the book sells, in the book's order. Each is lower case, with its symbol and minor units per major unit (100 for all three today). |
+| `country_currency` | ISO 3166-1 alpha-2 country, upper case, to currency. Keys sorted. Countries on the default currency are absent. |
+| `free_accounts_per_person` | From the catalog. |
+| `plans` | Unpaid plans first, then by price in the default currency, then by key. |
+| `plans[].default` | True for the plan new accounts get. |
+| `plans[].annual_minor` | Currency to the yearly price in minor units, tax exclusive. Empty for an unpaid plan. Keys sorted. |
+| `plans[].memory_mb` | Memory per app for the plan's memory tier. `0` when the tier has no published figure yet: leave the memory row out. |
+| `plans[].limits` | The plan's limits exactly as the catalog writes them. A limit that is not set is absent, not zero. Ignore keys you don't use (the rate-limit ceilings, for example). |
+| `plans[].packs` | Pack keys the plan may buy, sorted. |
+| `packs` | Every pack a paid plan offers, sorted by key. |
+| `packs[].adds` | What one unit adds, in the same keys as `limits`. |
+| `packs[].max_quantity` | The most units one account may hold. |
+| `packs[].annual_minor` | Currency to the yearly price of one unit in minor units, tax exclusive. |
+
+Byte sizes (`disk_bytes`, `storage_bytes`, `bandwidth_bytes_month`) are
+binary: 1 GB is 1073741824 bytes. `idle_seconds` and
+`min_schedule_seconds` are seconds.
diff --git a/internal/cgroup/cgroup_test.go b/internal/cgroup/cgroup_test.go
index 11ee4812b..8b3601f2b 100644
--- a/internal/cgroup/cgroup_test.go
+++ b/internal/cgroup/cgroup_test.go
@@ -7,6 +7,8 @@ import (
"path/filepath"
"strconv"
"testing"
+
+ "github.com/carlosframework/platform/internal/plans"
)
func TestExecNameAndIsExecName(t *testing.T) {
@@ -473,3 +475,12 @@ func TestSetupAtRetainingPreservesClaimEvidence(t *testing.T) {
t.Fatalf("retained claim tree removed: %v", err)
}
}
+
+// The plans catalog names memory tiers; the numbers behind them are the
+// host's. The public price export quotes the default tier's memory, so the
+// two must agree.
+func TestPlansTierMemoryAgrees(t *testing.T) {
+ if got, want := plans.TierMemoryMB[plans.MemoryDefault], int(TierDefault.MemoryMax>>20); got != want {
+ t.Errorf("plans.TierMemoryMB[default] = %d, cgroup TierDefault = %d MB", got, want)
+ }
+}
diff --git a/internal/plans/export.go b/internal/plans/export.go
new file mode 100644
index 000000000..7f8db7a4b
--- /dev/null
+++ b/internal/plans/export.go
@@ -0,0 +1,142 @@
+package plans
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "sort"
+)
+
+// TierMemoryMB is the memory, in MB, behind each catalog memory tier, for
+// the public export. The host owns the number (internal/cgroup, and a test
+// there keeps them equal). The small tier is added by the plan that builds
+// it; until then a plan on it exports memory_mb 0 and the page leaves the
+// memory row out.
+var TierMemoryMB = map[string]int{MemoryDefault: 512}
+
+// currencyDisplay is what a page needs to show an amount in each sold
+// currency.
+var currencyDisplay = map[string]struct {
+ Symbol string
+ MinorPerMajor int
+}{
+ "usd": {"$", 100},
+ "eur": {"€", 100},
+ "gbp": {"£", 100},
+}
+
+// The public export, schema 2: the catalog and the book joined into what a
+// pricing page renders from. Ordered structs, not maps, at every level whose
+// order is part of the contract, so the bytes are stable.
+type publicExport struct {
+ Schema int `json:"schema"`
+ PriceBook string `json:"price_book"`
+ PriceBookID string `json:"price_book_id"`
+ Status string `json:"status"`
+ CatalogVersion string `json:"catalog_version"`
+ CatalogID string `json:"catalog_id"`
+ DefaultCurrency string `json:"default_currency"`
+ Currencies []publicCurrency `json:"currencies"`
+ CountryCurrency map[string]string `json:"country_currency"`
+ FreeAccountsPerPerson int `json:"free_accounts_per_person"`
+ Plans []publicPlan `json:"plans"`
+ Packs []publicPack `json:"packs"`
+}
+
+type publicCurrency struct {
+ Code string `json:"code"`
+ Symbol string `json:"symbol"`
+ MinorPerMajor int `json:"minor_per_major"`
+}
+
+type publicPlan struct {
+ Key string `json:"key"`
+ Paid bool `json:"paid"`
+ Default bool `json:"default"`
+ AnnualMinor map[string]int64 `json:"annual_minor"`
+ MemoryMB int `json:"memory_mb"`
+ Limits Limits `json:"limits"`
+ Packs []string `json:"packs"`
+}
+
+type publicPack struct {
+ Key string `json:"key"`
+ Adds Limits `json:"adds"`
+ MaxQuantity int `json:"max_quantity"`
+ AnnualMinor map[string]int64 `json:"annual_minor"`
+}
+
+// PublicExport joins a catalog and the book that prices it into the public
+// export (schema 2): byte-stable, two-space indented, ending in a newline.
+// It carries no billing provider's identifiers: the book has none.
+func PublicExport(c *Catalog, b *PriceBook) ([]byte, error) {
+ if b.CatalogVersion != c.Version {
+ return nil, fmt.Errorf("price book %s prices catalog %q, not %q", b.Version, b.CatalogVersion, c.Version)
+ }
+ e := publicExport{
+ Schema: 2,
+ PriceBook: b.Version,
+ PriceBookID: b.ID(),
+ Status: b.Status,
+ CatalogVersion: c.Version,
+ CatalogID: c.ID(),
+ DefaultCurrency: b.DefaultCurrency,
+ CountryCurrency: map[string]string{},
+ FreeAccountsPerPerson: c.FreeAccountsPerPerson,
+ Plans: []publicPlan{},
+ Packs: []publicPack{},
+ }
+ for _, code := range b.Currencies {
+ d := currencyDisplay[code]
+ e.Currencies = append(e.Currencies, publicCurrency{Code: code, Symbol: d.Symbol, MinorPerMajor: d.MinorPerMajor})
+ }
+ for cur, countries := range b.CountryCurrency {
+ for _, country := range countries {
+ e.CountryCurrency[country] = cur
+ }
+ }
+ for name, p := range c.Plans {
+ annual := map[string]int64{}
+ for cur, v := range b.Plans[name] {
+ annual[cur] = v
+ }
+ packs := slices.Clone(p.Packs)
+ if packs == nil {
+ packs = []string{}
+ }
+ slices.Sort(packs)
+ e.Plans = append(e.Plans, publicPlan{
+ Key: name, Paid: p.Paid, Default: name == c.DefaultPlan, AnnualMinor: annual,
+ MemoryMB: TierMemoryMB[p.Limits.MemoryTier], Limits: p.Limits, Packs: packs,
+ })
+ }
+ sort.Slice(e.Plans, func(i, j int) bool {
+ a, z := e.Plans[i], e.Plans[j]
+ if a.Paid != z.Paid {
+ return !a.Paid
+ }
+ pa, pz := a.AnnualMinor[b.DefaultCurrency], z.AnnualMinor[b.DefaultCurrency]
+ if pa != pz {
+ return pa < pz
+ }
+ return a.Key < z.Key
+ })
+ names := make([]string, 0, len(b.Packs))
+ for name := range b.Packs {
+ names = append(names, name)
+ }
+ slices.Sort(names)
+ for _, name := range names {
+ pk := c.Packs[name]
+ annual := map[string]int64{}
+ for cur, v := range b.Packs[name] {
+ annual[cur] = v
+ }
+ e.Packs = append(e.Packs, publicPack{Key: name, Adds: pk.Adds, MaxQuantity: pk.MaxQuantity, AnnualMinor: annual})
+ }
+ out, err := json.MarshalIndent(e, "", " ")
+ if err != nil {
+ return nil, err
+ }
+ return append(out, '\n'), nil
+}
diff --git a/internal/plans/export_test.go b/internal/plans/export_test.go
new file mode 100644
index 000000000..7a873c7a1
--- /dev/null
+++ b/internal/plans/export_test.go
@@ -0,0 +1,109 @@
+package plans
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+)
+
+const examplePublicPath = "testdata/example-public-pricebook.json"
+
+type exportShape struct {
+ Schema int `json:"schema"`
+ PriceBook string `json:"price_book"`
+ PriceBookID string `json:"price_book_id"`
+ Status string `json:"status"`
+ CatalogVersion string `json:"catalog_version"`
+ CatalogID string `json:"catalog_id"`
+ DefaultCurrency string `json:"default_currency"`
+ CountryCurrency map[string]string `json:"country_currency"`
+ Plans []struct {
+ Key string `json:"key"`
+ Paid bool `json:"paid"`
+ MemoryMB int `json:"memory_mb"`
+ } `json:"plans"`
+ Packs []struct {
+ Key string `json:"key"`
+ } `json:"packs"`
+}
+
+func exampleExport(t *testing.T) (raw []byte, e exportShape) {
+ t.Helper()
+ raw, err := PublicExport(exampleCatalog(t), exampleBook(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(raw, &e); err != nil {
+ t.Fatal(err)
+ }
+ return raw, e
+}
+
+// The golden is written by the command (go run ./cmd/pricebook-export ...),
+// never by hand.
+func TestPublicExportGolden(t *testing.T) {
+ raw, _ := exampleExport(t)
+ want, err := os.ReadFile(examplePublicPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(raw, want) {
+ t.Errorf("export differs from %s:\n%s", examplePublicPath, raw)
+ }
+}
+
+func TestPublicExportOrder(t *testing.T) {
+ raw, e := exampleExport(t)
+ var plans, packs []string
+ for _, p := range e.Plans {
+ plans = append(plans, p.Key)
+ }
+ for _, p := range e.Packs {
+ packs = append(packs, p.Key)
+ }
+ if !slices.Equal(plans, []string{"free", "personal"}) {
+ t.Errorf("plans = %v", plans)
+ }
+ if !slices.IsSorted(packs) || len(packs) != 4 {
+ t.Errorf("packs = %v", packs)
+ }
+ if e.Schema != 2 || e.Status != "draft" || e.PriceBook != "example-v1" || !strings.HasPrefix(e.PriceBookID, "example-v1@") ||
+ e.CatalogVersion != "2026-10-20-v1" || !strings.HasPrefix(e.CatalogID, "2026-10-20-v1@") || e.DefaultCurrency != "usd" {
+ t.Errorf("header = %+v", e)
+ }
+ if !bytes.HasSuffix(raw, []byte("}\n")) {
+ t.Error("export does not end in a newline")
+ }
+ // Field order is part of the contract: schema first, packs last.
+ if !bytes.HasPrefix(raw, []byte("{\n \"schema\": 2,\n \"price_book\": ")) {
+ t.Errorf("export does not open with schema, price_book: %.60s", raw)
+ }
+ // Provider price ids never reach the export.
+ if bytes.Contains(raw, []byte("price_")) && bytes.Contains(raw, []byte("\"price_1")) {
+ t.Error("export carries a provider price id")
+ }
+}
+
+func TestPublicExportMemory(t *testing.T) {
+ _, e := exampleExport(t)
+ got := map[string]int{}
+ for _, p := range e.Plans {
+ got[p.Key] = p.MemoryMB
+ }
+ if got["personal"] != 512 || got["free"] != 0 {
+ t.Errorf("memory_mb = %v, want personal 512 and free 0", got)
+ }
+}
+
+func TestPublicExportCountryMap(t *testing.T) {
+ _, e := exampleExport(t)
+ if e.CountryCurrency["IE"] != "eur" || e.CountryCurrency["GB"] != "gbp" {
+ t.Errorf("country_currency IE %q GB %q", e.CountryCurrency["IE"], e.CountryCurrency["GB"])
+ }
+ if _, ok := e.CountryCurrency["US"]; ok {
+ t.Error("US is in country_currency: the default currency needs no entry")
+ }
+}
diff --git a/internal/plans/pricebook.go b/internal/plans/pricebook.go
new file mode 100644
index 000000000..c8b1959e4
--- /dev/null
+++ b/internal/plans/pricebook.go
@@ -0,0 +1,298 @@
+package plans
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "slices"
+ "strings"
+)
+
+// A price book prices a catalog (spec §3, §9.3): one annual, tax-exclusive
+// price per paid plan and per pack, in each currency the book sells in.
+// It is a deployment's configured file, versioned and bound to one catalog
+// version. Nothing is ever converted between currencies.
+//
+// A book carries no billing provider's identifiers. Those live only in the
+// console's configuration, keyed by price key, so neither this file nor
+// the public export built from it can leak them.
+
+// A book's status. A live console refuses a draft (spec §3).
+const (
+ BookDraft = "draft"
+ BookApproved = "approved"
+)
+
+// SoldCurrencies is every currency a book may sell in, lower case as the
+// billing provider writes them. All three have 100 minor units to the
+// major unit; another currency needs code, not a book edit.
+var SoldCurrencies = []string{"usd", "eur", "gbp"}
+
+// ErrCurrencyNotSold refuses an explicit currency the book does not sell.
+// It is never replaced by one the buyer did not ask for.
+var ErrCurrencyNotSold = errors.New("currency not sold")
+
+// maxPriceMinor bounds one price: a million in major units.
+const maxPriceMinor = 100_000_000
+
+// PriceBook is one version of a deployment's prices.
+type PriceBook struct {
+ Version string `json:"version"`
+ Status string `json:"status"`
+ CatalogVersion string `json:"catalog_version"`
+ DefaultCurrency string `json:"default_currency"`
+ Currencies []string `json:"currencies"`
+ CountryCurrency map[string][]string `json:"country_currency"` // currency -> ISO 3166-1 alpha-2, upper case
+ Plans map[string]map[string]int64 `json:"plans"` // paid plan -> currency -> annual minor units
+ Packs map[string]map[string]int64 `json:"packs"` // pack -> currency -> annual minor units per unit
+
+ digest string
+ byCountry map[string]string
+}
+
+// LoadPriceBook reads and parses the book at path against cat.
+func LoadPriceBook(path string, cat *Catalog) (*PriceBook, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ book, err := ParsePriceBook(b, cat)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", path, err)
+ }
+ return book, nil
+}
+
+// ParsePriceBook parses and validates a book against the catalog it
+// prices. Unknown fields, duplicate keys and trailing content are refused:
+// each would let one price silently stand in for another.
+func ParsePriceBook(b []byte, cat *Catalog) (*PriceBook, error) {
+ if err := rejectDuplicateKeys(b); err != nil {
+ return nil, fmt.Errorf("price book: %w", err)
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ var book PriceBook
+ if err := dec.Decode(&book); err != nil {
+ return nil, fmt.Errorf("price book: %w", err)
+ }
+ if err := dec.Decode(new(json.RawMessage)); err != io.EOF {
+ return nil, errors.New("price book: trailing content after the JSON document")
+ }
+ if err := book.validate(cat); err != nil {
+ return nil, fmt.Errorf("price book: %w", err)
+ }
+ canon, err := json.Marshal(book) // map keys marshal sorted: canonical
+ if err != nil {
+ return nil, err
+ }
+ sum := sha256.Sum256(canon)
+ book.digest = hex.EncodeToString(sum[:])[:12]
+ return &book, nil
+}
+
+// ID names this book's exact content: its version and a digest, as
+// Catalog.ID does.
+func (b *PriceBook) ID() string { return b.Version + "@" + b.digest }
+
+// Digest is the content digest alone. A console refuses a book whose
+// digest changed under a version it has already started with.
+func (b *PriceBook) Digest() string { return b.digest }
+
+// Approved reports whether the book may price a live deployment.
+func (b *PriceBook) Approved() bool { return b.Status == BookApproved }
+
+// PlanPrice is the annual price of a paid plan in currency, in minor units.
+func (b *PriceBook) PlanPrice(plan, currency string) (int64, bool) {
+ v, ok := b.Plans[plan][currency]
+ return v, ok
+}
+
+// PackPrice is the annual price of one unit of a pack in currency.
+func (b *PriceBook) PackPrice(pack, currency string) (int64, bool) {
+ v, ok := b.Packs[pack][currency]
+ return v, ok
+}
+
+// ChooseCurrency is the one rule for a purchase's currency. An explicit
+// currency must be one the book sells, exactly as written. With none, the
+// billing country's currency, then the book's default.
+func (b *PriceBook) ChooseCurrency(explicit, country string) (string, error) {
+ if explicit != "" {
+ if !slices.Contains(b.Currencies, explicit) {
+ return "", fmt.Errorf("%w: %q", ErrCurrencyNotSold, explicit)
+ }
+ return explicit, nil
+ }
+ if c, ok := b.byCountry[strings.ToUpper(country)]; ok {
+ return c, nil
+ }
+ return b.DefaultCurrency, nil
+}
+
+func (b *PriceBook) validate(cat *Catalog) error {
+ if b.Version == "" {
+ return errors.New("version is required")
+ }
+ if b.Status != BookDraft && b.Status != BookApproved {
+ return fmt.Errorf("status %q is neither %q nor %q", b.Status, BookDraft, BookApproved)
+ }
+ if b.CatalogVersion != cat.Version {
+ return fmt.Errorf("catalog_version %q is not the catalog's %q", b.CatalogVersion, cat.Version)
+ }
+ if len(b.Currencies) == 0 {
+ return errors.New("no currencies")
+ }
+ sold := map[string]bool{}
+ for _, c := range b.Currencies {
+ if !slices.Contains(SoldCurrencies, c) {
+ return fmt.Errorf("currency %q is not one of %v", c, SoldCurrencies)
+ }
+ if sold[c] {
+ return fmt.Errorf("currency %q is listed twice", c)
+ }
+ sold[c] = true
+ }
+ if !sold[b.DefaultCurrency] {
+ return fmt.Errorf("default_currency %q is not one of the book's currencies", b.DefaultCurrency)
+ }
+ b.byCountry = map[string]string{}
+ for c, countries := range b.CountryCurrency {
+ if !sold[c] {
+ return fmt.Errorf("country_currency names %q, which the book does not sell in", c)
+ }
+ if c == b.DefaultCurrency {
+ return fmt.Errorf("country_currency lists the default currency %q: the default needs no country list", c)
+ }
+ for _, country := range countries {
+ if !isAlpha2(country) {
+ return fmt.Errorf("country_currency[%q] has %q, which is not an upper-case ISO 3166-1 alpha-2 code", c, country)
+ }
+ if other, dup := b.byCountry[country]; dup {
+ return fmt.Errorf("country %s is given both %q and %q", country, other, c)
+ }
+ b.byCountry[country] = c
+ }
+ }
+
+ offered := map[string]bool{}
+ for name, p := range cat.Plans {
+ if !p.Paid {
+ if _, priced := b.Plans[name]; priced {
+ return fmt.Errorf("plan %q is not paid and may not be priced", name)
+ }
+ continue
+ }
+ if name == "pack" {
+ return fmt.Errorf("a paid plan may not be named %q: its price keys would collide with the packs'", name)
+ }
+ if err := b.priced("plan", name, b.Plans[name], sold); err != nil {
+ return err
+ }
+ for _, pk := range p.Packs {
+ offered[pk] = true
+ }
+ }
+ for name := range b.Plans {
+ if _, ok := cat.Plans[name]; !ok {
+ return fmt.Errorf("%w: the book prices plan %q", ErrUnknownPlan, name)
+ }
+ }
+ for name := range offered {
+ if err := b.priced("pack", name, b.Packs[name], sold); err != nil {
+ return err
+ }
+ }
+ for name := range b.Packs {
+ if _, ok := cat.Packs[name]; !ok {
+ return fmt.Errorf("%w: the book prices pack %q", ErrUnknownPack, name)
+ }
+ if !offered[name] {
+ return fmt.Errorf("pack %q is priced but no paid plan offers it", name)
+ }
+ }
+ return nil
+}
+
+// priced checks that one plan or pack has a price in exactly the book's
+// currencies, each within bounds.
+func (b *PriceBook) priced(kind, name string, prices map[string]int64, sold map[string]bool) error {
+ if prices == nil {
+ return fmt.Errorf("%s %q is not priced", kind, name)
+ }
+ for c := range sold {
+ v, ok := prices[c]
+ if !ok {
+ return fmt.Errorf("%s %q has no %s price", kind, name, c)
+ }
+ if v <= 0 {
+ return fmt.Errorf("%s %q in %s: price must be positive", kind, name, c)
+ }
+ if v > maxPriceMinor {
+ return fmt.Errorf("%s %q in %s: price is too large", kind, name, c)
+ }
+ }
+ for c := range prices {
+ if !sold[c] {
+ return fmt.Errorf("%s %q is priced in %q, which the book does not sell in", kind, name, c)
+ }
+ }
+ return nil
+}
+
+func isAlpha2(s string) bool {
+ return len(s) == 2 && s[0] >= 'A' && s[0] <= 'Z' && s[1] >= 'A' && s[1] <= 'Z'
+}
+
+// rejectDuplicateKeys walks a JSON document and refuses one in which an
+// object has the same key twice, at any depth. encoding/json would keep
+// the last and say nothing: in a price list, one price silently replacing
+// another.
+func rejectDuplicateKeys(data []byte) error {
+ dec := json.NewDecoder(bytes.NewReader(data))
+ var walk func() error
+ walk = func() error {
+ tok, err := dec.Token()
+ if err != nil {
+ return err
+ }
+ delim, ok := tok.(json.Delim)
+ if !ok {
+ return nil
+ }
+ switch delim {
+ case '{':
+ seen := map[string]bool{}
+ for dec.More() {
+ keyTok, err := dec.Token()
+ if err != nil {
+ return err
+ }
+ // Folded: encoding/json matches a struct field without
+ // regard to case, so "eur" and "EUR" would be one field.
+ key := strings.ToLower(keyTok.(string))
+ if seen[key] {
+ return fmt.Errorf("the key %q appears twice in one object", key)
+ }
+ seen[key] = true
+ if err := walk(); err != nil {
+ return err
+ }
+ }
+ case '[':
+ for dec.More() {
+ if err := walk(); err != nil {
+ return err
+ }
+ }
+ }
+ _, err = dec.Token() // the closing delimiter
+ return err
+ }
+ return walk()
+}
diff --git a/internal/plans/pricebook_test.go b/internal/plans/pricebook_test.go
new file mode 100644
index 000000000..ed3dedfdf
--- /dev/null
+++ b/internal/plans/pricebook_test.go
@@ -0,0 +1,192 @@
+package plans
+
+import (
+ "errors"
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// The example book's pack amounts are placeholders: pack prices are Paul's
+// to set (spec §4.2), and the book refuses unknown fields, so it cannot say
+// so itself. Personal's 2800/2400/2200 are the draft book's figures.
+const exampleBookPath = "testdata/example-pricebook.json"
+
+func exampleBookBytes(t *testing.T) string {
+ t.Helper()
+ b, err := os.ReadFile(exampleBookPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+func exampleBook(t *testing.T) *PriceBook {
+ t.Helper()
+ b, err := LoadPriceBook(exampleBookPath, exampleCatalog(t))
+ if err != nil {
+ t.Fatalf("load example book: %v", err)
+ }
+ return b
+}
+
+func TestParsePriceBookExample(t *testing.T) {
+ b := exampleBook(t)
+ if !regexp.MustCompile(`^example-v1@[0-9a-f]{12}$`).MatchString(b.ID()) {
+ t.Errorf("ID = %q", b.ID())
+ }
+ if b.ID() != b.Version+"@"+b.Digest() {
+ t.Errorf("ID %q is not version@digest (%q)", b.ID(), b.Digest())
+ }
+ if b.Approved() {
+ t.Error("example book is a draft, Approved() = true")
+ }
+ if got, ok := b.PlanPrice("personal", "gbp"); !ok || got != 2200 {
+ t.Errorf("PlanPrice(personal, gbp) = %d, %v", got, ok)
+ }
+ if got, ok := b.PackPrice("apps", "usd"); !ok || got != 600 {
+ t.Errorf("PackPrice(apps, usd) = %d, %v", got, ok)
+ }
+ if _, ok := b.PlanPrice("free", "usd"); ok {
+ t.Error("PlanPrice(free) found a price")
+ }
+ if _, ok := b.PackPrice("apps", "jpy"); ok {
+ t.Error("PackPrice(apps, jpy) found a price")
+ }
+}
+
+func TestPriceBookRefusesGaps(t *testing.T) {
+ base := exampleBookBytes(t)
+ cases := []struct {
+ name, from, to, want string
+ }{
+ {"personal missing gbp", `"personal": {"usd": 2800, "eur": 2400, "gbp": 2200}`, `"personal": {"usd": 2800, "eur": 2400}`, `plan "personal"`},
+ {"pack email missing", `"email": {"usd": 300, "eur": 250, "gbp": 230},`, ``, `pack "email"`},
+ {"extra pack seats", `"packs": {`, `"packs": {"seats": {"usd": 1, "eur": 1, "gbp": 1},`, `no such pack`},
+ {"extra plan", `"plans": {`, `"plans": {"business": {"usd": 1, "eur": 1, "gbp": 1},`, `no such plan`},
+ {"free plan priced", `"plans": {`, `"plans": {"free": {"usd": 1, "eur": 1, "gbp": 1},`, `plan "free"`},
+ {"amount zero", `"usd": 2800`, `"usd": 0`, `must be positive`},
+ {"amount negative", `"usd": 2800`, `"usd": -1`, `must be positive`},
+ {"amount too large", `"usd": 2800`, `"usd": 100000001`, `too large`},
+ {"currency USD", `"currencies": ["usd", "eur", "gbp"]`, `"currencies": ["USD", "eur", "gbp"]`, `currency`},
+ {"currency jpy", `"currencies": ["usd", "eur", "gbp"]`, `"currencies": ["usd", "eur", "gbp", "jpy"]`, `currency`},
+ {"currency twice", `"currencies": ["usd", "eur", "gbp"]`, `"currencies": ["usd", "eur", "gbp", "eur"]`, `currency`},
+ {"no currencies", `"currencies": ["usd", "eur", "gbp"]`, `"currencies": []`, `currenc`},
+ {"default not sold", `"default_currency": "usd"`, `"default_currency": "jpy"`, `default_currency`},
+ {"status live", `"status": "draft"`, `"status": "live"`, `status`},
+ {"no version", `"version": "example-v1"`, `"version": ""`, `version`},
+ {"country lower case", `"gbp": ["GB"]`, `"gbp": ["gb"]`, `country`},
+ {"country three letters", `"gbp": ["GB"]`, `"gbp": ["GBR"]`, `country`},
+ {"country under two currencies", `"gbp": ["GB"]`, `"gbp": ["GB", "IE"]`, `country`},
+ {"country under the default", `"gbp": ["GB"]`, `"gbp": ["GB"], "usd": ["US"]`, `country`},
+ {"country currency not sold", `"currencies": ["usd", "eur", "gbp"]`, `"currencies": ["usd", "eur"]`, `gbp`},
+ {"catalog version mismatch", `"catalog_version": "2026-10-20-v1"`, `"catalog_version": "2026-01-01-v0"`, `catalog_version`},
+ {"unknown field", `"status": "draft",`, `"status": "draft", "stripe_prices": {},`, `unknown field`},
+ {"duplicate key", `"personal": {"usd": 2800,`, `"personal": {"usd": 2800, "usd": 2900,`, `twice`},
+ {"trailing content", `"bandwidth": {"usd": 1800, "eur": 1500, "gbp": 1400}
+ }
+}`, `"bandwidth": {"usd": 1800, "eur": 1500, "gbp": 1400}
+ }
+} {}`, `trailing`},
+ }
+ cat := exampleCatalog(t)
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if !strings.Contains(base, tc.from) {
+ t.Fatalf("mutation source %q not in the example book", tc.from)
+ }
+ _, err := ParsePriceBook([]byte(strings.Replace(base, tc.from, tc.to, 1)), cat)
+ if err == nil {
+ t.Fatal("accepted")
+ }
+ if !strings.Contains(err.Error(), tc.want) {
+ t.Errorf("error %q does not contain %q", err, tc.want)
+ }
+ })
+ }
+}
+
+// A paid plan named "pack" would collide with the pack price keys
+// (<book>/pack/<name>/<cur>), so the book refuses it.
+func TestPriceBookRefusesPaidPlanNamedPack(t *testing.T) {
+ cat := exampleCatalog(t)
+ p := cat.Plans["personal"]
+ cat.Plans["pack"] = p
+ delete(cat.Plans, "personal")
+ book := strings.Replace(exampleBookBytes(t), `"personal": {`, `"pack": {`, 1)
+ if _, err := ParsePriceBook([]byte(book), cat); err == nil || !strings.Contains(err.Error(), `"pack"`) {
+ t.Fatalf("err = %v, want a refusal naming \"pack\"", err)
+ }
+}
+
+func TestPriceBookIDChangesWithContent(t *testing.T) {
+ cat := exampleCatalog(t)
+ a := exampleBook(t)
+ b, err := ParsePriceBook([]byte(strings.Replace(exampleBookBytes(t), `"status": "draft"`, `"status": "approved"`, 1)), cat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !b.Approved() {
+ t.Error("approved book: Approved() = false")
+ }
+ if a.Digest() == b.Digest() {
+ t.Errorf("draft and approved under one version share digest %q", a.Digest())
+ }
+ c, err := ParsePriceBook([]byte(strings.Replace(exampleBookBytes(t), `"usd": 2800`, `"usd": 2900`, 1)), cat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a.ID() == c.ID() || a.Version != c.Version {
+ t.Errorf("one price changed: IDs %q and %q", a.ID(), c.ID())
+ }
+}
+
+func TestChooseCurrency(t *testing.T) {
+ b := exampleBook(t)
+ for _, tc := range []struct{ explicit, country, want string }{
+ {"", "DE", "eur"},
+ {"", "gb", "gbp"},
+ {"", "US", "usd"},
+ {"", "", "usd"},
+ {"gbp", "DE", "gbp"},
+ } {
+ got, err := b.ChooseCurrency(tc.explicit, tc.country)
+ if err != nil || got != tc.want {
+ t.Errorf("ChooseCurrency(%q, %q) = %q, %v; want %q", tc.explicit, tc.country, got, err, tc.want)
+ }
+ }
+ for _, tc := range []struct{ explicit, country string }{{"jpy", "US"}, {"USD", "US"}} {
+ if got, err := b.ChooseCurrency(tc.explicit, tc.country); !errors.Is(err, ErrCurrencyNotSold) {
+ t.Errorf("ChooseCurrency(%q, %q) = %q, %v; want ErrCurrencyNotSold", tc.explicit, tc.country, got, err)
+ }
+ }
+
+ // A book selling only usd and eur.
+ src := exampleBookBytes(t)
+ for _, r := range [][2]string{
+ {`"currencies": ["usd", "eur", "gbp"]`, `"currencies": ["usd", "eur"]`},
+ {`,
+ "gbp": ["GB"]`, ``},
+ {`"personal": {"usd": 2800, "eur": 2400, "gbp": 2200}`, `"personal": {"usd": 2800, "eur": 2400}`},
+ {`"apps": {"usd": 600, "eur": 500, "gbp": 450}`, `"apps": {"usd": 600, "eur": 500}`},
+ {`"storage": {"usd": 1200, "eur": 1000, "gbp": 900}`, `"storage": {"usd": 1200, "eur": 1000}`},
+ {`"email": {"usd": 300, "eur": 250, "gbp": 230}`, `"email": {"usd": 300, "eur": 250}`},
+ {`"bandwidth": {"usd": 1800, "eur": 1500, "gbp": 1400}`, `"bandwidth": {"usd": 1800, "eur": 1500}`},
+ } {
+ if !strings.Contains(src, r[0]) {
+ t.Fatalf("%q not in the example book", r[0])
+ }
+ src = strings.Replace(src, r[0], r[1], 1)
+ }
+ two, err := ParsePriceBook([]byte(src), exampleCatalog(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := two.ChooseCurrency("gbp", "GB"); !errors.Is(err, ErrCurrencyNotSold) {
+ t.Errorf("usd+eur book: ChooseCurrency(gbp, GB) = %q, %v; want ErrCurrencyNotSold", got, err)
+ }
+ if got, err := two.ChooseCurrency("", "GB"); err != nil || got != "usd" {
+ t.Errorf("usd+eur book: ChooseCurrency(\"\", GB) = %q, %v; want usd", got, err)
+ }
+}
diff --git a/internal/plans/testdata/example-pricebook.json b/internal/plans/testdata/example-pricebook.json
new file mode 100644
index 000000000..bff5ce431
--- /dev/null
+++ b/internal/plans/testdata/example-pricebook.json
@@ -0,0 +1,20 @@
+{
+ "version": "example-v1",
+ "status": "draft",
+ "catalog_version": "2026-10-20-v1",
+ "default_currency": "usd",
+ "currencies": ["usd", "eur", "gbp"],
+ "country_currency": {
+ "eur": ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE"],
+ "gbp": ["GB"]
+ },
+ "plans": {
+ "personal": {"usd": 2800, "eur": 2400, "gbp": 2200}
+ },
+ "packs": {
+ "apps": {"usd": 600, "eur": 500, "gbp": 450},
+ "storage": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "email": {"usd": 300, "eur": 250, "gbp": 230},
+ "bandwidth": {"usd": 1800, "eur": 1500, "gbp": 1400}
+ }
+}
diff --git a/internal/plans/testdata/example-public-pricebook.json b/internal/plans/testdata/example-public-pricebook.json
new file mode 100644
index 000000000..f44752764
--- /dev/null
+++ b/internal/plans/testdata/example-public-pricebook.json
@@ -0,0 +1,163 @@
+{
+ "schema": 2,
+ "price_book": "example-v1",
+ "price_book_id": "example-v1@5abc547e3db4",
+ "status": "draft",
+ "catalog_version": "2026-10-20-v1",
+ "catalog_id": "2026-10-20-v1@7a9ba092f2c0",
+ "default_currency": "usd",
+ "currencies": [
+ {
+ "code": "usd",
+ "symbol": "$",
+ "minor_per_major": 100
+ },
+ {
+ "code": "eur",
+ "symbol": "€",
+ "minor_per_major": 100
+ },
+ {
+ "code": "gbp",
+ "symbol": "£",
+ "minor_per_major": 100
+ }
+ ],
+ "country_currency": {
+ "AT": "eur",
+ "BE": "eur",
+ "BG": "eur",
+ "CY": "eur",
+ "CZ": "eur",
+ "DE": "eur",
+ "DK": "eur",
+ "EE": "eur",
+ "ES": "eur",
+ "FI": "eur",
+ "FR": "eur",
+ "GB": "gbp",
+ "GR": "eur",
+ "HR": "eur",
+ "HU": "eur",
+ "IE": "eur",
+ "IT": "eur",
+ "LT": "eur",
+ "LU": "eur",
+ "LV": "eur",
+ "MT": "eur",
+ "NL": "eur",
+ "PL": "eur",
+ "PT": "eur",
+ "RO": "eur",
+ "SE": "eur",
+ "SI": "eur",
+ "SK": "eur"
+ },
+ "free_accounts_per_person": 1,
+ "plans": [
+ {
+ "key": "free",
+ "paid": false,
+ "default": true,
+ "annual_minor": {},
+ "memory_mb": 0,
+ "limits": {
+ "running_things": 3,
+ "sidecars_per_app": 1,
+ "idle_seconds": 90,
+ "memory_tier": "small",
+ "awake_hours_month": 100,
+ "disk_bytes": 1073741824,
+ "storage_bytes": 1073741824,
+ "email_per_day": 50,
+ "bandwidth_bytes_month": 10737418240,
+ "min_schedule_seconds": 900
+ },
+ "packs": []
+ },
+ {
+ "key": "personal",
+ "paid": true,
+ "default": false,
+ "annual_minor": {
+ "eur": 2400,
+ "gbp": 2200,
+ "usd": 2800
+ },
+ "memory_mb": 512,
+ "limits": {
+ "running_things": 25,
+ "sidecars_per_app": 5,
+ "idle_seconds": 900,
+ "memory_tier": "default",
+ "awake_hours_month": 1500,
+ "disk_bytes": 10737418240,
+ "storage_bytes": 26843545600,
+ "storage_self_serve": true,
+ "email_per_day": 1000,
+ "bandwidth_bytes_month": 53687091200,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 60,
+ "history_days": 7
+ },
+ "packs": [
+ "apps",
+ "bandwidth",
+ "email",
+ "storage"
+ ]
+ }
+ ],
+ "packs": [
+ {
+ "key": "apps",
+ "adds": {
+ "running_things": 5
+ },
+ "max_quantity": 20,
+ "annual_minor": {
+ "eur": 500,
+ "gbp": 450,
+ "usd": 600
+ }
+ },
+ {
+ "key": "bandwidth",
+ "adds": {
+ "bandwidth_bytes_month": 214748364800
+ },
+ "max_quantity": 20,
+ "annual_minor": {
+ "eur": 1500,
+ "gbp": 1400,
+ "usd": 1800
+ }
+ },
+ {
+ "key": "email",
+ "adds": {
+ "email_per_day": 1000
+ },
+ "max_quantity": 20,
+ "annual_minor": {
+ "eur": 250,
+ "gbp": 230,
+ "usd": 300
+ }
+ },
+ {
+ "key": "storage",
+ "adds": {
+ "disk_bytes": 10737418240,
+ "storage_bytes": 53687091200
+ },
+ "max_quantity": 20,
+ "annual_minor": {
+ "eur": 1000,
+ "gbp": 900,
+ "usd": 1200
+ }
+ }
+ ]
+}