plans 6b: checkout flow, team plans and the billing page (plan, with the 6c runbook outline)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+958
−0
docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md+958 −0
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| new file mode 100644 |
| index 000000000..0b033e5d4 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md |
| @@ -0,0 +1,958 @@ |
| +# Plans 6b: Checkout Flow, Team Plans and the Billing Page Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** 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. |
| + |
| +**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. |
| + |
| +**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). |
| + |
| +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: |
| + - 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. |
| + - 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). |
| + |
| +## Base branch and order |
| + |
| +- 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. |
| + |
| +## Calls for Paul |
| + |
| +Each has a recommendation. Calls 7 to 14 come from the team-plan ruling. |
| + |
| +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**: |
| + - 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); |
| + - Stripe Checkout collects the billing address (`billing_address_collection=required`, saved to the customer) and computes tax from it. |
| + |
| + 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.** |
| +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. |
| +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. |
| + |
| +## 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`. |
| + |
| + 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. |
| +- **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)`); |
| + - 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: |
| + |
| + | Request | Key | |
| + | --- | --- | |
| + | customer | `customer:<sqid>` | |
| + | Checkout start | `checkout:<intent id>` | |
| + | 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. |
| +- **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). |
| +- **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. |
| +- **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. |
| +- **Tests:** |
| + - TDD with no network: console tests use `billingtest.Fake`, 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. |
| + |
| +## 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`). |
| + |
| +--- |
| + |
| +### Task 0: Record the rulings |
| + |
| +**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; |
| + - §9.1: the team plan is the plan item, with quantity `max(members, 10)`. |
| + |
| +- [ ] **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)`. |
| + |
| +### Task 1: Team plans and member caps in the catalog |
| + |
| +**Files:** |
| +- Create: `internal/plans/team.go`, `internal/plans/team_test.go`. |
| +- Modify: |
| + - `internal/plans/catalog.go`: `Plan.Team`, `Plan.MaxMembers`, validation, and `Effective`'s new parameter; |
| + - `internal/plans/testdata/example-catalog.json`: add `community` and `business`, and `max_members: 3` on `free` and `personal`; |
| + - `internal/plans/testdata/example-pricebook.json`: `community` 600 / 500 / 450, `business` 6000 / 5000 / 4500; |
| + - every `Effective` caller, so it compiles: `internal/console/planlimits.go`, `apiaccountplan.go` and `planlapse.go` (main) each pass `1` for now; Task 3 passes the real count. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + type Team struct { |
| + Base string `json:"base"` // a paid, non-team plan whose pooled limits multiply |
| + PerMemberMilli int `json:"per_member_milli"` // the multiple per member in thousandths: 200 = 0.2, 2000 = 2 |
| + MinMembers int `json:"min_members"` // billed and limited at no fewer |
| + } |
| + // Plan gains: |
| + Team *Team `json:"team,omitempty"` |
| + 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 |
| + 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) |
| + ``` |
| +- 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 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`). |
| + 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. |
| + 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): |
| + - `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. |
| + |
| +- [ ] **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 |
| + 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 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 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)`. |
| + |
| +### 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). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + // publicExport.Schema = 3. publicPlan gains: |
| + Team *publicTeam `json:"team,omitempty"` |
| + MaxMembers int `json:"max_members,omitempty"` |
| + type publicTeam struct { |
| + Base string `json:"base"` |
| + PerMember string `json:"per_member"` // Team.PerMember() |
| + MinMembers int `json:"min_members"` |
| + Pooled []string `json:"pooled"` // PooledLimits, in that order |
| + } |
| + func FormatMinor(currency string, minor int64) string // "$28", "€24", "£4.50", "$0.07"; whole units without decimals |
| + ``` |
| +- 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. |
| + |
| +- [ ] **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 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 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 |
| + |
| +**Files:** |
| +- Create: `internal/console/planmembers.go` (`planMembers`, `membersChanged`, `checkMemberCap`'s count). |
| +- 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/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`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1 (`Effective(..., members)`, `Plan.Team`, `Plan.MaxMembers`). |
| +- Produces: |
| + ```go |
| + // AccountPlanRow gains Seats int: the paid seat count billing wrote; 0 = count members now. |
| + func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, seats int, source string, |
| + sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) |
| + func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, seats int, |
| + source string, sponsored *plans.Limits, reason, by string, now time.Time) error |
| + func (s *Store) MemberCount(accountID int64) (int, error) // owners + members; never invites or services |
| + func (s *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 |
| + ``` |
| +- `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. |
| + |
| +- [ ] **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 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)`. |
| + |
| +### Task 4: Provider boundary for purchases and changes |
| + |
| +**Files:** |
| +- Modify: |
| + - `internal/billing/billing.go`: `Item.ItemID`, `Subscription.PendingUpdate`, the new 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`). |
| +- 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. |
| + type Proration string |
| + const (ProrateNone Proration = "none"; ProrateNow Proration = "now") // now: charged at once, applied only once paid |
| + 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 |
| + IdempotencyKey string |
| + } |
| + 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 |
| + ExpiresAt time.Time |
| + IdempotencyKey string |
| + } |
| + type CheckoutSession struct { ID, URL string } |
| + var ErrPaymentFailed = errors.New("billing: payment failed") |
| + // 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 |
| + 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 |
| + ``` |
| +- `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>`. |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **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 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)`. |
| + |
| +### 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. |
| +- Test: `internal/billingstripe/adapter_test.go`, `client_test.go`, `customer_test.go`; `cmd/console/billing_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 4. |
| +- Produces: |
| + ```go |
| + type SubscriptionItemUpdate struct { ID, PriceID string; Quantity int64; Deleted bool } |
| + type SubscriptionUpdate struct { |
| + Items []SubscriptionItemUpdate |
| + Proration string // ProrationNone | ProrationAlwaysInvoice; "" sends none of it |
| + ProrationDate time.Time |
| + PendingIfIncomplete bool // payment_behavior=pending_if_incomplete |
| + CancelAtPeriodEnd *bool |
| + } |
| + func (c *Client) UpdateSubscription(ctx context.Context, id string, p SubscriptionUpdate, idempotencyKey string) (*Subscription, error) // POST /v1/subscriptions/{id} |
| + ``` |
| +- 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` | |
| + | `PortalURL` | `CreatePortal` with the configured configuration | |
| + |
| + 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) |
| + ```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 |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ -run 'ChangeItems|StartCheckout|EnsureCustomer|ExpireCheckout|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)`. |
| + |
| +### Task 6: Billing state for seats, intents and the house flag |
| + |
| +**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. |
| +- 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`). |
| +- 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). |
| + type checkoutIntent struct { |
| + AccountID int64 |
| + ID, Session, Plan, Currency string |
| + Seats int |
| + Packs map[string]int |
| + CreatedAt, ExpiresAt, ReturnedAt, CompletedAt 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) 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 |
| + ``` |
| +- 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`. |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideTeam|DecideUpgrade|DecidePending|SyncWritesSeats|CheckoutIntent|BillingHouse|BillingRenewing|WebhookCheckout'`. 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)`. |
| + |
| +### Task 7: The billing page and the upgrade entry |
| + |
| +**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`. |
| +- 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`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 6 (store), Task 2 (`FormatMinor`), Task 1 (`Team.Billed`), `s.cfg.GeoIPReader`, `s.clientIP`. |
| +- Produces: |
| + ```go |
| + type billingPageInput struct { |
| + Row *AccountPlanRow // nil: the default plan |
| + Billing *billingAccount // nil: never bought |
| + Intent *checkoutIntent |
| + Problems int // open billing problems for this account |
| + 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 |
| + } |
| + func decideBillingPage(in billingPageInput) billingPageState |
| + func (s *Server) requestCountry(r *http.Request) string // ISO alpha-2 from GeoIP, "" when none |
| + 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. |
| + ``` |
| +- `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. |
| + |
| + | 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` | |
| + | `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` | |
| + | 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>¤cy=<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. |
| + - 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): |
| + |
| + | key | draft | |
| + | --- | --- | |
| + | `page.title` | Billing | |
| + | `notice.not_ready` | Billing isn't available right now. Try again in a few minutes. | |
| + | `notice.problem` | We're checking this purchase. Your plan hasn't changed yet, and nothing more will be charged. | |
| + | `notice.operator_plan` | An operator set this account's plan, so there's nothing to buy here. | |
| + | `notice.settling` | We're confirming your payment. This page shows your new plan once it's done. | |
| + | `notice.pending_payment` | A change is waiting for payment. Pay it from Payment and invoices, or it's dropped after a day. | |
| + | `notice.past_due` | Your last payment didn't go through. Update your card in Payment and invoices. Your plan stays while we retry. | |
| + | `notice.ending` | Your plan ends on %s. After that the account moves to the free plan. | |
| + | `notice.owners_only` | Only an owner of this account can change its plan. | |
| + | `currency.refused` | We don't sell in %q. Choose usd, eur or gbp. | |
| + | `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 | |
| + | `renews` | Renews on %s | |
| + | `upgrade.not_owner_title` / `upgrade.not_owner` | Only owners can upgrade / Only an owner of an account can upgrade it. Create an account of your own to choose a plan. | |
| + | `pick.title` | Which account? | |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestDecideBillingPage(t *testing.T) // one case per table row, 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¤cy=eur: 303 to /?next=%2Fupgrade%3Fcurrency%3Deur%26plan%3Dpersonal; |
| + // ?plan=../x¤cy=<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 |
| + ``` |
| +- [ ] **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)`. |
| + |
| +### Task 8: Starting Checkout and coming back |
| + |
| +**Files:** |
| +- Create: `internal/console/billingcheckout.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`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 4 (`EnsureCustomer`, `StartCheckout`, `ExpireCheckout`, `CheckoutSubscription`), Task 6 (intents, house, `SetBillingCustomer`), 6a (`syncSubscription`). |
| +- Produces: |
| + ```go |
| + const checkoutLifetime = time.Hour |
| + func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) |
| + func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) |
| + ``` |
| +- 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. |
| +- 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." |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|DeleteRefusedWhileRenewing'`. 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)`. |
| + |
| +### Task 9: Pack changes, plan upgrades and renewal |
| + |
| +**Files:** |
| +- Create: `internal/console/billingchange.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`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 4 (`ChangeItems`, `SetRenewal`, `FindItem`), Task 6 (`PaidPacks`, `PaidSeats`, `Book`), 6a `syncSubscription`, `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 (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." |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'QuantitySteps|ProrateEstimate|Pack|NewPack|ChangeTwice|ChangeComputes|ChangePending|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal'`. 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)`. |
| + |
| +### Task 10: Seats follow members |
| + |
| +**Files:** |
| +- Create: `internal/console/billingseats.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`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 9 (`changeItem`, `quantitySteps`, `prorateEstimate`), Task 3 (`MemberCount`, `checkMemberCap`), Task 6 (`Seats`, `PaidSeats`). |
| +- 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 |
| + ``` |
| +- **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." |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteShowsSeat|Join|Leave|Rejoin|PassOpensSeats|PassReconciles'`. 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)`. |
| + |
| +### Task 11: 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`. |
| + |
| +**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). |
| + 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". |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **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)`. |
| + |
| +### Task 12: 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. |
| +- 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. |
| + |
| +- [ ] **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 |
| + ``` |
| +- [ ] **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.** |
| + - `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. |
| + |
| +## 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. |
| + |
| +--- |
| + |
| +## 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. |
| + |
| +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: |
| + |
| + | Item | usd | eur | gbp | |
| + | --- | --- | --- | --- | |
| + | personal | 2800 | 2400 | 2200 | |
| + | community (per member) | 600 | 500 | 450 | |
| + | business (per member) | 6000 | 5000 | 4500 | |
| + | pack apps | 1200 | 1000 | 900 | |
| + | pack disk | 3600 | 3100 | 2800 | |
| + | pack storage | 1200 | 1000 | 900 | |
| + | pack email | 2400 | 2100 | 1900 | |
| + | pack bandwidth | 4800 | 4100 | 3800 | |
| + |
| + The book holding them 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; |
| + - 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. |
| +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; |
| + - 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>¤cy=<cur>`. IE and OSS tax registrations already exist. |