plans 6b: revision 3 after Astra's round 2. Six invariants replace the replay machinery: an operation is one request persisted exactly and sent once, recovery only observes; paid capacity is decided at every admission and an applied invite charge is a credit with single-use consent; provider lists are exhaustive or refuse; refresh is separate from the allowance check; passes only observe and never expire a session; terminal intents are history. Call 17 (unclear outcomes: observe after 10 minutes, problem after an hour) for Paul; budget by branch and cardinality with call-count assertions; fake covers failure before delivery and renewal across a period
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+683
−907
docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md+683 −907
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md| index 6fdca5d2c..df3a91900 100644 |
| --- a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md |
| +++ b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md |
| @@ -3,7 +3,7 @@ |
| > **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:** On a console with billing configured, an account owner can: |
| -- buy Personal, Community or Business, with packs, through Stripe Checkout; |
| +- buy Personal, Community or Business (with packs) through Stripe Checkout; |
| - add and reduce packs; |
| - add and lose team members, with the seat count following; |
| - upgrade between paid plans; |
| @@ -12,212 +12,218 @@ |
| A static pricing page links to one stable console URL, which takes a signed-out visitor through sign-in or sign-up first. |
| -**Revision 2 (2026-10-25).** This revision fixes Astra's plan review (`plans6b-plan-review.md`, at `b6005e86`): 12 Important findings, 1 Minor, the gaps and the request budget. "Revision 2 fixes" at the end maps each finding to where it is now handled. Paul's sixteen calls stand as ruled. |
| +**Revision 3 (2026-10-25).** Revision 2 fixed Astra's round 1 (`plans6b-plan-review.md`). Round 2 (`plans6b-plan-review-r2.md`, at `d705d1c7`) accepted most of it. Its eight new findings came from revision 2's replay and recovery machinery. Revision 3 deletes that machinery rather than patching it: |
| +- nothing is ever resent after a call returns; |
| +- recovery only observes; |
| +- the six invariants below govern every flow. |
| + |
| +"Review record" at the end maps each finding to its fix. Paul's sixteen calls stand as ruled. Call 17 is a new choice the simplification raises. |
| + |
| +## Invariants |
| + |
| +Every task obeys these. A reviewer rejects any step that contradicts one. |
| + |
| +1. **Never replay a saved step.** |
| + - An operation is **one provider request**, written to `billing_operations` before it is sent. The row holds the exact request: the subscription id **and its period end**, item id or absence, price id, quantity, proration, proration timestamp and idempotency key. |
| + - It is sent exactly once. The 6a client never retries, and 6b adds no retry. |
| + - After the call, recovery **re-reads the provider** (the subscription with its items and period, or the session) and records what happened: applied, pending payment, or not done. |
| + - Anything further is **recomputed from scratch** by a new request, under the current period and authorisation. |
| + - A step that was never sent is abandoned, never executed. So is one whose context changed (a new period, a new book, consumed consent, an expired intent). |
| + - A second step (restore, then charge) is computed only from a **definite** response to the first, inside the same request. |
| +2. **Paid capacity is decided at admission, every time.** |
| + - An applied invite charge is **a credit that reconciliation absorbs**, not an entitlement to skip the capacity check. |
| + - No seat is reserved for an invite. Each admission recomputes `need` against the freshened paid capacity. If a paid seat is free, whoever is admitted next takes it. |
| + - A seat authorisation is **single use**: it is consumed when a charge under it is applied. A retry that needs another charge needs fresh consent. |
| +3. **Provider enumeration is exhaustive or it refuses.** Every list (live subscriptions, a customer's Checkout sessions) pages to completion, up to `billing.MaxListPages` (10) pages of 100. More than that is `billing.ErrIncomplete`, and the caller refuses. |
| +4. **Refresh and the allowance invariant are separate.** |
| + - `refreshLocked` is the plain 6a sync of the recorded subscription, with no period check. Checkout, retirement and the page use it. |
| + - `allowanceLocked` refreshes, then requires the row's `PaidPeriodEnd` to equal the read's period end. Only quantity changes on a live, paid subscription use it. |
| +5. **Background passes only observe.** |
| + - The hourly pass reads sessions and subscriptions and records what they show. |
| + - It never expires an unexpired open Checkout session, never sends a change, and never creates a session. |
| + - Only an owner's explicit new Checkout (replacement) or the retirement gate expires a session. |
| +6. **A terminal intent is history.** Once its outcome is recorded (`completed` with its subscription synced, `expired` or `abandoned`), an intent blocks nothing. Checkout and retirement judge the account's **subscriptions**, from an exhaustive list, never a past intent. |
| **Architecture:** |
| - **Team plans in the catalog** (`internal/plans`): |
| - A plan may carry a `team` block: a base plan, a per-member multiple in thousandths, and a minimum. |
| - `Effective` takes a member count. It multiplies the base plan's pooled limits by `multiple × max(members, minimum)`. |
| - Non-team plans may carry `max_members`. |
| - - The public export moves to schema 3, so a team plan's price reads as per member. |
| + - The public export moves to schema 3. |
| - **Seats and membership** (`internal/console`): |
| - `account_plans.seats` is the paid seat count billing wrote. 0 means "count the members now". |
| - - Every membership change goes through one transition, `membershipTransition`. It wraps 6a's `transitionAccountPlan`, so a fall in a live-counted team's limits starts the 4d lapse lifecycle, and a rise re-converges at once. |
| - - Every join is admitted under a per-account member lock, with every check re-run inside it. |
| -- **Provider writes** (`internal/billing`, `internal/billingstripe`): new `Provider` methods for the customer, Checkout start, read and expiry, item changes, renewal, the portal and live-subscription listing, all behind the 6a boundary. Stripe status words stay in the adapter. The console sees only neutral facts: live, collecting, pending update, cancel at period end. |
| -- **Durable billing operations** (`internal/console`): |
| - - Every charge-capable or quantity-changing request is a `billing_operations` row, written before the provider call. |
| - - Each row has a deterministic idempotency key per step, and carries the item id between steps. |
| - - At most one operation per subscription is outstanding at a time. |
| - - A fresh read settles the row: applied, pending payment, failed or abandoned. Retries and a crash resume the same row with the same keys. |
| -- **The console flow:** the billing page, the `/upgrade` entry, Checkout start, resume and return, pack, plan and seat changes, renewal, the portal and a retirement gate for account deletion. |
| - - Every flow takes the account's billing lock through `holdBilling`. |
| - - It first applies a fresh read of the subscription ("freshen"), so stored per-period allowances match the provider's period. |
| - - It runs its operation, then settles it with one more fresh read, applied through 6a's `applyBillingRead`. |
| - - The plan row moves only through 6a's sync path. |
| + - Every membership change goes through `membershipTransition`, which wraps 6a's `transitionAccountPlan`. |
| + - Every join is admitted under a per-account member lock, with all checks re-run inside it. |
| +- **Provider writes** (`internal/billing`, `internal/billingstripe`): new `Provider` methods behind the 6a boundary. Stripe status words stay in the adapter. |
| +- **Operations and intents** (`internal/console`): |
| + - A `billing_operations` row is one provider request: written before sending, settled only by observing. At most one is outstanding per subscription. |
| + - A Checkout intent is created before the session, and recovered only by observing the customer's sessions. |
| +- **The console flow:** the billing page, `/upgrade`, Checkout, pack, plan and seat changes, renewal, the portal, and a retirement gate for deletion. |
| + - Every flow takes the billing lock through `holdBilling`. |
| + - It refreshes, or for quantity changes passes the allowance check. |
| + - It sends at most the requests it can compute from definite answers. |
| + - It settles with one more read through 6a's `applyBillingRead`. |
| **Tech Stack:** Go, stdlib only (no stripe-go); SQLite console store; `html/template`; `internal/plans`, `internal/billing`, `internal/billingstripe`, `internal/console`, `cmd/console`, `cmd/pricebook-export`, 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, in its currency: Personal ×1 plus one item per pack, with quantity; |
| - - adding a pack mid-year prorates, and is granted once paid; reducing takes effect at renewal; |
| + - adding a pack mid-year prorates and is granted once paid; reducing takes effect at renewal; |
| - upgrading from free is Checkout in subscription mode; |
| - - payment method and invoices go through the customer portal, locked to those functions; |
| + - payment method and invoices go through the locked portal; |
| - the console changes plans and quantities, never the portal. |
| - §9.2: paid limits while Stripe retries; Plan 4d owns what falls. |
| -- §9.6: the live setup (the 6c outline at the end). |
| +- §9.6: live setup (the 6c outline at the end). |
| - §10: the provider boundary. |
| -- §3: |
| - - currencies usd, eur and gbp, defaulted by billing country with a visible override; |
| - - an explicit unsold currency is refused, and nothing is converted; |
| - - a live console refuses a draft book; |
| - - `rk_` keys in the EnvironmentFile. |
| +- §3: usd, eur and gbp; default by billing country with a visible override; an explicit unsold currency refused; nothing converted; a live console refuses a draft book; `rk_` keys in the EnvironmentFile. |
| - §8.1: one free account per person. |
| Also binding: |
| - **Plan 6a** (`docs/superpowers/plans/2026-10-25-plans-6a-checkout.md`): all of its Calls are accepted, and its outline of 6b is the starting shape. |
| -- **Paul's team-plan ruling** (2026-10-25, via the coordinator). It reverses "team plans after launch", and is amended only by Paul's acceptance of Call 7. Task 0 records it in the spec: |
| +- **Paul's team-plan ruling** (2026-10-25), amended only by his acceptance of Call 7. Task 0 records it: |
| - Community and Business are "just different multiples of the same gates". |
| - Prices are per member per year, usd / eur / gbp: Community 6 / 5 / 4.50, Business 60 / 50 / 45. The account pays for at least 10 members. |
| - Limits are Personal's × 0.2 per member (Community) or × 2 per member (Business), pooled across the account, for running things, awake hours, bandwidth, object storage and email. |
| - - **Disk is neither multiplied nor pooled** (Call 7, accepted by Paul). Team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count. |
| + - **Disk is neither multiplied nor pooled** (Call 7, accepted). Team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count. |
| - Flags (custom domains, the 15-minute idle window) are as Personal. Business also gets 7-day history and priority support. |
| - Every member who can access and ship counts. Adding a member charges the rest of the year at once, prorated to the day. A member who leaves comes off the bill at renewal. |
| -- **Pricing-page ruling:** the carloku.com pricing page publishes only when checkout is live, and its buttons go straight to the console's upgrade entry (Task 8 defines the contract). |
| +- **Pricing-page ruling:** the pricing page publishes only when checkout is live, and its buttons go straight to the console's upgrade entry (Task 8). |
| ## Base branch, order and 6a's names |
| -- This branch, `plans-6b-checkout-flow`, was cut from `plans-6-checkout` (Plan 6a) at `f4ce6bda`. 6a has since merged main (4d-1) and routed billing through 4d's transition (`f713e241`). Its Astra round 2 is still pending. |
| -- **Rebase 6b onto main after 6a merges,** before Task 1 is built. |
| -- If 6a has not merged when building starts, merge `origin/plans-6-checkout` and then `origin/main` into this branch. Build Tasks 0 to 2 (they touch only `internal/plans`), and stop before Task 3 until 6a merges. |
| +- This branch was cut from `plans-6-checkout` at `f4ce6bda`. |
| +- **Rebase it onto main after 6a merges,** before Task 1. If 6a has not merged, merge `origin/plans-6-checkout` and then `origin/main`. Build Tasks 0 to 2 only, and stop before Task 3 until 6a merges. |
| - **6a's merged names, which this plan uses:** |
| - |
| - | Name | What it is | |
| - | --- | --- | |
| - | `applyAccountPlan` | the operator plan change | |
| - | `applyBillingPlan` | billing's plan change | |
| - | `transitionAccountPlan(ctx, acct, now, write func(old *AccountPlanRow) (bool, error))` | the shared lifecycle under the lapse lock | |
| - | `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)` | the one transaction for the billing row, the guarded plan write and the lapse mark | |
| - | `syncSubscription` | takes the billing lock itself | |
| - | `applyBillingRead` | the caller holds the billing lock | |
| - | `subscriptionMissing`, `endMissingSubscription` | the `subscription_missing` path | |
| - | `billingDiscoveryPass`, `DiscoverableBillingAccounts` | discovery of missed first purchases | |
| - | `billingReadyCheck`, `StartBillingSyncPass` | readiness and the sync worker | |
| - | `s.billing.locks` | the per-account billing lock (`keyedLocks`, by sqid) | |
| -- **6a's round-2 fix pass is assumed** to change three things, all under the billing lock: discovery, pending-replacement adoption, and the closing of `subscription_missing`. Wherever that pass merges a name or signature different from this table, use 6a's and note the ruling in the ledger. This plan never weakens those paths. It only adds hooks: seats in `decideBilling`, operation settlement after `applyBillingRead`, and intent resolution in discovery. |
| + - `applyAccountPlan`, `applyBillingPlan`; |
| + - `transitionAccountPlan(ctx, acct, now, write func(old *AccountPlanRow) (bool, error))`; |
| + - `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)`; |
| + - `syncSubscription` (takes the billing lock); |
| + - `applyBillingRead` (the caller holds it); |
| + - `subscriptionMissing`, `endMissingSubscription`; |
| + - `billingDiscoveryPass`, `DiscoverableBillingAccounts`; |
| + - `billingReadyCheck`, `StartBillingSyncPass`; |
| + - `s.billing.locks`. |
| +- **6a's round-2 fix pass** is assumed to change discovery, pending-replacement adoption and the closing of `subscription_missing`, all under the billing lock. Where that pass merges different names, use 6a's, and note the ruling in the ledger. 6b only adds hooks: |
| + - seats in `decideBilling`; |
| + - operation settlement after `applyBillingRead`; |
| + - intent observation in discovery. |
| ## Calls for Paul |
| -**Ruled 2026-10-25: Paul accepted every recommendation (1 to 16) as written.** Task 0 records them in the spec. Don't reopen them. Revision 2 changes only how some calls are made safe (Calls 6, 11 and 15), never what they decide. Each place is marked "(revision 2)". |
| - |
| -1. **The upgrade URL and which account it upgrades.** The contract is Task 8's. After sign-in, the console looks at the accounts the viewer **owns**: |
| - - one: straight to its billing page; |
| - - several: a short picker, the most recent account first; |
| - - none: a page saying only an owner can upgrade an account, with a link to create one. |
| - |
| - A brand-new sign-up owns exactly the account minted on landing, so it goes straight through. **Recommend: as stated.** |
| -2. **How the default currency is chosen.** |
| - - The billing page preselects the currency for the **visitor's country from the console's GeoIP database** (`s.cfg.GeoIPReader`), falling back to the book's default. |
| - - The buyer can override it (three radio buttons). |
| - - Stripe Checkout collects the billing address (`billing_address_collection=required`, saved to the customer) and computes tax from it. |
| - - An explicit currency we do not sell (from the pricing-page link or a hand-edited URL) is refused with a banner, and nothing is preselected. |
| - |
| - **Recommend: GeoIP default, Checkout collects the address.** |
| -3. **An account's currency is fixed after its first purchase.** A Stripe customer cannot hold subscriptions in two currencies. After a first subscription, the billing page shows the account's currency and offers no override. Changing it is an operator task. **Recommend: as stated.** |
| -4. **Switching between paid plans: upgrades only, in 6b.** |
| - - An upgrade is a switch to a plan whose lowest yearly total in the configured book is higher. It swaps the plan item's price at once, prorated and charged now, and is granted once paid. |
| - - A downgrade between paid plans is not self-serve in 6b. **Recommend: as stated.** |
| -5. **The prorated amount quoted before a charge** is a local estimate: "about $X now for the rest of the year, plus any tax", from the book price × the days left / 365, rounded up. **Recommend: local estimate.** |
| -6. **A fresh sign-in proof before charging a saved card or opening the portal.** Pack raises beyond the paid count, plan upgrades and the portal go through `requireFreshAuth`. Checkout itself does not, and stopping renewal does not. (Revision 2: the invite confirm that records a seat authorisation also goes through `requireFreshAuth`. It is a consent to charge the saved card later, with the owner absent.) **Recommend: as stated.** |
| -7. **Disk is not pooled.** Disk is a per-running-thing cap (spec §5.4), enforced on each box. Team plans keep Personal's 10 GB per running thing; total disk grows with the team only through the running-things count. Running things, awake hours, bandwidth, object storage and email multiply and pool. **Recommend: as stated.** |
| -8. **Ceilings scale with the team.** On a team plan, each pooled ceiling is multiplied by the same factor as the limits (`multiple × billed members`) when that factor is above 1. **Recommend: as stated.** |
| -9. **Community's history:** the latest copy only (history 0). Business gets 7 days. Sidecars, the memory tier, the minimum schedule and fleets are as Personal for both. **Recommend: as read.** |
| -10. **Packs on team plans:** the same five packs, flat per account, at the same prices. **Recommend: yes.** |
| +**Ruled 2026-10-25: Paul accepted every recommendation (1 to 16) as written.** Task 0 records them. Don't reopen them. Revisions 2 and 3 change only how Calls 6, 11 and 15 are made safe, never what they decide; those places are marked. Call 17 is new in revision 3. |
| + |
| +1. **The upgrade URL and which account it upgrades.** The contract is Task 8's. Owns one account: its billing page. Several: a picker, the most recent first. None: a not-owner page. **Recommend: as stated.** |
| +2. **Default currency:** from the visitor's GeoIP country, with an override. Checkout collects the billing address. An explicit unsold currency is refused. **Recommend: as stated.** |
| +3. **An account's currency is fixed after its first purchase.** **Recommend: as stated.** |
| +4. **Paid-to-paid switches: upgrades only in 6b**, charged at once and granted once paid. **Recommend: as stated.** |
| +5. **Quotes are a local estimate.** **Recommend: as stated.** |
| +6. **A fresh sign-in proof before charging a saved card or opening the portal.** (Revision 2: the invite confirm that records a seat authorisation also needs one.) **Recommend: as stated.** |
| +7. **Disk is not pooled.** Team plans keep Personal's 10 GB per running thing. **Recommend: as stated.** |
| +8. **Ceilings scale with the team.** **Recommend: as stated.** |
| +9. **Community's history:** the latest copy only. Business gets 7 days. **Recommend: as read.** |
| +10. **Packs on team plans:** the same five, flat per account. **Recommend: yes.** |
| 11. **A member joins while the card fails.** |
| - - The owner sees the cost when inviting someone who will need a new paid seat, and confirms it. |
| - - **The charge happens when the invite is accepted, before the membership is created.** If the payment fails or needs action, the person does not join yet. The invite stays valid, the invitee is told, and the owners' billing page shows the waiting payment. |
| - - Operator-added members are never charged automatically; excess opens `seats_unpaid`. |
| - |
| - (Revision 2: the confirmation is stored on the invite as a durable authorisation of plan, book, currency and per-seat price. An accept that needs a charge the invite doesn't cover waits, and the owner invites again. The charge is a durable operation bound to the invite, so a retry or a crash never buys twice. Task 11.) **Recommend: as stated.** |
| -12. **A member who leaves.** The seat comes off at once with no proration, and the renewal bills the lower count. The account keeps the period's highest paid seat count until renewal. Rejoining within the period, up to that count, is not charged again. **Recommend: as stated.** |
| -13. **Who counts as a member:** every owner and member. Not pending invites, and not service credentials. Below the minimum, the account is billed and limited at 10. **Recommend: as stated.** |
| -14. **Free and Personal accounts with more than one member.** `max_members` on non-team plans, **3 for both**, checked at invite and accept only. Nobody is removed, and sponsored accounts are exempt. **Recommend: as stated.** |
| -15. **Deleting an account that is still renewing** is refused. It is allowed once renewal is stopped. (Revision 2: "stopped" is checked by a durable retirement gate under the billing lock, against the provider's fresh state. Every live subscription must have cancel at period end set, with no payment being collected and no pending update. No billing operation may be outstanding, and every Checkout attempt must be resolved. Purchase, change, renewal and join handlers refuse while the account is retiring. Task 13.) **Recommend: as stated.** |
| -16. **A second account (§8.1).** No separate create-as-paid path. The free-account refusal copy says to upgrade the free account first. **Recommend: as stated.** |
| + - The owner confirms the cost at invite time. |
| + - The charge happens at accept, before the membership is created. |
| + - On failure the person does not join yet, and the invite stays valid. |
| + - Operator-added members are never charged; any excess opens `seats_unpaid`. |
| + |
| + (Revision 3: the stored authorisation is single use. If a charge it paid for ends up seating someone else, the retry asks the owner again, Invariant 2.) **Recommend: as stated.** |
| +12. **A member who leaves:** comes off at once with no proration. The account keeps the period's highest paid seats. A rejoin within the period is free. **Recommend: as stated.** |
| +13. **Who counts:** owners and members. Not invites, not service credentials. Billed and limited at a minimum of 10. **Recommend: as stated.** |
| +14. **`max_members` 3 on Free and Personal,** checked at invite and accept only. **Recommend: as stated.** |
| +15. **Deleting a renewing account is refused; allowed once renewal is stopped.** (Revision 2: a durable retirement gate checks provider truth. Revision 3: it judges an exhaustive subscription list, and ignores reconciled intents.) **Recommend: as stated.** |
| +16. **No create-as-paid path for a second account.** **Recommend: as stated.** |
| +17. **(New, revision 3) An operation whose outcome the provider leaves unclear.** Invariant 1 never resends, so an operation with no definite answer (a timeout, a crash mid-send) is **observed**. The first applied read at least `opQuiet` (10 minutes) after the send records it as applied, pending, or abandoned. Until then, changes on that subscription are refused (one outstanding operation). |
| + - **Recommend: (a) as stated, plus a refusal backstop.** If an operation is still unresolved after `opStuck` (1 hour), which happens only when the provider can't be read, the console opens an `operation_unresolved` billing problem. All changes on the account are refused until an operator closes it. The close is allowed once a fresh read settles the operation. |
| + - **Alternative (b):** drop observation. Every unclear outcome opens `operation_unresolved` at once, and nothing is settled automatically. That is less logic but more operator work: every timeout reaches a person. |
| ## Global Constraints |
| - **Dormant unless configured.** `cfg.Billing == nil` means: |
| - - every new web route (`/upgrade`, `/a/{sqid}/billing` and its doors) answers `http.NotFound`; |
| - - the billing nav link is hidden; |
| - - the invite and accept flows have no billing step; |
| - - the house door answers 409 `billingCopyOff`; |
| - - the retirement gate is skipped. |
| + - every new web route answers `http.NotFound`; |
| + - no billing nav link; |
| + - no billing step in invites; |
| + - the house door answers 409; |
| + - no retirement gate. |
| - Team-plan limits, `max_members`, the member lock and `membershipTransition` work with a catalog and no billing (an operator assigns plans, spec §10). Without a catalog, `membershipTransition` is only the membership write. |
| + Team limits, `max_members`, the member lock and `membershipTransition` work with a catalog and no billing. |
| - **6a's rules hold:** |
| - the event body is never trusted; |
| - - the plan follows only a fresh `Provider.Subscription` read applied under the account's billing lock; |
| - - billing writes only `default` or `billing` plan rows (6a Call 11); |
| + - the plan follows only a fresh read applied under the billing lock; |
| + - billing writes only `default` or `billing` rows; |
| - a live console refuses a draft book; |
| - - keys are `rk_` keys from the EnvironmentFile only. |
| -- **Locks and their order: member → billing → lapse → store.** |
| - - The member lock is `s.memberLocks`, a new `keyedLocks` by sqid. |
| - - The billing lock is `s.billing.locks`, by sqid, and is taken only through `holdBilling`. |
| - - The lapse lock is taken inside `transitionAccountPlan`. |
| - - Store transactions are innermost. |
| - |
| - Nothing takes them in another order. |
| -- **Lock-holding helpers are named and typed.** |
| - - `holdBilling(sqid) (billingHold, func())` is the only way to take the billing lock in 6b code. |
| - - A function whose name ends in `Locked` takes a `billingHold` as its first parameter. It never calls `holdBilling`, `syncSubscription`, `endMissingSubscription` or `s.billing.locks.lock`. |
| - - `TestBillingLockedHelpersNeverLock` (Task 7) parses `internal/console` with `go/ast` and fails on any such call. Timeout-bounded tests (5 s) cover change, renewal, accept, removal, deletion and the pass. |
| -- **Freshen, operate, settle.** Every flow that changes a subscription, under `holdBilling`: |
| - 1. **Freshen:** `freshenLocked` reads the subscription, applies it through `applyBillingRead`, and reloads the billing row. It proceeds only when the row names that subscription and its `PaidPeriodEnd` equals the read's period end. Stored per-period allowances (`PaidPacks`, `PaidSeats`) therefore belong to the provider's current period before anything is computed (finding 4). |
| - 2. **Operate:** refuse if an operation is outstanding for the subscription, or the read has a pending update. Otherwise write a `billing_operations` row, then run its steps. |
| - 3. **Settle:** one more fresh read, applied through `applyBillingRead`, which also settles the operation. |
| - |
| - A change response is used only to learn the next step's item id, never to move the plan row. |
| -- **Granted once paid.** Charges use `billing.ProrateNow`, sent as `proration_behavior=always_invoice` with `payment_behavior=pending_if_incomplete` (6a Call 8). Reductions and restores up to the period's paid quantity use `billing.ProrateNone`. |
| -- **One outstanding operation per subscription.** A partial unique index on `billing_operations(subscription)` covers rows in `started` or `pending`. A fresh read with `PendingUpdate` counts as outstanding even with no row (a change made before a restart, or by an operator). Handlers and the seat path refuse with `change.outstanding` (finding 5). |
| -- **Idempotency keys are persisted and deterministic:** |
| - |
| - | Request | Key | |
| - | --- | --- | |
| - | customer | `customer:<sqid>` | |
| - | Checkout start | `checkout:<intent id>`, reused by every resend of that intent | |
| - | Checkout expiry | `expire:<intent id>` | |
| - | operation step | `<operation id>:<step index>` | |
| - | portal | `portal:<customer>:<16 random hex>` | |
| - |
| - A step is resent with its key only within 23 hours of its first send. After that, a fresh read decides. |
| -- **Changes use the subscription's own book and currency.** Price ids come from `cfg.Prices.ID(PriceRef{Book: row.Book, ...})`. A target the subscription's book does not price is refused (`change.book`). New purchases use `cfg.Book.Version`. |
| -- **Currencies:** exactly `usd`, `eur`, `gbp`. `plans.ErrCurrencyNotSold` covers anything else, upper case and malformed values included: an explicit value is never replaced by a default (finding 13). An account with a fixed currency (Call 3) is offered only that currency, and the Checkout door re-checks it under the lock. |
| -- **Provider neutrality.** Console code reads only `billing` facts: `State`, `Live`, `Collecting`, `CancelAtPeriodEnd`, `PendingUpdate`, `PendingExpires`, and `CheckoutState`. Stripe status words appear only in `internal/billingstripe`. `TestConsoleBillingHasNoProviderWords` (Task 7) scans `internal/console/billing*.go` for the Stripe status literals. `ProviderStatus` is kept for operator display only. |
| -- **Money moves only on an owner's POST** with the session's CSRF token, or on an invitee's accept that a stored, matching seat authorisation covers (Call 11). |
| -- **Redirect targets:** success, cancel and portal return URLs are built from `s.cfg.Origin` and the account's sqid only. |
| -- **Request budget** (Astra's table, corrected for revision 2). Stripe requests: |
| - |
| - | Operation | Requests | |
| - | --- | --- | |
| - | Readiness attempt | merchant 1 + prices 24 + products 8 + portal 1 = **34**, 35 with a house coupon. It stops at the first failure. | |
| - | Readiness retries | back off 1, 2, 4, 8, 16, then every 30 minutes: at most 6 attempts in the first hour (≤ 210 reads), then 2 an hour (≤ 70). The backoff resets on success. | |
| - | Billing page view | 0 (store only) | |
| - | Checkout start | 1 live-subscription list + ≤ 1 customer create + ≤ 2 for an earlier intent (one resend or session read, then ≤ 1 expiry) + 1 session create: **2 to 5** | |
| - | Checkout return | 1 session read + one sync (2 reads, 3 when another recorded subscription is live): **3 to 4** | |
| - | Pack, plan or seat change | freshen 1 + steps 1 to 2 + settle 1 (2 when another recorded subscription is live): **3 to 5** | |
| - | Renewal change | freshen 1 + 1 write + settle 1: **3 to 4** | |
| - | Portal | 1 | |
| - | Join on a billing team plan | freshen 1 (enough for a free seat), then for a restore or charge 1 to 2 steps + settle 1: **1 to 5** | |
| - | Deletion gate | 1 live-subscription list + ≤ 2 per unresolved intent; run twice (before the step-up and at the tombstone): **2 to 6** | |
| - | Hourly pass, per account | 6a's sync and discovery, plus: 1 session read per unresolved intent younger than 25 h; per seat drift, freshen 1 + ≤ 2 steps + settle 1; per outstanding operation of unknown outcome, 1 read and ≤ 1 resend within 23 h | |
| - | Persistent `seats_unpaid` | re-checked once a day per account, or when its membership changes, never hourly | |
| - |
| - S3: nothing polled. A limits publication is a GET and a conditional PUT, with retries on conflict. The 4d transition (`transitionAccountPlan`) adds its own inventory reads and convergence writes per plan or membership change that moves limits. Per-change cost: one transition. A membership change that leaves limits unchanged publishes nothing. |
| -- **No product name** in code, tests, copy or example data. Examples are neutral (shop, example.com). |
| -- **Names:** no helper or type name containing `Record`. |
| + - `rk_` keys only. |
| +- **Locks: member → billing → lapse → store.** |
| + - The member lock is `s.memberLocks`, by sqid. |
| + - The billing lock is taken only through `holdBilling`. |
| + - Functions named `*Locked` take a `billingHold` first and never lock; an AST test enforces it. |
| + - 5-second timeout tests. |
| +- **Granted once paid.** Charges are `billing.ProrateNow` (`always_invoice` + `pending_if_incomplete`). Reductions, and restores up to the period's paid quantity, are `billing.ProrateNone`. |
| +- **One outstanding operation per subscription:** a partial unique index over `sending`, `uncertain` and `pending`. A read with `PendingUpdate` counts as outstanding even with no row. |
| +- **Idempotency keys:** |
| + - customer: `customer:<sqid>`; |
| + - Checkout create: `checkout:<intent id>`; |
| + - Checkout expiry: `expire:<intent id>`; |
| + - an operation: `op:<operation id>`; |
| + - portal: `portal:<customer>:<16 random hex>`. |
| + |
| + Keys are persisted with the exact request, and each request is sent once (Invariant 1). |
| +- **Changes use the subscription's own book and currency.** New purchases use `cfg.Book.Version`. |
| +- **Currencies:** exactly `usd`, `eur`, `gbp`. Any other explicit value is refused, never defaulted. A fixed currency is re-checked under the Checkout hold. |
| +- **Provider neutrality:** the console reads only `billing` facts. A scan test keeps Stripe status words out of `internal/console/billing*.go`. |
| +- **Money moves only** on an owner's POST with CSRF, or on an accept covered by an unconsumed, matching seat authorisation. |
| +- **Redirect targets** are built from `s.cfg.Origin` and the sqid only. |
| +- **Request budget, by branch and cardinality.** |
| + - Stripe requests. Notation: `L(n)` is one list of `n` objects, `ceil(n/100)` requests, at most 10, else `ErrIncomplete`; `S` is one sync of a subscription, 1 read plus 1 more when another recorded subscription is live, so 1 to 2. |
| + |
| + | Operation | Branch | Requests | |
| + | --- | --- | --- | |
| + | Readiness attempt | all prices good | 34 (35 with a house coupon); stops at the first failure. Retries back off 1, 2, 4, 8, 16, then every 30 min: ≤ 6 attempts in the first hour, then 2 an hour | |
| + | Billing page view | any | 0 | |
| + | Checkout start | first purchase, no prior intent | `L(live subs)` + 1 customer create + 1 session create | |
| + | | prior intent `open`, same request | `L` + 1 session read (reuse) | |
| + | | prior intent `open`, other request | `L` + 1 session read + 1 expiry (+1 session read if the expiry is refused) + 1 create | |
| + | | prior intent `creating`, older than `opQuiet` | `L` + `L(customer sessions since the intent)` (+1 sync if one completed) + 1 create | |
| + | | prior intent `creating`, younger than `opQuiet` | `L`, then a refusal ("still preparing") | |
| + | | a live subscription found | `L` + `S` per live id, then a refusal | |
| + | Checkout return | any | 1 session read + `S` | |
| + | Pack or plan change | no step | `allowance` (`S`) | |
| + | | one step | `S` + 1 send + settle `S` | |
| + | | restore, then charge | `S` + 1 send + 1 send (computed from the first's definite response) + settle `S`. A lost first response stops after its send, then a settle read | |
| + | Renewal change | any | `S` + 1 send + `S` | |
| + | Portal | any | 1 | |
| + | Join on a billing team | seat free | `S` | |
| + | | restore | `S` + 1 + `S` | |
| + | | charge | `S` + 1 + `S` | |
| + | | restore, then charge | `S` + 2 + `S` | |
| + | Deletion gate, per run (runs twice) | `k` live subscriptions, `j` non-terminal intents | `L(live subs)` + `k` sync reads + per intent: 1 session read (`open`; +1 expiry, +1 read if refused) or `L(customer sessions)` (`creating`) | |
| + | Hourly pass, per account | — | 6a's sync and discovery; + per non-terminal intent: 1 session read (`open`) or `L` (`creating` older than `opQuiet`); + per unresolved operation older than `opQuiet`: `S`; + per seat drift: as a join or a reduction; + `seats_unpaid` re-checked at most daily | |
| + |
| + - S3: nothing polled. A limits publication is a GET plus a conditional PUT, with retries on conflict. `transitionAccountPlan` adds 4d's inventory reads and convergence writes per change that moves limits. A change that moves no limit publishes nothing. |
| + - **Call-count assertions:** every recovery, retirement and Checkout-branch test asserts `Fake.Calls` (by method) against this table. |
| +- **No product name; no `Record` in helper names.** |
| - **Copy:** |
| - - Every new human string lives in `internal/console/billingpage_copy.go` (`billingCopy`), in `plancaps_copy.go`, or in `billing_cli_copy.go`. |
| - - Tests compare against the copy maps, never against literal text. |
| - - House rules: no em dashes, plain words, CLI lower case. Error fragments, diagnostics and JSON keys stay out. |
| + - It lives in `billingpage_copy.go`, `plancaps_copy.go` and `billing_cli_copy.go`. Tests compare against the maps. House rules apply. |
| + - Where a task says "revision 2's" draft strings, they are in revision 2 of this file (`git show c86d0692:docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md`), same task. The Luna pass replaces every draft, so none of them is load-bearing. |
| + - Test bodies marked "(as revision 2)" have their one-line assertions there too. |
| - **Census:** |
| - - Each route-adding task adds its `testdata/claim-routes.txt` line, fixture and probe in the same commit. |
| - - New tables go in `claimSQLTables` as `NonApp`. |
| - - The units and envelopes are derived from the **final diff** in Task 15, never from this plan's list. |
| + - route lines, fixtures and probes go with each route-adding task; |
| + - new tables are `NonApp`; |
| + - units are derived from the final diff (Task 15). |
| - **Tests:** |
| - - TDD with no network: console tests use `billingtest.Fake`, which models outstanding payments, later payment, expiry, lost responses and idempotency (Task 4). Adapter tests use an `httptest` Stripe. |
| - - Inject `now`. |
| - - Run touched packages with `-run`, niced. Run the `-run Claim` suite (about 15 minutes) once per route-adding task. CI runs everything. |
| -- **Cross-compile:** nothing here is Linux-only. |
| + - TDD, no network; inject `now`; |
| + - the Fake models idempotency, pending updates, later payment, expiry, failure **before** delivery, lost responses **after** applying, renewal across a period boundary, list paging and Checkout races; |
| + - run touched packages, niced; one `-run Claim` run per route-adding task. |
| ## Review Focus |
| -1. **Submitting again while a payment is outstanding.** A double click, or a retry after a decline or action-required payment, must not start a second charge-capable update. Pinned in Task 10 (`TestOneOutstandingOperation`, `TestRetryAfterDeclineIsRefusedUntilSettled`). |
| -2. **Two joins racing for one free seat.** With 9 members and 10 paid seats, two accepts must not admit 11 for 10. The second charges, under its own authorisation, or waits. Pinned in Task 11 (`TestConcurrentJoinsShareNoSeat`). |
| -3. **A crash or lost response between the seat payment and the membership.** The retry admits without a second charge, and a revoked invite never starts a purchase. Pinned in Task 11 (`TestJoinRecoversAfterLostResponse`, `TestJoinRecoversAfterCrashBeforeMembership`, `TestRevokedInviteStartsNoPurchase`). |
| -4. **A renewal webhook delayed past the renewal.** The previous period's paid quantities must not restore packs or seats free of charge. Pinned in Task 10 (`TestChangeAfterDelayedRenewal`) and Task 11 (`TestJoinAfterDelayedRenewal`). |
| -5. **Hostile or malformed upgrade input.** `?currency=usd1`, `?currency=USD` and `?currency=<script>` are refused, never defaulted and never reflected. The `next` parameter stays local. Pinned in Task 8 (`TestUpgradeEntry`, `TestBillingPageCurrencyRefusals`). |
| +1. **A lost response, then the clock moves on.** A lost add response must never be resent or turned into an update. A crash before sending, followed by a renewal, must send nothing in the new period. Pinned in Task 7 (`TestLostAddResponseIsObservedNotResent`, `TestUnsentRestoreAbandonedAcrossRenewal`) and Task 11 (`TestUnsentSeatRestoreAbandonedAcrossRenewal`). |
| +2. **A paid invite seat taken by another joiner.** The members never exceed the paid seats, and the first invitee's retry needs fresh consent. Pinned in Task 11 (`TestAppliedInviteChargeIsACreditNotAPass`). |
| +3. **A live subscription on page two.** Checkout and deletion must see it, and refuse when the list is incomplete. Pinned in Task 5 (`TestLiveSubscriptionsPagesToCompletion`), Task 9 (`TestCheckoutSeesLiveSubscriptionOnPageTwo`) and Task 13 (`TestDeleteSeesLiveSubscriptionOnPageTwo`, `TestDeleteRefusesIncompleteList`). |
| +4. **A buyer mid-Checkout when the hourly pass runs.** Their session survives. Pinned in Task 9 (`TestPassRightAfterCheckoutKeepsSession`). |
| +5. **Purchase, stop renewal, delete.** Deletion succeeds; the completed intent does not block it. Pinned in Task 13 (`TestDeleteAfterCompletedPurchaseAndStop`). |
| --- |
| @@ -225,11 +231,11 @@ Also binding: |
| **Files:** |
| - Modify: `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| - - §3: a bullet with Paul's team-plan ruling (2026-10-25), worded as in this plan's Spec block. It includes the disk sentence: "Disk is neither multiplied nor pooled: team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count (Call 7, accepted)." |
| - - §4.1: team plans (base, multiple, minimum, the five pooled fields, `max_members`). |
| - - §4.2: Community and Business columns and prices. The disk row reads "10 GB per running thing (not pooled)". |
| - - §9.1: the team plan is the plan item, with quantity `max(members, 10)`. |
| - - A "Plan 6b rulings" list holding Calls 1 to 16 as ruled by Paul on 2026-10-25. |
| + - §3: Paul's team-plan ruling (2026-10-25), worded as in the Spec block, including "Disk is neither multiplied nor pooled: team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count (Call 7, accepted)"; |
| + - §4.1: team plans; |
| + - §4.2: the Community and Business columns, with disk at "10 GB per running thing (not pooled)"; |
| + - §9.1: the team plan item, with quantity `max(members, 10)`; |
| + - a "Plan 6b rulings" list with Calls 1 to 16 as ruled. Add Call 17 once Paul rules on it. |
| - [ ] **Step 1:** Make the edits. |
| - [ ] **Step 2: Commit** `spec: team plans and the Plan 6b rulings (Paul, 2026-10-25) in the plans and packs design (plans 6b)`. |
| @@ -239,165 +245,114 @@ Also binding: |
| **Files:** |
| - Create: `internal/plans/team.go`, `internal/plans/team_test.go`. |
| - Modify: |
| - - `internal/plans/catalog.go`: `Plan.Team`, `Plan.MaxMembers`, validation, and `Effective`'s new parameter; |
| - - `internal/plans/testdata/example-catalog.json`: add `community` and `business`, and `max_members: 3` on `free` and `personal`; |
| - - `internal/plans/testdata/example-pricebook.json`: `community` 600 / 500 / 450, `business` 6000 / 5000 / 4500; |
| - - every `Effective` caller, so it compiles: `planlimits.go`, `apiaccountplan.go` and `planlapse.go` each pass `1` for now; Task 3 passes the real count. |
| + - `internal/plans/catalog.go`; |
| + - `internal/plans/testdata/example-catalog.json`: `community`, `business`, and `max_members: 3` on `free` and `personal`; |
| + - `internal/plans/testdata/example-pricebook.json`: community 600 / 500 / 450, business 6000 / 5000 / 4500; |
| + - every `Effective` caller passes `1` until Task 3. |
| **Interfaces:** |
| - Produces: |
| ```go |
| type Team struct { |
| - Base string `json:"base"` // a paid, non-team plan whose pooled limits multiply |
| - PerMemberMilli int `json:"per_member_milli"` // the multiple per member in thousandths: 200 = 0.2, 2000 = 2 |
| - MinMembers int `json:"min_members"` // billed and limited at no fewer |
| + Base string `json:"base"` |
| + PerMemberMilli int `json:"per_member_milli"` // 200 = 0.2, 2000 = 2 |
| + MinMembers int `json:"min_members"` |
| } |
| - // Plan gains: |
| - Team *Team `json:"team,omitempty"` |
| - MaxMembers int `json:"max_members,omitempty"` // non-team plans only; 0 = no cap |
| + // Plan gains Team *Team `json:"team,omitempty"` and MaxMembers int `json:"max_members,omitempty"`. |
| const MaxTeamMembers = 10000 |
| var ErrTeamMembers = errors.New("team member count out of range") |
| - // Call 7: disk_bytes is deliberately absent. |
| - var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month"} |
| - func (t *Team) Billed(members int) int // max(members, MinMembers) |
| - func (t *Team) PerMember() string // the multiple as a decimal: 200 "0.2", 2000 "2", 1250 "1.25" |
| + var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month"} // Call 7: no disk_bytes |
| + func (t *Team) Billed(members int) int |
| + func (t *Team) PerMember() string |
| func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits, members int) (Limits, error) |
| ``` |
| -- Validation additions: |
| - - `team.base` names a paid plan with no `team`; |
| - - `per_member_milli` is 1 to 100000, and `min_members` is 1 to `MaxTeamMembers`; |
| - - a team plan's own `limits` sets none of the `PooledLimits` fields; |
| - - a team plan with `max_members` is refused; |
| - - `max_members` is non-negative. |
| -- `Effective` on a team plan: |
| - 1. Start from the team plan's `limits`, including its own `disk_bytes`. |
| - 2. For each `PooledLimits` field: `floor(base × PerMemberMilli × Billed(members) / 1000)`, overflow-checked with `math/bits` (an overflow is `ErrTeamMembers`). |
| - 3. Add packs as today. |
| - 4. Clamp to the ceilings. Only the five pooled fields' non-zero ceilings scale, by the same factor, when it exceeds 1 (Call 8). |
| - 5. Merge the sponsored override as today. |
| - |
| - `members` outside 0 to `MaxTeamMembers` is `ErrTeamMembers`. On a non-team plan, `members` is ignored. |
| -- The example team plans: |
| - - `limits`: `sidecars_per_app` 5, `idle_seconds` 900, `memory_tier` default, `disk_bytes` 10737418240, `storage_self_serve`, `custom_domains`, `fleets`, `min_schedule_seconds` 60; |
| - - `business` adds `history_days` 7; |
| - - `packs`: all five; |
| - - `team`: `{"base":"personal","per_member_milli":200,"min_members":10}`, with 2000 for business. |
| +- Validation: |
| + - the base is a paid, non-team plan; |
| + - milli is 1 to 100000; the minimum is 1 to `MaxTeamMembers`; |
| + - a team plan sets no pooled field of its own and no `max_members`; |
| + - `max_members` ≥ 0. |
| +- Team `Effective`: |
| + 1. The team plan's own limits, its `disk_bytes` included. |
| + 2. Pooled fields: `floor(base × milli × Billed / 1000)`, overflow-checked (an overflow is `ErrTeamMembers`). |
| + 3. Packs. |
| + 4. Ceilings; only the pooled fields' ceilings scale by the same factor when it is above 1 (Call 8). |
| + 5. The sponsored merge. |
| + |
| + Members outside 0 to `MaxTeamMembers` is `ErrTeamMembers`. On non-team plans, members is ignored. |
| +- Example team plans: `sidecars_per_app` 5, `idle_seconds` 900, `memory_tier` default, `disk_bytes` 10737418240, `storage_self_serve`, `custom_domains`, `fleets`, `min_schedule_seconds` 60. Business adds `history_days` 7. All five packs. Community milli 200, Business 2000, both minimum 10. |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestEffectiveCommunityAtMinimum(t *testing.T) // members 4 -> billed 10: RunningThings 50, AwakeHoursMonth 3000, EmailPerDay 2000, |
| - // StorageBytes 53687091200, BandwidthBytesMonth 107374182400, DiskBytes 10737418240 (not multiplied), IdleSeconds 900, HistoryDays 0 |
| - func TestEffectiveCommunityTwentyThree(t *testing.T) // members 23: RunningThings 115, AwakeHoursMonth 6900, EmailPerDay 4600, StorageBytes 123480309760, DiskBytes 10737418240 |
| - func TestEffectiveBusinessScalesCeilings(t *testing.T) // members 12: RunningThings 600 (ceiling 200 x 24), EmailPerDay 24000, HistoryDays 7, DiskBytes 10737418240 |
| - func TestEffectiveTeamWithPacks(t *testing.T) // community, members 10, apps 2: RunningThings 60; disk 1: DiskBytes 21474836480 |
| - func TestEffectiveIgnoresMembersOffTeam(t *testing.T) // personal with members 0, 1 and 50: identical Limits |
| - func TestEffectiveTeamMemberBounds(t *testing.T) // members -1 and 10001: errors.Is ErrTeamMembers |
| - func TestCatalogRefusesBadTeams(t *testing.T) // base missing; base free; base a team; milli 0; min 0; team limits with running_things; team with max_members; max_members -1 |
| - func TestTeamBilledAndPerMember(t *testing.T) // Billed(3)=10, Billed(12)=12; PerMember 200 "0.2", 2000 "2", 1250 "1.25" |
| + func TestEffectiveCommunityAtMinimum(t *testing.T) // 4 -> 10: RunningThings 50, AwakeHoursMonth 3000, EmailPerDay 2000, StorageBytes 53687091200, |
| + // BandwidthBytesMonth 107374182400, DiskBytes 10737418240, IdleSeconds 900, HistoryDays 0 |
| + func TestEffectiveCommunityTwentyThree(t *testing.T) // 23: RunningThings 115, AwakeHoursMonth 6900, EmailPerDay 4600, StorageBytes 123480309760, DiskBytes 10737418240 |
| + func TestEffectiveBusinessScalesCeilings(t *testing.T) // 12: RunningThings 600, EmailPerDay 24000, HistoryDays 7, DiskBytes 10737418240 |
| + func TestEffectiveTeamWithPacks(t *testing.T) // community 10 + apps 2: 60; disk 1: DiskBytes 21474836480 |
| + func TestEffectiveIgnoresMembersOffTeam(t *testing.T) |
| + func TestEffectiveTeamMemberBounds(t *testing.T) |
| + func TestCatalogRefusesBadTeams(t *testing.T) |
| + func TestTeamBilledAndPerMember(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/plans/ -run 'Effective|Team|Catalog'`. Expected: FAIL (`Team` undefined). |
| -- [ ] **Step 3: Implement,** then fix the callers so `go build ./...` passes. |
| +- [ ] **Step 2: Run** `go test ./internal/plans/ -run 'Effective|Team|Catalog'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement,** and fix the callers. |
| - [ ] **Step 4: Run** `go test ./internal/plans/ ./internal/console/ -run 'Effective|Team|Catalog|PriceBook|AccountPlan|PlanLimits'`. Expected: PASS. |
| - [ ] **Step 5: Commit** `plans: team plans multiply a base plan's pooled limits per member, with a minimum; disk stays per running thing; max_members on other plans (plans 6b)`. |
| ### Task 2: Public export schema 3 and money formatting |
| **Files:** |
| -- Modify: `internal/plans/export.go`, `internal/plans/export_test.go`, the regenerated golden `internal/plans/testdata/example-public-pricebook.json`, and any `cmd/pricebook-export` test that pins the schema. |
| -- Create: `docs/superpowers/specs/2026-10-25-public-price-export-schema-3.md` (schema 2 plus the changes below, and a "what changed" list for the website). |
| +- Modify: `internal/plans/export.go`, `export_test.go`, the regenerated golden, and the `cmd/pricebook-export` tests. |
| +- Create: `docs/superpowers/specs/2026-10-25-public-price-export-schema-3.md`. |
| **Interfaces:** |
| -- Produces: |
| - ```go |
| - // publicExport.Schema = 3. publicPlan gains: |
| - Team *publicTeam `json:"team,omitempty"` |
| - MaxMembers int `json:"max_members,omitempty"` |
| - type publicTeam struct { |
| - Base string `json:"base"` |
| - PerMember string `json:"per_member"` // Team.PerMember() |
| - MinMembers int `json:"min_members"` |
| - Pooled []string `json:"pooled"` // PooledLimits, in that order; disk is not among them |
| - } |
| - func FormatMinor(currency string, minor int64) string // "$28", "€24", "£4.50", "$0.07" |
| - ``` |
| -- On a team plan, `annual_minor` is per member per year. The team plan's export `limits` carry the pooled fields computed at `min_members`. Plans are ordered: free first, then by `annual_minor[default] × max(1, min_members)`, then by key. |
| +- Produces: schema 3. `publicPlan` gains `Team *publicTeam` (base, `per_member`, `min_members`, `pooled` without disk) and `MaxMembers`. Also `func FormatMinor(currency string, minor int64) string`. |
| +- A team plan's `annual_minor` is per member. Its `limits` carry the pooled fields at `min_members`. The order is free first, then `annual × max(1, min_members)`, then key. |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestPublicExportSchema3Team(t *testing.T) // schema 3; community team {personal, "0.2", 10, pooled 5 without disk_bytes}; annual_minor usd 600; |
| - // limits.running_things 50, disk_bytes 10737418240; personal max_members 3; order free, personal, community, business |
| - func TestPublicExportGolden(t *testing.T) // regenerated golden |
| - func TestFormatMinor(t *testing.T) // ("usd",2800) "$28"; ("gbp",450) "£4.50"; ("eur",2400) "€24"; ("usd",7) "$0.07" |
| - ``` |
| +- [ ] **Step 1: Write the failing tests:** `TestPublicExportSchema3Team`, `TestPublicExportGolden`, `TestFormatMinor` (`"$28"`, `"£4.50"`, `"€24"`, `"$0.07"`). |
| - [ ] **Step 2: Run** `go test ./internal/plans/ ./cmd/pricebook-export/ -run 'PublicExport|FormatMinor|Golden'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement,** then regenerate the golden with `go run ./cmd/pricebook-export`. |
| +- [ ] **Step 3: Implement,** and regenerate the golden. |
| - [ ] **Step 4: Run** again. Expected: PASS. |
| - [ ] **Step 5: Commit** `plans: public export schema 3 prices team plans per member, with minimum and multiple (plans 6b)`. |
| ### Task 3: Seats, the member lock and membership transitions |
| +Accepted in round 2; unchanged from revision 2. |
| + |
| **Files:** |
| -- Create: `internal/console/planmembers.go`, `internal/console/planmembers_test.go`. |
| +- Create: `internal/console/planmembers.go`, `planmembers_test.go`. |
| - Modify: |
| - - `internal/console/store.go`: `migratePlanSeats()`, adding `account_plans.seats INTEGER NOT NULL DEFAULT 0` (guarded); |
| - - `internal/console/accountplans.go`: `AccountPlanRow.Seats`, the columns, `SetAccountPlan` and the upsert statement carrying seats; billing's guarded write in `SaveBillingSync` compares seats too; |
| - - `internal/console/planlapse.go`: `applyAccountPlan` and `lapseStarted` carry seats; |
| - - `internal/console/planlimits.go`: `EffectiveLimits` and `publishAccountLimits` pass `planMembers`; |
| - - `internal/console/apiaccountplan.go`: the operator door passes seats 0 and validates with the live count; |
| - - `internal/console/store.go` membership functions: transaction variants `acceptInviteTx`, `addMemberTx`, `removeMemberTx`, with the existing functions wrapping them; |
| - - `internal/console/server.go` (`handleInvite`, `handleAcceptInvite`, `handleRevokeInvite`) and `internal/console/ownership.go` (`handleRemoveMember`): the member lock, re-checks inside it, and `membershipTransition`; |
| - - `internal/console/plancaps.go` and `plancaps_copy.go`: `checkMemberCap`, and the free-account copy per Call 16; |
| - - `cmd/console/member.go`: add and remove through `Store.MembershipTransition`, with the catalog loaded when `CARLOS_PLAN_CATALOG` is set. |
| + - `store.go`: `account_plans.seats`, and the `acceptInviteTx`, `addMemberTx`, `removeMemberTx` variants; |
| + - `accountplans.go`: seats in the row, `SetAccountPlan` and the upsert; `SaveBillingSync`'s guard compares seats; |
| + - `planlapse.go`: `applyAccountPlan` and `lapseStarted` carry seats; |
| + - `planlimits.go`: `planMembers`; |
| + - `apiaccountplan.go`; |
| + - `server.go` (`handleInvite`, `handleAcceptInvite`, `handleRevokeInvite`) and `ownership.go` (`handleRemoveMember`): the member lock and in-lock re-checks; |
| + - `plancaps.go`, `plancaps_copy.go`; |
| + - `cmd/console/member.go`: through `Store.MembershipTransition`. |
| **Interfaces:** |
| -- Consumes: Task 1; 6a's `transitionAccountPlan`. |
| - Produces: |
| ```go |
| - // AccountPlanRow gains Seats int: the paid seat count billing wrote; 0 = count members now. |
| func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, seats int, source string, |
| sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) |
| func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, seats int, |
| source string, sponsored *plans.Limits, reason, by string, now time.Time) error |
| - func (s *Store) MemberCount(accountID int64) (int, error) // owners + members; never invites or services |
| - func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) // row.Seats when > 0, else MemberCount |
| - func (s *Server) lockMembers(sqid string) func() // s.memberLocks; outermost of member -> billing -> lapse -> store |
| - |
| - // membershipFell: the row is a live-counted team row (seats 0, a team plan), paid and not sponsored, |
| - // and Effective(before) -> Effective(after) is plans.LimitsFell. |
| + func (s *Store) MemberCount(accountID int64) (int, error) |
| + func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) |
| + func (s *Server) lockMembers(sqid string) func() |
| func membershipFell(cat *plans.Catalog, row *AccountPlanRow, before, after int) bool |
| - // MembershipTransition runs write in one store transaction, counting members before and after. On a |
| - // live-counted team row whose Billed count changed, it bumps the revision; when membershipFell, it |
| - // marks the lapse and deletes the lapse caps' states in the same transaction. changed reports the bump. |
| func (s *Store) MembershipTransition(accountID int64, cat *plans.Catalog, old *AccountPlanRow, |
| write func(tx *sql.Tx) error, now time.Time) (changed bool, err error) |
| - // membershipTransition is the server's only membership write: transitionAccountPlan around |
| - // MembershipTransition, so a change re-converges at once and publishes (finding 10). |
| func (s *Server) membershipTransition(ctx context.Context, acct *Account, now time.Time, write func(tx *sql.Tx) error) error |
| - func (s *Server) checkMemberCap(acct *Account, adding int) error // *planCapError when members+adding > MaxMembers; nil for team plans, sponsored rows, no catalog |
| + func (s *Server) checkMemberCap(acct *Account, adding int) error |
| ``` |
| -- `membershipTransition` passes the old row from `transitionAccountPlan`'s callback, so the before count and the before limits are read inside the same lapse lock and transaction as the write. Publication failure is retried by the limits pass, because `published_revision < revision`. |
| -- The CLI (`cmd/console member`) uses `Store.MembershipTransition` directly. It has no server, so the hourly grace and limits passes converge and publish. It is an operator path: the billing seat reconciliation catches its effect on seats (Task 11). |
| -- **Every invite and join runs under `lockMembers(sqid)`** (finding 2): |
| - - `handleInvite` counts pending invites, checks the cap and creates the invite inside the lock. |
| - - `handleAcceptInvite` finds the invite's account with `PendingInviteFor`, takes the lock, then **re-checks inside it**: `PendingInviteFor` again (still pending, addressed to this session, unexpired), not already a member, and `checkMemberCap(acct, 1)`. Only then does it call `membershipTransition(acceptInviteTx)`. Task 11 adds the billing step between the re-checks and the write. |
| - - `handleRemoveMember` and `handleRevokeInvite` take the lock too. |
| -- Draft copy: `browser.cap.members` "This plan has room for %d members. Move to a team plan to add more."; `browser.cap.members_join` "This account is full on its plan. Ask an owner to move it to a team plan."; `browser.cap.free_account` "You already own a free account, and each person can own one. Upgrade that account to create another, or ask an operator."; with `cli.` twins. |
| +- How these work: |
| + - `MembershipTransition` counts members before and after, in one transaction. On a live-counted team row whose billed count changed, it bumps the revision; on a fall, it marks the lapse and resets the lapse caps. |
| + - `membershipTransition` wraps it in `transitionAccountPlan`. The limits pass retries publication. |
| + - Every invite, join, revoke and removal runs under `lockMembers`. Accept re-checks inside the lock: the invite, existing membership and the cap. |
| +- Draft copy: `browser.cap.members`, `browser.cap.members_join`, `browser.cap.free_account` (Call 16), with `cli.` twins. |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestTeamLimitsFollowMembers(t *testing.T) // operator community (seats 0); 12 members: RunningThings 60; remove 2: 50 (min 10) |
| - func TestSeatsPinTeamLimits(t *testing.T) // SetAccountPlan(community, seats 14) with 3 members: RunningThings 70 |
| - func TestMembershipRiseReconvergesAndPublishes(t *testing.T) // community seats 0, 10 -> 11 members: revision+1, limits record republished, grace pass ran |
| - func TestMembershipFallStartsLapse(t *testing.T) // operator community, 14 -> 11 members: LapseSince set, lapse cap states reset |
| - func TestMembershipNoLimitChangeWritesNothing(t *testing.T) // community 4 -> 5 members (billed 10 both): no revision bump, no publish |
| - func TestMembershipPublishFailureRetried(t *testing.T) // publish fails on the change: published_revision < revision; limits pass publishes |
| - func TestCLIMembershipTransition(t *testing.T) // cmd/console member -remove on a live-counted community: revision bumped, LapseSince set |
| - func TestConcurrentInvitesRespectCap(t *testing.T) // personal max 3, 2 members: two invites in parallel: one created, one refused |
| - func TestConcurrentAcceptsRespectCap(t *testing.T) // personal, 2 members, two pending invites: two accepts in parallel: members 3, one refused, its invite still pending |
| - func TestAcceptRechecksInsideLock(t *testing.T) // revoke lands while accept waits on the lock: accept refused as gone |
| - func TestMemberCapAtInvite(t *testing.T) // personal 2 members + 1 pending: refused; community: allowed; sponsored: allowed |
| - func TestMemberCountExcludesInvitesAndServices(t *testing.T) // 2 members, 1 pending invite, 1 service credential: 2 |
| - ``` |
| +- [ ] **Step 1: Write the failing tests:** `TestTeamLimitsFollowMembers`, `TestSeatsPinTeamLimits`, `TestMembershipRiseReconvergesAndPublishes`, `TestMembershipFallStartsLapse`, `TestMembershipNoLimitChangeWritesNothing`, `TestMembershipPublishFailureRetried`, `TestCLIMembershipTransition`, `TestConcurrentInvitesRespectCap`, `TestConcurrentAcceptsRespectCap`, `TestAcceptRechecksInsideLock`, `TestMemberCapAtInvite`, `TestMemberCountExcludesInvitesAndServices` (as revision 2). |
| - [ ] **Step 2: Run** `go test ./internal/console/ -run 'TeamLimits|SeatsPin|Membership|CLIMembership|Concurrent(Invites|Accepts)|AcceptRechecks|MemberCap|MemberCount'` and `go test ./cmd/console/ -run Member`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'AccountPlan|PlanLimits|Lapse|Invite|ClaimSQL'`. Expected: PASS. |
| @@ -406,405 +361,327 @@ Also binding: |
| ### Task 4: Provider boundary and a payment-faithful fake |
| **Files:** |
| -- Modify: |
| - - `internal/billing/billing.go`: new facts, types and `Provider` methods; |
| - - `internal/billing/recognise.go`: team quantities, `Purchase.Seats`, `FindItem`; |
| - - `internal/billing/billingtest/fake.go`. |
| -- Test: `internal/billing/recognise_test.go`, `internal/billing/billingtest/fake_test.go`. |
| +- Modify: `internal/billing/billing.go`, `recognise.go`, `billingtest/fake.go`. |
| +- Test: `recognise_test.go`, `billingtest/fake_test.go`. |
| **Interfaces:** |
| -- Consumes: Task 1. |
| - Produces: |
| ```go |
| - // Item gains ItemID string. |
| - // Subscription gains: |
| - // PendingUpdate bool // a change waits for payment |
| - // PendingExpires time.Time // when the provider drops it |
| - // Collecting bool // the provider is retrying or is owed a payment (adapter: past_due, unpaid, incomplete) |
| + // Item gains ItemID. Subscription gains PendingUpdate bool, PendingExpires time.Time, Collecting bool. |
| func (s *Subscription) Renewing() bool // Live && !CancelAtPeriodEnd |
| // Purchase gains Seats int. |
| type Proration string |
| const (ProrateNone Proration = "none"; ProrateNow Proration = "now") |
| - type ItemChange struct { ItemID, PriceID string; Quantity int64; Delete bool } // ItemID "" adds; another PriceID swaps |
| + type ItemChange struct { ItemID, PriceID string; Quantity int64; Delete bool } |
| type ChangeRequest struct { |
| Subscription string |
| Items []ItemChange |
| Proration Proration |
| - ProrationDate time.Time |
| + ProrationDate time.Time // persisted with the operation; never recomputed |
| IdempotencyKey string |
| } |
| type CheckoutState string |
| const (CheckoutOpen CheckoutState = "open"; CheckoutComplete CheckoutState = "complete"; CheckoutExpired CheckoutState = "expired") |
| - type CheckoutInfo struct { ID, URL, Subscription, Customer, IntentID string; State CheckoutState } |
| + type CheckoutInfo struct { ID, URL, Subscription, Customer, IntentID string; State CheckoutState; ExpiresAt time.Time } |
| type CheckoutItem struct { PriceID string; Quantity int64 } |
| type CheckoutRequest struct { |
| Customer, AccountSqid, IntentID, Book, Currency string |
| - Items []CheckoutItem |
| - SuccessURL string // carries the literal {CHECKOUT_SESSION_ID} |
| - CancelURL string |
| - House bool |
| - ExpiresAt time.Time |
| - IdempotencyKey string |
| + Items []CheckoutItem |
| + SuccessURL, CancelURL string |
| + House bool |
| + ExpiresAt time.Time |
| + IdempotencyKey string |
| } |
| + const MaxListPages = 10 // of 100 |
| var ( |
| - ErrPaymentFailed = errors.New("billing: payment failed") // the charge was declined; nothing applied |
| - ErrUncertain = errors.New("billing: outcome unknown") // transport error, timeout or 5xx: the request may have run |
| + ErrPaymentFailed = errors.New("billing: payment failed") // declined; nothing applied |
| + ErrRefused = errors.New("billing: request refused") // a definite 4xx refusal; nothing applied |
| + ErrUncertain = errors.New("billing: outcome unknown") // transport, timeout or 5xx |
| + ErrIncomplete = errors.New("billing: list incomplete") // more than MaxListPages pages |
| ErrNoHouseCoupon = errors.New("billing: no house coupon configured") |
| ) |
| // Provider gains: |
| EnsureCustomer(ctx context.Context, accountSqid, idempotencyKey string) (string, error) |
| - LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // one request; ids of Live subscriptions only |
| + LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // exhaustive or ErrIncomplete |
| + CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) // exhaustive or ErrIncomplete |
| StartCheckout(ctx context.Context, req CheckoutRequest) (CheckoutInfo, error) |
| Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error) |
| - ExpireCheckout(ctx context.Context, sessionID, idempotencyKey string) (CheckoutState, error) // the state after the call: expired, or complete if it completed first; never "success" for a completed session |
| + ExpireCheckout(ctx context.Context, sessionID, idempotencyKey string) (CheckoutState, error) // expired, or complete if it completed first |
| ChangeItems(ctx context.Context, req ChangeRequest) (*Subscription, error) |
| SetRenewal(ctx context.Context, subscription string, renew bool, idempotencyKey string) (*Subscription, error) |
| PortalURL(ctx context.Context, customer, returnURL, idempotencyKey string) (string, error) |
| - func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool) // KindPlan with name "" finds the plan item |
| + func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool) |
| ``` |
| -- `Recognise`: a non-team plan item needs quantity 1; a team plan item needs `Team.MinMembers` to `MaxTeamMembers`, and sets `Purchase.Seats`. |
| -- **`billingtest.Fake` models payments faithfully:** |
| - - **Idempotency:** a key seen before, with the same parameters, returns the stored result and applies nothing. With other parameters it returns an error. `Keys map[string]int` counts the sends. |
| - - **Outstanding payments:** with `FailPayment` set, a `ProrateNow` change leaves the items alone and sets `PendingUpdate`, with `PendingExpires = now + 23h`. `DeclineHard` returns `ErrPaymentFailed` instead. |
| - - **Later payment:** `PayPending(sub)` applies the pending items and clears the flag. `ExpirePending(sub)` drops them. |
| - - **Lost responses:** `LoseNextResponse` applies the next write, then returns `ErrUncertain`. |
| - - **Checkout sessions:** sessions are open, complete or expired. `CompleteCheckout(cs, sub)` and `CompleteBeforeExpire(cs)` (an expiry that loses the race returns `CheckoutComplete`) model the races. |
| - - **Lists:** `LiveSubscriptions` lists `Live` subs per customer. `Customers` maps a sqid to its customer, stable across calls. |
| - - **Records:** `Changes`, `Started`, `Expired`, `Renewals`, `PortalCalls`; new item ids are `si_<n>`. |
| - - **Reordering:** none is needed. Tests deliver webhook events in any order, because every event triggers a fresh read. |
| +- `Recognise`: a team plan item needs `MinMembers` to `MaxTeamMembers`, and sets `Seats`. Other plan items need quantity 1. |
| +- **`billingtest.Fake`** models: |
| + - **Idempotency:** the same key with the same parameters returns the stored result and applies nothing; with other parameters, an error. |
| + - **Pending payments:** `FailPayment` gives a pending update (`PendingExpires` +23 h); `DeclineHard` gives `ErrPaymentFailed`; `PayPending` and `ExpirePending` resolve it. |
| + - **Failure before delivery:** `FailBeforeDelivery` returns `ErrUncertain` and applies nothing, and records no key. |
| + - **Lost responses:** `LoseNextResponse` applies, then returns `ErrUncertain`. |
| + - **Renewal:** `Renew(sub)` moves `PeriodEnd` a year on. Items carry over at their current quantities, and any pending update is dropped. |
| + - **Paging:** `PageSize` (default 100) and counted pages. More than `MaxListPages` pages gives `ErrIncomplete`. |
| + - **Checkout:** sessions open, complete or expired; `CompleteCheckout`, `CompleteBeforeExpire`, `SessionsFor(customer)`. |
| + - **Call counts by method:** `CallsBy map[string]int`. |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestRecogniseTeamSeats(t *testing.T) // community x 12 + apps x 1: Seats 12, Packs {apps:1}; personal: Seats 0 |
| - func TestRecogniseTeamRefuses(t *testing.T) // community x 9; x 10001; personal x 2: ErrUnrecognised |
| - func TestFindItem(t *testing.T) // plan and pack items with ItemID; absent pack: false |
| - func TestFakeIdempotency(t *testing.T) // same key twice: applied once, same result; same key, other quantity: error |
| - func TestFakePendingPayLaterExpire(t *testing.T) // FailPayment: PendingUpdate, items unchanged; PayPending: applied; again with ExpirePending: dropped |
| - func TestFakeLostResponse(t *testing.T) // LoseNextResponse: ErrUncertain, change applied; resend same key: stored result, not reapplied |
| - func TestFakeCheckoutRaces(t *testing.T) // ExpireCheckout open: expired; CompleteBeforeExpire: CheckoutComplete |
| + func TestRecogniseTeamSeats(t *testing.T) |
| + func TestRecogniseTeamRefuses(t *testing.T) |
| + func TestFindItem(t *testing.T) |
| + func TestFakeIdempotency(t *testing.T) |
| + func TestFakePendingPayLaterExpire(t *testing.T) |
| + func TestFakeFailBeforeDelivery(t *testing.T) // ErrUncertain, nothing applied, key unknown |
| + func TestFakeLostResponse(t *testing.T) // ErrUncertain, applied |
| + func TestFakeRenew(t *testing.T) // PeriodEnd +1y, items kept, pending dropped |
| + func TestFakePagingAndIncomplete(t *testing.T) // PageSize 2, 5 live subs: 3 pages counted; 21 pages: ErrIncomplete |
| + func TestFakeCheckoutRaces(t *testing.T) |
| ``` |
| - [ ] **Step 2: Run** `go test ./internal/billing/... -run 'Recognise|FindItem|Fake'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Temporary `errors.New("not built")` adapter methods keep the build until Task 5. |
| +- [ ] **Step 3: Implement.** Temporary adapter stubs keep the build. |
| - [ ] **Step 4: Run** again, plus `go build ./...`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `billing: team items, item ids, neutral collecting and pending facts, checkout states, and a fake that models idempotency, pending payments, expiry and lost responses (plans 6b)`. |
| +- [ ] **Step 5: Commit** `billing: team items, neutral facts, exhaustive lists, checkout states, and a fake that models failure before delivery, lost responses, pending payments and renewal (plans 6b)`. |
| ### Task 5: Stripe adapter writes and the extended readiness check |
| **Files:** |
| - Modify: |
| - - `internal/billingstripe/client.go`: |
| - - `UpdateSubscription`; |
| - - `Subscription.PendingUpdate` and `PendingExpires`, from `pending_update` and `pending_update.expires_at`; |
| - - `CreateCheckoutParams.CollectAddress` and `.ExpiresAt`; |
| - - `ListLiveSubscriptions` (one `status=all` page, filtered in the adapter); |
| - - `internal/billingstripe/customer.go`: `CreateCustomer` accepts an empty `Country` (no address, no `tax[validate_location]`); |
| - - `internal/billingstripe/adapter.go`: |
| - - the new methods; |
| - - `collectingOf(status)` beside 6a's `stateOf`/`liveOf`; |
| - - `ProviderConfig.PortalConfiguration` and `.HouseCoupon`; |
| - - the `Check` additions; |
| - - error classification: `card_error` is `ErrPaymentFailed`; transport errors, timeouts and 5xx are `ErrUncertain`; |
| - - `cmd/console/billing.go` and its test: `CARLOS_STRIPE_PORTAL_CONFIGURATION` (required, `bpc_`) and `CARLOS_STRIPE_HOUSE_COUPON` (optional). |
| -- Test: `internal/billingstripe/adapter_test.go`, `client_test.go`, `customer_test.go`; `cmd/console/billing_test.go`. |
| + - `internal/billingstripe/client.go`: `UpdateSubscription`; pending-update decoding; checkout address collection and expiry; `ListCustomerSubscriptionsAll` and `ListCustomerCheckoutsSince`, which page with `starting_after` up to `MaxListPages`, else `ErrIncomplete`; |
| + - `customer.go`: an empty country is allowed; |
| + - `adapter.go`: the methods, `collectingOf`, portal and coupon configuration, the `Check` additions, error classification (`card_error` is `ErrPaymentFailed`; other 4xx `ErrRefused`; transport, timeout and 5xx `ErrUncertain`); |
| + - `cmd/console/billing.go`: `CARLOS_STRIPE_PORTAL_CONFIGURATION` (required), `CARLOS_STRIPE_HOUSE_COUPON` (optional). |
| **Interfaces:** |
| -- Consumes: Task 4. |
| -- Produces: |
| - ```go |
| - type SubscriptionItemUpdate struct { ID, PriceID string; Quantity int64; Deleted bool } |
| - type SubscriptionUpdate struct { |
| - Items []SubscriptionItemUpdate |
| - Proration string |
| - ProrationDate time.Time |
| - PendingIfIncomplete bool |
| - CancelAtPeriodEnd *bool |
| - } |
| - func (c *Client) UpdateSubscription(ctx context.Context, id string, p SubscriptionUpdate, idempotencyKey string) (*Subscription, error) |
| - func collectingOf(status string) bool // past_due, unpaid, incomplete |
| - ``` |
| +- Produces: `SubscriptionItemUpdate`, `SubscriptionUpdate`, `(*Client).UpdateSubscription`, `collectingOf`, and the two list functions. |
| +- The client keeps 6a's rule: **no retries**. A send is one HTTP request. |
| - Mappings: |
| | Method | Stripe | |
| | --- | --- | |
| - | `StartCheckout` | `billing_address_collection=required`, `customer_update[address]=auto`, `expires_at`, and the configured coupon when `House` (`ErrNoHouseCoupon` with none configured, before any request) | |
| - | `Checkout` | `GetCheckout`; `status` mapped to `CheckoutState`, plus the subscription, customer and `metadata[checkout_intent]` | |
| - | `ExpireCheckout` | POST expire; on a Stripe 400, `GetCheckout`, returning its state (`complete` or `expired`). Never nil-as-success. | |
| - | `ChangeItems` | `ProrateNow`: `always_invoice` + `pending_if_incomplete`; `ProrateNone`: `none`; items by id, price, quantity, deleted; `proration_date` | |
| - | `SetRenewal` | `cancel_at_period_end = !renew` | |
| - | `PortalURL` | `CreatePortal` with the configured configuration | |
| + | `StartCheckout` | address collection, `expires_at`, the house coupon (`ErrNoHouseCoupon` before any request) | |
| + | `Checkout` | status, subscription, customer, `metadata[checkout_intent]`, `expires_at` | |
| + | `ExpireCheckout` | on a 400, a session read returning its state | |
| + | `ChangeItems` | `always_invoice` + `pending_if_incomplete`, or `none`; items; the given `proration_date`, sent unchanged | |
| + | `SetRenewal` | `cancel_at_period_end` | |
| + | `PortalURL` | the configured configuration | |
| + | `LiveSubscriptions` | every page, filtered by the adapter's `liveOf` | |
| + | `CustomerCheckouts` | every page created after the time given | |
| - `Check` additions: |
| - - **Portal configuration:** active; this mode; payment method update on; invoice history on; subscription update off; subscription cancel off; customer update off or limited to `address`, `name`, `tax_id`. |
| - - **Coupon,** when set: valid; this mode; 100% off; no `amount_off`; `forever`; no product restriction. |
| - - Errors name the variable, never ids. |
| + - **Portal:** active; mode; payment method update on; invoice history on; subscription update and cancel off; customer update off or ⊆ {address, name, tax_id}. |
| + - **Coupon:** valid; mode; 100%; no amount off; forever; unrestricted. |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestChangeItemsSendsProration(t *testing.T) // ProrateNow form; ProrateNone form; add, swap, delete; Idempotency-Key |
| - func TestChangeItemsOutcomes(t *testing.T) // pending_update in response: PendingUpdate + PendingExpires; 402 card_error: ErrPaymentFailed; 500 and timeout: ErrUncertain |
| - func TestStartCheckoutCollectsAddress(t *testing.T) // address collection, expires_at, coupon only when House; House without coupon: ErrNoHouseCoupon and no request sent |
| + func TestChangeItemsSendsProration(t *testing.T) // includes proration_date exactly as given |
| + func TestChangeItemsOutcomes(t *testing.T) // pending; 402 card_error ErrPaymentFailed; 400 ErrRefused; 500 and timeout ErrUncertain |
| + func TestNoClientRetry(t *testing.T) // a 500 or timeout: exactly one HTTP request |
| + func TestStartCheckoutCollectsAddress(t *testing.T) |
| func TestEnsureCustomerSendsNoAddress(t *testing.T) |
| - func TestExpireCheckoutStates(t *testing.T) // 200: expired; 400 then GET complete: CheckoutComplete (not success); 400 then GET open: error |
| - func TestLiveSubscriptions(t *testing.T) // list with active, canceled, past_due with cancel_at_period_end, incomplete_expired: ids of active and past_due only |
| - func TestCollectingOf(t *testing.T) // past_due, unpaid, incomplete true; active, canceled false |
| + func TestExpireCheckoutStates(t *testing.T) |
| + func TestLiveSubscriptionsPagesToCompletion(t *testing.T) // page 1 ended only, page 2 has an active sub: returned; requests == 2 |
| + func TestLiveSubscriptionsIncomplete(t *testing.T) // 11 full pages: ErrIncomplete |
| + func TestCustomerCheckoutsPages(t *testing.T) |
| + func TestCollectingOf(t *testing.T) |
| func TestSetRenewal(t *testing.T) |
| - func TestCheckRefusesUnlockedPortal(t *testing.T) // inactive; other mode; payment_method_update off; invoice history off; subscription_update on; cancel on; |
| - // customer_update allows email: each an error naming CARLOS_STRIPE_PORTAL_CONFIGURATION |
| - func TestCheckRefusesBadHouseCoupon(t *testing.T) // valid false; other mode; 50% off; once; amount_off; product-restricted: each an error; good coupon: nil |
| + func TestCheckRefusesUnlockedPortal(t *testing.T) // inactive; other mode; payment method update off; invoice history off; update on; cancel on; email allowed |
| + func TestCheckRefusesBadHouseCoupon(t *testing.T) // invalid; other mode; 50%; once; amount_off; restricted |
| func TestBillingConfigPortalAndCoupon(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ -run 'ChangeItems|StartCheckout|EnsureCustomer|ExpireCheckout|LiveSubscriptions|CollectingOf|SetRenewal|CheckRefuses|BillingConfig'`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ -run 'ChangeItems|NoClientRetry|StartCheckout|EnsureCustomer|ExpireCheckout|LiveSubscriptions|CustomerCheckouts|CollectingOf|SetRenewal|CheckRefuses|BillingConfig'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/billingstripe/` and `GOOS=darwin go vet ./internal/billingstripe/`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `billingstripe: subscription updates with pending-if-incomplete, checkout states that tell expired from completed, live-subscription listing, and a readiness check that the portal is locked and the house coupon is free forever (plans 6b)`. |
| +- [ ] **Step 5: Commit** `billingstripe: single-send subscription updates, exhaustive paged lists, checkout states that tell expired from completed, and a readiness check for the locked portal and house coupon (plans 6b)`. |
| ### Task 6: Billing state: seats, facts, intents, house, retirement |
| **Files:** |
| - Modify: |
| - `internal/console/billingstore.go`: |
| - - columns on `billing_accounts`: `plan`, `seats`, `paid_seats`, `live`, `collecting`, `pending_update`, `pending_expires`, `seats_checked_at` (guarded `ALTER TABLE`s); |
| - - tables `billing_checkout_intents`, `billing_house` and `billing_retirements`; |
| - - methods; |
| - - `internal/console/billingsync.go`: `decideBilling` carries seats and the neutral facts; `planChange.Seats` flows through 6a's `applyBillingPlan` → `SaveBillingSync`, the single atomic billing, plan and lapse transaction (no separate write path); |
| - - `internal/console/store_gate.go`: the three tables. |
| -- Test: `internal/console/billingstore_test.go`, `internal/console/billingsync_test.go`. |
| + - columns `plan`, `seats`, `paid_seats`, `live`, `collecting`, `pending_update`, `pending_expires`, `seats_checked_at` on `billing_accounts`; |
| + - tables `billing_checkout_intents`, `billing_house`, `billing_retirements`; |
| + - `billingsync.go`: seats and facts in `decideBilling`; `planChange.Seats` goes through 6a's `applyBillingPlan` → `SaveBillingSync`; |
| + - `store_gate.go`. |
| **Interfaces:** |
| -- Consumes: Task 3 (seats on the plan write), Task 4 (facts, `Purchase.Seats`). |
| - Produces: |
| ```go |
| - // billingAccount gains: Plan string; Seats int (the current team quantity); PaidSeats int (the period's highest paid); |
| - // Live, Collecting, PendingUpdate bool; PendingExpires, SeatsCheckedAt time.Time. |
| - // planChange gains Seats int (0 for non-team plans). |
| - func billingRenewing(b *billingAccount) bool // b.Live && !b.CancelAtPeriodEnd: neutral facts only |
| + // billingAccount gains Plan; Seats; PaidSeats; Live, Collecting, PendingUpdate; PendingExpires, SeatsCheckedAt. |
| + func billingRenewing(b *billingAccount) bool // b.Live && !b.CancelAtPeriodEnd |
| type checkoutIntent struct { |
| - AccountID int64 |
| - ID, Session, URL string |
| - Book, Plan, Currency string |
| - Seats int |
| - Packs map[string]int |
| - Items []billing.CheckoutItem // the exact request, price ids and quantities |
| - House bool |
| - State string // intentOpen | intentCompleted | intentExpired | intentAbandoned |
| - CreatedAt, ExpiresAt, ReturnedAt time.Time |
| + AccountID int64 |
| + ID, Session, URL string |
| + Book, Plan, Currency string |
| + Seats int |
| + Packs map[string]int |
| + Items []billing.CheckoutItem |
| + House bool |
| + State string // intentCreating | intentOpen | intentCompleted | intentExpired | intentAbandoned |
| + CreatedAt, ExpiresAt, ReturnedAt, ResolvedAt time.Time |
| } |
| - func (s *Store) PutCheckoutIntent(ci checkoutIntent) error // one row per account; replaced only by callers that resolved the old one |
| + func intentTerminal(ci *checkoutIntent) bool // completed, expired or abandoned (Invariant 6) |
| + func (s *Store) PutCheckoutIntent(ci checkoutIntent) error |
| func (s *Store) CheckoutIntent(accountID int64) (*checkoutIntent, error) |
| func (s *Store) CheckoutIntentBySession(session string) (*checkoutIntent, error) |
| - func (s *Store) UnresolvedCheckoutIntents(createdAfter time.Time, limit int) ([]checkoutIntent, error) // state open |
| + func (s *Store) NonTerminalCheckoutIntents(limit int) ([]checkoutIntent, error) |
| func (s *Store) SetBillingHouse(accountID int64, on bool, by, note string, now time.Time) error |
| func (s *Store) BillingHouse(accountID int64) (bool, error) |
| func (s *Store) BeginRetirement(accountID int64, by string, now time.Time) error |
| func (s *Store) EndRetirement(accountID int64) error |
| - func (s *Store) Retiring(accountID int64, now time.Time) (bool, error) // a row younger than retirementTTL (1 h); older rows are stale and cleared |
| + func (s *Store) Retiring(accountID int64, now time.Time) (bool, error) // rows older than retirementTTL (1 h) are stale and cleared |
| ``` |
| -- Schema: |
| - - `billing_checkout_intents(account_id INTEGER PRIMARY KEY, intent_id TEXT NOT NULL UNIQUE, session TEXT NOT NULL DEFAULT '', url TEXT NOT NULL DEFAULT '', book TEXT NOT NULL, plan TEXT NOT NULL, currency TEXT NOT NULL, seats INTEGER NOT NULL DEFAULT 0, packs TEXT NOT NULL DEFAULT '{}', items TEXT NOT NULL, house INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, returned_at INTEGER NOT NULL DEFAULT 0)`, with a partial unique index on `session` where non-empty; |
| - - `billing_house(account_id INTEGER PRIMARY KEY, set_by TEXT NOT NULL, note TEXT NOT NULL, set_at INTEGER NOT NULL)`; |
| - - `billing_retirements(account_id INTEGER PRIMARY KEY, started_by TEXT NOT NULL, started_at INTEGER NOT NULL)`. |
| -- `decideBilling` additions: |
| - - every saved row copies `Live`, `Collecting`, `PendingUpdate` and `PendingExpires` from the read; |
| - - paid and recognised: `Next.Plan`, and `Next.Seats = Purchase.Seats`; |
| - - `PaidSeats = Purchase.Seats` when the period changed, the plan changed, or the subscription identity changed (6a already clears per-period state on a new subscription); else `max(Prev.PaidSeats, Purchase.Seats)`; |
| +- Schema as revision 2, with `state` in the intents table taking the five values above. |
| +- `decideBilling`: |
| + - copies the facts; |
| + - `PaidSeats` resets on a new period, plan or subscription identity, and otherwise takes the max; |
| - `planChange.Seats = PaidSeats`; |
| - - ended: clear `Plan`, `Seats` and `PaidSeats`. |
| -- **6a integration tests** (gap), against 6a's merged sync, discovery and missing-subscription paths: |
| - - discovery adopting a missed purchase, then seats written; |
| - - pending-replacement adoption, then payment, then seats; |
| - - a new subscription identity clearing the old seat allowance; |
| - - `subscription_missing` closure racing a seat write, both under the billing lock, ending in one consistent state. |
| + - an ended subscription clears the team fields. |
| +- **6a integration tests:** discovery → seats; pending replacement → payment; identity change clears seats; `subscription_missing` closure racing a seat write; seats through `SaveBillingSync`'s one transaction. |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestDecideTeamSeatsHoldUntilRenewal(t *testing.T) // community 14 then 11 same period: Seats 14; raised to 12: 14; new period with 11: 11 |
| - func TestDecideUpgradeResetsSeats(t *testing.T) // personal -> business x 10 same period: PaidSeats 10 |
| - func TestDecideNewSubscriptionClearsSeats(t *testing.T) // old sub ended with PaidSeats 20, new sub community x 10: PaidSeats 10 |
| - func TestDecideSavesFacts(t *testing.T) // Live, Collecting, PendingUpdate, PendingExpires copied |
| - func TestSyncSeatsGoThroughOneTransaction(t *testing.T) // a trigger failing the plan write: billing row and seats unchanged (6a's SaveBillingSync atomicity) |
| - func TestDiscoveryThenSeats(t *testing.T) |
| - func TestPendingReplacementThenPayment(t *testing.T) |
| - func TestMissingClosureRacesSeatWrite(t *testing.T) // hook between steps; both orders end consistent |
| - func TestCheckoutIntentRoundTrip(t *testing.T) |
| - func TestBillingHouseOnOff(t *testing.T) |
| - func TestRetirementRowsExpire(t *testing.T) // Retiring true; after 1 h: false and cleared |
| - func TestBillingRenewingUsesFacts(t *testing.T) // Live+!Cancel true; Live+Cancel false; !Live false |
| - ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideTeam|DecideUpgrade|DecideNewSubscription|DecideSaves|SyncSeats|DiscoveryThenSeats|PendingReplacementThen|MissingClosureRaces|CheckoutIntent|BillingHouse|Retirement|BillingRenewing'`. Expected: FAIL. |
| +- [ ] **Step 1: Write the failing tests:** `TestDecideTeamSeatsHoldUntilRenewal`, `TestDecideUpgradeResetsSeats`, `TestDecideNewSubscriptionClearsSeats`, `TestDecideSavesFacts`, `TestSyncSeatsGoThroughOneTransaction`, `TestDiscoveryThenSeats`, `TestPendingReplacementThenPayment`, `TestMissingClosureRacesSeatWrite`, `TestCheckoutIntentRoundTrip`, `TestIntentTerminal`, `TestBillingHouseOnOff`, `TestRetirementRowsExpire`, `TestBillingRenewingUsesFacts`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideTeam|DecideUpgrade|DecideNewSubscription|DecideSaves|SyncSeats|DiscoveryThenSeats|PendingReplacementThen|MissingClosureRaces|CheckoutIntent|IntentTerminal|BillingHouse|Retirement|BillingRenewing'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Decide|Sync|BillingWebhook|BillingSyncPass|ClaimSQL'`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: billing keeps team seats and neutral provider facts through 6a's one transaction; Checkout intents keep the whole request; house and retirement rows (plans 6b)`. |
| +- [ ] **Step 5: Commit** `console: billing keeps team seats and neutral provider facts through 6a's one transaction; Checkout intents, house and retirement rows (plans 6b)`. |
| -### Task 7: The billing hold, durable operations and the locked sync |
| +### Task 7: The billing hold, single-send operations and observation |
| **Files:** |
| -- Create: |
| - - `internal/console/billinghold.go`: `billingHold`, `holdBilling`, `syncSubscriptionLocked`, `freshenLocked`; |
| - - `internal/console/billingops.go`: the operations table and runner; |
| - - `internal/console/billinghold_test.go`, `internal/console/billingops_test.go`, `internal/console/billinglint_test.go`. |
| +- Create: `internal/console/billinghold.go`, `billingops.go`, `billinghold_test.go`, `billingops_test.go`, `billinglint_test.go`. |
| - Modify: |
| - - `internal/console/billingsync.go`: 6a's `syncSubscription` becomes the customer lookup, then `holdBilling`, then `syncSubscriptionLocked`. `endMissingSubscription` and 6a's other locking paths take the lock through `holdBilling`. After each `applyBillingRead`, call `settleOpsLocked`. |
| - - `internal/console/billingpass.go`: |
| - - the readiness backoff; |
| - - the pass resolves outstanding operations; |
| - - discovery also selects accounts with an unresolved Checkout intent (Task 9 resolves them). |
| - - `internal/console/store_gate.go`: `billing_operations`. |
| + - `billingsync.go`: `syncSubscription` becomes lookup → `holdBilling` → `syncSubscriptionLocked`; 6a's other locking paths go through `holdBilling`; `settleOpsLocked` runs after each `applyBillingRead`; |
| + - `billingpass.go`: readiness backoff, and the observation of operations; |
| + - `store_gate.go`: `billing_operations`; |
| + - `billingstore.go`: `problemOperationUnresolved`, for Call 17. |
| **Interfaces:** |
| - Consumes: Tasks 4 and 6; 6a's `applyBillingRead`. |
| - Produces: |
| ```go |
| - type billingHold struct{ sqid string } // proof the caller holds s.billing.locks for sqid; only holdBilling makes one |
| + type billingHold struct{ sqid string } |
| func (s *Server) holdBilling(sqid string) (billingHold, func()) |
| func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error |
| - // freshenLocked: read the account's recorded subscription, apply it, reload. Errors when the row and the read |
| - // disagree on identity or period after applying (the caller refuses with change.retry). |
| - func (s *Server) freshenLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error) |
| - |
| - type opStep struct { |
| - Ref string // the price key |
| - To int64 // 0 deletes |
| - Swap string // a price key to swap the plan item to (plan upgrades); "" otherwise |
| - Proration billing.Proration |
| - } |
| + // refreshLocked: the plain sync of the recorded subscription, if any; no period check (Invariant 4). |
| + func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, error) |
| + // allowanceLocked: refreshLocked, then the read must be Live and paid, and row.Subscription == read.ID |
| + // and row.PaidPeriodEnd == read.PeriodEnd; else errAllowanceStale (the caller says change.retry). |
| + // Only quantity changes and joins on a live paid subscription call it. |
| + func (s *Server) allowanceLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error) |
| + |
| + const (opQuiet = 10 * time.Minute; opStuck = time.Hour) |
| type billingOp struct { |
| - ID, Subscription, Kind string // Kind: opPack | opPlan | opSeat | opRestore | opRenewal |
| - AccountID int64 |
| - Steps []opStep |
| - Done int // steps confirmed |
| - ItemID string // the item the next step addresses: carried from each step's response (finding 11) |
| - InviteToken string // opSeat bound to one invite |
| - Renew *bool // opRenewal |
| - State string // opStarted | opPending | opApplied | opFailed | opAbandoned |
| - CreatedAt, UpdatedAt, ExpiresAt time.Time |
| + ID string |
| + AccountID int64 |
| + Subscription string |
| + PeriodEnd time.Time // the period the request was computed in (Invariant 1) |
| + Kind string // opPack | opPlan | opSeat | opRestore | opRenewal |
| + Request billing.ChangeRequest // exact, including ItemID or "", PriceID, Quantity, Proration, ProrationDate, key |
| + Renew *bool // opRenewal instead of Request.Items |
| + InviteToken string // opSeat or opRestore for one join |
| + AuthorisedBy string // the seat authorisation it consumes (opSeat), "" otherwise |
| + State string // opSending | opUncertain | opPending | opApplied | opFailed | opAbandoned |
| + SentAt, SettledAt time.Time |
| } |
| var ErrOpOutstanding = errors.New("billing: another change is in progress") |
| - func (s *Store) BeginBillingOp(op billingOp) error // ErrOpOutstanding when a started|pending row holds the subscription |
| + func (s *Store) BeginBillingOp(op billingOp) error // ErrOpOutstanding when sending|uncertain|pending holds the subscription |
| func (s *Store) PutBillingOp(op billingOp) error |
| func (s *Store) OutstandingBillingOp(subscription string) (*billingOp, error) |
| - func (s *Store) BillingOpForInvite(token string) (*billingOp, error) // the newest op for the invite |
| - func (s *Store) OutstandingBillingOps(limit int) ([]billingOp, error) |
| - func quantitySteps(ref string, current, target, paidHighest int64) []opStep // below |
| + func (s *Store) UnresolvedBillingOps(sentBefore time.Time, limit int) ([]billingOp, error) |
| + func quantityPlan(current, target, paidHighest int64) (restoreTo int64, chargeTo int64) // 0 for "no such step" |
| type opOutcome int |
| const (opOutcomeApplied opOutcome = iota; opOutcomePending; opOutcomeFailed; opOutcomeUncertain) |
| - func (s *Server) beginOpLocked(h billingHold, sub *billing.Subscription, op billingOp, now time.Time) error // ErrOpOutstanding also when sub.PendingUpdate |
| - func (s *Server) runOpLocked(h billingHold, ctx context.Context, acct *Account, op *billingOp, row *billingAccount, now time.Time) (opOutcome, error) |
| + // sendOpLocked writes the row (state sending) with the exact request, sends it once, and records the answer: |
| + // a response at the target -> applied; with PendingUpdate -> pending; ErrPaymentFailed or ErrRefused -> failed; |
| + // ErrUncertain -> uncertain. It never sends again. It returns the response for a following step's item id. |
| + func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error) |
| func (s *Server) settleOpsLocked(h billingHold, acct *Account, sub *billing.Subscription, now time.Time) error |
| - func billingCheckDelay(failures int) time.Duration // 1m doubling to 30m |
| + func billingCheckDelay(failures int) time.Duration |
| ``` |
| -- Schema: `billing_operations(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, subscription TEXT NOT NULL, kind TEXT NOT NULL, steps TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, item_id TEXT NOT NULL DEFAULT '', invite_token TEXT NOT NULL DEFAULT '', renew INTEGER, state TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, expires_at INTEGER NOT NULL DEFAULT 0)`, with: |
| - - a unique partial index on `subscription` WHERE `state IN ('started','pending')`; |
| - - a unique partial index on `invite_token` WHERE `invite_token != '' AND state IN ('started','pending','applied')`. |
| - |
| - Classification: `"billing_operations": {NonApp: "an account's in-flight subscription changes, with their provider idempotency keys; names no app"}`. |
| -- `quantitySteps` (6a Calls 6 and 8): |
| - - `target < current`: `{target, none}`; |
| - - `target > current`: `{min(target, paidHighest), none}` if that exceeds `current`, then `{target, now}` if `target > paidHighest`; |
| - - equal: none. |
| -- `runOpLocked`, for each step from `op.Done`: |
| - 1. Build the `ItemChange`. The item is `op.ItemID`, or found with `FindItem` on the row's last read; with neither, it is an add. |
| - 2. Call `ChangeItems` with key `op.ID:<index>` and `ProrationDate: now`. |
| - 3. **Success:** take the step's item id from the response (`FindItem` by its price), store it in `op.ItemID`, set `op.Done++`, and `PutBillingOp` before the next step. A response without the item makes the runner re-read with `Provider.Subscription` and find it, so the second step of "add 3 then charge to 4" always updates the item the first step created (finding 11). |
| - 4. **Response `PendingUpdate`:** state `pending`, `ExpiresAt = PendingExpires`, stop. |
| - 5. **`ErrPaymentFailed`:** state `failed`, stop. |
| - 6. **`ErrUncertain`:** keep `started`, stop. A retry or the pass resumes the same step with the same key. |
| - |
| - All steps done: `applied`. The runner never starts a step whose index is `< op.Done`. |
| -- `settleOpsLocked`, for the subscription's outstanding operation, on every applied read (webhook, pass, settle): |
| - - `PendingUpdate` set: `pending`; |
| - - the items match the final step's target (`opRenewal`: `CancelAtPeriodEnd == !*Renew`): `applied`; |
| - - the row was `pending`, `PendingUpdate` is gone, and the target was not reached: `abandoned` (expired or declined); |
| - - `started` and older than 23 h without reaching the target: `abandoned`. |
| - |
| - Reordered webhooks change nothing: each settles from the fresh read. |
| -- Pass additions: |
| - - **Readiness:** `StartBillingSyncPass` waits `billingCheckDelay(failures)` between failed checks instead of 6a's fixed minute. |
| - - **Operations:** for each outstanding operation: `holdBilling`, a fresh read with `applyBillingRead` (which settles it), then, still `started`, younger than 23 h and short of its target, `runOpLocked` resumes it with the same keys. |
| +- Schema: `billing_operations(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, subscription TEXT NOT NULL, period_end INTEGER NOT NULL, kind TEXT NOT NULL, request TEXT NOT NULL, renew INTEGER, invite_token TEXT NOT NULL DEFAULT '', authorised_by TEXT NOT NULL DEFAULT '', state TEXT NOT NULL, sent_at INTEGER NOT NULL, settled_at INTEGER NOT NULL DEFAULT 0)`, with a partial unique index on `subscription` WHERE `state IN ('sending','uncertain','pending')`. It is `NonApp`. |
| +- `quantityPlan(current, target, paid)`: |
| + - `target < current`: a reduction (the caller sends `ProrateNone` to `target`); |
| + - otherwise `restoreTo = min(target, paid)` if that is above `current`, and `chargeTo = target` if `target > paid`. |
| +- **Multi-step changes (Invariant 1):** |
| + 1. The handler sends the restore operation. |
| + 2. Only if that returns `applied` with a definite response does it compute the charge request. The item id comes from that response (`FindItem` by price) and the period from the response's `PeriodEnd`. If the period moved, the charge is not sent. |
| + 3. Any other outcome ends the request after the first send. The owner sees the outcome, and a later request recomputes from scratch. |
| +- `settleOpsLocked`, for the subscription's unresolved operation, on every applied read: |
| + 1. `read.ID != op.Subscription` or `read.PeriodEnd != op.PeriodEnd`: `abandoned` (the context moved; the sync already governs the plan). |
| + 2. The items match the request's target, or `CancelAtPeriodEnd == !*Renew`: `applied`. |
| + 3. `PendingUpdate`: `pending`. |
| + 4. The op was `pending`, there is no pending update, and the target is not met: `abandoned`. |
| + 5. The op is `sending` or `uncertain`, the target is not met, there is no pending update, and `now ≥ SentAt + opQuiet`: `abandoned`. |
| + 6. Otherwise unchanged. |
| + |
| + An operation with `AuthorisedBy` set consumes that authorisation when it becomes `applied`, never before (a pending charge that expires leaves the authorisation usable; the one-outstanding rule stops a second charge meanwhile) (Task 11). |
| +- **Observation pass:** for `UnresolvedBillingOps(now - opQuiet)`: `holdBilling`, `syncSubscriptionLocked` (which settles). It sends nothing. With Call 17 (a), an operation still unresolved at `SentAt + opStuck` opens `operation_unresolved`, and changes refuse while it is open. The operator close door allows closing once a fresh read settles it. |
| +- Readiness backoff: `billingCheckDelay` (1, 2, 4, 8, 16, then 30 minutes). |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestBillingLockedHelpersNeverLock(t *testing.T) // go/ast over internal/console: any func with a billingHold param calling holdBilling, syncSubscription, |
| - // endMissingSubscription or locks.lock fails |
| - func TestConsoleBillingHasNoProviderWords(t *testing.T) // billing*.go non-test sources contain none of "past_due","trialing","incomplete","unpaid","canceled","paused" |
| - func TestSyncSubscriptionLockedSharesTheLock(t *testing.T) // holdBilling then syncSubscriptionLocked returns within 5 s |
| - func TestFreshenAppliesDelayedRenewal(t *testing.T) // stored PaidPacks {apps:3} period P1; Fake sub renewed to P2 with apps 1, no webhook: freshen -> row PaidPacks {apps:1}, PaidPeriodEnd P2 |
| - func TestFreshenRefusesIdentityMismatch(t *testing.T) // row names sub_a, read returns a replacement it can't adopt: error |
| - func TestQuantitySteps(t *testing.T) // (1,3,1) [{3,now}]; (1,3,3) [{3,none}]; (1,4,3) [{3,none},{4,now}]; (0,4,3) [{3,none},{4,now}]; (3,1,3) [{1,none}]; (2,2,5) [] |
| - func TestRunOpCarriesNewItemID(t *testing.T) // current 0, paid 3, target 4: step 0 adds -> si_9; step 1 updates si_9 (not a second add) |
| - func TestRunOpResumesAfterFailureBetweenSteps(t *testing.T) // LoseNextResponse on step 0: started, Done 0; resume: same key, Fake applies once; step 1 on the right item |
| - func TestRunOpPendingThenPaid(t *testing.T) // FailPayment: pending; PayPending + webhook: applied |
| - func TestRunOpPendingThenExpired(t *testing.T) // FailPayment: pending; ExpirePending + webhook: abandoned |
| - func TestOneOutstandingPerSubscription(t *testing.T) // BeginBillingOp twice: ErrOpOutstanding; read with PendingUpdate and no row: ErrOpOutstanding |
| - func TestReorderedWebhooksSettleOnce(t *testing.T) // deliver "paid" before "updated" and the reverse: same final op state and plan |
| - func TestReadinessBackoff(t *testing.T) // delays 1m,2m,4m,8m,16m,30m,30m; reset after success; Fake.Calls per failed attempt stops at the failing price |
| + func TestBillingLockedHelpersNeverLock(t *testing.T) |
| + func TestConsoleBillingHasNoProviderWords(t *testing.T) |
| + func TestSyncSubscriptionLockedSharesTheLock(t *testing.T) |
| + func TestRefreshHasNoPeriodCheck(t *testing.T) // ended sub with PeriodEnd, row PaidPeriodEnd cleared: refresh ok |
| + func TestAllowanceAppliesDelayedRenewal(t *testing.T) // PaidPacks {apps:3} P1; Fake Renew to P2 apps 1, no webhook: allowance -> PaidPacks {apps:1}, P2 |
| + func TestAllowanceRefusesEndedOrMismatched(t *testing.T) |
| + func TestQuantityPlan(t *testing.T) // (1,3,1) charge 3; (1,3,3) restore 3; (1,4,3) restore 3 charge 4; (0,4,3) restore 3 charge 4; (2,2,5) none |
| + func TestRequestPersistedBeforeSend(t *testing.T) // FailBeforeDelivery: row exists with exact request, state uncertain; CallsBy[ChangeItems] == 1 |
| + func TestLostAddResponseIsObservedNotResent(t *testing.T) // restore add 3, LoseNextResponse; clock +2h: no second ChangeItems; settle read shows qty 3: applied; |
| + // the charge to 4 never sent; a new owner request computes one ProrateNow to 4 on the existing item |
| + func TestUnsentRestoreAbandonedAcrossRenewal(t *testing.T) // FailBeforeDelivery on a restore to 3 in P1; Renew; pass: abandoned; CallsBy[ChangeItems] == 1 total |
| + func TestChargeNotSentWhenFirstStepPeriodMoved(t *testing.T) // restore response carries P2 (renewed between): charge not sent |
| + func TestPendingThenPaidThenExpired(t *testing.T) // pending -> PayPending -> applied; second run: ExpirePending -> abandoned |
| + func TestUncertainSettledAfterQuiet(t *testing.T) // uncertain, not applied: refused before opQuiet; abandoned at the first read after |
| + func TestOneOutstandingPerSubscription(t *testing.T) |
| + func TestReorderedWebhooksSettleOnce(t *testing.T) |
| + func TestStuckOperationOpensProblem(t *testing.T) // provider unreadable for 1 h: operation_unresolved open, changes refused; read recovers: close allowed |
| + func TestObservationPassSendsNothing(t *testing.T) // CallsBy has no ChangeItems/SetRenewal/StartCheckout/ExpireCheckout after a pass |
| + func TestReadinessBackoff(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|SyncSubscriptionLocked|Freshen|QuantitySteps|RunOp|OneOutstanding|ReorderedWebhooks|ReadinessBackoff'`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|RequestPersisted|LostAdd|UnsentRestore|ChargeNotSent|PendingThen|UncertainSettled|OneOutstanding|ReorderedWebhooks|StuckOperation|ObservationPass|ReadinessBackoff'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Sync|BillingWebhook|BillingSyncPass|Missing|ClaimSQL'`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: a typed billing hold, durable subscription operations with persisted keys and carried item ids, settlement from fresh reads, readiness backoff (plans 6b)`. |
| +- [ ] **Step 5: Commit** `console: typed billing hold; single-send operations bound to subscription and period, settled only by observation; refresh separate from the allowance check (plans 6b)`. |
| ### Task 8: The billing page and the upgrade entry |
| -**Files:** |
| -- Create: `internal/console/billingpage.go`, `internal/console/billingpage_copy.go`, `internal/console/templates/billing.html`, `internal/console/templates/billing_pick.html`, `internal/console/billingpage_test.go`. |
| -- Modify: |
| - - `internal/console/server.go`: the routes, plus `page.Billing *billingView`, `page.BillingPick []Account` and `page.BillingNav bool`; |
| - - `internal/console/templates/layout.html`: the nav link; |
| - - claim files: `route GET /upgrade` and `route GET /a/{sqid}/billing` as `claimRead`, with probes. |
| +Accepted in round 2, except that it now reads intents and operations under the new states. |
| + |
| +**Files:** as revision 2: `billingpage.go`, `billingpage_copy.go`, `templates/billing.html`, `templates/billing_pick.html`, `billingpage_test.go`; the routes, the nav link and the claim entries. |
| **Interfaces:** |
| -- Consumes: Tasks 1, 2, 6, 7; `s.cfg.GeoIPReader`, `s.clientIP`. |
| -- Produces: |
| - ```go |
| - type billingPageInput struct { |
| - Row *AccountPlanRow |
| - Billing *billingAccount |
| - Intent *checkoutIntent |
| - Op *billingOp // the outstanding operation, nil for none |
| - Problems []string // open problem reasons for this account |
| - Retiring bool |
| - Ready bool |
| - Owner bool |
| - Now time.Time |
| - } |
| - type billingPageState struct { Notice string; Buy, Change bool; Renewal string; Portal bool } |
| - func decideBillingPage(in billingPageInput) billingPageState |
| - func (s *Server) requestCountry(r *http.Request) string |
| - // currencyQuery classifies an explicit currency: "" absent; a sold code; or refused. shown is the value |
| - // only when it matches ^[a-z0-9]{1,8}$ (case-folded for display), else "". |
| - func currencyQuery(raw string, book *plans.PriceBook) (code string, refused bool, shown string) |
| - func (s *Server) handleBilling(w http.ResponseWriter, r *http.Request) |
| - func (s *Server) handleUpgrade(w http.ResponseWriter, r *http.Request) |
| - // billingView is billing.html's data, already formatted; field names are the builder's. |
| - ``` |
| -- `decideBillingPage`, first match wins. Actions are offered to owners only; a member gets `notice.owners_only` where an owner would act. No row reads a provider status word. |
| +- Produces: `billingPageInput`, `billingPageState`, `decideBillingPage`, `requestCountry`, `currencyQuery`, `handleBilling`, `handleUpgrade` (as revision 2). |
| +- `decideBillingPage` rows, first match: |
| | Condition | Notice | Offered | |
| | --- | --- | --- | |
| - | `!Ready` | `notice.not_ready` | nothing | |
| - | `Retiring` | `notice.retiring` | nothing | |
| - | problems include `seats_unpaid` | `notice.seats_unpaid` | `Portal` | |
| - | any other problem | `notice.problem` | `Portal` if a customer is bound | |
| + | not ready | `notice.not_ready` | nothing | |
| + | retiring | `notice.retiring` | nothing | |
| + | `seats_unpaid` | `notice.seats_unpaid` | Portal | |
| + | `operation_unresolved` | `notice.unresolved` | Portal | |
| + | other problem | `notice.problem` | Portal if bound | |
| | operator or sponsored row | `notice.operator_plan` | nothing | |
| - | `Op` outstanding, or `Billing.PendingUpdate` | `notice.pending_payment` | `Portal` | |
| - | no live subscription, intent open and returned in the last 24 h | `notice.settling` | nothing | |
| - | no live subscription (`!Billing.Live`) | none | `Buy` | |
| - | `State` pending | `notice.settling` | nothing | |
| - | `Collecting` | `notice.past_due` | `Portal` | |
| - | `CancelAtPeriodEnd` | `notice.ending` | `Renewal` "resume", `Portal` | |
| - | paid | none | `Change`, `Renewal` "stop", `Portal` | |
| -- **Currencies** (finding 13): |
| - - A query `currency` that is absent preselects `ChooseCurrency("", requestCountry(r))`. |
| - - A sold code preselects it. |
| - - Anything else, upper case or malformed (`usd1`, `<script>`), shows `currency.refused` with the value only when `currencyQuery` gives a `shown`, otherwise `currency.refused_unshown`, and preselects nothing. |
| - - When the account has a fixed currency (`Billing.Currency` from any earlier subscription, live or ended), the Buy form shows it as text with a hidden field and no radios. A different explicit query value shows `currency.fixed`. |
| -- `/upgrade` contract (Call 1): |
| + | an unresolved operation, or `PendingUpdate` | `notice.pending_payment` | Portal | |
| + | intent `creating` or `open`, not live | `notice.settling` | nothing | |
| + | not `Live` | none | Buy | |
| + | pending state | `notice.settling` | nothing | |
| + | `Collecting` | `notice.past_due` | Portal | |
| + | `CancelAtPeriodEnd` | `notice.ending` | resume, Portal | |
| + | paid | none | Change, stop, Portal | |
| + |
| + Terminal intents are ignored (Invariant 6). |
| +- **Currencies** (round 2 accepted these): |
| + - absent: preselect `ChooseCurrency("", requestCountry(r))`; |
| + - a sold code: preselect it; |
| + - anything else (upper case, `usd1`, `<script>`): `currency.refused` showing the value only when `currencyQuery` returns a safe `shown` (`^[a-z0-9]{1,8}$` after case folding), else `currency.refused_unshown`, with nothing preselected. |
| + |
| + An account with a fixed currency (from any earlier subscription) gets that currency as text and a hidden field, with no radios. A different explicit value shows `currency.fixed`. |
| +- **`/upgrade` contract:** |
| - `GET /upgrade?plan=<plan>¤cy=<currency>`, both optional. |
| - - `plan` is kept only if it is a paid catalog plan. |
| - - `currency` is kept as given when it matches `^[A-Za-z0-9]{1,8}$`. Any other non-empty value becomes the literal `invalid`. Either way the billing page refuses what isn't sold, so a malformed value is refused, never defaulted, and never reflected. |
| + - `plan` is kept if it is a paid catalog plan. `currency` is kept as given if it matches `^[A-Za-z0-9]{1,8}$`; any other non-empty value becomes `invalid`. |
| - Billing off: 404. |
| - Signed out: 303 to `/?next=` + `url.QueryEscape("/upgrade?" + kept.Encode())`. |
| - - Signed in: own one account, 303 to `/a/<sqid>/billing?` + kept; own several, the picker (most recent first); own none, the not-owner message. |
| -- Draft copy (Luna pass in Task 15): |
| + - Signed in, by the accounts the viewer owns: one, 303 to `/a/<sqid>/billing?` + kept; several, a picker (most recent first); none, the not-owner message. |
| +- Draft copy (`billingCopy`; the Luna pass replaces every draft): |
| | key | draft | |
| | --- | --- | |
| @@ -813,470 +690,369 @@ Also binding: |
| | `notice.retiring` | This account is being deleted, so nothing can be bought or changed. | |
| | `notice.problem` | We're checking this purchase. Your plan hasn't changed yet, and nothing more will be charged. | |
| | `notice.seats_unpaid` | This account has more members than it pays for. Remove members, or ask an operator. | |
| + | `notice.unresolved` | We couldn't confirm a recent change, and someone is checking it. Nothing more will be charged. | |
| | `notice.operator_plan` | An operator set this account's plan, so there's nothing to buy here. | |
| | `notice.settling` | We're confirming your payment. This page shows your new plan once it's done. | |
| | `notice.pending_payment` | A change is waiting for payment. Pay it from Payment and invoices, or it's dropped after a day. | |
| | `notice.past_due` | Your last payment didn't go through. Update your card in Payment and invoices. Your plan stays while we retry. | |
| | `notice.ending` | Your plan ends on %s. After that the account moves to the free plan. | |
| | `notice.owners_only` | Only an owner of this account can change its plan. | |
| - | `currency.refused` | We don't sell in %q. Choose usd, eur or gbp. | |
| - | `currency.refused_unshown` | We don't sell in that currency. Choose usd, eur or gbp. | |
| + | `currency.refused` / `currency.refused_unshown` | We don't sell in %q. Choose usd, eur or gbp. / We don't sell in that currency. Choose usd, eur or gbp. | |
| | `currency.fixed` | This account pays in %s. To change that, ask an operator. | |
| | `buy.title` / `buy.button` | Choose a plan / Continue to payment | |
| - | `team.price` | %s per member a year, for at least %d members | |
| - | `team.members` | %d members, paid for %d | |
| + | `team.price` / `team.members` | %s per member a year, for at least %d members / %d members, paid for %d | |
| | `renews` | Renews on %s | |
| | `upgrade.not_owner_title` / `upgrade.not_owner` | Only owners can upgrade / Only an owner of an account can upgrade it. Create an account of your own to choose a plan. | |
| | `pick.title` | Which account? | |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestDecideBillingPage(t *testing.T) // one case per table row; member vs owner on "paid" |
| - func TestBillingPageOffAndGate(t *testing.T) // billing nil 404; non-member 404; member no forms; owner free: Buy with three plans |
| - func TestBillingPageCurrencyRefusals(t *testing.T) // GeoIP DE: eur; ?currency=gbp: gbp; jpy: refused shown "jpy"; USD: refused shown "usd"; usd1: refused shown "usd1"; |
| - // %3Cscript%3E: refused_unshown, body contains no "<script"; nothing preselected in each refusal |
| - func TestBillingPageFixedCurrency(t *testing.T) // ended sub in gbp: Buy shows gbp text, no radios; ?currency=eur: currency.fixed |
| - func TestBillingPageTeamTotals(t *testing.T) // 4 members: community 6000 total; 12: 7200 |
| - func TestUpgradeEntry(t *testing.T) // signed out: next local and escaped; ?plan=../x dropped; ?currency=<script>: next carries currency=invalid; |
| - // owner of one: billing; of two: picker; member only: not-owner, no sqid; billing nil: 404; hostile next variants stay local |
| - func TestUpgradeAfterSignupLandsOnBilling(t *testing.T) |
| - ``` |
| +- [ ] **Step 1: Write the failing tests:** `TestDecideBillingPage` (one case per row, terminal intents ignored), `TestBillingPageOffAndGate`, `TestBillingPageCurrencyRefusals`, `TestBillingPageFixedCurrency`, `TestBillingPageTeamTotals`, `TestUpgradeEntry`, `TestUpgradeAfterSignupLandsOnBilling`. |
| - [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideBillingPage|BillingPage|UpgradeEntry|UpgradeAfterSignup'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim' -timeout 40m` (niced). Expected: PASS. |
| - [ ] **Step 5: Commit** `console: billing page from neutral facts, refusing every unsold or malformed currency, and the /upgrade entry (plans 6b)`. |
| -### Task 9: Checkout: start, resume, return |
| +### Task 9: Checkout: start, replace, observe, return |
| **Files:** |
| -- Create: `internal/console/billingcheckout.go`, `internal/console/billingcheckout_test.go`. |
| +- Create: `internal/console/billingcheckout.go`, `billingcheckout_test.go`. |
| - Modify: |
| - - `internal/console/server.go`: `POST /a/{sqid}/billing/checkout` and `GET /a/{sqid}/billing/done`; |
| - - `internal/console/billingpass.go`: unresolved intents in the pass; |
| - - `internal/console/billingwebhook.go`: `EventCheckout` resolves the intent through `resolveIntentLocked`; |
| - - claim files: both routes as `claimNonApp`, with Fake probes. |
| + - `server.go`: `POST /a/{sqid}/billing/checkout`, `GET /a/{sqid}/billing/done`; |
| + - `billingpass.go`: intent observation; |
| + - `billingwebhook.go`: `EventCheckout` observes its intent; |
| + - the claim entries. |
| **Interfaces:** |
| - Consumes: Tasks 4, 6, 7. |
| - Produces: |
| ```go |
| const checkoutLifetime = time.Hour |
| - type intentVerdict int |
| - const (intentClear intentVerdict = iota; intentReuse; intentPurchased) |
| - // resolveIntentLocked settles the account's previous intent before anything new: |
| - // open, no session, younger than 23 h: resend StartCheckout with the stored request and key "checkout:<id>", store the session (finding 7); |
| - // open, no session, older: abandoned (any session it made has expired; LiveSubscriptions below still catches a completed one); |
| - // with a session, Checkout(session) says: |
| - // open, and the same request as want: intentReuse; |
| - // open, otherwise: ExpireCheckout, whose returned state decides: expired -> mark expired, intentClear; |
| - // complete (it completed first) -> sync its subscription, mark completed, intentPurchased; |
| - // complete: sync its subscription, mark completed, intentPurchased; |
| - // expired: mark expired, intentClear. |
| - func (s *Server) resolveIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, want []billing.CheckoutItem, now time.Time) (intentVerdict, error) |
| + // observeIntentLocked records what the provider shows for a non-terminal intent. It never expires, creates or resends (Invariant 5): |
| + // open with a session: Checkout(session): complete -> sync its subscription, completed; expired -> expired; open -> unchanged. |
| + // creating: if SentAt + opQuiet has passed, CustomerCheckouts(customer, CreatedAt) (exhaustive): |
| + // a session whose IntentID matches -> record it, then observe it as above; |
| + // none -> abandoned (the create never ran, or ran and its session is what the list shows); |
| + // ErrIncomplete -> unchanged, logged. |
| + // creating within opQuiet: unchanged. |
| + func (s *Server) observeIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error |
| + // replaceIntentLocked is the only path that expires a session (besides retirement): an owner's explicit new |
| + // Checkout with a different request. ExpireCheckout; expired -> expired; complete -> sync, completed. |
| + func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error |
| func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) |
| func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) |
| - func (s *Server) billingIntentPass(ctx context.Context, now time.Time) // UnresolvedCheckoutIntents younger than 7 days: holdBilling, resolveIntentLocked with want=nil (never reuse) |
| + func (s *Server) billingIntentPass(ctx context.Context, now time.Time) // NonTerminalCheckoutIntents: holdBilling, observeIntentLocked only |
| ``` |
| -- Checkout, in order: |
| - 1. Owner gate, CSRF, ready. Not ready means no provider call and no session (`TestCheckoutNotReadyStartsNothing`). |
| - 2. Parse `plan`, `pack_<name>` and `currency` (`currencyQuery`, so refusals are as on the page). |
| - 3. `holdBilling`. Inside the hold: |
| - 4. Refuse when retiring; when the row is operator or sponsored; when a problem is open; and when the currency differs from a fixed currency, re-read under the hold (finding 13). |
| - 5. **No second live subscription** (finding 6): |
| - - with a recorded subscription, `freshenLocked`; refuse if the read is `Live`, including cancel at period end; |
| - - with a bound customer, `LiveSubscriptions(customer)` (one request); any live id is synced with `syncSubscriptionLocked`, then refused (`checkout.already`). |
| - 6. Seats are `Team.Billed(MemberCount)` for a team plan. |
| - 7. Build `want` (price ids under `cfg.Book.Version`). |
| - 8. Bind a customer if none. |
| - 9. `resolveIntentLocked(prev, want)`: |
| - - `intentPurchased`: refuse with `checkout.already`; |
| - - `intentReuse`: 303 to the stored URL; |
| - - `intentClear`: carry on. |
| - 10. Put a new intent: state open, the whole request, key `checkout:<id>`, `ExpiresAt now+checkoutLifetime`. |
| - 11. `StartCheckout`, store the session and URL, 303. |
| - |
| - An `ErrUncertain` leaves the intent open with no session. The next attempt, or the pass, resends it with the same key and stored request. |
| -- Done: |
| - 1. Owner gate. `CheckoutIntentBySession(session)` must be this account's, else 303 with no flash. |
| - 2. Mark returned. |
| - 3. `holdBilling`, then `resolveIntentLocked(want=nil)` within 10 s. |
| - 4. 303 with `checkout.done` when the plan row is now paid; otherwise the page shows `notice.settling`. |
| -- **Discovery integration** (finding 7): 6a's `billingDiscoveryPass` (as merged) also selects accounts with an open intent younger than 7 days, whether or not a subscription is recorded. That covers returning customers and replacement purchases. `billingIntentPass` resolves each one. If 6a's merged discovery already selects them, only the resolution is added. |
| -- Draft copy: `checkout.already` "This account already has a paid plan, or a payment is finishing. Check back in a minute."; `checkout.failed` "We couldn't start the payment. Try again in a minute."; `checkout.done` "You're on %s."; `billing.retiring` "This account is being deleted."; `checkout.operator_plan` = `notice.operator_plan`. |
| +- **Checkout:** |
| + 1. Owner, CSRF, ready; parse; `currencyQuery`. |
| + 2. `holdBilling`. |
| + 3. Refuse when retiring, on an operator or sponsored row, on an open problem, or on a currency mismatch (the fixed currency read under the hold). |
| + 4. `refreshLocked` (Invariant 4: no allowance check). Refuse if the recorded subscription is `Live`. |
| + 5. With a bound customer, `LiveSubscriptions` (exhaustive). Any live id: `syncSubscriptionLocked`, then refuse with `checkout.already`. `ErrIncomplete`: refuse with `checkout.failed` (Invariant 3). |
| + 6. Handle the previous intent, if non-terminal: |
| + - `observeIntentLocked` first. If it becomes `completed`, refuse (`checkout.already`). |
| + - Still `creating` (within `opQuiet`): refuse (`checkout.preparing`). |
| + - Still `open`: if its stored request equals the new one and `ExpiresAt` is more than 5 minutes away, 303 to its URL (reuse). Otherwise `replaceIntentLocked`; `completed` refuses. |
| + |
| + Terminal intents are ignored. |
| + 7. Bind a customer if none. |
| + 8. Put a new intent: `creating`, the whole request, `ExpiresAt = now+checkoutLifetime`, key `checkout:<id>`. |
| + 9. `StartCheckout`, sent once: |
| + - success: `open`, with session and URL; 303; |
| + - `ErrRefused`: `abandoned`, with `checkout.failed`; |
| + - `ErrUncertain`: stays `creating`, with `checkout.uncertain`. Observation settles it after `opQuiet`. |
| + |
| + **No resend, ever** (Invariant 1). |
| +- **Done:** |
| + 1. Owner; the intent named by the session. |
| + 2. `holdBilling`; mark returned. |
| + 3. `observeIntentLocked`. |
| + 4. 303 with `checkout.done` if the plan is now paid, otherwise `notice.settling`. |
| +- **Discovery:** 6a's discovery selects accounts with a non-terminal intent. `billingIntentPass` observes them only. |
| +- Draft copy: revision 2's, plus `checkout.preparing` "A payment page is still being prepared. Try again in a minute." and `checkout.uncertain` "We couldn't confirm the payment page was created. Try again in a few minutes." |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestCheckoutStartsSession(t *testing.T) // personal + apps 2 in eur: Started items, currency, success URL, ExpiresAt; intent stores Items, Book, key |
| - func TestCheckoutTeamSeats(t *testing.T) // 4 members community: qty 10; 13: 13 |
| - func TestCheckoutReusesTheSameRequest(t *testing.T) // double click: one Started, both redirect to the same URL |
| - func TestCheckoutExpiresTheOpenSession(t *testing.T) // different request: Expired [first], second Started |
| - func TestCheckoutExpiryLosesToCompletion(t *testing.T) // CompleteBeforeExpire: no second session, subscription synced, flash checkout.already |
| - func TestCheckoutRefusesScheduledCancellation(t *testing.T) // active with cancel_at_period_end: refused, no Started (finding 6) |
| - func TestCheckoutRefusesUnrecordedLiveSubscription(t *testing.T) // customer has a live sub the row doesn't name: synced, refused |
| - func TestCheckoutLostResponseResumes(t *testing.T) // LoseNextResponse on StartCheckout: intent open, no session; retry: same key, same request, Fake.Keys == 1 create |
| - func TestCheckoutSaveFailureResumes(t *testing.T) // session store fails after StartCheckout: next attempt resends with the same key and gets the same session |
| - func TestIntentPassResolvesReturningCustomer(t *testing.T) // ended account checks out again, webhooks lost: pass resolves the intent, plan paid |
| - func TestCheckoutRefusesOperatorRows(t *testing.T) // sponsored; operator; open problem; retiring: no provider call |
| - func TestCheckoutNotReadyStartsNothing(t *testing.T) // readiness refused: no Started, no customer created |
| - func TestCheckoutHouseWithoutCoupon(t *testing.T) // house account, no coupon configured: checkout.failed, no session |
| - func TestCheckoutCurrencyRules(t *testing.T) // jpy, USD, usd1: refused before any call; fixed gbp posting eur: refused under the hold |
| + func TestCheckoutStartsSession(t *testing.T) |
| + func TestCheckoutTeamSeats(t *testing.T) |
| + func TestCheckoutReusesTheSameRequest(t *testing.T) |
| + func TestCheckoutReplacesOnExplicitNewRequest(t *testing.T) |
| + func TestCheckoutExpiryLosesToCompletion(t *testing.T) |
| + func TestCheckoutAfterCancellationWithOldRecorded(t *testing.T) // old sub ended, still recorded with a PeriodEnd: Checkout proceeds (Invariant 4) |
| + func TestCheckoutRefusesScheduledCancellation(t *testing.T) |
| + func TestCheckoutSeesLiveSubscriptionOnPageTwo(t *testing.T) // PageSize 2, live sub on page 2: refused; CallsBy[LiveSubscriptions pages] == 2 |
| + func TestCheckoutRefusesIncompleteList(t *testing.T) |
| + func TestCheckoutFailBeforeDelivery(t *testing.T) // FailBeforeDelivery: creating; immediate retry: checkout.preparing, no call; after opQuiet: observed abandoned; retry creates once |
| + func TestCheckoutLostResponseObserved(t *testing.T) // LoseNextResponse: creating; after opQuiet the customer list finds the session by intent id: open, reused; StartCheckout calls == 1 |
| + func TestCheckoutCreateRefused(t *testing.T) // ErrRefused: abandoned at once |
| + func TestPassRightAfterCheckoutKeepsSession(t *testing.T) // pass 1 s after start: session still open, CallsBy[ExpireCheckout] == 0 |
| + func TestPassObservesCompletedIntent(t *testing.T) |
| + func TestCompletedIntentDoesNotBlockNextPurchase(t *testing.T) // completed intent, subscription since ended: Checkout proceeds |
| + func TestCheckoutRefusesOperatorRows(t *testing.T) |
| + func TestCheckoutNotReadyStartsNothing(t *testing.T) |
| + func TestCheckoutHouseWithoutCoupon(t *testing.T) |
| + func TestCheckoutCurrencyRules(t *testing.T) |
| func TestCheckoutDoneSyncs(t *testing.T) |
| func TestCheckoutDoneSettling(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|IntentPass'`. Expected: FAIL. |
| + Each test asserts `CallsBy` against the budget's Checkout branches. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|PassRightAfter|PassObserves|CompletedIntent'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: Checkout that never makes a second live subscription, resumes an uncertain start with the same key, and resolves intents in the pass (plans 6b)`. |
| +- [ ] **Step 5: Commit** `console: Checkout sends each create once, observes rather than resends, never expires a session from the pass, and judges subscriptions, not past intents (plans 6b)`. |
| ### Task 10: Pack changes, plan upgrades and renewal |
| **Files:** |
| -- Create: `internal/console/billingchange.go`, `internal/console/billingchange_test.go`. |
| -- Modify: |
| - - `internal/console/server.go`: `POST /a/{sqid}/billing/change` and `POST /a/{sqid}/billing/renewal`; |
| - - claim files: both as `claimNonApp`, with Fake probes. |
| +- Create: `internal/console/billingchange.go`, `billingchange_test.go`. |
| +- Modify: `server.go` (the change and renewal routes); the claim entries. |
| **Interfaces:** |
| -- Consumes: Task 7 (`holdBilling`, `freshenLocked`, `beginOpLocked`, `runOpLocked`, `quantitySteps`, `syncSubscriptionLocked`), `requireFreshAuth`, `ConfirmView`. |
| -- Produces: |
| - ```go |
| - func prorateEstimate(annualMinor, qty int64, now, periodEnd time.Time) int64 |
| - func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) |
| - func (s *Server) handleBillingRenewal(w http.ResponseWriter, r *http.Request) |
| - ``` |
| -- Change: the form has `kind` (`pack` or `plan`), `name`, `quantity` (absolute) and `confirmed`. |
| - 1. Owner gate and CSRF. |
| - 2. For a confirmed charge, `requireFreshAuth` before taking the hold, since the step-up may redirect. |
| - 3. `holdBilling`. Refuse when retiring, on an open problem, or on a row that isn't billing-owned. |
| - 4. `freshenLocked`. Refuse unless the read is paid and not cancel at period end. |
| - 5. **Refuse when an operation is outstanding or the read has `PendingUpdate`** (`change.outstanding`, finding 5). |
| - 6. Compute from the freshened row: |
| - - **pack:** `quantitySteps(ref, current, target, row.PaidPacks[name])`; |
| - - **plan (Call 4):** one swap step to `Billed(MemberCount)` or 1, `ProrateNow`. |
| - 7. With no steps: `change.none`. |
| - 8. When a step charges and `confirmed != "1"`: release the hold and render the confirm page with the estimate. |
| - 9. Otherwise `beginOpLocked`, then `runOpLocked`, then `syncSubscriptionLocked` (settle). |
| - 10. Flash by outcome: `change.done`, `change.pending`, `change.declined`, `change.uncertain` ("we couldn't confirm the change. it's being checked; nothing more will be charged"), or `change.failed`. |
| -- Renewal: owner, CSRF, `holdBilling`, then refuse when retiring. `freshenLocked`, then refuse on an outstanding operation. Then an `opRenewal` operation (`SetRenewal` with key `op.ID:0`), and settle. |
| -- Draft copy: as revision 1 (`confirm.*`, `change.done`, `change.pending`, `change.none`, `change.failed`, `change.book`, `renewal.*`), plus: |
| - - `change.outstanding` "Another change is still being paid for. Finish or wait for it first."; |
| - - `change.declined` "Your card was declined, so nothing changed."; |
| - - `change.uncertain` "We couldn't confirm that change yet. We're checking, and nothing more will be charged."; |
| - - `change.retry` "Your plan just renewed. Try again in a minute." |
| +- Produces: `prorateEstimate`, `handleBillingChange`, `handleBillingRenewal`. |
| +- **Change:** |
| + 1. Owner, CSRF, `requireFreshAuth` for a confirmed charge (before the hold). |
| + 2. `holdBilling`. Refuse when retiring, on a problem, or on a row that isn't billing-owned. |
| + 3. `allowanceLocked` (Invariant 4); `errAllowanceStale` gives `change.retry`. |
| + 4. Refuse on an outstanding operation or `PendingUpdate` (`change.outstanding`). |
| + 5. **pack:** `quantityPlan(current, target, row.PaidPacks[name])`: |
| + - a reduction is one `opPack` with `ProrateNone`; |
| + - otherwise the restore, then the charge only after a definite applied restore (Task 7). |
| + 6. **plan:** one `opPlan` swap with `ProrateNow`. |
| + 7. With no step: `change.none`. |
| + 8. A charge without `confirmed`: release, and render the confirm page. |
| + 9. Each operation's `ProrationDate` is `now`, captured once and persisted. |
| + 10. Settle: `syncSubscriptionLocked`. |
| + 11. Flash by the last outcome: `change.done`, `change.pending`, `change.declined`, `change.uncertain`, or `change.failed`. |
| +- **Renewal:** `holdBilling`, then refuse when retiring. `refreshLocked`; refuse on an outstanding operation. One `opRenewal`, sent once, then settle. |
| +- Draft copy: revision 2's. |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestPackRaiseCharges(t *testing.T) // confirm page; confirmed with fresh auth: one op, ProrateNow to 2; packs {apps:2} |
| - func TestPackReduceAndBuyBack(t *testing.T) // 3 -> 1 ProrateNone, limits keep 3; 1 -> 3 ProrateNone, no confirm |
| - func TestDeletedPackRestoreThenCharge(t *testing.T) // apps item deleted, paid 3, target 4: add 3 (ProrateNone) -> si_n, then si_n to 4 (ProrateNow); one op, two keys |
| - func TestOneOutstandingOperation(t *testing.T) // FailPayment: first pending; second confirmed post: change.outstanding, no Fake change |
| - func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T) // pending op; resubmit: refused; ExpirePending + webhook: abandoned; resubmit: new op allowed |
| - func TestChangeTwiceChargesOnce(t *testing.T) // two confirmed posts in parallel: one op, one ProrateNow send |
| - func TestChangeComputesFromTheFreshRead(t *testing.T) // another tab already at 2: change.none |
| - func TestChangeAfterDelayedRenewal(t *testing.T) // stored PaidPacks {apps:3} P1; Fake renewed P2 with apps 1, no webhook; request 3: ProrateNow to 3 (not ProrateNone) |
| - func TestChangeAfterReplacementSubscription(t *testing.T) // stored allowance from sub_old; fresh sub_new adopted: allowance from sub_new only |
| - func TestChangeUncertainResumedByPass(t *testing.T) // LoseNextResponse: change.uncertain; pass resumes same key; applied once |
| - func TestPlanUpgrade(t *testing.T) // personal -> business 3 members: swap to business x 10 ProrateNow; downgrade refused, no call |
| + func TestPackRaiseCharges(t *testing.T) |
| + func TestPackReduceAndBuyBack(t *testing.T) |
| + func TestDeletedPackRestoreThenCharge(t *testing.T) // 0 -> restore 3 (add, si_n from the response) -> charge si_n to 4; two ops; CallsBy[ChangeItems] == 2 |
| + func TestOneOutstandingOperation(t *testing.T) |
| + func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T) |
| + func TestChangeTwiceChargesOnce(t *testing.T) |
| + func TestChangeComputesFromTheFreshRead(t *testing.T) |
| + func TestChangeAfterDelayedRenewal(t *testing.T) // charged, not restored free |
| + func TestChangeAfterReplacementSubscription(t *testing.T) |
| + func TestChangeUncertainNotResent(t *testing.T) // LoseNextResponse: change.uncertain; pass after opQuiet settles applied; CallsBy[ChangeItems] == 1 |
| + func TestPlanUpgrade(t *testing.T) |
| func TestUpgradeRefusedWhenPackNotOffered(t *testing.T) |
| func TestChangeUsesTheSubscriptionsBook(t *testing.T) |
| func TestRenewalStopAndResume(t *testing.T) |
| - func TestChangeAndRenewalReturnUnderTimeout(t *testing.T) // each handler returns within 5 s with the hold (finding 1) |
| + func TestChangeAndRenewalReturnUnderTimeout(t *testing.T) |
| ``` |
| - [ ] **Step 2: Run** `go test ./internal/console/ -run 'Pack|DeletedPack|OneOutstanding|RetryAfterDecline|ChangeTwice|ChangeComputes|ChangeAfter|ChangeUncertain|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal|ChangeAndRenewal'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: pack changes and upgrades as durable operations computed after a fresh read, one at a time per subscription; stop and resume renewal (plans 6b)`. |
| +- [ ] **Step 4: Run** again, plus the Claim suite (niced). Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: pack changes and upgrades as single-send operations after the allowance check; stop and resume renewal (plans 6b)`. |
| -### Task 11: Seats: authorised invites, serialised admission, reconciliation |
| +### Task 11: Seats: authorised invites, admission, reconciliation |
| **Files:** |
| -- Create: `internal/console/billingseats.go`, `internal/console/billingseats_test.go`. |
| +- Create: `internal/console/billingseats.go`, `billingseats_test.go`. |
| - Modify: |
| - - `internal/console/store.go`: invite columns `seat_plan`, `seat_book`, `seat_currency`, `seat_price_minor`, `seat_authorised_by`, `seat_authorised_at` (guarded `ALTER TABLE`s); `SetInviteSeatAuthorisation`; `PendingInviteFor` returns them; |
| - - `internal/console/server.go`: `handleInvite` (the confirm and authorisation), `handleAcceptInvite` (`admitMember`), `handleRevokeInvite` (refused while the invite's operation is outstanding); |
| - - `internal/console/ownership.go`: `handleRemoveMember` calls `reconcileSeatsLocked`, under the member lock, then the billing hold; |
| - - `internal/console/billingpass.go`: seat drift; |
| - - `internal/console/apibilling.go`: the `seats_unpaid` close path; |
| - - `internal/console/billingstore.go`: `problemSeatsUnpaid`, and `CloseBillingProblemsByReason`. |
| + - `store.go`: the invite seat-authorisation columns, plus `seat_consumed_at`; |
| + - `server.go`: invite, accept, revoke; |
| + - `ownership.go`: removal; |
| + - `billingpass.go`: seat drift; |
| + - `apibilling.go`: the `seats_unpaid` close; |
| + - `billingstore.go`. |
| **Interfaces:** |
| -- Consumes: Tasks 3, 6 and 7. |
| - Produces: |
| ```go |
| - type seatAuthorisation struct { Plan, Book, Currency string; PriceMinor int64; By string; At time.Time } |
| + type seatAuthorisation struct { Plan, Book, Currency string; PriceMinor int64; By string; At, ConsumedAt time.Time } |
| func (s *Store) SetInviteSeatAuthorisation(token string, a seatAuthorisation) error |
| - // seatCovered: the invite's authorisation matches the freshened row's plan, book and currency, and the per-seat price |
| - // in the subscription's book (when it is the configured book) is not above PriceMinor. |
| - func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool |
| + func (s *Store) ConsumeInviteSeatAuthorisation(token string, now time.Time) error // called by settleOpsLocked when an opSeat becomes applied |
| + func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool // unconsumed, same plan, book, currency, price not above |
| type admitOutcome int |
| - const (admitJoined admitOutcome = iota; admitWaitPayment; admitNeedsConsent; admitOutstanding; admitRefused) |
| - func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr string, now time.Time) (admitOutcome, error) // takes the member lock, then holdBilling when needed |
| + const (admitJoined admitOutcome = iota; admitWaitPayment; admitNeedsConsent; admitOutstanding; admitUncertain; admitRefused) |
| + func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr string, now time.Time) (admitOutcome, error) |
| func (s *Server) reconcileSeatsLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error |
| func (s *Server) closeSeatsUnpaidLocked(h billingHold, ctx context.Context, acct *Account, by, note string, now time.Time) (bool, error) |
| func (s *Store) CloseBillingProblemsByReason(accountID int64, reason, by, note string, now time.Time) (int, error) |
| ``` |
| -- **Invite** (Calls 6 and 11; finding 3), on an account whose row is a billing-owned team plan, under the member lock and `holdBilling`: |
| - 1. `freshenLocked`. |
| - 2. If `Billed(members + pending + 1) > max(cur, PaidSeats)`, the owner must confirm: |
| - - render the confirm with the per-seat estimate, carrying `to`; |
| - - on a confirmed POST, `requireFreshAuth` (the hold is released first); |
| - - then `CreateInvite` and `SetInviteSeatAuthorisation` with the current plan, book, currency and per-seat price. |
| - |
| - Invites made before billing, or while a seat was free, carry no authorisation. |
| -- **`admitMember`** (findings 2, 3, 4, 5), under `lockMembers(sqid)`: |
| - 1. Re-check: invite pending and addressed to this session, not a member, `checkMemberCap(acct, 1)`. |
| - 2. Not a billing-owned team row: `membershipTransition(acceptInviteTx)`. Done. |
| - 3. Billing team row: `holdBilling`. Refuse when retiring. Then `freshenLocked`, which applies a delayed renewal before any capacity is read. |
| - 4. Look up the invite's latest operation with `BillingOpForInvite(token)`: |
| - - `applied` (the seat was paid and the membership never landed: a crash or lost response): skip to step 7, with no charge; |
| - - `started`: `runOpLocked` resumes it with the same keys; |
| - - `pending`: `admitWaitPayment`. |
| - 5. Any other outstanding operation, or a read with `PendingUpdate`: `admitOutstanding`. |
| - 6. Compute `need = Billed(members+1)`, `cur` = the plan item's quantity, `cap = PaidSeats`: |
| - - `need ≤ cur`: free; |
| - - `cur < need ≤ cap`: an `opRestore` operation, `ProrateNone` to `need`. It must reach `applied` before admission, so a renewal can't fall between admission and reconciliation; |
| - - `need > cap`: `seatCovered` must hold, else `admitNeedsConsent`. Then an `opSeat` operation bound to the token (`quantitySteps(planRef, cur, need, cap)`). `applied` goes on; `pending` or `failed` gives `admitWaitPayment`; `uncertain` gives `admitWaitPayment`, and the pass or the next accept resumes it. |
| - 7. `membershipTransition(acceptInviteTx)`, then `syncSubscriptionLocked` (settle), all inside both locks. |
| -- **Revoke:** refused while the invite's operation is `started` or `pending` (`seats.revoke_wait`). A revoked or used token fails the step 1 re-check, so it can never start an operation. |
| +- **Invite:** as revision 2. Under the member lock and `holdBilling`: `allowanceLocked`. A seat charge would be needed if `Billed(members + pending + 1) > max(cur, PaidSeats)`. Then the confirm, `requireFreshAuth`, and storing the authorisation. |
| +- **`admitMember`** (Invariant 2), under `lockMembers(sqid)`: |
| + 1. Re-check the invite, existing membership and the cap. |
| + 2. Not a billing team: `membershipTransition(acceptInviteTx)`. |
| + 3. Billing team: `holdBilling`, refuse when retiring, `allowanceLocked`. |
| + 4. An outstanding operation or `PendingUpdate`: if it is this invite's `opSeat` in `pending`, `admitWaitPayment`; otherwise `admitOutstanding`. |
| + 5. **Recompute capacity from scratch, every time:** `need = Billed(members+1)`, `cur` = the plan item's quantity, `paid = PaidSeats`. A previous applied charge for this invite only raised `cur` and `paid`; it is not consulted. |
| + - `need ≤ cur`: free. |
| + - `cur < need ≤ paid`: one `opRestore` (`ProrateNone`). It must return `applied` definitely, else `admitUncertain` or `admitWaitPayment`. |
| + - `need > paid`: `seatCovered` must hold (unconsumed), else `admitNeedsConsent`. Then `quantityPlan(cur, need, paid)`: a restore, then a charge (an `opSeat` carrying the token and the authorisation) only after a definite applied restore. `applied` goes on; `pending` or `failed` gives `admitWaitPayment`; `uncertain` gives `admitUncertain`. |
| + 6. `membershipTransition(acceptInviteTx)`, then settle, inside both locks. |
| +- If the membership write fails after an applied charge, the paid seat stays: a credit. The next admission (anyone's) finds `need ≤ cur` and takes it. The first invitee's retry recomputes; if it needs another charge, its consumed authorisation gives `admitNeedsConsent`. |
| +- **Revoke:** refused while the invite's `opSeat` is `sending`, `uncertain` or `pending`. |
| - **`reconcileSeatsLocked`:** |
| - - Requires a billing-owned team row; refuses when retiring. |
| - - `freshenLocked`. Refuse on an outstanding operation; the pass comes back later. |
| - - `want = Billed(MemberCount)`, `cur` = the plan item's quantity: |
| - - `want < cur`: an `opSeat` operation, `ProrateNone` (Call 12); |
| - - `cur < want ≤ PaidSeats`: an `opRestore` operation, `ProrateNone`; |
| - - `want > PaidSeats`: open `seats_unpaid` ("the account has N members and pays for M"), with no charge. |
| - - When `want ≤ max(cur, PaidSeats)` after the steps, close any open `seats_unpaid` with `CloseBillingProblemsByReason` (by "billing"). |
| - - Set `SeatsCheckedAt`. |
| - - Callers: member removal and the CLI's effect (through the pass); the pass when the stored `Seats` differs from `Billed(MemberCount)`; while `seats_unpaid` is open, at most once a day or when membership changed. |
| -- **`seats_unpaid` close** (finding 9): 6a's operator close door gains a reason-specific branch. For `seats_unpaid` it runs `closeSeatsUnpaidLocked` under `holdBilling`: freshen, then close only when members ≤ paid capacity, else 409 `billingCopySeatsStillOver`. Every other reason keeps 6a's gate unchanged, including the `subscription_missing` closure, which 6a's fix pass runs under the billing lock. |
| -- Draft copy: `seats.invite_line` "When %s joins, the account pays about %s now for the rest of the year, plus any tax."; `seats.join_wait_title` "Not yet"; `seats.join_wait` "This account can't add you yet because its payment didn't go through. Its owners can see this on their billing page. Try the link again later."; `seats.join_consent` "This invitation doesn't cover a new paid seat. Ask an owner to invite you again."; `seats.join_busy` "This account is in the middle of another change. Try the link again in a minute."; `seats.revoke_wait` "This person's payment is still going through. Try again in a minute."; door `billingCopySeatsStillOver` "the account still has more members than paid seats. remove members first". |
| + - `refreshLocked`, then `allowanceLocked` when live and paid. |
| + - Refuse on an outstanding operation. |
| + - `want < cur`: `opSeat`, `ProrateNone`. |
| + - `cur < want ≤ PaidSeats`: `opRestore`, `ProrateNone`. |
| + - `want > PaidSeats`: open `seats_unpaid`. Close it when resolved. |
| + - Daily re-check while it is open. |
| + - Callers: removal; the pass on drift. |
| +- **The `seats_unpaid` close door:** as revision 2 (accepted). |
| +- Draft copy: revision 2's, plus `seats.join_uncertain` "We couldn't confirm the account's payment for your seat. Try the link again in a few minutes." |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| - func TestInviteRecordsSeatAuthorisation(t *testing.T) // community 10 members, seats 10: confirm + fresh auth; invite carries plan, book, currency, 600 |
| - func TestJoinChargesAuthorisedSeat(t *testing.T) // accept: op ProrateNow to 11, member added, Seats 11 |
| - func TestJoinWaitsForPayment(t *testing.T) // FailPayment: seats.join_wait, invite pending, members 10 |
| - func TestJoinNeedsConsentWithoutAuthorisation(t *testing.T) // invite made when a seat was free; now full: seats.join_consent, no charge |
| - func TestJoinNeedsConsentAfterPlanSwitch(t *testing.T) // authorised under community; account now business: seats.join_consent |
| - func TestConcurrentJoinsShareNoSeat(t *testing.T) // 9 members, 10 paid, two accepts in parallel (one authorised): never 11 members on 10 seats; |
| - // the second charges under its authorisation or waits |
| - func TestJoinRecoversAfterLostResponse(t *testing.T) // LoseNextResponse on the seat step: wait; retry: same key, not reapplied, joined |
| - func TestJoinRecoversAfterCrashBeforeMembership(t *testing.T) // op applied, membership write fails: retry joins with no ChangeItems call |
| - func TestRevokedInviteStartsNoPurchase(t *testing.T) // revoke after a declined op: no new op on accept; revoke while op pending: refused |
| - func TestJoinAfterDelayedRenewal(t *testing.T) // stored PaidSeats 12 P1; Fake renewed P2 at 10, no webhook; 10 members accept: charged to 11, not restored free |
| - func TestRejoinRestoresBeforeAdmission(t *testing.T) // 12 paid, reduced to 11 at Stripe after a leave; accept: opRestore to 12 applied before the member row exists |
| - func TestLeaveReducesAtRenewal(t *testing.T) // remove: ProrateNone to 11, limits keep 12 until the period moves |
| - func TestPassOpensAndClosesSeatsUnpaid(t *testing.T) // CLI adds members beyond paid: problem opened, no charge; members removed: problem closed by billing |
| - func TestSeatsUnpaidCloseDoor(t *testing.T) // still over: 409; resolved: closed; subscription_missing still refused while live (6a gate unchanged) |
| - func TestSeatsUnpaidRecheckedDaily(t *testing.T) // open problem: two passes in an hour make one freshen |
| - func TestAcceptAndRemoveReturnUnderTimeout(t *testing.T) // 5 s bound with member lock + hold (finding 1) |
| + func TestInviteRecordsSeatAuthorisation(t *testing.T) |
| + func TestJoinChargesAuthorisedSeat(t *testing.T) // authorisation consumed |
| + func TestJoinWaitsForPayment(t *testing.T) |
| + func TestJoinNeedsConsentWithoutAuthorisation(t *testing.T) |
| + func TestJoinNeedsConsentAfterPlanSwitch(t *testing.T) |
| + func TestConcurrentJoinsShareNoSeat(t *testing.T) |
| + func TestAppliedInviteChargeIsACreditNotAPass(t *testing.T) // 10 members: A's charge applied, A's membership write fails; B joins free (CallsBy[ChangeItems] unchanged); |
| + // A retries: need 12 > paid 11, authorisation consumed -> admitNeedsConsent; members 11, paid 11 |
| + func TestJoinUncertainNotResent(t *testing.T) // LoseNextResponse on the seat charge: admitUncertain; retry before opQuiet: admitOutstanding, no call; |
| + // after settle (applied): retry joins free; CallsBy[ChangeItems] == 1 |
| + func TestJoinFailBeforeDelivery(t *testing.T) // FailBeforeDelivery: uncertain; after opQuiet: abandoned; retry charges once (authorisation unconsumed) |
| + func TestRevokedInviteStartsNoPurchase(t *testing.T) |
| + func TestJoinAfterDelayedRenewal(t *testing.T) |
| + func TestUnsentSeatRestoreAbandonedAcrossRenewal(t *testing.T) // FailBeforeDelivery on opRestore in P1; Renew; pass: abandoned; nothing sent in P2 |
| + func TestRejoinRestoresBeforeAdmission(t *testing.T) |
| + func TestLeaveReducesAtRenewal(t *testing.T) |
| + func TestPassOpensAndClosesSeatsUnpaid(t *testing.T) |
| + func TestSeatsUnpaidCloseDoor(t *testing.T) |
| + func TestSeatsUnpaidRecheckedDaily(t *testing.T) |
| + func TestAcceptAndRemoveReturnUnderTimeout(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteRecords|Join|ConcurrentJoins|RevokedInvite|Rejoin|Leave|SeatsUnpaid|PassOpens|AcceptAndRemove'`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteRecords|Join|ConcurrentJoins|AppliedInvite|RevokedInvite|UnsentSeat|Rejoin|Leave|SeatsUnpaid|PassOpens|AcceptAndRemove'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Invite|BillingSyncPass|Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: team seats from authorised invites, admitted one at a time, charged once through a durable operation; leaves reduce at renewal; seats_unpaid resolves itself (plans 6b)`. |
| +- [ ] **Step 5: Commit** `console: team seats decided at admission every time, single-use authorisations, applied charges as credits; leaves reduce at renewal; seats_unpaid resolves itself (plans 6b)`. |
| ### Task 12: The locked portal |
| -**Files:** |
| -- Create: `internal/console/billingportal.go`, `internal/console/billingportal_test.go`. |
| -- Modify: `internal/console/server.go` (`POST /a/{sqid}/billing/portal`); claim files (`claimNonApp`, writes nothing locally). |
| - |
| -**Interfaces:** |
| -- Produces: `func (s *Server) handleBillingPortal(w http.ResponseWriter, r *http.Request)`. |
| -- The handler: |
| - 1. Owner, CSRF, ready. |
| - 2. A bound customer. |
| - 3. `requireFreshAuth`. |
| - 4. `PortalURL(customer, s.cfg.Origin+"/a/"+sqid+"/billing", "portal:"+customer+":"+nonce)`, then 303. |
| +Unchanged from revision 2. |
| - It doesn't take the hold, because it changes nothing billing owns. |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestPortalOpens(t *testing.T) |
| - func TestPortalGates(t *testing.T) // member 404; no customer: portal.none; stale auth: step-up, no call; billing nil: 404; not ready: no call |
| - ``` |
| -- [ ] **Steps 2-5:** run (FAIL), implement, run (PASS), commit `console: owners reach the locked portal for cards and invoices (plans 6b)`. |
| +- Produces `handleBillingPortal`: owner, CSRF, ready, a bound customer, `requireFreshAuth`, `PortalURL`, then 303. No hold. |
| +- **Tests:** `TestPortalOpens`; `TestPortalGates`. |
| +- [ ] **Steps 1-5:** write the failing tests, run them (FAIL), implement, run them (PASS), commit `console: owners reach the locked portal for cards and invoices (plans 6b)`. |
| ### Task 13: The retirement gate for account deletion |
| **Files:** |
| -- Create: `internal/console/billingretire.go`, `internal/console/billingretire_test.go`. |
| -- Modify: `internal/console/ownership.go` (`handleDeleteAccount`). |
| +- Create: `internal/console/billingretire.go`, `billingretire_test.go`. |
| +- Modify: `ownership.go` (`handleDeleteAccount`). |
| **Interfaces:** |
| -- Consumes: Tasks 6, 7, 9. |
| - Produces: |
| ```go |
| - // retireGateLocked verifies, from the provider's fresh state, that deleting the account leaves nothing to charge: |
| - // every LiveSubscriptions id read fresh is CancelAtPeriodEnd, not Collecting, without PendingUpdate; no billing |
| - // operation is outstanding; the Checkout intent resolves (resolveIntentLocked with want=nil) to expired or abandoned. |
| - // A completed Checkout is synced and refuses. |
| - func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error // nil or a *billingRefusal carrying a billingCopy key |
| + // retireGateLocked (Invariants 3 and 6): |
| + // 1. with a bound customer, LiveSubscriptions (exhaustive; ErrIncomplete refuses: delete.unverified); |
| + // each live id: syncSubscriptionLocked, then require CancelAtPeriodEnd && !Collecting && !PendingUpdate; |
| + // 2. no unresolved operation on any of them; |
| + // 3. the intent, only if non-terminal: observeIntentLocked; still open -> replaceIntentLocked (expire); |
| + // still creating -> refuse (delete.checkout); completed -> its subscription is judged in step 1 on the next run. |
| + // Terminal intents are ignored. |
| + func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error |
| ``` |
| -- `handleDeleteAccount` (Call 15, finding 8), with billing configured, after its existing checks and CSRF: |
| - 1. `holdBilling`, `BeginRetirement`, then `retireGateLocked`. A refusal is `EndRetirement` and a flash (`delete.renewing`, `delete.collecting`, `delete.pending`, `delete.checkout`). Then release. |
| - 2. `requireFreshAuth`. That may stash and redirect; the retirement row stays for up to `retirementTTL`. |
| - 3. On the replayed POST: `holdBilling`, then `Retiring` must still hold (else start again from step 1), then `retireGateLocked` again, then `DeleteAccount`. A gate refusal is `EndRetirement` and a flash. |
| -- Every purchase, change, renewal, join and reconciliation path refuses when `Retiring` is true, checked **after** taking the hold (Tasks 9, 10, 11). |
| -- Draft copy: `delete.renewing` "This account renews on %s. Stop renewal first, then you can delete it."; `delete.collecting` "A payment for this account is still being collected. Settle it in Payment and invoices first."; `delete.pending` "A change is waiting for payment. Finish or cancel it first."; `delete.checkout` "A payment for this account is finishing. Try again in a few minutes." |
| +- `handleDeleteAccount`: |
| + 1. `holdBilling`, `BeginRetirement`, then the gate. A refusal is `EndRetirement` and a flash. |
| + 2. `requireFreshAuth`. |
| + 3. On the replayed POST: `holdBilling`; `Retiring` must still hold; the gate again; then `DeleteAccount`. |
| + |
| + Every purchase, change, renewal, join and reconciliation refuses while retiring, checked after the hold. |
| +- Draft copy: revision 2's, plus `delete.unverified` "We couldn't check every subscription for this account. Try again later, or ask an operator." |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| func TestDeleteRefusedWhileRenewing(t *testing.T) |
| - func TestDeleteAllowedAfterStop(t *testing.T) // cancel_at_period_end, not collecting: proceeds to step-up, then deletes |
| - func TestDeleteRefusedWhileCollecting(t *testing.T) // past_due with cancel scheduled: delete.collecting |
| - func TestDeleteRefusedWithPendingOp(t *testing.T) |
| - func TestDeleteResolvesOpenCheckout(t *testing.T) // open session: expired then allowed; CompleteBeforeExpire: synced, refused |
| - func TestResumeDuringRetirementRefused(t *testing.T) // retiring row: renewal resume, checkout and accept all refused after the hold |
| - func TestDeleteGateRerunsAfterStepUp(t *testing.T) // renewal resumed by an operator between the passes: second gate refuses, nothing deleted |
| - func TestStaleRetirementClears(t *testing.T) // abandoned step-up: after 1 h purchases work again |
| + func TestDeleteAfterCompletedPurchaseAndStop(t *testing.T) // purchase -> completed intent -> stop renewal -> delete: allowed; CallsBy per gate run == L(1) + 1 sync |
| + func TestDeleteRefusedWhileCollecting(t *testing.T) |
| + func TestDeleteRefusedWithUnresolvedOp(t *testing.T) |
| + func TestDeleteSeesLiveSubscriptionOnPageTwo(t *testing.T) |
| + func TestDeleteRefusesIncompleteList(t *testing.T) |
| + func TestDeleteExpiresOpenCheckout(t *testing.T) // open session expired by the gate; CompleteBeforeExpire: synced, then judged as a live sub (refused) |
| + func TestDeleteRefusedWhileCheckoutCreating(t *testing.T) |
| + func TestResumeDuringRetirementRefused(t *testing.T) |
| + func TestDeleteGateRerunsAfterStepUp(t *testing.T) |
| + func TestStaleRetirementClears(t *testing.T) |
| ``` |
| -- [ ] **Steps 2-5:** run (FAIL), implement, run (PASS), commit `console: a durable retirement gate checks the provider before an account is deleted (plans 6b)`. |
| + Each test asserts `CallsBy` against the deletion-gate row of the budget. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Delete|ResumeDuringRetirement|StaleRetirement'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: a retirement gate that judges every live subscription and ignores reconciled intents (plans 6b)`. |
| ### Task 14: The house flag |
| -**Files:** |
| -- Create: `internal/console/apibillinghouse.go`. |
| -- Modify: |
| - - `internal/console/apibilling_copy.go`, `billing_cli.go` and `billing_cli_copy.go`: `carlos billing house`; |
| - - `internal/console/authcli.go`: `POST /api/cli/billing/house`; |
| - - the empty-role allowlist and the closed-door count; |
| - - claim files. |
| -- Test: `internal/console/apibillinghouse_test.go`, `billing_cli_test.go`. |
| +Unchanged from revision 2: the `POST /api/cli/billing/house` operator door and `carlos billing house -account <sqid> -on|-off -note`. |
| -**Interfaces:** |
| -- Produces: `func (s *Server) handleAPIBillingHouse(w http.ResponseWriter, r *http.Request)`: |
| - - body `{"account","on","note"}`; |
| - - operator only (6a's `billingDoor`); |
| - - an empty note is 400; an unknown account is 404; |
| - - it writes an audit line. |
| - |
| - CLI: `carlos billing house -account <sqid> -on|-off -note "..."`. |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestBillingHouseDoor(t *testing.T) |
| - func TestBillingCLIHouse(t *testing.T) |
| - ``` |
| -- [ ] **Steps 2-5:** run `go test ./internal/console/ -run 'BillingHouseDoor|EveryCLIDoor|EveryClosedDoor'` and `go test . -run BillingCLI` (FAIL), implement, run (PASS), commit `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`. |
| +- **Tests:** `TestBillingHouseDoor`, `TestBillingCLIHouse`. |
| +- [ ] **Steps 1-5:** write the failing tests, run them (FAIL), implement, run them (PASS), commit `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`. |
| ### Task 15: Copy, docs, census and gates |
| -- [ ] **Luna copy pass.** Commit `LUNA-COPY-BRIEF-PLANS-6B.md`, in 6a's shape. It carries: |
| - - the house rules; |
| - - the facts that must stay true: |
| - - nothing is charged without the owner's button or a stored seat authorisation; |
| - - reductions keep limits until renewal; |
| - - a join waits for payment; |
| - - the currency is fixed after the first purchase; |
| - - the portal is for cards and invoices only; |
| - - deletion needs renewal stopped and payments settled; |
| - - every new string, with example renderings. |
| - |
| - Run Luna, commit the result unedited, apply it verbatim, and show Paul only the strings Luna flags. |
| -- [ ] **Docs.** Extend `docs/site/plans.md`: |
| - - "Billing (operators)": the new variables; the house flag; `seats_unpaid` and how it closes; operations and what "being checked" means; |
| - - an owner section: buying, packs, members and seats, stopping renewal, deleting a paid account, the portal. |
| - |
| - Add `carlos billing house` to the CLI reference. |
| -- [ ] **Census, from the final diff** (gap): |
| - - Run `make census-card` on the finished branch. Take every unit and envelope from its output, not from this plan. Expect among them: admission (`admitMember`), membership transitions (`MembershipTransition`, `membershipTransition`, the `*Tx` membership writes), the retirement gate, intent and operation recovery (`resolveIntentLocked`, `runOpLocked`, `settleOpsLocked`, the passes), the eight routes, and the five tables. |
| - - Body and sites changes go through `make census-propose NAME=plans-6b-checkout-flow CLAIMS=<file>`. New units and new kinds of read are hand-written decisions (`census-ruling-plans-6b-units`). |
| - - The reviewer reads every changed function in each re-pinned envelope. The record-write census (`TestPlan9B8RecordWriteCensus`) stays a separate gate, with a layer only if it names a site. |
| - - Astra approves on #280. Decisions go to Paul. |
| -- [ ] **Gates:** |
| - - `GOOS=darwin go build ./...` and `GOOS=windows go build ./...`; |
| - - `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestPlan9B8|Census'`; |
| - - `go test ./internal/plans/ ./internal/billing/... ./internal/billingstripe/ ./cmd/console/ ./cmd/pricebook-export/ ./internal/docsite/`. |
| -- [ ] **Finish:** merge main (6a on it), push, wait for green CI, then Astra's whole-branch review. |
| +- [ ] **Luna copy pass,** as revision 2. Add to the facts: |
| + - nothing is retried behind the owner's back; |
| + - an unclear change is checked and never charged twice. |
| +- [ ] **Docs,** as revision 2. Add `operation_unresolved` to the operators' section. |
| +- [ ] **Census from the final diff:** `make census-card` on the finished branch, with units and envelopes from its output. Expect admission, membership transitions, the retirement gate, `sendOpLocked`, `settleOpsLocked`, `observeIntentLocked`, `replaceIntentLocked`, the passes, eight routes and five tables. `census-propose` takes the body and sites changes; hand-written decisions take new units. Review every changed function in each re-pinned envelope, and keep the record-write gate. Astra approves; Paul takes the decisions. |
| +- [ ] **Gates:** the darwin and windows builds; `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestPlan9B8|Census'`; `go test ./internal/plans/ ./internal/billing/... ./internal/billingstripe/ ./cmd/console/ ./cmd/pricebook-export/ ./internal/docsite/`. |
| +- [ ] **Finish:** merge main (with 6a), 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, nothing user-facing changes beyond `max_members` and team limits where a catalog sets them. |
| -- Census approved from the final diff; CI green after merging main; Astra's whole-branch review has no open Critical or Important finding. |
| +- Every task's tests pass, including the call-count assertions, and Review Focus 1 to 5 are pinned. |
| +- With `CARLOS_BILLING` unset, nothing user-facing changes beyond `max_members` and team limits under a catalog. |
| +- The census is approved from the final diff; CI is green after merging main; the whole-branch review has no open Critical or Important finding. |
| - The website has the schema-3 document and the `/upgrade` contract. |
| -## Revision 2 fixes (Astra plan review at `b6005e86`) |
| +## Review record |
| + |
| +**Round 1** (`b6005e86`). Round 2 accepted fixes 1, 9, 10, 12 and 13, and the readiness, census and neutrality gaps. Fixes 2 to 8 and 11 are reworked in revision 3, below. |
| + |
| +**Round 2** (`d705d1c7`): |
| -| Finding | Where the plan now handles it | |
| +| Finding | Revision 3 | |
| | --- | --- | |
| -| 1. billing-lock deadlock | `holdBilling` and the typed `billingHold`; `*Locked` helpers never lock (an AST test); 6a's `syncSubscription` split into lookup + `syncSubscriptionLocked`; order member → billing → lapse → store; 5 s timeout tests (Tasks 7, 10, 11) | |
| -| 2. concurrent accepts | every invite, join, revoke and removal under `lockMembers`; `admitMember` re-checks invite, membership, cap and paid capacity inside; a free rejoin restores the reduced quantity (`opRestore`) before admission (Tasks 3, 11) | |
| -| 3. non-durable invite consent | a seat authorisation (plan, book, currency, per-seat price, who, when) stored on the invite under fresh auth; a mismatch needs consent again; the seat charge is an operation bound to the token; an applied op admits after a crash; revoked tokens never start one (Task 11) | |
| -| 4. previous-period allowances | `freshenLocked` applies the fresh read before anything is computed and requires matching identity and period; delayed-renewal and replacement tests for packs and seats (Tasks 7, 10, 11) | |
| -| 5. pending payments vs double submit | `billing_operations`: one outstanding per subscription (unique index), `PendingUpdate` counts as outstanding, persisted keys, settlement on pay, expiry and reorder, enforced in the change, renewal and seat handlers (Tasks 7, 10, 11) | |
| -| 6. second live subscription | Checkout refuses any `Live` subscription (cancel scheduled included) and any live one on the customer (`LiveSubscriptions`); `ExpireCheckout` returns `complete` versus `expired`, and a completion is synced and refused (Tasks 5, 9) | |
| -| 7. uncertain Checkout creation | intents keep the whole request and book; an open intent with no session is resent with the same key and parameters within 23 h; save failures resume; discovery selects open intents, and `billingIntentPass` resolves them (Task 9) | |
| -| 8. deletion not fenced | `billing_retirements` and `retireGateLocked` under the hold, before the step-up and again at the tombstone: live subscriptions cancelled at period end, not collecting, no pending update, no outstanding op, Checkout resolved; every purchase path refuses while retiring (Task 13) | |
| -| 9. `seats_unpaid` blocks forever | reconciliation closes it when members ≤ paid capacity; a reason-specific close door checks the same under the hold; 6a's other close gates and `subscription_missing` path unchanged (Task 11) | |
| -| 10. live team counts bypass the transition | `membershipTransition` wraps `transitionAccountPlan`; `Store.MembershipTransition` counts before and after in one transaction, bumps, and marks the lapse on a fall; the CLI uses it; the limits pass retries publication (Task 3) | |
| -| 11. item id between steps | `billingOp.ItemID` is carried from each step's response, or a re-read before the next step; the restore-then-charge case and a failure between steps are tested (Tasks 7, 10) | |
| -| 12. Call 7 vs the ruling | the ruling text now states disk is neither multiplied nor pooled (Paul accepted Call 7); Task 0 writes it into the spec that way; `PooledLimits` excludes disk, and the tests pin per-thing disk | |
| -| 13. malformed currencies | `currencyQuery` refuses any explicit value not sold, shows it only when safe, and `/upgrade` maps malformed input to `invalid`; fixed currency rendered consistently; re-checked under the Checkout hold (Tasks 8, 9) | |
| -| gap: 6a integration | discovery → seats; pending replacement → payment; identity change clears seats; `subscription_missing` closure racing a seat write; seats through 6a's `SaveBillingSync` (Task 6) | |
| -| gap: payment fake | idempotency, pending updates with expiry, later payment, lost responses, checkout races; reorder tests (Tasks 4, 7) | |
| -| gap: readiness | wrong-mode portal, payment method update off, invalid coupon, house without coupon, no session after a readiness refusal (Tasks 5, 9) | |
| -| gap: census | derived from the final diff, including admission, transitions, deletion and recovery helpers; envelope functions reviewed; record-write gate kept (Task 15) | |
| -| gap: provider neutrality | `Live`, `Collecting`, `PendingUpdate`, `CheckoutState` from the adapter; `billingRenewing` uses facts; a scan test keeps Stripe status words out of console billing code (Tasks 4, 6, 7) | |
| -| request budget | rewritten from Astra's table; readiness backs off 1 to 30 minutes; `seats_unpaid` re-checked daily (Global Constraints, Task 7) | |
| +| 1. replay changes the request under the same key | Invariant 1: an operation is one request, persisted exactly (item id or absence, price, quantity, proration, proration timestamp, key) before its single send. Nothing is ever resent. A lost response is observed (`TestLostAddResponseIsObservedNotResent`, clock advanced). | |
| +| 2. a free restore in another period | Operations are bound to subscription and period. Unsent steps are never executed later. Settlement abandons on a moved period. A charge step is computed only from a definite response in the same period (`TestUnsentRestoreAbandonedAcrossRenewal`, the seat twin). | |
| +| 3. an applied invite charge as an admission pass | Invariant 2: capacity is recomputed at every admission. An applied charge is a credit any admission can take, and authorisations are single use (`TestAppliedInviteChargeIsACreditNotAPass`). | |
| +| 4. one page of live subscriptions | Invariant 3: lists page to completion, up to 10 pages, else `ErrIncomplete`, and the caller refuses (page-two tests in Tasks 5, 9 and 13). | |
| +| 5. freshen blocks returning customers | Invariant 4: `refreshLocked` with no period check for Checkout, retirement and the page; `allowanceLocked` only for quantity changes and joins on a live paid subscription (`TestCheckoutAfterCancellationWithOldRecorded`). | |
| +| 6. the pass expires a live Checkout | Invariant 5: the passes only observe. Only an explicit replacement or the retirement gate expires a session (`TestPassRightAfterCheckoutKeepsSession`). | |
| +| 7. a completed intent blocks retirement | Invariant 6: terminal intents are history. The gate judges the exhaustive subscription list (`TestDeleteAfterCompletedPurchaseAndStop`). | |
| +| 8. replaying an expired, never-executed create | No Checkout create is resent. A `creating` intent is observed after `opQuiet` through the customer's sessions, by intent id. If none is found, it is abandoned. `ErrRefused` abandons at once. The Fake models failure before delivery (`TestCheckoutFailBeforeDelivery`). | |
| +| 9. the budget misses algorithm costs | The budget is by branch and cardinality (`L(n)`, `S`, `k`, `j`). The recovery, Checkout and retirement tests assert `CallsBy`. | |
| +| Fake gaps | Failure before delivery, `Renew` across a period boundary, paging, and call counts by method (Task 4). | |
| --- |
| ## Plan 6c: Stripe setup runbook (outline) |
| -A runbook at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`, following `165472b8:implementation/carloku-paid-launch/ENABLEMENT.md`, reshaped. **Every live step is Paul's.** Test mode on dev comes first, and live comes after spec §12 steps 1 to 4. |
| +The runbook goes at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`, reshaped from the old `ENABLEMENT.md`. **Every live step is Paul's.** Test mode on dev comes first, and live comes after spec §12 steps 1 to 4. |
| -1. **Products:** Personal, Community, Business and the five packs: 8 products. Tax code to confirm with the accountant. |
| -2. **Prices:** 24, each yearly, licensed, per unit, tax exclusive and in a single currency, with `metadata[price_key]`. In minor units, usd / eur / gbp: |
| +1. **Products:** Personal, Community, Business and the five packs (8). |
| +2. **Prices:** 24, yearly, licensed, per unit, tax exclusive, one currency each, with `metadata[price_key]`. In minor units, usd / eur / gbp: |
| | Item | usd | eur | gbp | |
| | --- | --- | --- | --- | |
| | personal | 2800 | 2400 | 2200 | |
| - | community (per member) | 600 | 500 | 450 | |
| - | business (per member) | 6000 | 5000 | 4500 | |
| - | pack apps | 1200 | 1000 | 900 | |
| - | pack disk | 3600 | 3100 | 2800 | |
| - | pack storage | 1200 | 1000 | 900 | |
| - | pack email | 2400 | 2100 | 1900 | |
| - | pack bandwidth | 4800 | 4100 | 3800 | |
| + | community, per member | 600 | 500 | 450 | |
| + | business, per member | 6000 | 5000 | 4500 | |
| + | apps | 1200 | 1000 | 900 | |
| + | disk | 3600 | 3100 | 2800 | |
| + | storage | 1200 | 1000 | 900 | |
| + | email | 2400 | 2100 | 1900 | |
| + | bandwidth | 4800 | 4100 | 3800 | |
| The book becomes a new `approved` version before live. |
| -3. **The locked portal configuration:** |
| - - on: payment method update and invoice history; |
| - - customer update limited to address, name and tax id; |
| - - off: subscription update, cancel and pause. |
| - |
| - Its id goes to `CARLOS_STRIPE_PORTAL_CONFIGURATION`. |
| -4. **The house coupon:** 100% off, forever, unrestricted, no promotion code. Its id goes to `CARLOS_STRIPE_HOUSE_COUPON`. |
| -5. **The webhook:** `https://<console>/billing/webhook`, the six events of spec §9.6, API version `2025-02-24.acacia`, with its secret in `CARLOS_STRIPE_WEBHOOK_SECRET`. |
| -6. **Retry settings:** cancel after all retries fail. Pending updates expire on Stripe's default (about 23 hours). |
| -7. **The restricted key:** |
| - - granted: Checkout Sessions write, Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices, Products and Coupons read; |
| - - not granted: refunds, charges, events, invoices, webhook endpoints, keys. |
| -8. **Console variables** (EnvironmentFile only): as 6a, plus `CARLOS_STRIPE_PORTAL_CONFIGURATION`, and optionally `CARLOS_STRIPE_HOUSE_COUPON`. |
| -9. **Test-mode rehearsal on dev** (test clocks): |
| - - `/upgrade` while signed out, through sign-up, to Checkout; |
| - - Personal with packs; Community at 4 and at 12 members; |
| - - a declined pack raise, then paid from the portal, then a resubmit refused while pending; |
| - - a pending update left to expire; |
| - - a deleted pack restored and charged above its paid count; |
| - - a delayed renewal webhook followed by a pack request; |
| - - a member join with a good card, a declining card, and a lost response; |
| - - two joins at once; |
| - - a leave, then a rejoin within the period; |
| - - Personal → Business (`pending_if_incomplete` with a price swap); |
| - - stop and resume renewal; |
| - - deletion refused while renewing or collecting, then allowed; |
| - - an expiry racing a completed Checkout; |
| - - a Checkout resent after a lost response; |
| - - a failed renewal, then cancellation; |
| - - out-of-order events; |
| - - `incomplete_expired` from Checkout; |
| - - webhook secret rotation; |
| - - readiness refusing a wrong price, an unlocked portal and a bad coupon, with backoff observed; |
| - - a house account at zero; |
| - - the customer-currency lock. |
| -10. **Flagship:** the same in live mode on Paul's approval. Then publish the pricing page's buttons to `https://<console>/upgrade?plan=<plan>¤cy=<cur>`. |
| +3. **Locked portal configuration.** Its id goes to `CARLOS_STRIPE_PORTAL_CONFIGURATION`. |
| +4. **House coupon:** 100% off, forever. Its id goes to `CARLOS_STRIPE_HOUSE_COUPON`. |
| +5. **Webhook:** `https://<console>/billing/webhook`, the six events, API version `2025-02-24.acacia`. |
| +6. **Retry settings:** cancel after all retries. Pending updates expire after about 23 hours. |
| +7. **The restricted key:** Checkout Sessions write (which also allows listing a customer's sessions), Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices, Products and Coupons read. Nothing else. |
| +8. **Console variables:** as 6a, plus the portal configuration and the house coupon. |
| +9. **Test-mode rehearsal on dev** (test clocks), the revision-2 list plus: |
| + - a request timed out at the network edge, then observed after 10 minutes (Call 17); |
| + - a Checkout create whose response is lost, found again by intent id; |
| + - a customer with more than 100 subscriptions (paging); |
| + - a pack restore interrupted across a renewal; |
| + - the hourly pass running while a buyer is on the Checkout page. |
| +10. **Flagship:** the same in live mode on Paul's approval, then publish `https://<console>/upgrade?plan=<plan>¤cy=<cur>`. |