carlos / platform Public

plans 6b: revision 2 after Astra's plan review. Typed billing hold and lock order member, billing, lapse, store; serialised admission with in-lock re-checks; durable seat authorisation on invites; freshen before computing allowances; durable subscription operations, one outstanding per subscription, persisted keys and carried item ids; no second live subscription and expiry that tells completed from expired; resumable Checkout intents; a retirement gate for deletion; seats_unpaid resolution; membership through transitionAccountPlan; malformed currencies refused; disk neither multiplied nor pooled (Call 7); 6a integration, payment fake, readiness and census gaps; request budget rewritten with readiness backoff

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c86d06923d19105bbb8e8775ae823f49fa397b2a parent 69b01f3
1 file changed, +871 −549
  • docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md +871 −549

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 07591cd73..6fdca5d2c 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
@@ -2,162 +2,222 @@
> **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:** An account owner on a console with billing configured can 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, stop or resume renewal, and reach a locked Stripe portal for cards and invoices. A static pricing page links to one stable console URL that takes a signed-out visitor through sign-in or sign-up first.
+**Goal:** On a console with billing configured, an account owner can:
+- 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;
+- stop or resume renewal;
+- reach a locked Stripe portal for cards and invoices.
+
+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.
**Architecture:**
-- **Team plans in the catalog** (`internal/plans`): a plan may carry a `team` block (base plan, a per-member multiple in thousandths, a minimum). `Effective` takes a member count and 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.
-- **Seats on the plan row** (`internal/console`): `account_plans.seats` is the paid seat count billing wrote; 0 means "count the members now". `EffectiveLimits` and the limits record use it, and a membership change republishes a live-counted team row.
-- **Provider writes** (`internal/billing`, `internal/billingstripe`): six new `Provider` methods (customer, Checkout start and expiry, item changes, renewal, portal) behind the 6a boundary. The console still imports only `internal/billing`.
-- **The console flow** (`internal/console`): a billing page, the `/upgrade` entry, Checkout start and return, pack, plan and seat changes, renewal and the portal. Every change re-reads the subscription under the account's billing lock, asks the provider for the change, then runs 6a's `syncSubscription`. The plan row moves only through the sync, never from a change response.
+- **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.
+- **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.
**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; upgrade from free is Checkout in subscription mode; payment method and invoices through the customer portal, locked to those functions; the console changes plans and quantities, never the portal);
-- §9.2 (paid limits while Stripe retries; Plan 4d owns what falls);
-- §9.6 (live setup: the 6c outline at the end);
-- §10 (provider boundary);
-- §3 (usd/eur/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).
+- §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;
+ - upgrading from free is Checkout in subscription mode;
+ - payment method and invoices go through the customer portal, locked to those functions;
+ - 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).
+- §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.
+- §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), which reverses "team plans after launch". Task 0 records it in the spec:
+- **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:
- 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, storage, disk and email. Flags (custom domains, the 15-minute idle window) are as Personal. Business also gets 7-day history and priority support.
+ - 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.
+ - 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 7 defines the contract).
+- **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).
-## Base branch and order
+## Base branch, order and 6a's names
-- This branch, `plans-6b-checkout-flow`, was cut from `plans-6-checkout` (Plan 6a, at `f4ce6bda`). 6a is still in its fix pass and is not on main.
-- **6b must be rebased onto main after 6a merges,** and before Task 1 is built. Main carries Plan 4d-1 (`9b81d97b`): `applyAccountPlan` is the single plan-change path, and 6a routes billing through it before merging (6a's Astra finding 5).
-- **If 6a has not merged when building starts:** merge `origin/main` into this branch for 4d-1, build Tasks 0 to 2 (they touch only `internal/plans`), and stop before Task 3 until 6a's finding-5 integration lands. Task 3 changes the signature of the function that integration calls.
-- Wherever 6a's merged code names something differently from what this plan quotes (for example a wrapper around `applyAccountPlan` with an ownership guard), use 6a's name, and note the ruling in the ledger.
+- 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.
+- **6a's merged names, which this plan uses:**
-## Calls for Paul
+ | 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.
-**Ruled 2026-10-25: Paul accepted every recommendation (1 to 16) as written.** Task 0 records them in the spec. Don't reopen them.
+## Calls for Paul
-Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
+**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 7's. After sign-in, the console looks at the accounts the viewer **owns**:
+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.** Spec §3 says "default by billing country". The console doesn't know the billing country before Checkout, so:
- - the billing page preselects the currency for the **visitor's country from the console's GeoIP database** (`s.cfg.GeoIPReader`, live on flagship), falling back to the book's default;
- - the buyer can override it (three radio buttons);
+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.
- This avoids a 250-name country picker, which would be copy that nobody reviews well. 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.** The alternative is a country select before Checkout, as the old branch did.
-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: a new customer, which is a later rebind path. **Recommend: as stated.**
+ **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 (Personal 28 → Community 60 at 10 members → Business 600 at 10). It swaps the plan item's price at once, prorated and charged now, and is granted once paid (6a Call 8's mechanics).
- - A downgrade between paid plans is not self-serve in 6b. The owner stops renewal and buys the other plan once it ends (4d's 7-day grace covers the gap), or an operator does it.
-
- Holding a downgrade until renewal needs a "held plan" beside 6a's held packs. That is a design change worth its own review. **Recommend: as stated; downgrades in a later plan if owners ask.**
-5. **The prorated amount quoted before a charge.** The confirm page shows a local estimate: "about $X now for the rest of the year, plus any tax". It is computed from the book price × the days left / 365, rounded up. Stripe's own invoice preview would cost one more request and an Invoices read permission per quote, and Stripe's figure arrives on the receipt anyway. **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` (the existing step-up). Checkout itself does not, because the buyer is at Stripe with a card in hand. Stopping renewal does not. **Recommend: as stated.**
-7. **Disk is not pooled.** Disk is a per-running-thing cap (spec §5.4), enforced on each box. "Pooled disk" would need an account-wide disk pool that no box can enforce today. Team plans keep Personal's 10 GB per running thing. Total disk still grows with the team, because the running-things count multiplies. Running things, awake hours, bandwidth, object storage and email multiply and pool. **Recommend: as stated.** If Paul wants disk multiplied too, it is one entry in `plans.PooledLimits`, and the per-thing figure grows with the team.
-8. **Ceilings scale with the team.** The catalog's hard ceilings (200 running things and 10,000 emails a day "without an operator") would clamp Business at 10 members (500 running things, 20,000 emails) below what it sells. On a team plan, each ceiling is multiplied by the same factor as the limits (`multiple × billed members`) when that factor is above 1. **Recommend: as stated.** The alternative is selling Business with limits we then clamp.
-9. **Community's history.** The ruling reads "flags as Personal; Business also gets 7-day history". So Community gets the latest database copy only (history 0), and Business gets 7 days. Sidecars, the memory tier, the minimum schedule and fleets are as Personal for both. **Recommend: as read; say so if Community should keep 7 days.** It is configuration in the catalog either way.
-10. **Packs on team plans.** Both team plans offer the same five packs as Personal, flat per account (not per member), at the same prices. **Recommend: yes.** The machinery is identical, and a team that needs more email shouldn't have to buy members.
+ - 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.**
11. **A member joins while the card fails.**
- - The owner sees the cost when inviting someone who will need a new paid seat. The invite form adds a confirm step: "When they join, the account pays about $X now for the rest of the year, plus any tax".
- - **The charge happens when the invite is accepted, before the membership is created.** If the payment fails or needs the owner's action, the person does not join yet. The invite stays valid, the invitee sees "this account can't add you yet; its owners have been told", and the owners' billing page shows "a change is waiting for payment".
- - The invitee can try again once it is paid. A paid pending update applies the seat, so the retry joins without a second charge.
- - Members added by an operator (`console member -add`, a manifest rebuild) are never charged automatically. When they leave the account with more members than paid seats, the hourly pass opens a `seats_unpaid` billing problem.
-
- **Recommend: as stated.** The alternative, letting the person in and charging later, gives away seats whenever a card fails.
-12. **A member who leaves.** The seat comes off the subscription at once with no proration (no refund), so the renewal bills the lower count. The account keeps the period's highest paid seat count, and the limits that come with it, until renewal. Someone joining again within the period, up to that count, is not charged again. This is the same rule as 6a Call 6 for packs. **Recommend: as stated.**
-13. **Who counts as a member.** Every owner and member (both can reach the account and ship). Pending invites and service credentials do not count. A team below the minimum is billed for, and limited at, the minimum of 10. **Recommend: as stated.**
-14. **Free and Personal accounts with more than one member.** Otherwise Personal plus unlimited members undercuts Community.
- - The catalog gains `max_members` per non-team plan. **Recommend 3 for both Free and Personal** (the owner plus two).
- - It is checked only when an invite is sent and when it is accepted, like Plan 3a's creation caps. Nobody is removed.
- - Sponsored accounts are exempt.
- - The refusal says to move to a team plan. The number is Paul's.
-15. **Deleting an account that is still renewing** is refused: "stop renewal first; you can delete the account after that". It is allowed once renewal is stopped (nothing more will be charged). **Recommend: as stated.**
-16. **A second account (§8.1, "more accounts are created as paid").** No separate create-as-paid path. Upgrading the free account frees the one-free allowance, and the free-account refusal copy now says so. **Recommend: as stated.** Creating an account at Checkout would mean minting from a webhook, which is a much larger change.
+ - 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.**
## 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, and the invite and accept flows are unchanged;
- - the house door answers 409 `billingCopyOff`.
+ - 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.
- Team-plan limits and `max_members` work with a catalog and no billing (an operator assigns plans, spec §10). Without a catalog, nothing in this plan acts.
+ 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.
- **6a's rules hold:**
- the event body is never trusted;
- - the plan follows only a fresh `Provider.Subscription` read under the account's billing lock (`s.billing.locks.lock(sqid)`);
+ - 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);
- a live console refuses a draft book;
- keys are `rk_` keys from the EnvironmentFile only.
-- **Lock order:** the billing lock (`s.billing.locks`, by sqid) is taken before Plan 4d's lapse lock (`s.lapseLock`, by account id), never the other way round.
-- **Every change re-reads, then syncs.**
- 1. A pack, plan, seat or renewal change takes the billing lock.
- 2. It re-reads the subscription with `Provider.Subscription` and computes from that read, not from the stored row.
- 3. It calls the provider.
- 4. It calls `syncSubscription`.
-
- A change response is never written to the plan row.
-- **Granted once paid.** Charges use `billing.ProrateNow`, which the adapter sends as `proration_behavior=always_invoice` with `payment_behavior=pending_if_incomplete` (6a Call 8). Reductions use `billing.ProrateNone`.
-- **Changes use the subscription's own book and currency.** Price ids come from `cfg.Prices.ID(PriceRef{Book: prev.Book, ...})`. A target the subscription's book does not price is refused with `billingCopy["change.book"]`. New purchases use `cfg.Book.Version`.
-- **Currencies:** exactly `usd`, `eur`, `gbp`; `plans.ErrCurrencyNotSold` for anything else, upper case included; nothing converted (§3, Calls 2 and 3).
-- **Money moves only on an owner's POST,** with the session's CSRF token (`r.FormValue("csrf")` against the raw session, as `handlePlanKeepSave` does). The two exceptions are an invitee's accept, which charges a seat the owner confirmed at invite time (Call 11), and nothing else.
-- **Double submits are harmless.** Forms carry the absolute target (a quantity or a plan), not "+1". Under the lock, a re-read that is already at the target is a no-op that says so. Idempotency keys:
+- **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>` |
+ | Checkout start | `checkout:<intent id>`, reused by every resend of that intent |
| Checkout expiry | `expire:<intent id>` |
- | item change, renewal, portal | `<kind>:<subscription or customer>:<16 random hex>`, generated per handled request and reused only by that request's retries |
-- **Redirect targets:** success, cancel and portal return URLs are built from `s.cfg.Origin` and the account's sqid only, never from request input.
-- **Request budget.**
- - Stripe, per owner action:
- - billing page view: 0 requests (store only);
- - Checkout start: ≤1 customer create, ≤1 session expiry, 1 session create;
- - Checkout return: 1 session read plus one 6a sync (2 or 3 subscription reads);
- - a change: 1 subscription read, 1 or 2 updates, one sync;
- - renewal: 1 read, 1 update, one sync;
- - portal: 1 session create;
- - invite accept needing a seat: 1 read, 1 or 2 updates, one sync.
- - Readiness: 6a's, plus 1 portal configuration read, plus 1 coupon read when a house coupon is configured.
- - Hourly pass: no new reads. Seat reconciliation compares the stored `billing_accounts.seats` with a SQLite member count, and calls Stripe only when they differ.
- - S3: nothing polled. A membership change on a live-counted team row republishes the limits record (one PUT, rare). A seat or plan change publishes through the existing path.
+ | 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` (the record-write census matches on it).
+- **Names:** no helper or type name containing `Record`.
- **Copy:**
- - Every new human string lives in `internal/console/billingpage_copy.go` (`billingCopy map[string]string`), in `plancaps_copy.go` (member cap and free-account refusals), or in `billing_cli_copy.go` (CLI, lower case).
- - Tests compare against `billingCopy[key]`, never against literal text, so the Luna pass can change any string.
- - House rules: no em dashes (a full stop and a new sentence), plain words, CLI lower case. Error fragments, diagnostics and JSON keys stay out.
+ - 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.
- **Census:**
- - Each task that adds a route adds its `testdata/claim-routes.txt` line, fixture (`claim_invariant_fixtures_test.go`) and probe in the same commit, so `TestClaimConsoleRouteCensus` stays green.
- - New tables go in `claimSQLTables` (`store_gate.go`) as `NonApp`.
- - Task 13 runs `make census-card` and `make census-propose`. New units are hand-written decisions; Astra approves; decisions go to Paul.
+ - 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.
- **Tests:**
- - TDD with no network: console tests use `billingtest.Fake`, adapter tests use an `httptest` Stripe.
+ - 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. The `-run Claim` suite takes about 15 minutes: run it once per route-adding task, not in a loop. CI runs everything.
-- **Cross-compile:** nothing here is Linux-only. Task 13 runs `GOOS=darwin` and `GOOS=windows` builds.
+ - 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.
## Review Focus
-1. **Two tabs, two Checkouts.** The second Checkout start must expire the first open session, so only one can complete. A double click on "Pay now" must charge once (the re-read sees the target already reached). Pinned in Task 8 (`TestCheckoutExpiresTheOpenSession`) and Task 9 (`TestChangeTwiceChargesOnce`).
-2. **A hostile or stale upgrade link.** The checks:
- - `?currency=USD`, `?currency=jpy` and `?plan=../x` must not default, crash or reflect raw input;
- - the signed-out redirect's `next` must stay a local path;
- - a signed-in member who owns nothing must not reach another account's billing.
-
- Pinned in Task 7 (`TestUpgradeEntry`).
-3. **The card fails on a member's join.** No membership, the invite still valid, limits unchanged, and the owners see the waiting payment. Pinned in Task 10 (`TestJoinWaitsForPayment`).
-4. **A sponsored or operator-assigned account visits billing or `/upgrade`.** It is offered nothing to buy, is told why, and a POST to checkout is refused before any provider call. Pinned in Task 8 (`TestCheckoutRefusesOperatorRows`).
-5. **Stored state older than Stripe at change time.** Say a pack was raised in another tab. The change must compute from the fresh read, and must not re-charge or undo the other tab's change. Pinned in Task 9 (`TestChangeComputesFromTheFreshRead`).
+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`).
---
@@ -165,13 +225,14 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
**Files:**
- Modify: `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`:
- - §3: a bullet with Paul's team-plan ruling, dated 2026-10-25, quoted as in this plan's Spec block;
- - §4.1: a paragraph on team plans (base, multiple, minimum, pooled fields, `max_members`);
- - §4.2: Community and Business columns and their prices;
+ - §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.
-- [ ] **Step 1:** Make the edits. Mark each of Calls 2, 4, 7, 8, 9, 10, 14 "(proposed in Plan 6b, awaiting Paul)" where the spec states it.
-- [ ] **Step 2: Commit** `spec: team plans (Paul, 2026-10-25) in the plans and packs design (plans 6b)`.
+- [ ] **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)`.
### Task 1: Team plans and member caps in the catalog
@@ -181,7 +242,7 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
- `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: `internal/console/planlimits.go`, `apiaccountplan.go` and `planlapse.go` (main) each pass `1` for now; Task 3 passes the real count.
+ - every `Effective` caller, so it compiles: `planlimits.go`, `apiaccountplan.go` and `planlapse.go` each pass `1` for now; Task 3 passes the real count.
**Interfaces:**
- Produces:
@@ -196,7 +257,8 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
MaxMembers int `json:"max_members,omitempty"` // non-team plans only; 0 = no cap
const MaxTeamMembers = 10000
var ErrTeamMembers = errors.New("team member count out of range")
- var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month"} // Call 7
+ // 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"
func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits, members int) (Limits, error)
@@ -204,46 +266,45 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
- 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 (they come from the base);
+ - 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`.
- 2. For each `PooledLimits` field: `floor(base × PerMemberMilli × Billed(members) / 1000)`, overflow-checked with `math/bits` (an overflow returns `ErrTeamMembers`).
+ 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. For the five pooled fields only, each non-zero ceiling is scaled by the same `PerMemberMilli × Billed / 1000` when that factor exceeds 1 (Call 8). Idle and rate ceilings never scale.
+ 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 > MaxTeamMembers` or `members < 0` is `ErrTeamMembers`. On a non-team plan, `members` is ignored.
-- The example catalog's team plans (Calls 7, 9, 10):
+ `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}` for community, and 2000 for business.
+ - `team`: `{"base":"personal","per_member_milli":200,"min_members":10}`, with 2000 for business.
- [ ] **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, IdleSeconds 900, HistoryDays 0
- func TestEffectiveCommunityTwentyThree(t *testing.T) // members 23: RunningThings 115, AwakeHoursMonth 6900, EmailPerDay 4600, StorageBytes 123480309760
- func TestEffectiveBusinessScalesCeilings(t *testing.T) // members 12: RunningThings 600 (ceiling 200 x 24 = 4800), EmailPerDay 24000, HistoryDays 7
- func TestEffectiveTeamWithPacks(t *testing.T) // community, members 10, apps 2: RunningThings 60
+ // 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) // table: base missing; base free; base itself a team; milli 0; min 0; team limits with running_things;
- // team with max_members; max_members -1; each refused
+ 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"
```
- [ ] **Step 2: Run** `go test ./internal/plans/ -run 'Effective|Team|Catalog'`. Expected: FAIL (`Team` undefined).
-- [ ] **Step 3: Implement** in `team.go` and `catalog.go`, then fix the callers so `go build ./...` passes.
+- [ ] **Step 3: Implement,** then fix the callers so `go build ./...` passes.
- [ ] **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; max_members on other plans (plans 6b)`.
+- [ ] **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`, `internal/plans/testdata/example-public-pricebook.json` (regenerated golden), and `cmd/pricebook-export` golden or tests where they pin the schema.
-- Create: `docs/superpowers/specs/2026-10-25-public-price-export-schema-3.md` (the schema-2 document plus the changes below, and a "what changed" list for the website).
+- 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).
**Interfaces:**
- Produces:
@@ -255,43 +316,41 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
Base string `json:"base"`
PerMember string `json:"per_member"` // Team.PerMember()
MinMembers int `json:"min_members"`
- Pooled []string `json:"pooled"` // PooledLimits, in that order
+ 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"; whole units without decimals
+ func FormatMinor(currency string, minor int64) string // "$28", "€24", "£4.50", "$0.07"
```
-- On a team plan, `annual_minor` is the price **per member per year**. The schema document says so, with a worked example: Community at 10 members in usd is 6000. A team plan's `limits` in the export are its own limits **with the pooled fields computed at `min_members`**, so a page can show the 10-member figures without doing the arithmetic.
-- Plan order: free first, then by `annual_minor[default] × max(1, min_members)`, then key. That gives personal, community, business.
+- 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.
- [ ] **Step 1: Write the failing tests**
```go
- func TestPublicExportSchema3Team(t *testing.T) // schema 3; community: team {base personal, per_member "0.2", min_members 10, pooled [...5]}, annual_minor usd 600,
- // limits.running_things 50; personal max_members 3; plan keys in order free, personal, community, business
- func TestPublicExportGolden(t *testing.T) // the regenerated golden (existing test, new bytes)
+ 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 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` against the example files.
+- [ ] **Step 3: Implement,** then regenerate the golden with `go run ./cmd/pricebook-export`.
- [ ] **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: Members drive team limits; seats on the plan row; member caps
+### Task 3: Seats, the member lock and membership transitions
**Files:**
-- Create: `internal/console/planmembers.go` (`planMembers`, `membersChanged`, `checkMemberCap`'s count).
+- Create: `internal/console/planmembers.go`, `internal/console/planmembers_test.go`.
- Modify:
- - `internal/console/store.go`: a `migratePlanSeats()` chained after the last plan migration: `ALTER TABLE account_plans ADD COLUMN seats INTEGER NOT NULL DEFAULT 0`, guarded like the other column adds;
- - `internal/console/accountplans.go`: `AccountPlanRow.Seats`, `accountPlanColumns`, `SetAccountPlan`, and `accountPlanUpsertSQL`/`accountPlanUpsertArgs` carrying seats; billing's guarded write compares seats as well;
+ - `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 member count;
- - `internal/console/plancaps.go` and `plancaps_copy.go`: `checkMemberCap`; the free-account refusal copy per Call 16;
- - `internal/console/server.go`: `handleInvite` and `handleAcceptInvite` call `checkMemberCap`, and accept calls `membersChanged`;
- - `internal/console/ownership.go`: `handleRemoveMember` calls `membersChanged`;
- - `cmd/console/member.go`: after add or remove, `st.BumpPlanForMembers`.
-- Test: `internal/console/planmembers_test.go`.
+ - `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.
**Interfaces:**
-- Consumes: Task 1 (`Effective(..., members)`, `Plan.Team`, `Plan.MaxMembers`).
+- Consumes: Task 1; 6a's `transitionAccountPlan`.
- Produces:
```go
// AccountPlanRow gains Seats int: the paid seat count billing wrote; 0 = count members now.
@@ -299,114 +358,153 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
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 *Store) BumpPlanForMembers(accountID int64, now time.Time) (bool, error) // revision+1 where the row exists and seats = 0; leaves the throttle
- func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) // row.Seats when > 0, else MemberCount
- func (s *Server) membersChanged(ctx context.Context, acct *Account, now time.Time) // live-counted team row: bump + publishPlanNow; billing team row: Task 10 adds reconcileSeats
- func (s *Server) checkMemberCap(acct *Account, adding int) error // *planCapError when members+adding > plan MaxMembers; nil for team plans, sponsored rows, no catalog
+ 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 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
```
-- `checkMemberCap` call sites:
- - in `handleInvite`, after the "already a member" check, with `adding = CountPendingInvites + 1`; a refusal is `back("err", planCap.Browser())`;
- - in `handleAcceptInvite`, before `AcceptInvite`, with `adding = 1`, using the invite's account from `PendingInviteFor(token, addr, now)`. A refusal renders `renderMessage(409, ...)` with the browser text, and the invite stays unused.
-- Draft copy (`plancaps_copy.go`):
- - `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` (Call 16): "You already own a free account, and each person can own one. Upgrade that account to create another, or ask an operator."
- - The `cli.` twin follows the lower-case rule.
+- `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.
- [ ] **Step 1: Write the failing tests**
```go
- func TestTeamLimitsFollowMembers(t *testing.T) // operator sets community (seats 0) on bab; 12 members: EffectiveLimits.RunningThings 60; remove 2: 50 (min 10)
- func TestSeatsPinTeamLimits(t *testing.T) // SetAccountPlan(community, seats 14): 3 members, RunningThings 70
- func TestMembershipChangeRepublishes(t *testing.T) // community seats 0: accept an invite -> revision+1 and limits record republished; personal: no bump
- func TestBumpPlanForMembersKeepsThrottle(t *testing.T) // SetAccountThrottle then BumpPlanForMembers: Throttle still set
- func TestSeatsFallStartsLapse(t *testing.T) // billing row community seats 20 -> applyAccountPlan(community, seats 10): LapseSince set
- func TestMemberCapAtInvite(t *testing.T) // personal max 3, 2 members + 1 pending: invite refused with browser.cap.members; community: allowed; sponsored: allowed
- func TestMemberCapAtAccept(t *testing.T) // personal, 3 members, an invite made before the cap: accept refused, invite still pending, members 3
+ 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 2: Run** `go test ./internal/console/ -run 'TeamLimits|SeatsPin|MembershipChange|BumpPlanForMembers|SeatsFall|MemberCap|MemberCount'`. Expected: FAIL.
-- [ ] **Step 3: Implement.** `go build ./...` finds every caller of the changed signatures. 6a's billing write passes seats from Task 6 (0 until then).
-- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'AccountPlan|PlanLimits|Lapse|Invite|ClaimSQL'` and `go test ./cmd/console/ -run Member`. Expected: PASS.
-- [ ] **Step 5: Commit** `console: team limits follow the member count or the paid seats; member caps on invite and accept; membership changes republish (plans 6b)`.
+- [ ] **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.
+- [ ] **Step 5: Commit** `console: seats on the plan row; every membership change goes through the plan transition under a member lock; member caps checked inside it (plans 6b)`.
-### Task 4: Provider boundary for purchases and changes
+### Task 4: Provider boundary and a payment-faithful fake
**Files:**
- Modify:
- - `internal/billing/billing.go`: `Item.ItemID`, `Subscription.PendingUpdate`, the new types and `Provider` methods;
+ - `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`.
**Interfaces:**
-- Consumes: Task 1 (`Plan.Team`, `MaxTeamMembers`).
+- Consumes: Task 1.
- Produces:
```go
- // Item gains ItemID string. Subscription gains PendingUpdate bool: a change waits for payment.
- // Purchase gains Seats int: the team plan item's quantity; 0 for a non-team plan.
+ // 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)
+ func (s *Subscription) Renewing() bool // Live && !CancelAtPeriodEnd
+ // Purchase gains Seats int.
type Proration string
- const (ProrateNone Proration = "none"; ProrateNow Proration = "now") // now: charged at once, applied only once paid
+ const (ProrateNone Proration = "none"; ProrateNow Proration = "now")
type ItemChange struct { ItemID, PriceID string; Quantity int64; Delete bool } // ItemID "" adds; another PriceID swaps
type ChangeRequest struct {
Subscription string
Items []ItemChange
Proration Proration
- ProrationDate time.Time // inside the current period: a change decided in one period can't be charged into the next
+ ProrationDate time.Time
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 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 // attach the configured 100% house coupon
+ House bool
ExpiresAt time.Time
IdempotencyKey string
}
- type CheckoutSession struct { ID, URL string }
- var ErrPaymentFailed = errors.New("billing: payment failed")
+ 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
+ ErrNoHouseCoupon = errors.New("billing: no house coupon configured")
+ )
// Provider gains:
EnsureCustomer(ctx context.Context, accountSqid, idempotencyKey string) (string, error)
- StartCheckout(ctx context.Context, req CheckoutRequest) (CheckoutSession, error)
- ExpireCheckout(ctx context.Context, sessionID, idempotencyKey string) error // nil when already expired or complete
- ChangeItems(ctx context.Context, req ChangeRequest) (*Subscription, error) // a declined charge is PendingUpdate true or ErrPaymentFailed
+ LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // one request; ids of Live subscriptions only
+ 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
+ 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) // kind KindPlan with name "" finds the plan item
+ func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool) // KindPlan with name "" finds the plan item
```
-- `Recognise`:
- - a non-team plan item still needs quantity 1;
- - a team plan item needs quantity from `Team.MinMembers` to `plans.MaxTeamMembers`, and sets `Purchase.Seats`;
- - anything else wraps `ErrUnrecognised`.
-- `billingtest.Fake` gains:
- - `FailPayment bool`: a `ProrateNow` change sets `PendingUpdate` and leaves items alone;
- - `Changes []billing.ChangeRequest`, `Started []billing.CheckoutRequest`, `Expired []string`, `Renewals []string`, `PortalCalls int`, `Customers map[string]string` (sqid to customer; `EnsureCustomer` returns the same id twice);
- - `ChangeItems` applies changes to `Subs` (add, quantity, swap, delete), giving new items ids `si_<n>`;
- - `StartCheckout` returns `cs_<n>` and the URL `https://checkout.example.com/cs_<n>`.
+- `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.
- [ ] **Step 1: Write the failing tests**
```go
- func TestRecogniseTeamSeats(t *testing.T) // community x 12 + apps x 1: Purchase{Plan community, Seats 12, Packs {apps:1}}; personal: Seats 0
- func TestRecogniseTeamRefuses(t *testing.T) // community x 9; community x 10001; personal x 2: each errors.Is ErrUnrecognised
- func TestFindItem(t *testing.T) // plan item and pack item found with ItemID; absent pack: false
- func TestFakeChangeItems(t *testing.T) // quantity, add, swap, delete applied; FailPayment with ProrateNow: items unchanged, PendingUpdate true; ProrateNone ignores FailPayment
+ 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
```
- [ ] **Step 2: Run** `go test ./internal/billing/... -run 'Recognise|FindItem|Fake'`. Expected: FAIL.
-- [ ] **Step 3: Implement.** The Stripe adapter gets temporary `errors.New("not built")` methods so the build holds until Task 5.
+- [ ] **Step 3: Implement.** Temporary `errors.New("not built")` adapter methods keep the build until Task 5.
- [ ] **Step 4: Run** again, plus `go build ./...`. Expected: PASS.
-- [ ] **Step 5: Commit** `billing: team items with quantity, item ids, pending updates, and the purchase and change methods of the provider boundary (plans 6b)`.
+- [ ] **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)`.
### Task 5: Stripe adapter writes and the extended readiness check
**Files:**
- Modify:
- - `internal/billingstripe/client.go`: `UpdateSubscription`; `Subscription.PendingUpdate` decoded from `pending_update` (non-null means true); `CreateCheckoutParams.CollectAddress` and `.ExpiresAt`;
- - `internal/billingstripe/customer.go`: `CreateCustomer` accepts an empty `Country`, sending then no address and no `tax[validate_location]`;
- - `internal/billingstripe/adapter.go`: the six methods, `ProviderConfig.PortalConfiguration` and `.HouseCoupon`, and `Check`'s portal and coupon checks;
- - `cmd/console/billing.go` and its test: `CARLOS_STRIPE_PORTAL_CONFIGURATION` (required, `bpc_`) and `CARLOS_STRIPE_HOUSE_COUPON` (optional, `validID`), each failing with the 6a "names the variable" error.
+ - `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`.
**Interfaces:**
@@ -416,192 +514,305 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
type SubscriptionItemUpdate struct { ID, PriceID string; Quantity int64; Deleted bool }
type SubscriptionUpdate struct {
Items []SubscriptionItemUpdate
- Proration string // ProrationNone | ProrationAlwaysInvoice; "" sends none of it
+ Proration string
ProrationDate time.Time
- PendingIfIncomplete bool // payment_behavior=pending_if_incomplete
+ PendingIfIncomplete bool
CancelAtPeriodEnd *bool
}
- func (c *Client) UpdateSubscription(ctx context.Context, id string, p SubscriptionUpdate, idempotencyKey string) (*Subscription, error) // POST /v1/subscriptions/{id}
+ func (c *Client) UpdateSubscription(ctx context.Context, id string, p SubscriptionUpdate, idempotencyKey string) (*Subscription, error)
+ func collectingOf(status string) bool // past_due, unpaid, incomplete
```
- Mappings:
| Method | Stripe |
| --- | --- |
- | `EnsureCustomer` | `CreateCustomer{AccountSqid, IntentID: "customer"}` with no country |
- | `StartCheckout` | `CreateCheckout` with `CollectAddress` (`billing_address_collection=required`, `customer_update[address]=auto`), `expires_at`, and `HouseCoupon` from config when `House`; `House` with no coupon configured is an error |
- | `ExpireCheckout` | on a Stripe 400, `GetCheckout`; a status other than `open` is nil |
- | `ChangeItems` | `ProrateNow`: `always_invoice` + `PendingIfIncomplete`; `ProrateNone`: `none`; `items[i][id\|price\|quantity\|deleted]`; `proration_date`; a Stripe `card_error` becomes `billing.ErrPaymentFailed` |
- | `SetRenewal` | `CancelAtPeriodEnd: !renew` |
+ | `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 |
+- `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.
- Every result is mapped through the same code as `Subscription`.
-- `Check` additions, after the prices:
- - `GetPortalConfiguration(cfg.PortalConfiguration)`: active; this mode; payment method update on; invoice history on; subscription update off; subscription cancel off; customer update either off or its allowed updates a subset of `address`, `name`, `tax_id`.
- - With `HouseCoupon` set, `GetCoupon`: valid; this mode; `percent_off` 100; no `amount_off`; duration `forever`; no product restriction.
- - Failures name the variable, never ids.
-
-- [ ] **Step 1: Write the failing tests** (`httptest` Stripe, asserting the form sent)
+- [ ] **Step 1: Write the failing tests**
```go
- func TestChangeItemsSendsProration(t *testing.T) // ProrateNow: proration_behavior=always_invoice, payment_behavior=pending_if_incomplete, proration_date; ProrateNone: none, no payment_behavior;
- // add (no id), swap (id + price), delete (id + deleted=true); Idempotency-Key header
- func TestChangeItemsPendingAndDeclined(t *testing.T) // response with pending_update: PendingUpdate true; 402 card_error: ErrPaymentFailed
- func TestStartCheckoutCollectsAddress(t *testing.T) // billing_address_collection=required, customer_update[address]=auto, expires_at, discounts[0][coupon] only when House
- func TestEnsureCustomerSendsNoAddress(t *testing.T) // no address[country], no tax[validate_location]; metadata account_sqid
- func TestExpireCheckoutAlreadyDone(t *testing.T) // 400 then GET status complete: nil; GET status open: the error
- func TestSetRenewal(t *testing.T) // renew false -> cancel_at_period_end=true; true -> false
- func TestCheckRefusesUnlockedPortal(t *testing.T) // table: inactive; subscription_update on; cancel on; customer_update allows email; invoice history off: each an error naming CARLOS_STRIPE_PORTAL_CONFIGURATION
- func TestCheckRefusesBadHouseCoupon(t *testing.T) // 50% off; duration once; amount_off set; product-restricted: each error; good coupon: nil
- func TestBillingConfigPortalAndCoupon(t *testing.T) // missing portal: error naming it; "pc_x": error; coupon "bad id!": error; both good: set on ProviderConfig
+ 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 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 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 TestBillingConfigPortalAndCoupon(t *testing.T)
```
-- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ -run 'ChangeItems|StartCheckout|EnsureCustomer|ExpireCheckout|SetRenewal|CheckRefuses|BillingConfig'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ -run 'ChangeItems|StartCheckout|EnsureCustomer|ExpireCheckout|LiveSubscriptions|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 with address collection, renewal, portal; readiness checks the portal is locked and the house coupon is 100% forever (plans 6b)`.
+- [ ] **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)`.
-### Task 6: Billing state for seats, intents and the house flag
+### Task 6: Billing state: seats, facts, intents, house, retirement
**Files:**
- Modify:
- - `internal/console/billingstore.go`: columns `plan`, `seats`, `paid_seats`, `pending_update` on `billing_accounts`, added with guarded `ALTER TABLE`s; tables `billing_checkout_intents` and `billing_house`; methods;
- - `internal/console/billingsync.go`: seats in `decideBilling` and `planChange`;
- - `internal/console/billingwebhook.go`: `EventCheckout` also marks the intent completed;
- - `internal/console/store_gate.go`: the two tables.
+ - `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`.
**Interfaces:**
-- Consumes: Task 3 (seats on the plan write), Task 4 (`Purchase.Seats`, `PendingUpdate`).
+- Consumes: Task 3 (seats on the plan write), Task 4 (facts, `Purchase.Seats`).
- Produces:
```go
- // billingAccount gains: Plan string (the purchase's plan); Seats int (current team quantity);
- // PaidSeats int (the period's highest paid team quantity); PendingUpdate bool.
- // planChange gains Seats int; the plan write passes it (0 for non-team plans).
+ // 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
type checkoutIntent struct {
- AccountID int64
- ID, Session, Plan, Currency string
- Seats int
- Packs map[string]int
- CreatedAt, ExpiresAt, ReturnedAt, CompletedAt time.Time
+ 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
}
- func (s *Store) PutCheckoutIntent(ci checkoutIntent) error // one row per account, replaced
- func (s *Store) CheckoutIntent(accountID int64) (*checkoutIntent, error) // nil, nil when none
- func (s *Store) MarkCheckoutReturned(accountID int64, session string, now time.Time) (bool, error) // false when session is not the account's intent
- func (s *Store) MarkCheckoutCompleted(session string, now time.Time) error // unknown session: nil
+ func (s *Store) PutCheckoutIntent(ci checkoutIntent) error // one row per account; replaced only by callers that resolved the old one
+ 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) SetBillingHouse(accountID int64, on bool, by, note string, now time.Time) error
func (s *Store) BillingHouse(accountID int64) (bool, error)
- func billingRenewing(b *billingAccount) bool // provider status active|trialing|past_due|incomplete|unpaid and not CancelAtPeriodEnd
+ 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
```
- Schema:
- - `billing_checkout_intents(account_id INTEGER PRIMARY KEY, intent_id TEXT NOT NULL UNIQUE, session TEXT NOT NULL DEFAULT '', plan TEXT NOT NULL, currency TEXT NOT NULL, seats INTEGER NOT NULL DEFAULT 0, packs TEXT NOT NULL DEFAULT '{}', created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, returned_at INTEGER NOT NULL DEFAULT 0, completed_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)`; off deletes the row.
-- Classification:
- - `"billing_checkout_intents": {NonApp: "an account's open Checkout attempt: session, plan, seats, packs and currency; names no app"}`;
- - `"billing_house": {NonApp: "accounts an operator marked as the house, whose Checkout carries the 100% coupon; names no app"}`.
-- `decideBilling` additions, in the paid-and-recognised row:
- - `Next.Plan = Purchase.Plan` and `Next.Seats = Purchase.Seats`;
- - `PaidSeats = Purchase.Seats` when the period changed or `Prev.Plan != Purchase.Plan`, else `max(Prev.PaidSeats, Purchase.Seats)`;
- - `planChange.Seats = PaidSeats`.
-
- Every saved row sets `Next.PendingUpdate = Sub.PendingUpdate`. Ended clears `Plan`, `Seats` and `PaidSeats`.
+ - `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)`;
+ - `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.
- [ ] **Step 1: Write the failing tests**
```go
- func TestDecideTeamSeatsHoldUntilRenewal(t *testing.T) // community 14 then 11 same period: Plan.Seats 14; raised to 12: 14; new period with 11: 11
- func TestDecideUpgradeResetsSeats(t *testing.T) // Prev personal; Sub business x 10 same period: PaidSeats 10, Plan {business, seats 10}
- func TestDecidePendingUpdateSaved(t *testing.T) // paid sub with PendingUpdate: Next.PendingUpdate true, Plan unchanged from items
- func TestSyncWritesSeats(t *testing.T) // Fake community x 12 for bab: AccountPlan(bab).Seats 12, EffectiveLimits.RunningThings 60
- func TestCheckoutIntentRoundTrip(t *testing.T) // put, read, replace (one row), MarkCheckoutReturned wrong session false, right session true, completed by session
- func TestBillingHouseOnOff(t *testing.T) // on: true; off: false
- func TestBillingRenewing(t *testing.T) // active true; active + cancel_at_period_end false; unpaid true; canceled false
- func TestWebhookCheckoutCompletesIntent(t *testing.T) // EventCheckout cs_1 with an intent: CompletedAt set
+ 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|DecidePending|SyncWritesSeats|CheckoutIntent|BillingHouse|BillingRenewing|WebhookCheckout'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideTeam|DecideUpgrade|DecideNewSubscription|DecideSaves|SyncSeats|DiscoveryThenSeats|PendingReplacementThen|MissingClosureRaces|CheckoutIntent|BillingHouse|Retirement|BillingRenewing'`. Expected: FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Decide|Sync|BillingWebhook|ClaimSQL'`. Expected: PASS.
-- [ ] **Step 5: Commit** `console: billing keeps team seats with the period's highest, pending updates, Checkout intents and the house flag (plans 6b)`.
+- [ ] **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)`.
-### Task 7: The billing page and the upgrade entry
+### Task 7: The billing hold, durable operations and the locked sync
**Files:**
- Create:
- - `internal/console/billingpage.go`: `handleBilling`, `handleUpgrade`, `decideBillingPage`, the view, `requestCountry`;
- - `internal/console/billingpage_copy.go`;
- - `internal/console/templates/billing.html` and `internal/console/templates/billing_pick.html`.
+ - `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`.
+- 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`.
+
+**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
+ 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
+ }
+ 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
+ }
+ 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) 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
+ 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)
+ 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
+ ```
+- 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.
+
+- [ ] **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
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|SyncSubscriptionLocked|Freshen|QuantitySteps|RunOp|OneOutstanding|ReorderedWebhooks|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)`.
+
+### 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`: routes beside `/a/{sqid}/plan/keep`, and `page.Billing *billingView`, `page.BillingPick []Account`, `page.BillingNav bool` (set in `accountPage` when `s.billing != nil`);
- - `internal/console/templates/layout.html`: the nav link `{{if .BillingNav}}<a href="{{.Nav}}/billing"...>Billing</a>{{end}}`;
- - claim files: `route GET /upgrade` and `route GET /a/{sqid}/billing` as `claimRead`, with `claimPageRead` probes asserting `<h1>Billing</h1>` and an upgrade redirect probe.
-- Test: `internal/console/billingpage_test.go`.
+ - `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.
**Interfaces:**
-- Consumes: Task 6 (store), Task 2 (`FormatMinor`), Task 1 (`Team.Billed`), `s.cfg.GeoIPReader`, `s.clientIP`.
+- Consumes: Tasks 1, 2, 6, 7; `s.cfg.GeoIPReader`, `s.clientIP`.
- Produces:
```go
type billingPageInput struct {
- Row *AccountPlanRow // nil: the default plan
- Billing *billingAccount // nil: never bought
+ Row *AccountPlanRow
+ Billing *billingAccount
Intent *checkoutIntent
- Problems int // open billing problems for this account
+ 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 // a billingCopy key, "" for none
- Buy bool // the Checkout form
- Change bool // pack, plan upgrade
- Renewal string // "", "stop", "resume"
- Portal bool
- }
+ 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 // ISO alpha-2 from GeoIP, "" when none
+ 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: billingPageState plus the lines below, already formatted
- // (FormatMinor amounts, UTC dates, billingCopy text). Its field names are the builder's.
+ // billingView is billing.html's data, already formatted; field names are the builder's.
```
-- `decideBillingPage`, first match wins. Actions are offered only to owners. A member sees the same notice, plus `notice.owners_only` when an owner would have been offered something.
+- `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.
| Condition | Notice | Offered |
| --- | --- | --- |
| `!Ready` | `notice.not_ready` | nothing |
- | `Problems > 0` | `notice.problem` (6a Call 5) | `Portal` if a customer is bound |
- | `Row.Source` is `operator` or `sponsored` | `notice.operator_plan` | nothing |
- | no subscription, or ended, with an intent returned in the last 24 h and not completed | `notice.settling` | nothing |
- | no subscription, or ended | none | `Buy` |
+ | `Retiring` | `notice.retiring` | nothing |
+ | problems include `seats_unpaid` | `notice.seats_unpaid` | `Portal` |
+ | any other problem | `notice.problem` | `Portal` if a customer is 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 |
- | paid, `PendingUpdate` | `notice.pending_payment` | `Portal`, `Renewal` |
- | paid, `ProviderStatus` `past_due` | `notice.past_due` | `Portal` |
- | paid, `CancelAtPeriodEnd` | `notice.ending` (with the date) | `Renewal` "resume", `Portal` |
+ | `Collecting` | `notice.past_due` | `Portal` |
+ | `CancelAtPeriodEnd` | `notice.ending` | `Renewal` "resume", `Portal` |
| paid | none | `Change`, `Renewal` "stop", `Portal` |
-- The page shows:
- - the plan name, packs with quantities, and for a team plan "members N, paid for M";
- - the currency (fixed after a first purchase, Call 3);
- - the renewal or end date (`2 January 2006`, UTC).
-
- Then the forms that `billingPageState` allows:
- - **Buy:**
- - a radio of the paid plans with each yearly price (a team plan shows "per member, for at least 10", and today's total at `Billed(MemberCount)`);
- - a quantity input per pack the plan offers (0 to `MaxQuantity`);
- - a radio of the sold currencies, preselected by `ChooseCurrency(query currency, requestCountry(r))`. On `ErrCurrencyNotSold` there is a `currency.refused` banner and nothing is preselected;
- - `?plan=` preselects a paid catalog plan, and is ignored otherwise.
- - **Change:** each pack's quantity with Save, and upgrade buttons for the plans Call 4 allows.
-- `/upgrade` contract (Call 1), the stable URL the pricing page links to:
- - `GET /upgrade?plan=<plan>&currency=<currency>`. Both are optional.
- - `plan` is kept only if it is a paid catalog plan key.
- - `currency` is kept if it is 1 to 8 ASCII letters, so the billing page can **refuse** an unsold one rather than default it. Anything else is dropped.
+- **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):
+ - `GET /upgrade?plan=<plan>&currency=<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.
- Billing off: 404.
- - Signed out: 303 to `/?next=` + `url.QueryEscape("/upgrade?" + kept.Encode())`. The front door's one form serves sign-in and sign-up alike, a new address becomes an account, and `finishSignin` returns through `safeNext` after minting the account.
- - Signed in:
- - owns one account: 303 to `/a/<sqid>/billing?` + kept;
- - owns several: `billing_pick` lists them (most recent first), each linking there;
- - owns none: `renderMessage(200, billingCopy["upgrade.not_owner_title"], billingCopy["upgrade.not_owner"])`.
-- Draft copy (`billingCopy`, Luna pass in Task 13):
+ - 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):
| key | draft |
| --- | --- |
| `page.title` | Billing |
| `notice.not_ready` | Billing isn't available right now. Try again in a few minutes. |
+ | `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.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. |
@@ -609,6 +820,8 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
| `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.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 |
@@ -618,297 +831,406 @@ Each has a recommendation. Calls 7 to 14 come from the team-plan ruling.
- [ ] **Step 1: Write the failing tests**
```go
- func TestDecideBillingPage(t *testing.T) // one case per table row, plus member vs owner on "paid": member gets notice.owners_only and nothing offered
- func TestBillingPageOffAndGate(t *testing.T) // billing nil: 404; non-member: 404; member: 200 without forms; owner free: Buy form with three plans
- func TestBillingPageCurrencyDefault(t *testing.T) // GeoIP fake DE: eur checked; ?currency=gbp: gbp checked; ?currency=jpy and ?currency=USD: currency.refused, none checked
- func TestBillingPageTeamTotals(t *testing.T) // 4 members: community shows FormatMinor 6000 total; 12 members: 7200
- func TestUpgradeEntry(t *testing.T) // signed out ?plan=personal&currency=eur: 303 to /?next=%2Fupgrade%3Fcurrency%3Deur%26plan%3Dpersonal;
- // ?plan=../x&currency=<script>: next carries neither; owner of one: 303 /a/bab/billing?...; owner of two: picker, MRU first;
- // member only: not-owner message, no account sqid in the body; billing nil: 404
- func TestUpgradeAfterSignupLandsOnBilling(t *testing.T) // email code sign-in of a new address with next=/upgrade?plan=personal: lands on /upgrade, then /a/<new>/billing?plan=personal
+ 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 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 and the /upgrade entry for the pricing page (plans 6b)`.
+- [ ] **Step 5: Commit** `console: billing page from neutral facts, refusing every unsold or malformed currency, and the /upgrade entry (plans 6b)`.
-### Task 8: Starting Checkout and coming back
+### Task 9: Checkout: start, resume, return
**Files:**
-- Create: `internal/console/billingcheckout.go`.
+- Create: `internal/console/billingcheckout.go`, `internal/console/billingcheckout_test.go`.
- Modify:
- `internal/console/server.go`: `POST /a/{sqid}/billing/checkout` and `GET /a/{sqid}/billing/done`;
- - `internal/console/ownership.go`: `handleDeleteAccount` refuses while `billingRenewing` (Call 15), after CSRF and before the step-up;
- - claim files: both routes as `claimNonApp` ("starts a Checkout: billing customer and intent; names no app", and "syncs the returned subscription: billing and plan rows; names no app"), with probes on a Fake (a POST yields one `Fake.Started` and an intent; done with `cs_1` mapped to an active sub writes a personal plan row).
-- Test: `internal/console/billingcheckout_test.go`.
+ - `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.
**Interfaces:**
-- Consumes: Task 4 (`EnsureCustomer`, `StartCheckout`, `ExpireCheckout`, `CheckoutSubscription`), Task 6 (intents, house, `SetBillingCustomer`), 6a (`syncSubscription`).
+- 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)
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)
```
- Checkout, in order:
- 1. Owner gate, CSRF, ready.
- 2. Parse `plan` (a paid catalog plan), `pack_<name>` (0 to `MaxQuantity`, offered by the plan) and `currency` (`ChooseCurrency(form, "")`; must equal the fixed currency when the account has one).
- 3. Take the billing lock.
- 4. Refuse, before any provider call, with a flash and a redirect to the billing page:
- - an `operator` or `sponsored` row (`checkout.operator_plan`);
- - `billingRenewing` or state pending (`checkout.already`);
- - an open problem (`notice.problem`).
- 5. Seats are `Team.Billed(MemberCount)` for a team plan, else 0.
- 6. Look up every item's price id under `cfg.Book.Version`.
- 7. Bind a customer if none: `EnsureCustomer(sqid, "customer:"+sqid)`, then `SetBillingCustomer`.
- 8. If an earlier intent has a session that is neither completed nor expired, `ExpireCheckout` it. An error stops with `checkout.failed`.
- 9. Put a new intent (`ci_` + 16 random hex, empty session).
- 10. `StartCheckout` with:
- - success `s.cfg.Origin + "/a/" + sqid + "/billing/done?session={CHECKOUT_SESSION_ID}"`;
- - cancel `.../billing`;
- - `House` from `BillingHouse`;
- - `ExpiresAt now+checkoutLifetime`.
- 11. Store the session, then 303 to its URL.
+ 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.
- 2. `MarkCheckoutReturned(acct, session)`. If false, 303 to the billing page with no flash.
- 3. Within a 10-second context: `CheckoutSubscription(session)`, then `syncSubscription` when non-empty, and `MarkCheckoutCompleted`.
- 4. 303 to the billing page, with `ok` flash `checkout.done` (with the plan name) when the plan row is now paid. Otherwise no flash: the page shows `notice.settling`.
-
- A provider error is logged and still redirects. The webhook and the hourly pass finish the job.
-- Draft copy: `checkout.operator_plan` = `notice.operator_plan`; `checkout.already` "This account already has a paid plan. Change it below."; `checkout.failed` "We couldn't start the payment. Try again in a minute."; `checkout.done` "You're on %s."; `delete.renewing` "This account renews on %s. Stop renewal first, then you can delete it."
+ 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`.
- [ ] **Step 1: Write the failing tests**
```go
- func TestCheckoutStartsSession(t *testing.T) // free owner posts personal + apps 2, eur: Fake.Started[0] items [personal/eur x1, apps/eur x2], Currency eur,
- // SuccessURL ends "/billing/done?session={CHECKOUT_SESSION_ID}", ExpiresAt now+1h; 303 to the session URL; customer bound
- func TestCheckoutTeamSeats(t *testing.T) // 4 members, community: plan item quantity 10; 13 members: 13
- func TestCheckoutExpiresTheOpenSession(t *testing.T) // two posts: Fake.Expired == [first session]; one intent row naming the second
- func TestCheckoutRefusesOperatorRows(t *testing.T) // sponsored row; operator row; live subscription; open problem; not ready: no Fake call, flash per case
- func TestCheckoutCurrencyRules(t *testing.T) // "jpy": refused, no call; "USD": refused; account with currency gbp fixed posting eur: refused
- func TestCheckoutHouse(t *testing.T) // BillingHouse on: Started[0].House true
- func TestCheckoutDoneSyncs(t *testing.T) // done?session=cs_1, Fake cs_1 -> active sub: plan personal, flash checkout.done; wrong session: redirect, nothing synced
- func TestCheckoutDoneSettling(t *testing.T) // cs_1 -> incomplete sub: billing page shows notice.settling
- func TestDeleteRefusedWhileRenewing(t *testing.T) // active: refused with delete.renewing; cancel_at_period_end: proceeds to the step-up
+ 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 TestCheckoutDoneSyncs(t *testing.T)
+ func TestCheckoutDoneSettling(t *testing.T)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|DeleteRefusedWhileRenewing'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|IntentPass'`. 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 for Personal and team plans with packs, one open session per account, the return syncs at once; no deleting a renewing account (plans 6b)`.
+- [ ] **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)`.
-### Task 9: Pack changes, plan upgrades and renewal
+### Task 10: Pack changes, plan upgrades and renewal
**Files:**
-- Create: `internal/console/billingchange.go`.
+- 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 (a pack raise yields one `Fake.Changes`; stop yields one `Fake.Renewals`).
-- Test: `internal/console/billingchange_test.go`.
+ - claim files: both as `claimNonApp`, with Fake probes.
**Interfaces:**
-- Consumes: Task 4 (`ChangeItems`, `SetRenewal`, `FindItem`), Task 6 (`PaidPacks`, `PaidSeats`, `Book`), 6a `syncSubscription`, `requireFreshAuth`, `ConfirmView`.
+- Consumes: Task 7 (`holdBilling`, `freshenLocked`, `beginOpLocked`, `runOpLocked`, `quantitySteps`, `syncSubscriptionLocked`), `requireFreshAuth`, `ConfirmView`.
- Produces:
```go
- type quantityStep struct { To int64; Proration billing.Proration }
- func quantitySteps(current, target, paidHighest int64) []quantityStep
- func prorateEstimate(annualMinor, qty int64, now, periodEnd time.Time) int64 // ceil(annual*qty*remaining/365d), never above annual*qty, 0 when periodEnd passed
- type changeOutcome int
- const (changeNone changeOutcome = iota; changeApplied; changePendingPayment)
- func (s *Server) changeItem(ctx context.Context, acct *Account, sub *billing.Subscription, ref billing.PriceRef, target, paidHighest int64, now time.Time) (changeOutcome, error) // caller holds the billing lock
+ 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)
```
-- `quantitySteps` (6a Calls 6 and 8):
- - `target < current`: one `{target, none}`, where `target == 0` deletes the item;
- - `target > current`: `{min(target, paidHighest), none}` if that exceeds `current`, then `{target, now}` if `target > paidHighest`;
- - equal: none.
-- `changeItem`:
- - runs the steps in order through `ChangeItems`, with `ProrationDate: now`, a new key per step, and an `ItemChange` with no `ItemID` when the item is new;
- - stops at the first `PendingUpdate` or `ErrPaymentFailed` (`changePendingPayment`);
- - then calls `syncSubscription(sub.ID)`.
-- The change form has `kind` (`pack` or `plan`), `name`, `quantity` (packs, absolute) and `confirmed`. The handler:
- 1. Owner gate, CSRF, billing lock.
- 2. Requires state paid, not `CancelAtPeriodEnd`, no open problem, and a billing-owned row.
- 3. Re-reads with `Provider.Subscription(prev.Subscription)` and `Recognise`s it.
- 4. **pack:** target ≤ `MaxQuantity`, offered by the plan; `paidHighest = prev.PaidPacks[name]`.
- 5. **plan (Call 4):** the target is a paid plan whose lowest total `price × max(1, MinMembers)` in `cfg.Book` exceeds the current plan's, offering every pack held. One `ItemChange` swaps the plan item's price, at quantity `Team.Billed(MemberCount)` or 1, with `ProrateNow`.
- 6. When any step charges and `confirmed != "1"`: render `confirm_action`, with `prorateEstimate` lines when `prev.Book == cfg.Book.Version`, otherwise `change.no_estimate`.
- 7. When confirmed and charging: `requireFreshAuth` (Call 6).
- 8. Flash by outcome: `change.done`, `change.pending`, `change.none` ("already set"), or `change.failed` on an error.
-- Renewal: `action` is `stop` or `resume`. Owner, CSRF, lock, a re-read, then `SetRenewal`, then sync. Flash `renewal.stopped` (with the date) or `renewal.resumed`.
-- Draft copy: `confirm.title` "Pay for this change?"; `confirm.line` "You'll pay about %s now for the rest of the year, plus any tax."; `change.no_estimate` "Stripe charges the difference for the rest of the year."; `confirm.button` "Pay now"; `change.done` "Done. Your new limits apply now."; `change.pending` "Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish."; `change.none` "That's already your plan."; `change.failed` "We couldn't make that change. Try again in a minute."; `change.book` "This change isn't available on your current prices. It can be made at renewal by an operator."; `renewal.stopped` "Renewal stopped. Your plan ends on %s."; `renewal.resumed` "Renewal is back on."
+- 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."
- [ ] **Step 1: Write the failing tests**
```go
- func TestQuantitySteps(t *testing.T) // (1,3,1) [{3,now}]; (1,3,3) [{3,none}]; (1,4,3) [{3,none},{4,now}]; (3,1,3) [{1,none}]; (1,0,1) [{0,none}]; (2,2,5) []
- func TestProrateEstimate(t *testing.T) // 1200 x1, half a year left: 600; 4800 x2, 1 day left: 27 (ceil); period passed: 0; never above 1200
- func TestPackRaiseCharges(t *testing.T) // apps 1 -> 2: confirm page with FormatMinor estimate; confirmed with fresh auth: Fake.Changes[0] ProrateNow quantity 2; plan packs {apps:2}
- func TestPackReduceAndBuyBack(t *testing.T) // apps 3 -> 1: ProrateNone, limits keep 3; 1 -> 3: ProrateNone, no confirm page
- func TestNewPackAddsItem(t *testing.T) // email 0 -> 1: ItemChange ItemID "", the email price of the subscription's book
- func TestChangeTwiceChargesOnce(t *testing.T) // two confirmed posts apps -> 2: one Fake.Changes, second flash change.none
- func TestChangeComputesFromTheFreshRead(t *testing.T) // stored apps 1, Fake sub already apps 2 (another tab), post target 2: no change call
- func TestChangePendingPayment(t *testing.T) // FailPayment: flash change.pending, plan packs unchanged, page notice.pending_payment
- func TestPlanUpgrade(t *testing.T) // personal -> business, 3 members: swap to business x 10, ProrateNow; business -> personal: refused, no call
- func TestUpgradeRefusedWhenPackNotOffered(t *testing.T) // target plan without a held pack: refused
- func TestChangeUsesTheSubscriptionsBook(t *testing.T) // sub under example-v0 with v0 prices mapped: the apps price id is v0's; a v0 book without email: change.book
- func TestRenewalStopAndResume(t *testing.T) // stop: Fake.Renewals, CancelAtPeriodEnd true, notice.ending; resume: false
+ 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 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)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'QuantitySteps|ProrateEstimate|Pack|NewPack|ChangeTwice|ChangeComputes|ChangePending|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal'`. Expected: FAIL.
+- [ ] **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 charged on the way up and held until renewal on the way down, upgrades between paid plans, stop and resume renewal (plans 6b)`.
+- [ ] **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)`.
-### Task 10: Seats follow members
+### Task 11: Seats: authorised invites, serialised admission, reconciliation
**Files:**
-- Create: `internal/console/billingseats.go`.
+- Create: `internal/console/billingseats.go`, `internal/console/billingseats_test.go`.
- Modify:
- - `internal/console/server.go`: `handleInvite` (the cost confirm step) and `handleAcceptInvite` (charge, then join, under the billing lock);
- - `internal/console/planmembers.go` (Task 3): `membersChanged` calls `reconcileSeats` for a billing team row;
- - `internal/console/billingpass.go`: after each `syncSubscription` in `billingSyncPass`, `reconcileSeats` when the stored `Seats` differs from `Team.Billed(MemberCount)`;
- - `internal/console/billingstore.go`: `problemSeatsUnpaid = "seats_unpaid"`.
-- Test: `internal/console/billingseats_test.go`.
+ - `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`.
**Interfaces:**
-- Consumes: Task 9 (`changeItem`, `quantitySteps`, `prorateEstimate`), Task 3 (`MemberCount`, `checkMemberCap`), Task 6 (`Seats`, `PaidSeats`).
+- Consumes: Tasks 3, 6 and 7.
- Produces:
```go
- func (s *Server) seatCharged(acct *Account, adding int) (bool, *billingAccount, error) // a billing team row, paid, where Billed(members+adding) > max(Seats, PaidSeats)
- func (s *Server) raiseSeatForJoin(ctx context.Context, acct *Account, now time.Time) (bool, error) // caller holds the billing lock; true when the seat is paid (or none was needed)
- func (s *Server) reconcileSeats(ctx context.Context, acct *Account, now time.Time) error // takes the billing lock
+ type seatAuthorisation struct { Plan, Book, Currency string; PriceMinor int64; By string; At 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
+ 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
+ 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** (Call 11): when `seatCharged(acct, pending+1)` and `confirmed != "1"`, render `confirm_action` with `seats.invite_line` and the estimate (the `to` address carried as a field). Confirmed, carry on as today.
-- **Accept:**
- 1. Find the account through `PendingInviteFor`.
- 2. If `seatCharged(acct, 1)`: take the billing lock, then `raiseSeatForJoin`. That is a fresh read, then `changeItem` on the plan item to `Billed(members+1)` with `paidHighest = PaidSeats`.
- 3. If not paid: `renderMessage(409, billingCopy["seats.join_wait_title"], billingCopy["seats.join_wait"])`. `AcceptInvite` is not called.
- 4. If paid: `AcceptInvite`, then `membersChanged`, still under the lock, so two accepts can't share one seat.
-- **reconcileSeats:**
- - billing team row, paid, billing-owned only;
- - fresh read; `want = Billed(MemberCount)`; `cur` = the plan item's quantity;
- - `want < cur`: `changeItem(..., want, ...)` with `ProrateNone` (Call 12);
- - `want > cur` and `want ≤ PaidSeats`: raise with `ProrateNone`;
- - `want > PaidSeats`: open `seats_unpaid` ("the account has N members and pays for M"), with no charge (Call 11's operator path);
- - then sync.
-- 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."
+- **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.
+- **`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".
- [ ] **Step 1: Write the failing tests**
```go
- func TestInviteShowsSeatCost(t *testing.T) // community, 10 members, paid seats 10: invite renders the confirm with the estimate; 9 members: no confirm
- func TestJoinChargesASeat(t *testing.T) // 10 members, seats 10: accept -> Fake.Changes ProrateNow quantity 11; member added; plan Seats 11
- func TestJoinWaitsForPayment(t *testing.T) // FailPayment: 409 seats.join_wait, invite still pending, MemberCount 10, Seats 10, page notice.pending_payment
- func TestJoinBelowMinimumIsFree(t *testing.T) // 4 members on community (billed 10): accept, no change call
- func TestLeaveReducesAtRenewal(t *testing.T) // 12 members seats 12, remove one: ProrateNone quantity 11, limits keep 12 seats until the period moves
- func TestRejoinWithinPeriodIsFree(t *testing.T) // after the leave above, accept a new member: ProrateNone quantity 12, no confirm, no charge
- func TestPassOpensSeatsUnpaid(t *testing.T) // operator adds 3 members via AddMember beyond paid seats; billingSyncPass: problem seats_unpaid, no change call
- func TestPassReconcilesOnlyOnDrift(t *testing.T) // seats equal to Billed(members): no extra Fake call beyond the sync's reads
+ 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)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteShowsSeat|Join|Leave|Rejoin|PassOpensSeats|PassReconciles'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteRecords|Join|ConcurrentJoins|RevokedInvite|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 follow members; a join is charged before it happens, a leave comes off at renewal (plans 6b)`.
+- [ ] **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)`.
-### Task 11: The locked portal
+### Task 12: The locked portal
**Files:**
-- Create: `internal/console/billingportal.go`.
-- Modify:
- - `internal/console/server.go`: `POST /a/{sqid}/billing/portal`;
- - claim files: as `claimNonApp` ("opens a provider portal session; writes nothing locally"), with a Fake probe.
-- Test: `internal/console/billingportal_test.go`.
+- 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:**
-- Consumes: Task 4 (`PortalURL`), `requireFreshAuth`.
- Produces: `func (s *Server) handleBillingPortal(w http.ResponseWriter, r *http.Request)`.
- The handler:
1. Owner, CSRF, ready.
- 2. A bound customer, else `portal.none`.
- 3. `requireFreshAuth` (Call 6).
+ 2. A bound customer.
+ 3. `requireFreshAuth`.
4. `PortalURL(customer, s.cfg.Origin+"/a/"+sqid+"/billing", "portal:"+customer+":"+nonce)`, then 303.
- 5. An error flashes `portal.failed`.
- The billing page labels the button `portal.button` "Payment and invoices".
+ It doesn't take the hold, because it changes nothing billing owns.
- [ ] **Step 1: Write the failing tests**
```go
- func TestPortalOpens(t *testing.T) // owner with customer and fresh auth: 303 to the Fake URL; return URL is origin + /a/bab/billing
- func TestPortalGates(t *testing.T) // member: 404; no customer: flash portal.none; stale auth: step-up redirect, no Fake call; billing nil: 404
+ 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
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Portal'`. Expected: FAIL.
-- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** again. Expected: PASS.
-- [ ] **Step 5: Commit** `console: owners reach the locked portal for cards and invoices (plans 6b)`.
+- [ ] **Steps 2-5:** run (FAIL), implement, run (PASS), commit `console: owners reach the locked portal for cards and invoices (plans 6b)`.
-### Task 12: The house flag
+### 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`).
+
+**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
+ ```
+- `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."
+
+- [ ] **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
+ ```
+- [ ] **Steps 2-5:** run (FAIL), implement, run (PASS), commit `console: a durable retirement gate checks the provider before an account is deleted (plans 6b)`.
+
+### Task 14: The house flag
**Files:**
- Create: `internal/console/apibillinghouse.go`.
- Modify:
- - `internal/console/apibilling_copy.go` and `billing_cli.go`, `billing_cli_copy.go` (repo root): `carlos billing house`;
- - `internal/console/authcli.go`: `s.cliRoute("POST /api/cli/billing/house", svcrole.Set{}, s.handleAPIBillingHouse)`;
- - the empty-role allowlist and the closed-door count (`TestEveryCLIDoorNamesItsRoles`, `TestEveryClosedDoorRefusesAServiceCredential`), as 6a did;
- - claim files: `claimNonApp`, with a probe.
+ - `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`.
**Interfaces:**
-- Consumes: Task 6 (`SetBillingHouse`), 6a's `billingDoor` gate (signed in, operator, billing configured).
-- Produces:
- - `func (s *Server) handleAPIBillingHouse(w http.ResponseWriter, r *http.Request)`, with body `{"account":"<sqid>","on":true,"note":"..."}`. An empty note is 400; an unknown account is 404. It writes an audit line.
- - CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode only. Draft strings: `cli.house_on` "account %s is now the house: its checkout is free", `cli.house_off` "account %s pays like everyone else", `door.note_required` reused from 6a.
+- 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) // member 404; operator on: BillingHouse true, audit line; off: false; empty note 400; billing off 409
- func TestBillingCLIHouse(t *testing.T) // httptest console: -on sends on true; neither -on nor -off: usage error
+ func TestBillingHouseDoor(t *testing.T)
+ func TestBillingCLIHouse(t *testing.T)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingHouseDoor|EveryCLIDoor|EveryClosedDoor'` and `go test . -run BillingCLI`. Expected: FAIL.
-- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** again. Expected: PASS.
-- [ ] **Step 5: Commit** `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`.
-
-### Task 13: Copy, docs, census and gates
-
-- [ ] **Luna copy pass.**
- - Commit `docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-6B.md`, following `LUNA-COPY-BRIEF-PLANS-6A.md`'s shape. It carries:
- - the house rules: no em dashes (a full stop and a new sentence), plain words, `cli.`/`door.` keys lower case with no final full stop, placeholders kept in order, no product name, Stripe may be named;
- - the facts that must stay true: nothing is charged without the owner pressing the button; 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;
- - every string in `billingCopy`, the new `plancaps_copy.go` strings and the CLI strings, each with an example rendering.
- - Run Luna (gpt-5.6-luna via codex, the form in memory `codex-second-reader`). Commit `LUNA-COPY-RESULT-PLANS-6B.md` unedited, then apply it verbatim. Show Paul only the strings Luna flags.
-- [ ] **Docs.**
- - Extend `docs/site/plans.md` "Billing (operators)": the two new variables; the house flag; what owners see; how seats work; what `seats_unpaid` means.
- - Add an owner-facing "Plans and billing" section: buying, packs, members and seats, stopping renewal, the portal.
- - Write in plain prose (humane-docs). Add `carlos billing house` to the CLI reference.
-- [ ] **Census.**
- - Run `make census-card`, then `make census-propose NAME=plans-6b-checkout-flow CLAIMS=<file>` for body and sites changes.
- - Hand-write decision rows (`census-ruling-plans-6b-units`) for the new units:
- - the eight routes;
- - the two tables;
- - new store methods that read or write;
- - `planMembers` and `membersChanged`;
- - the adapter methods, if the envelope reaches `internal/billingstripe`.
- - Add a record-write layer only if `TestPlan9B8RecordWriteCensus` names a site. Publishing still goes through `publishAccountLimits`, via `publishPlanNow` and `applyAccountPlan`.
- - Astra approves the card, recorded on #280. Decisions go to Paul.
-- [ ] **Gates.**
+- [ ] **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)`.
+
+### 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 must be on it; see "Base branch and order"), push, wait for green CI, then Astra's whole-branch review.
+- [ ] **Finish:** merge main (6a on it), 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: the new routes 404, there is no nav link, and invites behave as before (unless the catalog sets `max_members`).
-- Census approved by Astra; CI green after merging main; Astra's whole-branch review has no open Critical or Important finding.
-- The pricing page owner (Plan 7 / the website) has the schema-3 document and the `/upgrade` contract.
+- 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.
+- The website has the schema-3 document and the `/upgrade` contract.
+
+## Revision 2 fixes (Astra plan review at `b6005e86`)
+
+| Finding | Where the plan now handles it |
+| --- | --- |
+| 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) |
---
## 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 only after spec §12 steps 1 to 4.
+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.
-1. **Products:** Personal, Community, Business, and one per pack (`apps`, `disk`, `storage`, `email`, `bandwidth`): 8 products. Tax code to confirm with the accountant (the old branch used `txcd_10102001`).
-2. **Prices:** 24 in all. Each is yearly, licensed, per unit, tax exclusive and in a single currency, with `metadata[price_key]` set to its key (`<book>/<plan>/<cur>` or `<book>/pack/<name>/<cur>`). In minor units, usd / eur / gbp:
+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:
| Item | usd | eur | gbp |
| --- | --- | --- | --- |
@@ -921,40 +1243,40 @@ A runbook at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`, follo
| pack email | 2400 | 2100 | 1900 |
| pack bandwidth | 4800 | 4100 | 3800 |
- The book holding them becomes a new `approved` version before live.
+ 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 `bpc_` id goes to `CARLOS_STRIPE_PORTAL_CONFIGURATION`.
-4. **The house coupon:** 100% off, `forever`, no product restriction and no promotion code. Its id goes to `CARLOS_STRIPE_HOUSE_COUPON`.
-5. **The webhook endpoint:**
- - `https://<console>/billing/webhook`;
- - events `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed`;
- - API version `2025-02-24.acacia`;
- - the signing secret goes to `CARLOS_STRIPE_WEBHOOK_SECRET`.
-6. **Retry settings:** after all retries fail, cancel the subscription (6a Call 12). Pending updates expire on Stripe's default (about 23 hours).
-7. **The restricted `rk_` key:**
- - granted: Checkout Sessions write, Customers write, Subscriptions write (which includes subscription items), Customer portal write, Billing portal configurations read, Prices read, Products read, Coupons read;
+ 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.
-
- Paul creates it in the Dashboard, and it goes straight into the console's EnvironmentFile.
-8. **Console variables** (EnvironmentFile only): `CARLOS_BILLING`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES`, `CARLOS_STRIPE_SECRET_KEY`, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_WEBHOOK_SECRET`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, and optionally `CARLOS_STRIPE_HOUSE_COUPON`. The catalog and book files come from the deployment's infrastructure repo.
+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` from a static page while signed out, through sign-up, to Checkout;
- - Checkout for Personal with packs, for Community at 4 members (billed 10) and at 12;
- - a pack added with a declining card (`pending_if_incomplete`: nothing granted, the notice shows), then paid from the portal's invoice;
- - a pack reduced and held until renewal, then bought back without a charge;
- - a member joining with a good card and with a declining one (Call 11);
- - a member leaving and rejoining within the period;
- - Personal → Business, confirming `pending_if_incomplete` accepts a price swap;
- - renewal stopped and resumed;
- - a failed renewal (past due keeps paid), then cancellation, dropping to free with 4d acting;
- - an out-of-order event;
- - whether Checkout ever leaves an `incomplete_expired` subscription;
+ - `/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;
- - the readiness check refusing a wrong price, an unlocked portal and a 50% coupon;
- - a house account checking out at zero;
- - confirming the API version and the customer-currency lock (Call 3).
-10. **Flagship:** the same in live mode on Paul's approval. Then publish the pricing page's buttons to `https://<console>/upgrade?plan=<plan>&currency=<cur>`. IE and OSS tax registrations already exist.
+ - 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>&currency=<cur>`.