Plans 6a: price book (shared with Plan 7 Task 1), provider-neutral billing boundary, harvested Stripe adapter, and plan sync from webhooks and an hourly pass; 6b and 6c outlined; Calls for Paul on decisions 1-8, 15 and pack prices
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+757
−0
docs/superpowers/plans/2026-10-25-plans-6a-checkout.md+757 −0
CI passed — run details
diff --git a/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md| new file mode 100644 |
| index 000000000..da7d4277c |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md |
| @@ -0,0 +1,757 @@ |
| +# Plans 6a: Price Book, Billing Adapter and Plan Sync Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A console with billing configured keeps each paying account's plan row in step with its subscription at the billing provider. Paid, past due and pack quantities lift the account; an ended subscription drops it to the default plan. Nobody can buy anything yet: checkout, pack changes, the portal and the billing page are Plan 6b. |
| + |
| +**Architecture:** |
| +- **Price book:** consumed from Plan 7 Task 1 (the pricing page plan, written in parallel), which puts a slim book in `internal/plans`. It is a configured, versioned file pricing every paid plan and every pack in usd, eur and gbp, tied to a catalog version, draft or approved. Plan 7 also owns the schema-2 public export and the `pricebook-export` command. This plan's Task 1 is that same book, **shared with Plan 7 Task 1, whichever lands first**. On top of it, 6a adds two things: a live console refuses a draft, and a book whose content changes under the same version is refused (approval is a new version). |
| +- **Provider boundary** (`internal/billing`): neutral types (`Subscription`, `Event`, `PriceMap`, `Purchase`), the `Provider` interface, and `Recognise`, which turns a subscription's set of items into a plan and packs. The console imports only this package. |
| +- **Stripe adapter** (`internal/billingstripe`): harvested from `165472b8` minus `invoices.go`, stripped of bands, terms and the legacy path, plus `adapter.go` implementing `billing.Provider`. |
| +- **Plan sync** (`internal/console`): every webhook and an hourly pass re-read the subscription from the provider (never the event body), run a pure decision function, and write the plan row through the same store upsert the operator door uses, guarded so billing writes only rows it owns and writes nothing when nothing changed. The existing limits pass publishes the record. |
| + |
| +**Tech Stack:** Go, stdlib only (no stripe-go); SQLite console store; `internal/plans`, new `internal/billing`, `internal/billingstripe`, `internal/console`, `cmd/console`, the `carlos` CLI at the repo root. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| +- §9.1 (one annual subscription per account, Personal quantity 1 plus one item per pack type; reductions at renewal); |
| +- §9.2 (paid limits while the provider retries; free limits when the subscription ends; the disable and delete lifecycle is Plan 4d, not this plan); |
| +- §9.3 (one price per currency, no bands); |
| +- §9.4 (what to harvest from `165472b8` and what to leave; the several-items rework); |
| +- §9.5 (decisions 1 to 8, 9 and 15: proposed in Calls for Paul below); |
| +- §3 (settled rulings: currencies, draft book refusal, restricted keys in the EnvironmentFile, no hostname activation); |
| +- §10 (provider boundary). |
| + |
| +Builds on Plans 1, 2, 3a, 3b, 4a, 4b and 4c, merged. Plan 4d (lapse lifecycle) is being planned in parallel: this plan only lowers the plan row and lets 4a/4d act on it. |
| + |
| +## Scope split (Plan 6) |
| + |
| +- **6a (this plan):** the price book (shared with Plan 7 Task 1), provider boundary, Stripe adapter, config and readiness, billing state tables, plan sync from webhooks and an hourly pass, operator view of billing problems. Nothing user-facing changes. |
| +- **6b (outline at the end):** customer and Checkout (upgrade from free), pack quantity changes, stop and resume renewal, the locked portal, the billing page, the house flag. |
| +- **6c (outline at the end):** the Stripe setup runbook, test mode on dev first, then live, every live step Paul's. |
| + |
| +## Calls for Paul |
| + |
| +Each has a recommendation. Decisions 1 to 8 and 15 are the old `DECISIONS-FOR-PAUL.md` items (at `165472b8:implementation/carloku-paid-launch/DECISIONS-FOR-PAUL.md`) recast for v1. The recast is possible because v1 drops the old design's intents-as-identity: **the customer the console creates for an account is the identity** (6b creates it before Checkout; the restricted key cannot create subscriptions by any other route). 6a builds to recommendations 1 to 4, the `PaidPacks` half of 6, and 10 to 14; 6b builds the rest; 15 and 16 are Paul's numbers and catalog. |
| + |
| +1. **Money taken on a refused purchase (decision 1).** A subscription the console cannot recognise (wrong prices, mixed currencies, a second live subscription) never changes the plan and is never kept as a one-off. The console opens a billing problem; the operator refunds and cancels in the Stripe Dashboard (the console's key has no refund permission, on purpose). **Recommend: as stated.** |
| +2. **What "settled" requires (decision 2).** The operator closes a problem with a note, after acting in Stripe. The console refuses the close while a fresh read shows the subscription still live (active, trialing, past due, incomplete or unpaid). It cannot see refunds (no charges permission), so "refunded" is the operator's word in the note. **Recommend: as stated.** The alternative, granting the key refund read access to check, widens the key for a rare case. |
| +3. **Stripe contradicting itself (decision 3).** There is no "contradiction" state in v1. Every event triggers a fresh read, and the latest read wins. Identity contradictions open a problem and leave the plan alone: the customer is not one the console bound, the metadata names another account, or the mode is wrong. **Recommend: as stated.** |
| +4. **A checkout the console never bound (decision 4).** Reversed from the old proposal: **keep it.** A subscription on the account's own customer whose items the book recognises is the purchase, whether or not a session was bound, because the customer is the identity. **Recommend: keep.** |
| +5. **What the buyer sees while a problem is open (decision 5).** The billing page (6b) shows a notice in place of the plan controls. Draft: "We're checking this purchase. Your plan hasn't changed yet, and nothing more will be charged." It is a console notice only until the console can email owners (§6 dependency). **Recommend: as stated, wording through the Luna pass.** |
| +6. **A pack reduced, then bought back before renewal (decision 6, recast).** A reduction is made at Stripe at once with proration `none`, so nothing is refunded and the renewal bills the lower count. The console keeps the period's highest paid quantity as the account's limit until the period ends (6a, `PaidPacks`). Buying back up to that quantity is set with proration `none` (no second charge); beyond it, the difference is prorated (6b). No subscription schedules and no 72-hour window. **Recommend: as stated.** |
| +7. **A missed reduction (decision 7, recast).** This can't happen: the reduction is on the subscription the moment the owner asks. If the Stripe call fails, the console says so and nothing changes. **Recommend: no credit-note path.** |
| +8. **Proration policy for additions (decision 8, recast).** Additions use `proration_behavior=always_invoice` with `payment_behavior=pending_if_incomplete`. The extra pack is charged now and granted only when paid: a failed card leaves the old quantity, not a past-due subscription. `create_prorations` would grant a year's pack against the next renewal's invoice. **Recommend: as stated, proven in the test-mode rehearsal (6c).** |
| +9. **Who is free on switch-on day (decision 9).** Answered by the spec (§3): existing accounts are sponsored, new accounts are free. Nothing to rule. |
| +10. **`incomplete_expired` (decision 15).** Treated as ended with nothing owed. A subscription that never left `incomplete` never changed the plan (6a: pending changes nothing), so its expiry changes nothing either, and nothing is held. **Recommend: yes.** The rehearsal still checks whether Checkout ever creates one. |
| +11. **Who owns the plan row.** Billing writes only rows whose source is `default` or `billing`. An `operator` or `sponsored` row is never overwritten. A paid subscription on such an account opens a `not_billing_owned` problem, and 6b refuses Checkout for those accounts up front. **Recommend: as stated.** |
| +12. **Statuses.** `active`, `trialing` and `past_due` keep paid limits (§9.2: "while Stripe retries"). `incomplete` changes nothing. `canceled`, `incomplete_expired`, `unpaid` and `paused` are ended. Stripe's "after all retries fail" setting is "cancel the subscription" (6c). **Recommend: as stated.** |
| +13. **No bands (spec §9.3, "Paul to confirm").** One price per plan or pack per currency. **Recommend: confirm.** |
| +14. **Price keys and where provider ids live.** The keys are the spec's, as Plan 7 uses them: `<book>/<plan>/<cur>` for each paid plan (today only `personal`, so `<book>/personal/<cur>`) and `<book>/pack/<name>/<cur>`. The plan name is the catalog's, not hard-coded. A paid plan named `pack` is refused, so the two forms can't collide. Provider price ids are **never** in the book or the public export. They live only in the console's `CARLOS_BILLING_PRICES`, keyed as above. Each Stripe price also carries `metadata[price_key]` equal to its key, so two packs at the same amount can't be swapped in the variable unnoticed. **Recommend: as stated.** |
| +15. **Pack prices (Paul's to set).** With the catalog's four packs, the book needs exactly **15 annual, tax-exclusive prices** in minor units (18 if Call 16 splits storage): |
| + |
| + | Item | usd | eur | gbp | |
| + | --- | --- | --- | --- | |
| + | plan `personal` | 2800 (draft) | 2400 (draft) | 2200 (draft) | |
| + | pack `apps` (+5 running things) | ? | ? | ? | |
| + | pack `storage` (+10 GB disk per running thing, +50 GB object storage) | ? | ? | ? | |
| + | pack `email` (+1,000 a day) | ? | ? | ? | |
| + | pack `bandwidth` (+200 GB a month) | ? | ? | ? | |
| + |
| + The pack names and increments are the example catalog's (`internal/plans/testdata/example-catalog.json`). If the deployed catalog differs, the book follows it. **Recommend:** Paul sets the four usd amounts. eur and gbp follow Personal's ratio (24/28 and 22/28), rounded to whole units, unless he says otherwise. Approving them is a new book version with `status: approved`. |
| +16. **Split the storage pack (open; raised by Plan 7).** Today one `storage` pack adds both 10 GB disk per running thing and 50 GB object storage. Plan 7 recommends two packs, `disk` and `objects`. Splitting is a catalog change (a new catalog version), and the book gains a fifth pack: 18 prices. Nothing in 6a depends on the answer: `Recognise` and the price map take whatever packs the catalog offers. **Recommend: decide with Plan 7, before the book is approved.** One argument for splitting: a buyer who only wants object storage shouldn't pay for disk on every running thing. |
| + |
| +## Global Constraints |
| + |
| +- **Dormant unless configured.** `CARLOS_BILLING` unset or `off` means: |
| + - `cfg.Billing == nil`; |
| + - `POST /billing/webhook` answers 404, the billing doors answer 409 `billing is off on this deployment`, and `StartBillingSyncPass` returns at once; |
| + - no billing table is written. |
| + |
| + Self-managed deployments are unaffected. Nothing switches on by hostname. |
| +- **Billing needs plans.** `CARLOS_BILLING=test|live` without `CARLOS_PLAN_CATALOG` is a configuration error at start. |
| +- **Modes and keys (§3).** |
| + - `test` needs an `rk_test_` key and `live` an `rk_live_` key, in `CARLOS_STRIPE_SECRET_KEY` from the console's EnvironmentFile. |
| + - Never a flag, a file path, the bucket or `carlos secrets set`. |
| + - The key is never logged: the client's `String`/`GoString` redact it. |
| +- **Draft refusal (§3).** `live` with a book whose `status` is not `approved` is a configuration error. `test` accepts a draft. |
| +- **Approval is a new version (§3).** The console stores each book version's digest the first time it starts with it. The same version with a different digest refuses to start: `price book <version> changed without a new version`. |
| +- **Currencies (§3):** exactly `usd`, `eur`, `gbp`, lower case. |
| + - A book may sell a subset. |
| + - An explicit currency not sold is refused (`plans.ErrCurrencyNotSold`), never defaulted. Upper case counts as not sold. |
| + - Default by billing country (EU member states `eur`, `GB` `gbp`, the rest `usd`), from the book's `country_currency` and `default_currency`. |
| + - Nothing is converted. |
| +- **Annual only.** Every price is yearly, licensed, per unit and tax-exclusive. The interval is code, not a book field. |
| +- **The event body is never trusted.** An event says which subscription to read. The plan follows only a fresh `Provider.Subscription` read, made under the account's lock. |
| +- **One writer of plan rows.** Billing writes through `Store.SetBillingPlan`, which shares `SetAccountPlan`'s upsert. Its guards: |
| + - source `default` or `billing` only (Call 11); |
| + - no write when plan, packs and source are unchanged, so 4c's throttle survives the hourly pass. |
| + |
| + It publishes through the operator door's best-effort `publishPlanNow`. The limits pass retries anything that misses. |
| +- **One console serves billing.** The per-account lock is in-process: the console runs as one process per deployment. |
| +- **Request budget.** |
| + - Stripe: one `GET /v1/subscriptions/{id}` per event and per live subscription per hourly pass, plus at most 16 reads (prices, products, account) per readiness check. |
| + - S3: nothing new. A plan change is the existing single limits-record PUT. |
| +- **No product name** in code, tests, copy or example data. Examples use neutral names (shop, example.com). |
| +- **Names:** no helper or type name containing `Record` (the record-write census matches on it). |
| +- **Copy:** operator CLI strings and door errors go in `billing_cli_copy.go` and `apibilling_copy.go`. Every human string gets a Luna pass (gpt-5.6-luna via codex) against Paul's house rules: no em dashes, a full stop and a new sentence, lower case for the CLI. Error fragments, diagnostics and JSON keys are left out. |
| +- **Census:** |
| + - new tables in `claimSQLTables` (`NonApp`); |
| + - the new worker in `claim_workers.go`, `cmd/console/main.go` and `testdata/claim-routes.txt`, with a claim fixture and a probe; |
| + - new routes in `testdata/claim-routes.txt` with fixtures and probes; |
| + - then `make census-card` and `make census-propose`. New units are hand-written decisions; Astra approves; decisions go to Paul. |
| +- **Tests:** TDD. |
| + - No network: console tests use `billingtest.Fake`, and adapter tests use an `httptest` Stripe. |
| + - Run touched packages only, with `-run`; CI runs the full suite. |
| + - Inject `now`. |
| + |
| +## Review Focus |
| + |
| +1. **An unchanged subscription writes nothing.** The hourly pass over a paid account whose subscription has not changed must not bump the revision, republish, or clear the 4c throttle (`SetAccountPlan` clears it on every write). Pinned in Task 6 (`TestSyncUnchangedKeepsThrottle`). |
| +2. **A sponsored or operator account is never overwritten by billing,** even if a subscription appears on its customer. Pinned in Task 5 (`TestSetBillingPlanLeavesSponsoredAndOperatorRows`) and Task 6 (`TestPaidSubscriptionOnSponsoredAccountOpensProblem`). |
| +3. **Events out of order.** A delayed `customer.subscription.updated` for a subscription that has since been deleted must leave the account on the default plan, because the fresh read says `canceled`. Pinned in Task 7 (`TestStaleEventAppliesTheFreshRead`). |
| +4. **A reduced pack keeps its limit until renewal,** a raise back within the period changes nothing, and the renewal (a new period end) drops it. Pinned in Task 6 (`TestPackReductionHoldsUntilRenewal`). |
| +5. **Stripe unreachable when the console starts.** The console serves, billing is not ready, the webhook answers 503 (Stripe retries for three days), no plan changes, and it becomes ready when Stripe answers. Pinned in Task 7 (`TestBillingNotReadyAnswers503ThenRecovers`). |
| + |
| +--- |
| + |
| +### Task 1: Price book (shared with Plan 7 Task 1, whichever lands first) |
| + |
| +Plan 7 (the pricing page, written in parallel) builds the slim book as its Task 1, because the page ships before checkout. |
| +- **If Plan 7 Task 1 has landed:** skip Steps 1 to 5 except anything in the "6a needs" list below that it lacks. Add those, with their tests, in this task. Use its names wherever they differ from the ones here, and update the later tasks' references to match. |
| +- **If this task lands first:** build the book below. Plan 7 then consumes it and adds the schema-2 public export and the `pricebook-export` command. Neither is built here. |
| + |
| +**Files:** |
| +- Create: `internal/plans/pricebook.go`, `internal/plans/testdata/example-pricebook.json`. |
| +- Test: `internal/plans/pricebook_test.go`. |
| +- Harvest from `165472b8:internal/plans/pricebook.go`: `rejectDuplicateKeys`, and the shape of `validateBook` and `ChooseCurrency`. Leave out: |
| + - bands, countries-as-bands, terms and overage; |
| + - the embedded books (the book is a deployment's configured file: production keeps the catalog and the book in the deployment's infrastructure repo, never in the binary); |
| + - the schema-1 public export (Plan 7 replaces it with schema 2). |
| + |
| +**Interfaces:** |
| +- Consumes: `plans.Catalog` (`Plans[name].Paid`, `Plans[name].Packs`, `Packs`, `Version`). |
| +- **6a needs from the book**, whoever builds it: |
| + ```go |
| + const (BookDraft = "draft"; BookApproved = "approved") |
| + var SoldCurrencies = []string{"usd", "eur", "gbp"} |
| + var ErrCurrencyNotSold = errors.New("currency not sold") |
| + 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 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 |
| + } |
| + func LoadPriceBook(path string, cat *Catalog) (*PriceBook, error) |
| + func ParsePriceBook(b []byte, cat *Catalog) (*PriceBook, error) |
| + func (b *PriceBook) ID() string // version + "@" + first 12 hex of sha256(canonical JSON), as Catalog.ID |
| + func (b *PriceBook) Digest() string // the 12 hex alone (Task 4's edit guard) |
| + func (b *PriceBook) Approved() bool |
| + func (b *PriceBook) ChooseCurrency(explicit, country string) (string, error) // 6b's checkout |
| + func (b *PriceBook) PlanPrice(plan, currency string) (int64, bool) // Task 3's price check |
| + func (b *PriceBook) PackPrice(pack, currency string) (int64, bool) |
| + ``` |
| + The book carries **no provider ids**: Stripe price ids live only in `CARLOS_BILLING_PRICES` (Task 2, Call 14). Neither the book nor the public export may grow a field for them. |
| +- Validation, in `ParsePriceBook`: |
| + - Unknown fields and duplicate keys are refused. |
| + - `version` is non-empty; `status` is draft or approved; `catalog_version == cat.Version`. |
| + - `currencies` is a non-empty, duplicate-free subset of `SoldCurrencies`, and `default_currency` is in it. |
| + - `country_currency` keys are sold currencies; codes match `^[A-Z]{2}$`; no code appears twice. |
| + - `plans` holds exactly the catalog's paid plans, `packs` exactly the union of packs those plans offer. Each is priced in every listed currency, with amounts from 1 to 100000000. A free plan with a price is refused, and so is a paid plan named `pack` (Call 14). |
| +- `ChooseCurrency` order: |
| + 1. A non-empty `explicit` must be exactly a listed currency, else `ErrCurrencyNotSold`. |
| + 2. Otherwise the country (upper-cased) is looked up. |
| + 3. Otherwise `default_currency`. |
| +- The example book: version `example-v1`, `draft`, catalog `2026-10-20-v1`. |
| + - Currencies: the EU-27 `eur` list and `GB` `gbp`, from `165472b8:internal/plans/pricebook.json`. |
| + - Personal: 2800/2400/2200. |
| + - Packs: **placeholder** amounts, marked as such in the test file's comment (the book refuses unknown fields, so it cannot carry a comment). |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestParsePriceBookExample(t *testing.T) // example book over example catalog: no error; ID "example-v1@<12hex>"; Approved false |
| + func TestPriceBookRefusesGaps(t *testing.T) // table: personal missing gbp; pack "email" missing; extra pack "seats"; free plan priced; amount 0; |
| + // currency "USD"; currency "jpy"; country "gb"; "GB" under two currencies; catalog_version mismatch; |
| + // unknown field; duplicate key "usd" twice in one object; each refused |
| + func TestPriceBookIDChangesWithContent(t *testing.T) // same version, status draft->approved: different Digest |
| + func TestChooseCurrency(t *testing.T) // ("", "DE") eur; ("", "gb") gbp; ("", "US") usd; ("", "") usd; ("gbp","DE") gbp; |
| + // ("jpy","US") ErrCurrencyNotSold; ("USD","US") ErrCurrencyNotSold; book selling only usd+eur: ("gbp","GB") ErrCurrencyNotSold, ("", "GB") usd |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/plans/ -run 'PriceBook|ChooseCurrency'`. Expected: FAIL (undefined `ParsePriceBook`). |
| +- [ ] **Step 3: Implement** in `pricebook.go`. |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/plans/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `plans: price book with draft/approved status and currency choice (plans 6a, shared with plans 7)`. |
| + |
| +### Task 2: Provider boundary |
| + |
| +**Files:** |
| +- Create: `internal/billing/billing.go` (types, `Provider`), `internal/billing/prices.go` (`PriceMap`), `internal/billing/recognise.go`, `internal/billing/billingtest/fake.go`. |
| +- Test: `internal/billing/prices_test.go`, `internal/billing/recognise_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's `PriceBook`; `plans.Catalog`. |
| +- Produces: |
| + ```go |
| + package billing |
| + type State string |
| + const (StatePaid State = "paid"; StatePending State = "pending"; StateEnded State = "ended") |
| + type Item struct { PriceID string; Quantity int64; Currency string } |
| + 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 (Call 12) |
| + 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 |
| + } |
| + type EventKind string |
| + const (EventSubscription EventKind = "subscription"; EventCheckout EventKind = "checkout"; EventIgnored EventKind = "ignored") |
| + type Event struct { ID string; Kind EventKind; Object string; LiveMode bool } // Object: subscription or checkout id |
| + var (ErrBadEvent = errors.New("billing: event refused"); ErrNotFound = errors.New("billing: not found")) |
| + type Provider interface { |
| + ParseEvent(raw []byte, header http.Header, now time.Time) (Event, error) // ErrBadEvent for any signature or shape failure |
| + Subscription(ctx context.Context, id string) (*Subscription, error) // ErrNotFound; any other error is transient |
| + CheckoutSubscription(ctx context.Context, checkoutID string) (string, error) // "" when the checkout made none |
| + Check(ctx context.Context, book *plans.PriceBook, prices PriceMap) error // the readiness check (Task 3) |
| + } |
| + |
| + type PriceRef struct { Book, Kind, Name, Currency string } // Kind "plan" | "pack" |
| + func (r PriceRef) Key() string // plan: "<book>/<name>/<currency>"; pack: "<book>/pack/<name>/<currency>" |
| + type PriceMap struct { /* byKey, byID */ } |
| + func ParsePriceMap(raw string, book *plans.PriceBook) (PriceMap, error) |
| + func (m PriceMap) Lookup(priceID string) (PriceRef, bool) |
| + func (m PriceMap) ID(r PriceRef) (string, bool) |
| + func (m PriceMap) Refs(book string) []PriceRef // sorted by Key |
| + |
| + type Purchase struct { Book, Currency, Plan string; Packs map[string]int } |
| + var ErrUnrecognised = errors.New("billing: subscription not recognised") |
| + func Recognise(sub *Subscription, prices PriceMap, cat *plans.Catalog) (Purchase, error) // errors wrap ErrUnrecognised with the reason |
| + ``` |
| +- `ParsePriceMap` rules: |
| + - The raw JSON object is at most 64 KiB. |
| + - Each key parses as `<book>/<plan>/<currency>` (three parts, a plan) or `<book>/pack/<name>/<currency>` (four parts, a pack), with the currency in `plans.SoldCurrencies`. Anything else is an error. |
| + - Each value matches `^price_[A-Za-z0-9]{1,250}$`, and no value appears twice. |
| + - Every plan and pack price of the configured book in each of its currencies is present. |
| + - Keys of other book versions are allowed: they recognise subscriptions bought under an earlier book, which keep it for life. |
| +- `Recognise` rules, each a distinct wrapped reason: |
| + - `ItemsComplete` is true. |
| + - Every item's price is in the map. |
| + - All items come from one book and are in one currency, equal to `sub.Currency`. |
| + - Exactly one `plan` item, quantity 1, naming a catalog plan with `Paid`. |
| + - Each pack appears at most once, is offered by that plan, and has quantity 1 to its `MaxQuantity`. |
| + - The book of an earlier version is not checked against the current one. Its keys alone carry book, kind, name and currency. |
| +- `billingtest.Fake` implements `Provider` in memory: |
| + - `Subs map[string]*billing.Subscription` and `Checkouts map[string]string`; |
| + - `Err error` (returned by every call when set), `CheckErr error`, `Calls int`; |
| + - `ParseEvent` accepts a JSON `{"id","kind","object","live"}` body with header `Fake-Signature: ok` and returns `ErrBadEvent` otherwise. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestParsePriceMap(t *testing.T) // full example set: ok; one missing key: error; duplicate price id under two keys: error; |
| + // "example-v0/personal/usd" extra: ok and Lookup finds Book "example-v0", Kind "plan"; "x/personal/jpy": error; "x/pack/apps": error; |
| + // value "prod_x": error; 64 KiB+1: error |
| + func TestRecognisePersonalWithPacks(t *testing.T) // personal x1 + apps x2 + email x1, all usd: Purchase{Plan "personal", Packs {"apps":2,"email":1}, Currency "usd", Book "example-v1"} |
| + func TestRecogniseRefuses(t *testing.T) // table, each errors.Is ErrUnrecognised: ItemsComplete false; unknown price; plan qty 2; no plan item; two plan items; |
| + // apps twice; apps qty 0; apps qty 21; eur pack on usd plan; sub.Currency "eur" with usd items; items from two books; |
| + // free plan priced under a hand-made key |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/billing/... -run 'PriceMap|Recognise'`. Expected: FAIL (package missing). |
| +- [ ] **Step 3: Implement** the four files. |
| +- [ ] **Step 4: Run** again. Expected: PASS. |
| +- [ ] **Step 5: Commit** `billing: provider-neutral subscription types, price map and item-set recognition (plans 6a)`. |
| + |
| +### Task 3: Stripe adapter (harvest) |
| + |
| +**Files:** |
| +- Create from `165472b8:internal/billingstripe/`: |
| + - `client.go`, `catalog.go`, `customer.go`, `merchant.go`, `portal.go` and `webhook.go`; |
| + - their `_test.go` files. |
| + |
| + Not taken: `invoices.go`, `invoices_test.go`, `sandbox_fence_test.go` (it calls live Stripe; 6b decides whether the fence returns) and `adversarial_test.go` (fold its one case into `webhook_test.go`). |
| +- Create: `internal/billingstripe/adapter.go`, `internal/billingstripe/adapter_test.go`. |
| +- Rework while copying: |
| + - **Package comment:** drop the old spec reference and any product name. |
| + - **`CheckoutMetadata`:** becomes `{AccountSqid, IntentID, PriceBook, Currency}` (no `TermsVersion`, `Plan`, `Band`). |
| + - **`CreateCheckoutParams`:** `PriceID`/`Quantity` become `Items []LineItem{PriceID string; Quantity int64}`. `LegacyAdaptive` is removed, and adaptive pricing is always sent off. |
| + - **Removed:** every reference to plans band or terms constants. |
| + - **Kept:** the API version pin `2025-02-24.acacia` (the rehearsal re-checks it), `UpdateQuantityWith` and `FenceQuantityKey` (6b decides). |
| +- Tests: |
| + - the copied tests are trimmed to the surviving API and keep their `httptest` server; |
| + - they pin the HTTP contract and carry no billing policy, so they come with the code; |
| + - all console-side tests are new. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `billing` types, `plans.PriceBook`. |
| +- Produces: |
| + ```go |
| + type ProviderConfig struct { |
| + SecretKey string |
| + Account string // acct_... |
| + WebhookSecrets []string // primary first, up to 3 |
| + LiveMode bool |
| + BaseURL string // tests only; "" is api.stripe.com |
| + } |
| + func NewProvider(cfg ProviderConfig) (*Provider, error) // *Provider implements billing.Provider |
| + func stateOf(status string) billing.State // Call 12 |
| + ``` |
| +- `ParseEvent`: `VerifyEvent` (signature, tolerance, rotation), then: |
| + |
| + | Stripe event | `Kind` | `Object` | |
| + | --- | --- | --- | |
| + | `customer.subscription.created`, `.updated`, `.deleted` | `EventSubscription` | the object's `id` | |
| + | `invoice.paid`, `invoice.payment_failed` | `EventSubscription` | the object's `subscription`, string or expanded; `EventIgnored` when empty | |
| + | `checkout.session.completed` | `EventCheckout` | the object's `id` | |
| + | anything else | `EventIgnored` | none | |
| + |
| + Any verify error becomes `billing.ErrBadEvent`. |
| +- `Subscription` maps `metadata[account_sqid]` to `Account`, and `current_period_end` to `PeriodEnd`. A Stripe 404 becomes `billing.ErrNotFound`. |
| +- `CheckoutSubscription` returns the session's subscription id. |
| +- `Check`: |
| + 1. `MerchantAccount` equals `cfg.Account`. |
| + 2. For every `prices.Refs(book.Version)`: `GetPrice` must be active, in the expected mode, in `ref.Currency`, with `unit_amount` equal to the book's amount. It must be recurring yearly with interval count 1, `usage_type` licensed, `billing_scheme` per_unit, `tax_behavior` exclusive, with no `transform_quantity`, `currency_options` only its own (harvest `priceCurrencyOptionsAreOwn` from `165472b8:internal/console/billingservice.go:183`), and `metadata[price_key] == ref.Key()` (Call 14). |
| + 3. Its product, read with `GetProduct`, is active. |
| + |
| + The first failure is returned with the key named and no amounts or ids. |
| + |
| +- [ ] **Step 1: Copy the files, apply the rework, and write the failing adapter tests** |
| + ```go |
| + func TestStateOf(t *testing.T) // active/trialing/past_due paid; incomplete pending; canceled/incomplete_expired/unpaid/paused ended; "weird" ended |
| + func TestParseEventKinds(t *testing.T) // signed fixtures for the six events + "charge.refunded": kinds and objects per the table; invoice with expanded subscription; |
| + // invoice with no subscription: ignored; bad signature: ErrBadEvent; previous secret: accepted |
| + func TestSubscriptionMapsFields(t *testing.T) // fake Stripe returns two items, metadata account_sqid "bab", current_period_end: fields mapped; 404: ErrNotFound |
| + func TestCheckRefusesMismatchedPrices(t *testing.T) // table on one price: inactive, wrong currency, amount off by 1, monthly, metered, tax inclusive, a second currency option, |
| + // price_key of another pack, archived product, wrong account: each an error naming the key; all good: nil |
| + func TestCreateCheckoutSendsItems(t *testing.T) // two items -> line_items[0][price], [0][quantity], [1][...]; adaptive_pricing[enabled]=false; Idempotency-Key header set |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/billingstripe/`. Expected: the new tests FAIL (`NewProvider` undefined), and the copied ones compile after the rework. |
| +- [ ] **Step 3: Implement** `adapter.go`. |
| +- [ ] **Step 4: Run** `go test ./internal/billingstripe/` and `GOOS=darwin go vet ./internal/billingstripe/ ./internal/billing/...`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `billingstripe: harvest the stdlib Stripe client from the integration branch, items-based checkout, billing.Provider adapter (plans 6a)`. |
| + |
| +### Task 4: Billing configuration and the book guard |
| + |
| +**Files:** |
| +- Create: `cmd/console/billing.go`, `cmd/console/billing_test.go` (adapted from `165472b8:cmd/console/billing.go`). |
| +- Create: `internal/console/billing.go` (`BillingConfig`, `billingRuntime`), `internal/console/billingstore.go` (the `billing_price_books` part only in this task). |
| +- Modify: |
| + - `internal/console/server.go:742` (`Config.Billing *BillingConfig`; `NewServer` builds `s.billing` when set); |
| + - `internal/console/store.go:554` (chain `migrateBilling()` after `migratePlanGrace()`); |
| + - `internal/console/store_gate.go:183` (`"billing_price_books": {NonApp: "price book versions and digests the console has started with; names no app"}`); |
| + - `cmd/console/main.go` (after the catalog load: `billingConfig(os.Getenv, catalog)`, fatal on error; after the store opens: `store.NotePriceBook`, fatal on error). |
| +- Test: `internal/console/billingstore_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1 (`LoadPriceBook`), Task 2 (`ParsePriceMap`, `Provider`), Task 3 (`NewProvider`). |
| +- Produces: |
| + ```go |
| + // cmd/console |
| + func billingConfig(getenv func(string) string, cat *plans.Catalog) (*console.BillingConfig, error) |
| + // console |
| + type BillingConfig struct { |
| + LiveMode bool |
| + Book *plans.PriceBook |
| + Prices billing.PriceMap |
| + Provider billing.Provider |
| + } |
| + type billingRuntime struct { cfg *BillingConfig; ready atomic.Bool; locks keyedLocks } // keyedLocks from applocks.go, keyed by account sqid |
| + var ErrPriceBookEdited = errors.New("price book changed without a new version") |
| + func (s *Store) NotePriceBook(version, digest, status string, now time.Time) error |
| + ``` |
| +- Environment: |
| + |
| + | Variable | Rule | |
| + | --- | --- | |
| + | `CARLOS_BILLING` | `off`, `test` or `live`; anything else is an error | |
| + | `CARLOS_PRICE_BOOK` | the path, loaded with `LoadPriceBook(path, cat)` | |
| + | `CARLOS_BILLING_PRICES` | the JSON for `ParsePriceMap` | |
| + | `CARLOS_STRIPE_SECRET_KEY` | the mode's `rk_` prefix | |
| + | `CARLOS_STRIPE_ACCOUNT` | `acct_` | |
| + | `CARLOS_STRIPE_WEBHOOK_SECRET` | `whsec_` | |
| + | `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS` | optional, comma separated, up to 2, each `whsec_`, no repeats | |
| + |
| + Every failure is one error, `console: billing configuration invalid: <variable name>`, with no value in it. |
| +- The table: `billing_price_books(version TEXT PRIMARY KEY, digest TEXT NOT NULL, status TEXT NOT NULL, first_seen INTEGER NOT NULL)`. `NotePriceBook` inserts on first sight, and returns `ErrPriceBookEdited` when the stored digest differs. A changed `status` means a changed digest, so draft-to-approved under one version is refused. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestBillingConfigOff(t *testing.T) // unset and "off": nil, nil, whatever else is set |
| + func TestBillingConfigRefuses(t *testing.T) // table: "on"; test with rk_live_; live with rk_test_; sk_test_ key; no account; whsec missing; three previous secrets; |
| + // repeated secret; no catalog; book path missing; book over another catalog version; live + draft book; prices missing a key; |
| + // error text names the variable and never contains the key value |
| + func TestBillingConfigTestModeAcceptsDraft(t *testing.T) // test + draft example book + full price map: LiveMode false, Book.Version "example-v1" |
| + func TestNotePriceBook(t *testing.T) // first: ok; same digest again: ok; same version, other digest: ErrPriceBookEdited; second version: ok |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./cmd/console/ -run BillingConfig` and `go test ./internal/console/ -run NotePriceBook`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'ClaimSQL'` (the new table is classified). Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: billing configuration, live refuses a draft book, a book edited under its version refuses to start (plans 6a)`. |
| + |
| +### Task 5: Billing state and the guarded plan write |
| + |
| +**Files:** |
| +- Modify: `internal/console/billingstore.go` (tables `billing_accounts`, `billing_problems`, and methods). |
| +- Modify: `internal/console/accountplans.go`: |
| + - factor `SetAccountPlan`'s upsert into `upsertAccountPlan`, used by both; |
| + - add `SetBillingPlan`. |
| +- Modify: `internal/console/apiaccountplan.go:129-137` (the best-effort reread-and-publish becomes `s.publishPlanNow`, called from the operator door and from Task 6). |
| +- Modify: `internal/console/store_gate.go:183`, adding: |
| + - `"billing_accounts": {NonApp: "an account's billing customer, subscription state and paid pack quantities; names no app"}`; |
| + - `"billing_problems": {NonApp: "billing problems for an operator, keyed by account and subscription; names no app"}`. |
| +- Test: `internal/console/billingstore_test.go`, `internal/console/accountplans_test.go`. |
| +- Not carried from `165472b8:internal/console/billingstore.go`: `billing_events` (dedupe) and `billing_rejected_events`. Every event is a fresh re-read, so a duplicate is harmless, and refusals become `billing_problems` rows. Checkout intents are 6b. Book assignments become `billing_accounts.book` plus `billing_price_books`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + type billingAccount struct { |
| + AccountID int64 |
| + Customer string |
| + Subscription string |
| + ProviderStatus string |
| + State billing.State // "" before any subscription |
| + Book, Currency string |
| + PeriodEnd time.Time |
| + CancelAtPeriodEnd bool |
| + PaidPacks map[string]int // highest quantity per pack paid for in the period ending PaidPeriodEnd |
| + PaidPeriodEnd time.Time |
| + SyncedAt time.Time |
| + } |
| + func (s *Store) BillingAccount(accountID int64) (*billingAccount, error) // nil, nil when none |
| + func (s *Store) BillingAccountByCustomer(customer string) (*billingAccount, error) // nil, nil when none |
| + func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time) error // 6b's checkout; a customer already bound elsewhere is an error |
| + func (s *Store) PutBillingState(b billingAccount) error // all columns but customer |
| + func (s *Store) LiveBillingAccounts(afterAccountID int64, limit int) ([]billingAccount, error) // State paid|pending, live accounts, account order |
| + |
| + type billingProblem struct { |
| + ID, AccountID int64 |
| + Subscription, Reason string |
| + Detail string |
| + OpenedAt, ClosedAt time.Time |
| + ClosedBy, Note string |
| + } |
| + const (problemUnknownCustomer = "unknown_customer"; problemAccountMismatch = "account_mismatch"; problemModeMismatch = "mode_mismatch" |
| + problemSecondSubscription = "second_subscription"; problemUnrecognised = "unrecognised"; problemNotBillingOwned = "not_billing_owned") |
| + func (s *Store) OpenBillingProblem(accountID int64, subscription, reason, detail string, now time.Time) (opened bool, err error) // one open row per (account, subscription, reason) |
| + func (s *Store) BillingProblems(includeClosed bool) ([]billingProblem, error) // newest first |
| + func (s *Store) BillingProblem(id int64) (*billingProblem, error) |
| + func (s *Store) CloseBillingProblem(id int64, by, note string, now time.Time) error // an already closed one is an error |
| + |
| + func (s *Store) SetBillingPlan(accountID int64, plan string, packs map[string]int, reason string, now time.Time) (written, owned bool, err error) |
| + func (s *Server) publishPlanNow(ctx context.Context, accountID int64, now time.Time) // best effort, logs; no-op without Releases |
| + ``` |
| +- Schema: |
| + - `billing_accounts(account_id INTEGER PRIMARY KEY, customer TEXT NOT NULL DEFAULT '', subscription TEXT NOT NULL DEFAULT '', provider_status, state, book, currency TEXT NOT NULL DEFAULT '', period_end INTEGER NOT NULL DEFAULT 0, cancel_at_period_end INTEGER NOT NULL DEFAULT 0, paid_packs TEXT NOT NULL DEFAULT '{}', paid_period_end INTEGER NOT NULL DEFAULT 0, synced_at INTEGER NOT NULL DEFAULT 0)`; |
| + - unique partial indexes on `customer` and `subscription` where non-empty; |
| + - `billing_problems(id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, subscription TEXT NOT NULL, reason TEXT NOT NULL, detail TEXT NOT NULL, opened_at INTEGER NOT NULL, closed_at INTEGER NOT NULL DEFAULT 0, closed_by TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '')`; |
| + - a unique partial index on `(account_id, subscription, reason) WHERE closed_at = 0`. |
| +- `SetBillingPlan`, in one transaction: |
| + - **Deleted account:** `ErrAccountGone`. |
| + - **No row:** insert with source `billing` (written, owned). |
| + - **Source `default` or `billing`:** update through `upsertAccountPlan` only if plan, canonical packs JSON or source differ (written or not, owned). |
| + - **Source `operator` or `sponsored`:** nothing written (not written, not owned). |
| + - `by` is always `"billing"`. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestSetBillingPlanWritesOnlyChanges(t *testing.T) // no row: written, revision 1, source billing; same again: not written, revision 1; packs {"apps":1}: written, revision 2 |
| + func TestSetBillingPlanTakesDefaultRows(t *testing.T) // EnsureDefaultPlans row: written, source becomes billing |
| + func TestSetBillingPlanLeavesSponsoredAndOperatorRows(t *testing.T) // SetAccountPlan(..., PlanSourceSponsored, ...) then SetBillingPlan: owned false, row unchanged; same for operator |
| + func TestSetBillingPlanKeepsThrottleWhenUnchanged(t *testing.T) // SetAccountThrottle, then SetBillingPlan with the same plan: Throttle still set |
| + func TestBillingCustomerIsUnique(t *testing.T) // cus_1 on account A; cus_1 on account B: error; BillingAccountByCustomer("cus_1").AccountID == A |
| + func TestBillingStateRoundTrips(t *testing.T) // PutBillingState with PaidPacks and times; BillingAccount returns equal values |
| + func TestOneOpenProblemPerReason(t *testing.T) // Open twice: opened true then false; close; open again: true; BillingProblems(false) lists one |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'SetBillingPlan|BillingCustomer|BillingState|OpenProblem'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'AccountPlan|ClaimSQL'`. Expected: PASS (the operator door still behaves as before). |
| +- [ ] **Step 5: Commit** `console: billing account state, billing problems, and a guarded plan write that skips unchanged rows (plans 6a)`. |
| + |
| +### Task 6: The sync decision |
| + |
| +**Files:** |
| +- Create: `internal/console/billingsync.go`. |
| +- Test: `internal/console/billingsync_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2 (`Recognise`, `Subscription`), Task 5 (store methods, `publishPlanNow`). |
| +- Produces: |
| + ```go |
| + 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 // the sqid of Prev.AccountID |
| + LiveMode bool |
| + DefaultPlan string |
| + } |
| + type planChange struct { Plan string; Packs map[string]int; Reason string } |
| + type problemNote struct { Reason, Detail string } |
| + type billingDecision struct { |
| + Save bool |
| + Next billingAccount |
| + Plan *planChange |
| + Problem *problemNote |
| + } |
| + func decideBilling(in billingInput) billingDecision |
| + func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, now time.Time) error // nil also when a problem was opened; transient provider errors returned |
| + ``` |
| +- `decideBilling` rules, first match wins: |
| + |
| + | Condition | Save | Plan | Problem | |
| + | --- | --- | --- | --- | |
| + | `Sub.LiveMode != LiveMode` | no | none | `mode_mismatch` | |
| + | `Sub.Account != AccountSqid` | no | none | `account_mismatch` | |
| + | `Prev.Subscription` is another id, `Prev.State` paid or pending, `Sub.State` paid or pending | no | none | `second_subscription` | |
| + | `Prev.Subscription` is another id and `Sub.State` ended | no | none | none (an old subscription ended) | |
| + | `Sub.State` pending | yes (adopt id, status) | none | none | |
| + | `Sub.State` paid, `Unrecognised != nil` | yes (adopt id, status) | none | `unrecognised`, detail from the error | |
| + | `Sub.State` paid, recognised | yes, `PaidPacks` per below | `{Purchase.Plan, PaidPacks, "subscription <id> <status>"}` | none | |
| + | `Sub.State` ended, the current subscription (or none recorded) | yes, `PaidPacks` cleared | `{DefaultPlan, nil, "subscription <id> ended (<status>)"}` | none | |
| + |
| +- `PaidPacks` keeps the period's highest paid quantity: |
| + - when `Prev.PaidPeriodEnd` differs from `Sub.PeriodEnd`, `PaidPacks = Purchase.Packs` and `PaidPeriodEnd = Sub.PeriodEnd` (a new period: reductions take effect); |
| + - otherwise, per pack, `max(Prev.PaidPacks[p], Purchase.Packs[p])`. A pack whose item was removed keeps its stored quantity. |
| +- `syncSubscription` does: |
| + 1. Read once to learn the customer. |
| + 2. Find the account with `BillingAccountByCustomer`. If there is none, open `unknown_customer` (account 0, or the account the metadata names if it exists) and return nil. |
| + 3. Take the account lock and **re-read**. |
| + 4. `Recognise`, then `decideBilling`. |
| + 5. Apply: `PutBillingState` if `Save`; `SetBillingPlan` if `Plan` (when `owned` is false and the state is paid, open `not_billing_owned`); `publishPlanNow` if written; `OpenBillingProblem` if `Problem`. |
| + 6. Every opened problem is logged once with account, subscription and reason. |
| + |
| +- [ ] **Step 1: Write the failing tests.** Pure tests call `decideBilling`. Store-backed tests use `billingtest.Fake`, the example catalog and book, and a server with `cfg.Billing` set. |
| + ```go |
| + func TestDecidePaidRecognised(t *testing.T) // personal + apps x2, active: Plan {personal, {apps:2}}, Next.Subscription set, PaidPeriodEnd = PeriodEnd |
| + func TestDecidePastDueKeepsPaid(t *testing.T) // past_due maps to paid: the same Plan as active |
| + func TestDecidePendingChangesNothing(t *testing.T) // incomplete: Save, no Plan, no Problem |
| + func TestDecideEndedDropsToDefault(t *testing.T) // canceled current: Plan {free, nil}; unpaid: same; incomplete_expired after pending: Plan {free, nil} (a no-op write in practice) |
| + func TestDecideOldSubscriptionEndedIsIgnored(t *testing.T) // Prev.Subscription "sub_new" paid, Sub "sub_old" canceled: no Save, no Plan |
| + func TestDecideSecondSubscription(t *testing.T) // Prev sub_a active, Sub sub_b active: Problem second_subscription, no Save, no Plan |
| + func TestDecideAdoptsAfterEnded(t *testing.T) // Prev sub_a canceled, Sub sub_b active: Save with sub_b, Plan personal |
| + func TestDecideIdentityProblems(t *testing.T) // account "zzz" vs "bab": account_mismatch; LiveMode false vs true: mode_mismatch; neither Saves |
| + func TestPackReductionHoldsUntilRenewal(t *testing.T) // apps 3 then apps 1 in the same period: Plan packs {apps:3}; raised to 2: still {apps:3}; |
| + // PeriodEnd moves a year on with apps 1: {apps:1} |
| + func TestSyncWritesThePlanRow(t *testing.T) // Fake sub active for customer cus_1 bound to bab: AccountPlan(bab) = personal, source billing; limits record published |
| + func TestSyncUnchangedKeepsThrottle(t *testing.T) // sync, SetAccountThrottle, sync again: revision unchanged, Throttle still set |
| + func TestPaidSubscriptionOnSponsoredAccountOpensProblem(t *testing.T) // sponsored row; active sub: row unchanged, problem not_billing_owned open |
| + func TestSyncUnknownCustomerOpensProblem(t *testing.T) // customer not bound: problem unknown_customer, no plan row change, returns nil |
| + func TestSyncTransientErrorIsReturned(t *testing.T) // Fake.Err set: error returned, nothing written |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Decide|PackReduction|Sync|SponsoredAccountOpens'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** `billingsync.go`. |
| +- [ ] **Step 4: Run** again. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: billing sync decides the plan from a fresh subscription read; pack reductions hold until renewal (plans 6a)`. |
| + |
| +### Task 7: Webhook, sync pass and readiness |
| + |
| +**Files:** |
| +- Create: `internal/console/billingwebhook.go`, `internal/console/billingpass.go`. |
| +- Modify: |
| + - `internal/console/server.go:1658` (beside `/api/ses/events`: `s.registerRoute("POST /billing/webhook", s.handleBillingWebhook)`, always registered); |
| + - `internal/console/claim_workers.go` (`"StartBillingSyncPass": s.StartBillingSyncPass`); |
| + - `cmd/console/main.go` (`go srv.RunClaimWorker(context.Background(), "StartBillingSyncPass")` beside `StartPlanLimitsPass`); |
| + - `internal/console/testdata/claim-routes.txt` (`route POST /billing/webhook`, `worker StartBillingSyncPass`); |
| + - `internal/console/claim_invariant_fixtures_test.go` (both entries, `claimNonApp`, beside `"route POST /api/ses/events"` and `"worker StartPlanLimitsPass"`); |
| + - `internal/console/claim_invariant_probes_nonapp_test.go` and `claim_invariant_probes_worker_test.go` (probes: a Fake subscription for `bab` yields a `personal` plan row). |
| +- Test: `internal/console/billingwebhook_test.go`, `internal/console/billingpass_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 6 (`syncSubscription`); Task 2 (`Provider.ParseEvent`, `CheckoutSubscription`, `Check`). |
| +- Produces: |
| + ```go |
| + func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) |
| + func (s *Server) StartBillingSyncPass(ctx context.Context) |
| + func (s *Server) billingReadyCheck(ctx context.Context) error // sets s.billing.ready on success |
| + func (s *Server) billingSyncPass(ctx context.Context, now time.Time) |
| + const billingSyncInterval = time.Hour |
| + const billingCheckRetry = time.Minute |
| + var billingSyncBatch = 200 |
| + ``` |
| +- The webhook answers: |
| + |
| + | Case | Answer | |
| + | --- | --- | |
| + | `s.billing == nil` | 404 | |
| + | not ready | 503 | |
| + | body over 1 MiB (`http.MaxBytesReader`) | 400 | |
| + | `ErrBadEvent` | 400 | |
| + | `event.LiveMode != cfg.LiveMode` | 400 | |
| + | `EventIgnored` | 204 | |
| + | `EventCheckout` whose `CheckoutSubscription` is "" | 204 | |
| + | `EventCheckout` with a subscription | sync that subscription, as below | |
| + | `EventSubscription` | `syncSubscription`: nil 204, error 503 | |
| + |
| + The answer body is always empty: the sender is Stripe, not a person. |
| +- The pass: |
| + 1. With billing nil, it returns. |
| + 2. It loops `billingReadyCheck` every `billingCheckRetry` until it succeeds. A failure is logged when its text differs from the last one. |
| + 3. It then runs `billingSyncPass` now and every `billingSyncInterval`: page `LiveBillingAccounts` by account id, `syncSubscription` each, serially. One account's error never stops the others. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestBillingWebhookOff(t *testing.T) // no billing: 404 |
| + func TestBillingNotReadyAnswers503ThenRecovers(t *testing.T) // Fake.CheckErr set: pass check fails, webhook 503, plan row unchanged; clear CheckErr, check again: ready; webhook 204 and plan personal |
| + func TestBillingWebhookRefusesBadEvents(t *testing.T) // no Fake-Signature: 400; live event on a test console: 400; 1 MiB+1 body: 400 |
| + func TestBillingWebhookIgnoredKinds(t *testing.T) // kind ignored: 204, Fake.Calls 0 |
| + func TestBillingWebhookCheckoutSyncsItsSubscription(t *testing.T) // checkout cs_1 -> sub_1 active: plan personal |
| + func TestBillingWebhookTransientIs503(t *testing.T) // Fake.Err set after ready: 503 |
| + func TestStaleEventAppliesTheFreshRead(t *testing.T) // sub active -> event: personal; Fake sub now canceled; deliver the old "updated" event again: free |
| + func TestBillingSyncPassCatchesMissedEvents(t *testing.T) // bound account with sub recorded active; Fake changes quantity with no event; billingSyncPass: packs updated |
| + func TestBillingSyncPassPagesPastErrors(t *testing.T) // billingSyncBatch = 1, first account's sub returns ErrNotFound: second still synced |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingWebhook|BillingNotReady|StaleEvent|BillingSyncPass'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim'` (routes file, fixtures and probes agree). Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: billing webhook and hourly sync pass, not ready until the provider check passes (plans 6a)`. |
| + |
| +### Task 8: Operator doors and CLI for billing problems |
| + |
| +**Files:** |
| +- Create: `internal/console/apibilling.go`, `internal/console/apibilling_copy.go`, `billing_cli.go`, `billing_cli_copy.go` (repo root). |
| +- Modify: |
| + - `internal/console/authcli.go:956` (`s.cliRoute("GET /api/cli/billing/problems", svcrole.Set{}, s.handleAPIBillingProblems)`, `s.cliRoute("POST /api/cli/billing/problems/{id}/close", svcrole.Set{}, s.handleAPIBillingProblemClose)`); |
| + - `main.go` (top-level `case "billing":`) and the usage text; |
| + - `testdata/claim-routes.txt`, fixtures and probes for both routes. |
| +- Test: `internal/console/apibilling_test.go`, `billing_cli_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 5 (problems), Task 2 (`Provider.Subscription`). |
| +- Produces: |
| + ```go |
| + type billingProblemReply struct { |
| + ID int64 `json:"id"`; Account string `json:"account"`; Subscription string `json:"subscription"` |
| + Reason string `json:"reason"`; Detail string `json:"detail"`; OpenedAt time.Time `json:"opened_at"` |
| + ClosedAt *time.Time `json:"closed_at,omitempty"`; ClosedBy string `json:"closed_by,omitempty"`; Note string `json:"note,omitempty"` |
| + } |
| + func (s *Server) handleAPIBillingProblems(w http.ResponseWriter, r *http.Request) // ?all=1 includes closed |
| + func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Request) // body {"note": "..."} |
| + ``` |
| +- The gate follows `accountPlanDoor`'s order (no account segment here): signed in (`cliUser`), then operator (404 otherwise), then billing configured (409 with `billingCopyOff`). |
| +- Close: |
| + - an empty note is 400; |
| + - unknown or closed is 404 / 409; |
| + - with a subscription, a fresh `Provider.Subscription` read: paid or pending is 409 `billingCopyStillLive`; `ErrNotFound` or ended allows the close; a transient error is 503. |
| +- CLI: |
| + - `carlos billing problems [-all]` prints one line per problem: id, account, reason, subscription, opened (UTC), detail. |
| + - `carlos billing close -id N -note "..."`. |
| + - Both need console mode; the direct-bucket shell is refused like `cliPlanCopyNeedsConsole`. |
| +- Draft copy (Luna pass in Task 9): |
| + - `billingCopyOff` = "billing is off on this deployment. set CARLOS_BILLING on the console to turn it on" |
| + - `billingCopyStillLive` = "the subscription is still live at the provider. cancel it there, then close the problem" |
| + - `billingCopyNoteRequired` = "say what you did in stripe with -note" |
| + - `billingCopyNoProblems` = "no open billing problems" |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestBillingProblemsDoorIsOperatorOnly(t *testing.T) // member: 404; operator: 200 with the open problem; billing off: 409 |
| + func TestCloseRefusedWhileLive(t *testing.T) // problem on sub_1, Fake active: 409; Fake canceled: 200, closed_by operator, note kept; close again: 409 |
| + func TestCloseNeedsANote(t *testing.T) // "" and " ": 400 |
| + func TestBillingCLIProblemsAndClose(t *testing.T) // against an httptest console: lines printed; close sends the note; -note missing: billingCopyNoteRequired |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingProblemsDoor|CloseRefused|CloseNeeds'` and `go test . -run BillingCLI`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console, cli: operators list and close billing problems (plans 6a)`. |
| + |
| +### Task 9: Copy, docs, census and gates |
| + |
| +- [ ] **Luna copy pass.** Commit a brief carrying: |
| + - the house rules (no em dashes; a full stop and a new sentence; lower case for the CLI; human text only); |
| + - every string in `apibilling_copy.go` and `billing_cli_copy.go`, plus the configuration error text, each with an example rendering. |
| + |
| + Apply Luna's changes, and show Paul only the strings it flags. |
| +- [ ] **Docs.** Add a "Billing (operators)" section to `docs/site/plans.md`, covering: |
| + - what billing does in 6a (keeps paying accounts' plans in step; nothing to buy yet); |
| + - the variables in Task 4 and where they live (the console's EnvironmentFile, never the bucket); |
| + - test and live modes, and the draft refusal; |
| + - "a new book version, never an edit"; |
| + - `carlos billing problems|close`; |
| + - what each problem reason means and what the operator does in Stripe. |
| + |
| + Write it in plain prose (humane-docs). |
| +- [ ] **Census:** |
| + - Run `make census-card`, then `make census-propose NAME=plans-6a-billing-sync CLAIMS=<file>`. |
| + - Write hand decision rows for the new units: the webhook route, two operator routes, the sync worker and three tables. |
| + - Add a record-write layer only if `TestPlan9B8RecordWriteCensus` names a site. This plan publishes only through the existing `publishAccountLimits`. |
| + - Astra approves the card, recorded on #280. Decisions go to Paul. |
| +- [ ] **Cross-compile:** run `GOOS=darwin go build ./...` and `GOOS=windows go build ./...`. Nothing here is Linux-only. |
| +- [ ] **Finish:** merge main, push, wait for green CI, then Astra's whole-branch review. |
| + |
| +## Done when |
| + |
| +- Every task's tests pass, and Review Focus 1 to 5 are pinned. |
| +- With `CARLOS_BILLING` unset, the console's behaviour is unchanged: the webhook answers 404, and no billing table row is written. |
| +- The census card is approved by Astra. |
| +- CI is green after merging current main. |
| +- Astra's whole-branch review has no open Critical or Important finding. |
| + |
| +--- |
| + |
| +## Later parts (outline) |
| + |
| +### Plan 6b: Checkout, packs, portal and the billing page |
| + |
| +Harvest the shapes of `billinghandlers`, `billingpage`, `billingoperator` (the house flag) and the quantity update from `billingquantity`, rewritten for several items. Tasks: |
| + |
| +1. **House flag.** A `billing_house` table and `carlos billing house -account <sqid> -on|-off -note`. A house account's checkout carries the 100% house coupon (`CARLOS_STRIPE_HOUSE_COUPON`, verified at the readiness check: valid, 100% off, `forever`). It exercises the real flow at no charge. |
| +2. **Customer and Checkout.** |
| + - `ensureCustomer`: billing country and postal code; idempotency key from the account; `SetBillingCustomer` before any session. |
| + - A `billing_checkout_intents` table: one standing intent per account. |
| + - `Provider.CreateCheckout`: subscription mode; items Personal ×1 plus chosen packs, in the chosen currency (`ChooseCurrency`, visible override); adaptive pricing off; `automatic_tax`; metadata `account_sqid`, intent id and book on both the session and `subscription_data`; success and cancel URLs on the console origin. |
| + - Refused up front: |
| + - a `sponsored` or `operator` plan row (Call 11); |
| + - an account with a live subscription; |
| + - an open billing problem; |
| + - billing not ready. |
| + - Account deletion is refused while a subscription is live. |
| + - §8.1 (extra accounts created as paid), if Plan 3a left it open. |
| + - `checkout.session.completed` also closes the intent. |
| +3. **Pack quantities** (Calls 6 and 8): |
| + - Adding sets the item quantity: `none` up to `PaidPacks`; above it, `always_invoice` + `pending_if_incomplete` for the difference (two idempotent calls when both apply). |
| + - A new pack type is a new item; reducing is `none`; removing the last unit deletes the item with `none`. |
| + - Each change syncs at once through `syncSubscription`. |
| + - The key gains Subscriptions write and Subscription items write. |
| +4. **Stop and resume renewal.** `cancel_at_period_end` from the console, shown as "ends on" and "renews on". |
| +5. **Portal.** `CARLOS_STRIPE_PORTAL_CONFIGURATION`. The readiness check verifies it is locked: payment method update and invoice history on; customer update limited to address, name and tax id; subscription update and cancel off. `POST /billing/portal` opens a session for owners. |
| +6. **Billing page** (`templates/billing.html`). It shows: |
| + - plan, packs, renewal date, currency and the currency override (country default shown); |
| + - upgrade (free to Personal plus packs) and pack plus/minus with the prorated amount quoted; |
| + - the open-problem notice (Call 5). |
| + |
| + Owners act; members read. Copy goes through the Luna pass. |
| +7. **Census, docs, gates.** New routes (`/billing`, `/billing/checkout`, `/billing/portal`, pack and renewal doors), tables (`billing_house`, `billing_checkout_intents`), fixtures and probes. |
| + |
| +### Plan 6c: Stripe setup runbook (test mode on dev, then live) |
| + |
| +A runbook under `docs/superpowers/plans/`, following `165472b8:implementation/carloku-paid-launch/ENABLEMENT.md`, reshaped. Every live step is Paul's. |
| + |
| +1. **Products:** Personal plus one per pack type. Tax code to confirm with the accountant (the old branch used `txcd_10102001` for personal-use software). |
| +2. **Prices:** 15 for the book in Call 15, each yearly, licensed, per unit, tax-exclusive, single currency, with `metadata[price_key]` set to its key (`<book>/personal/<cur>` or `<book>/pack/<name>/<cur>`). |
| +3. **Coupon and portal:** the 100% house coupon (no promotion code), and the locked portal configuration. |
| +4. **Webhook:** `https://<console>/billing/webhook`, the six events from spec §9.6, API version `2025-02-24.acacia`, and the signing secret to `CARLOS_STRIPE_WEBHOOK_SECRET`. |
| +5. **Retry settings:** after all retries fail, cancel the subscription (Call 12). |
| +6. **The restricted `rk_` key:** |
| + - granted: Checkout Sessions W, Customers W, Subscriptions W, Prices R, Products R, Customer portal W, Coupons R, Tax registrations R; |
| + - not granted: refunds, charges, events, webhook endpoints, keys. |
| + |
| + It is created in the Dashboard by Paul and goes straight into the EnvironmentFile. |
| +7. **Console variables:** set on dev first with `CARLOS_BILLING=test` and a draft book. Live needs a new `approved` book version. The catalog and book files come from the deployment's infrastructure repo (Plan 7 assumes `carloku-infrastructure/plans/`); `CARLOS_PRICE_BOOK` and `CARLOS_PLAN_CATALOG` name their installed paths. |
| +8. **Rehearsal checklist on dev (test clock):** |
| + - checkout to plan row; |
| + - a pack added (`pending_if_incomplete` with a declining card); |
| + - a reduction holding until renewal; |
| + - renewal; |
| + - a failed renewal (past due keeps paid), then cancellation, dropping to free and 4a/4d acting; |
| + - an out-of-order event; |
| + - whether Checkout ever leaves an `incomplete_expired` subscription (Call 10); |
| + - webhook secret rotation; |
| + - the readiness check refusing a wrong price. |
| +9. **Flagship:** the same steps in live mode on Paul's approval, after spec §12 steps 1 to 4. IE and OSS tax registrations already exist on the Dublin account. |