carlos / platform Public

plans 6c: Stripe setup script, price book and runbook

scripts/stripe-setup.sh makes the products, the 24 yearly prices, the
locked portal configuration, the house coupon and the webhook endpoint
console billing reads at start, in a sandbox or test mode only. Dry run
by default, --check reads only, --apply creates what is missing. It
finds objects by metadata and lookup_key, applies the readiness check's
rules to anything it finds, never deletes or edits, and has no live
path.

deploy/billing/pricebook-2026-10-27-v1.json is the draft book the
prices come from, against catalog 2026-10-20-v1.

The runbook lists every requirement the code checks, with file and
line, the sandbox run, the Dashboard steps, the dev rehearsal, and the
live step on Paul's approval, with existing accounts sponsored first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev ad09564e2551d68d4c3f5bb1e6f5b6ce67316dad parent 2d224b1
3 files changed, +930 −0
  • deploy/billing/pricebook-2026-10-27-v1.json +23 −0
  • docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md +332 −0
  • scripts/stripe-setup.sh +575 −0

CI failed — run details

diff --git a/deploy/billing/pricebook-2026-10-27-v1.json b/deploy/billing/pricebook-2026-10-27-v1.json
new file mode 100644
index 000000000..6df59b7d4
--- /dev/null
+++ b/deploy/billing/pricebook-2026-10-27-v1.json
@@ -0,0 +1,23 @@
+{
+ "version": "2026-10-27-v1",
+ "status": "draft",
+ "catalog_version": "2026-10-20-v1",
+ "default_currency": "usd",
+ "currencies": ["usd", "eur", "gbp"],
+ "country_currency": {
+ "eur": ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE"],
+ "gbp": ["GB"]
+ },
+ "plans": {
+ "personal": {"usd": 2800, "eur": 2400, "gbp": 2200},
+ "community": {"usd": 600, "eur": 500, "gbp": 450},
+ "business": {"usd": 6000, "eur": 5000, "gbp": 4500}
+ },
+ "packs": {
+ "apps": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "disk": {"usd": 3600, "eur": 3100, "gbp": 2800},
+ "storage": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "email": {"usd": 2400, "eur": 2100, "gbp": 1900},
+ "bandwidth": {"usd": 4800, "eur": 4100, "gbp": 3800}
+ }
+}
diff --git a/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
new file mode 100644
index 000000000..dfac96db8
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
@@ -0,0 +1,332 @@
+# Plans 6c: Stripe setup runbook
+
+This runbook sets up the Stripe objects that console billing (Plans 6a and 6b, merged to main) reads when it starts. It runs in the Carloku Sandbox first (`acct_1UVFkoIiAD0xflDQ`) against the dev console. Live setup is a later step, and only Paul can approve it.
+
+It replaces the outline at the end of `2026-10-25-plans-6b-checkout-flow.md` ("Plan 6c: Stripe setup runbook (outline)"). Where the outline and the code differ, the code wins, and the differences are listed below.
+
+Three files come with it:
+
+- `scripts/stripe-setup.sh` makes the objects with the stripe CLI. It runs in a sandbox or test mode only.
+- `deploy/billing/pricebook-2026-10-27-v1.json` is the price book the prices are made from. It is a `draft`.
+- This runbook.
+
+Nobody has run any of it against Stripe yet.
+
+## 1. What the console needs
+
+| Object | Count | Where its id goes |
+| --- | --- | --- |
+| Products: personal, community, business and the packs apps, disk, storage, email, bandwidth | 8 | nowhere; each price names its product |
+| Prices: one per product and currency (usd, eur, gbp) | 24 | `CARLOS_BILLING_PRICES` |
+| The locked customer portal configuration | 1 | `CARLOS_STRIPE_PORTAL_CONFIGURATION` |
+| The house coupon | 1 | `CARLOS_STRIPE_HOUSE_COUPON` |
+| The webhook endpoint at `https://<console>/billing/webhook` | 1 | its signing secret goes to `CARLOS_STRIPE_WEBHOOK_SECRET` |
+| A restricted `rk_test_` key, made by Paul in the Dashboard | 1 | `CARLOS_STRIPE_SECRET_KEY` |
+
+The amounts, in minor units a year:
+
+| Item | usd | eur | gbp |
+| --- | --- | --- | --- |
+| personal | 2800 | 2400 | 2200 |
+| community, per member | 600 | 500 | 450 |
+| business, per member | 6000 | 5000 | 4500 |
+| pack apps | 1200 | 1000 | 900 |
+| pack disk | 3600 | 3100 | 2800 |
+| pack storage | 1200 | 1000 | 900 |
+| pack email | 2400 | 2100 | 1900 |
+| pack bandwidth | 4800 | 4100 | 3800 |
+
+Community and Business are team plans: a price per member, with a minimum of 10 members (`internal/plans/testdata/example-catalog.json:56` and `:72`). In Stripe they are ordinary per-unit prices. The console sets the quantity.
+
+## 2. Exact requirements from the code
+
+These are what the console checks when it starts. The setup script applies the same rules to anything it finds or makes, and stops if an object breaks one.
+
+### The console's variables (`cmd/console/billing.go`)
+
+The console reads them in this order and stops at the first bad one, naming the variable and never its value.
+
+- `CARLOS_BILLING` is `off`, `test` or `live`. Unset is off (`billing.go:25-31`).
+- `CARLOS_PLAN_CATALOG` must be set when billing is on (`billing.go:33-35`, `cmd/console/main.go:1953`). It is a file path.
+- `CARLOS_STRIPE_SECRET_KEY` starts `rk_test_` in test mode and `rk_live_` in live mode (`billing.go:36-43`, again in `internal/billingstripe/adapter.go:63-69`). A standard `sk_` key is refused.
+- `CARLOS_STRIPE_ACCOUNT` starts `acct_` (`billing.go:44-47`). The readiness check also requires it to be the account the key belongs to, read from `GET /v1/account` (`adapter.go:267-273`, `merchant.go:17`).
+- `CARLOS_STRIPE_WEBHOOK_SECRET` starts `whsec_` (`billing.go:48-51`). `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS` is optional: up to two older `whsec_` secrets, comma separated, for a rotation (`billing.go:53-66`).
+- `CARLOS_PRICE_BOOK` is the path to the price book file, not its content (`billing.go:67-74`). A live console refuses a draft book (`billing.go:72`).
+- `CARLOS_BILLING_PRICES` is the price map (`billing.go:75`; format below).
+- `CARLOS_STRIPE_PORTAL_CONFIGURATION` must start `bpc_` and be id-shaped (`billing.go:79-82`, `adapter.go:39-41`).
+- `CARLOS_STRIPE_HOUSE_COUPON` is optional. If set, it must match `^[A-Za-z0-9_-]{1,200}$` (`billing.go:83-86`, `internal/billingstripe/catalog.go:285`).
+
+The console records each book version's digest the first time it starts with it. If the file under that version changes later, the console refuses to start (`cmd/console/main.go:377`). To change a price, write a new book with a new version.
+
+### Price keys and the price map (`internal/billing/prices.go`)
+
+- A plan's key is `<book>/<plan>/<currency>`. A pack's key is `<book>/pack/<pack>/<currency>` (`prices.go:35-42`). With this book that gives keys like `2026-10-27-v1/personal/usd`, `2026-10-27-v1/community/eur` and `2026-10-27-v1/pack/apps/gbp`.
+- The currency must be `usd`, `eur` or `gbp`, lower case (`prices.go:59`, `internal/plans/pricebook.go:34`).
+- `CARLOS_BILLING_PRICES` is one JSON object from price key to Stripe price id, for example `{"2026-10-27-v1/personal/usd":"price_..."}` (`prices.go:77-119`). Each id must match `^price_[A-Za-z0-9]{1,250}$` (`prices.go:26`). The same key twice is refused (`prices.go:92`), and so is one id under two keys (`prices.go:104`). Every price of the configured book must be in it (`prices.go:113-117`). Keys of other book versions are allowed, so a subscription bought under an older book keeps working (`prices.go:107`). The whole value is at most 64 KiB (`prices.go:24`).
+- In a systemd EnvironmentFile the value must be inside single quotes. Without them, systemd treats the JSON's double quotes as quoting and strips them. The script prints it that way.
+
+### Each price (`internal/billingstripe/adapter.go:385-449`)
+
+For every price in the map under the configured book, the readiness check reads `GET /v1/prices/<id>` with `currency_options` expanded (`catalog.go:107`) and requires all of these:
+
+- the book prices it (`adapter.go:394`);
+- active (`:396`), and in the console's mode (`:398`);
+- in the key's currency (`:400`), at the book's amount exactly (`:402`);
+- recurring once a year: interval `year`, interval count 1 (`:404`);
+- usage type `licensed` (`:406`), billing scheme `per_unit` (`:408`), tax behaviour `exclusive` (`:410`);
+- no `transform_quantity` (`:412`);
+- no currency option except its own currency at its own amount (`:414`, `:430-449`);
+- `metadata[price_key]` equal to its key (`:416`).
+
+Each price's product must be active and in the same mode (`adapter.go:285-295`). The product's tax code is not checked.
+
+The code never reads a price's `lookup_key`. The script sets `lookup_key` to the price key anyway, so it can find a price again. The products carry `metadata[carlos_product]` (`personal`, `pack/apps` and so on) for the same reason. The code does not read that either.
+
+### The price book (`internal/plans/pricebook.go`)
+
+- Unknown fields, the same key twice and trailing content are refused (`pricebook.go:74-89`).
+- `status` is `draft` or `approved` (`:142`). `catalog_version` must equal the installed catalog's `version` (`:145`).
+- Every paid plan in the catalog is priced, and nothing else is (`:183-205`). Every pack a paid plan offers is priced, and nothing else is (`:206-218`). No paid plan may be called `pack` (`:191`).
+- Each price is above 0 and at most 100,000,000 minor units (`:41`, `:233-238`), in exactly the book's currencies (`:228-244`).
+
+`deploy/billing/pricebook-2026-10-27-v1.json` is priced against catalog `2026-10-20-v1`, the spec's catalog (`internal/plans/testdata/example-catalog.json:2`). It loads cleanly:
+
+```sh
+go run ./cmd/pricebook-export -catalog internal/plans/testdata/example-catalog.json \
+ -book deploy/billing/pricebook-2026-10-27-v1.json
+```
+
+Its `country_currency` list is the one from the example book: the 27 EU states pay in eur, GB in gbp and everyone else in usd. That list gets approved together with the amounts.
+
+Plan 6a's outline expects deployment catalogs and books to live in the deployment's own infrastructure repo, in a `plans/` directory that Plan 7 creates. Until that exists, the book lives here, and the console box keeps a copy at the path `CARLOS_PRICE_BOOK` names.
+
+### The locked portal configuration (`adapter.go:308-349`)
+
+The check reads `GET /v1/billing_portal/configurations/<id>` and requires:
+
+- active (`:325`), in the console's mode (`:327`);
+- payment method update on (`:329`) and invoice history on (`:331`);
+- subscription update off (`:333`) and cancellation off (`:335`);
+- customer update either off, or limited to `address`, `name` and `tax_id` (`:311`, `:337-343`).
+
+The code does not read pause. The outline wants it off, and it is off unless someone turns it on. The script does not send it, and refuses a configuration whose read-back shows it on. The code ignores `business_profile` and the default return URL (`portal.go:34-39`). The console passes its own return URL with each portal session (`client.go:749`).
+
+### The house coupon (`adapter.go:351-383`)
+
+The check reads `GET /v1/coupons/<id>` with `applies_to` expanded (`catalog.go:298`) and requires:
+
+- valid (`:362`), in the console's mode (`:364`);
+- 100% off (`:366`) with no amount off (`:368`);
+- duration `forever` (`:370`);
+- not limited to any products (`:372`);
+- no `max_redemptions` (`:374`) and no `redeem_by` (`:376`).
+
+The code does not check for a promotion code. A house Checkout sends the coupon directly as `discounts[0][coupon]`, and only other Checkouts allow promotion codes (`client.go:704-711`). The script makes no promotion code.
+
+### The webhook endpoint
+
+- The route is `POST /billing/webhook` (`internal/console/server.go:1935`). It answers 404 with billing off and 503 until the readiness check has passed, so Stripe tries again later (`internal/console/billingwebhook.go:16-38`).
+- The console uses six events: `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed` (`adapter.go:176-199`). Other events are ignored.
+- The API version is pinned to `2025-02-24.acacia` on every call (`client.go:34`, `:251`). The endpoint must use the same version, because the handler reads `subscription` directly off an invoice event (`adapter.go:187-198`), and later versions move that field.
+- A signature older or newer than 5 minutes is refused (`webhook.go:15`), so the console box's clock matters.
+
+### The restricted key
+
+These are the endpoints `internal/billingstripe` calls:
+
+| Endpoint | Method | Used for |
+| --- | --- | --- |
+| `/v1/account` | GET | the readiness check's account match (`merchant.go:17`) |
+| `/v1/prices/<id>` | GET | readiness and the clock probe (`catalog.go:107`, `prepared.go:461`) |
+| `/v1/products/<id>` | GET | readiness (`merchant.go:67`) |
+| `/v1/coupons/<id>` | GET | readiness (`catalog.go:298`) |
+| `/v1/billing_portal/configurations/<id>` | GET | readiness (`portal.go:123`) |
+| `/v1/billing_portal/sessions` | POST | Payment and invoices (`client.go:764`) |
+| `/v1/customers`, `/v1/customers/<id>` | POST, GET | the account's customer (`customer.go:171`, `:205`, `:221`) |
+| `/v1/checkout/sessions` and `.../<id>`, `.../<id>/expire` | POST, GET, list | Checkout (`prepared.go:72`, `client.go:726`, `:738`, `catalog.go:162`, `prepared.go:346`) |
+| `/v1/subscriptions/<id>`, `/v1/subscriptions` | GET, POST, list | sync, packs, upgrades, renewal (`client.go:786`, `:940`, `prepared.go:138`, `:149`, `:321`) |
+| `/v1/subscription_items/<id>` | POST | seat and pack quantities (`client.go:839`, `:891`) |
+| `/v1/invoices`, `/v1/invoices/<id>/lines` | list | the late-restore check (`prepared.go:398`, `:420`) |
+
+`ActiveTaxRegistrations` (`catalog.go:209`) has no caller, so the key does not need tax registrations. Plan 6a's outline listed them; the 6b outline does not.
+
+## 3. Where the outline and the code differ
+
+- **Price keys.** The outline says only "set to the key". The keys are `<book>/<plan>/<currency>` and `<book>/pack/<pack>/<currency>`. The team plans' keys are plain `community` and `business`, with no "per member" in them.
+- **`CARLOS_BILLING_PRICES`.** The outline gives no format. It is a JSON object from price key to price id. Every price of the configured book must be there, and it must be single-quoted in an EnvironmentFile.
+- **`CARLOS_PRICE_BOOK`.** It is a file path. The book's `catalog_version` must equal the installed catalog's version.
+- **Pause.** The outline wants it off. The code does not check it.
+- **The house coupon.** The code also refuses an amount off, and "unrestricted" means three things: no products, no redemption limit and no deadline. "No promotion code" is not checked. The console just never offers one with the house coupon.
+- **Price checks the outline leaves out.** Active, the right mode, an active product, no quantity transform, no second currency, and an interval count of 1.
+- **The account read.** The readiness check reads `GET /v1/account`. The outline's key permissions have no row for it (see step 4).
+- **The webhook path, the API version, the six events and `metadata[price_key]`** all match the outline.
+- **Rotation.** `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS` exists but is missing from the outline's list of variables.
+
+## 4. The sandbox run
+
+Everything in this section happens in the Carloku Sandbox (`acct_1UVFkoIiAD0xflDQ`) and on the dev console (`https://platform.dev.carlosframework.com`). None of it touches live.
+
+### 4.1 Before you start
+
+- The dev console runs a build that includes Plans 6a and 6b, with billing off. `https://platform.dev.carlosframework.com/billing/webhook` answers 404.
+- The dev console has a plan catalog with version `2026-10-20-v1` (spec §12 step 2). Check with `systemctl cat console.service` and the environment it loads. If it has none, install `internal/plans/testdata/example-catalog.json` as `/etc/carlos/plans.json` and set `CARLOS_PLAN_CATALOG`. A catalog puts limits on every account, so mark every existing dev account sponsored straight after (`docs/site/plans.md`, "Sponsored accounts"). `carlos accounts plan` only works once a catalog is configured.
+- The stripe CLI is logged in to the sandbox: `stripe login`, then pick the Carloku Sandbox. Unset `STRIPE_API_KEY` in that shell; the script refuses a live key there anyway.
+
+### 4.2 Run the script
+
+From a checkout of main:
+
+```sh
+export CONSOLE_URL=https://platform.dev.carlosframework.com
+export STRIPE_TAX_CODE=txcd_10103000 # the sandbox code; the default
+scripts/stripe-setup.sh # dry run: sends nothing, prints every command
+scripts/stripe-setup.sh --check # reads only: what exists, what is wrong, what is missing
+scripts/stripe-setup.sh --apply # makes what is missing
+scripts/stripe-setup.sh --check # again: everything exists and nothing is wrong
+```
+
+Optional inputs: `PORTAL_HEADLINE`, `PORTAL_PRIVACY_URL`, `PORTAL_TERMS_URL`, `PORTAL_RETURN_URL` (default `$CONSOLE_URL/`), `PORTAL_CUSTOMER_UPDATES` (default `address name tax_id`), `HOUSE_COUPON_NAME`, `PRODUCT_NAME_<NAME>` and `STRIPE_PROJECT_NAME`. `scripts/stripe-setup.sh --help` lists them.
+
+What the script does:
+
+- It checks that the CLI is on the expected account (`STRIPE_ACCOUNT`, default `acct_1UVFkoIiAD0xflDQ`) and in test mode. Every object it reads or makes must say `livemode: false`. It never passes `--live`.
+- It finds existing objects first: products by `metadata[carlos_product]`, prices by `lookup_key` or `metadata[price_key]` on their product, the portal configuration by `metadata[carlos_portal]=locked`, the coupon by `metadata[carlos_coupon]=house` and the endpoint by its URL. It looks only at live objects: active products, prices and portal configurations, valid coupons and enabled endpoints. It makes only what is missing, so running it twice makes nothing the second time.
+- It never deletes, archives or edits anything. If something exists but breaks a rule in section 2, it stops, names the object and the rule, and leaves the fix to you in the Dashboard.
+- Each create carries an idempotency key (`stripe-setup:<kind>:<name>`). If a response gets lost, running again within 24 hours returns the same object instead of a second one.
+- When it makes the webhook endpoint, it prints the signing secret once, to stderr, and writes it nowhere. Copy it straight into the console's EnvironmentFile (4.4). If you lose it, roll the secret in the Dashboard.
+- At the end it prints the console's non-secret variables, ready to paste.
+
+Two questions only the sandbox can answer:
+
+- Whether Stripe accepts `name` in the portal's `allowed_updates` at `2025-02-24.acacia`. If it refuses, run again with `PORTAL_CUSTOMER_UPDATES="address tax_id"`. The console accepts any subset.
+- Whether the portal configuration needs a `business_profile` at this API version. If it does, set `PORTAL_PRIVACY_URL` and `PORTAL_TERMS_URL`.
+
+### 4.3 What Paul does in the Dashboard
+
+All of this happens in the sandbox. The CLI cannot do it, or should not.
+
+1. **Stripe Tax.** Every Checkout sets `automatic_tax[enabled]=true` (`client.go:697`). Stripe Tax needs to be set up in the sandbox (head office address, and at least one registration if you want to see a tax line), or every Checkout create fails.
+2. **Retries.** Billing, Revenue recovery, Retries: when all retries fail, cancel the subscription (outline step 6). There is no API for this.
+3. **The restricted key.** Developers, API keys, Create restricted key. Name it after the console it is for, for example `console dev`. Set these permissions and leave every other one at None:
+
+ | Dashboard permission | Level | Why |
+ | --- | --- | --- |
+ | Checkout Sessions | Write | create, read, list and expire Checkout sessions, including a customer's |
+ | Customers | Write | create, update and read the account's customer |
+ | Subscriptions | Write | read, list and change subscriptions, and their items (seat and pack quantities) |
+ | Customer portal | Write | open portal sessions |
+ | Billing portal configurations (if the Dashboard lists it on its own row) | Read | the readiness check reads the locked configuration |
+ | Prices | Read | readiness and the clock probe |
+ | Products | Read | readiness |
+ | Coupons | Read | readiness reads the house coupon |
+ | Invoices | Read | the late-restore check (Call 18, granted 2026-10-25) |
+
+ Leave these at None: Refunds, Charges, Events, Webhook endpoints, API keys and Subscription schedules.
+
+ The readiness check also reads `GET /v1/account`. The outline has no row for it. Save the key with the list above, start the console (4.4), and read its log. If the check fails with "reading the account", give the key the narrowest read of the account the Dashboard offers, and write down here which row that was.
+
+ If the Dashboard shows subscription items on a row of its own, set it to Write.
+
+ The key starts `rk_test_`. Stripe shows it once. It goes straight into the console's EnvironmentFile (4.4) and nowhere else: not a file in a repo, not a ticket, not a chat.
+
+### 4.4 The dev console's environment
+
+The dev console's systemd unit, `/etc/systemd/system/console.service`, exists only on the dev console box (carlos-dev-ie: profile `kass`, eu-west-1, `i-05498eada6f0afd23` when last recorded; confirm the instance before using it). It is not in any repo. Its drop-ins already follow one pattern: `console.service.d/release-key.conf` loads `EnvironmentFile=-/etc/carlos/release.env` (root:root 0600). Billing gets a drop-in of its own the same way.
+
+1. Look at what the unit loads now:
+
+ ```sh
+ systemctl cat console.service | grep -i EnvironmentFile
+ ```
+
+ `/etc/carlos/host.env` is shared with the box's other units, so the Stripe secrets do not go there.
+2. Copy `deploy/billing/pricebook-2026-10-27-v1.json` to `/etc/carlos/pricebook-2026-10-27-v1.json` (root:root 0644). Never edit it in place afterwards (section 2).
+3. Write `/etc/carlos/billing.env`, root:root, mode 0600, holding:
+ - the block the script printed (`CARLOS_BILLING=test`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES` in single quotes, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, `CARLOS_STRIPE_HOUSE_COUPON`);
+ - `CARLOS_STRIPE_SECRET_KEY=rk_test_...`, the key from 4.3;
+ - `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...`, the secret the script printed on stderr.
+
+ Keep the secrets off any command line, and out of SSM send-command output. Either put them in SSM Parameter Store as SecureStrings and have the box read them (the pattern in `2026-10-05-scanner-host-rollout.md`, Task 9, steps 3 and 5), or type them in an interactive session on the box.
+4. Add `/etc/systemd/system/console.service.d/billing.conf`:
+
+ ```ini
+ [Service]
+ EnvironmentFile=/etc/carlos/billing.env
+ ```
+
+ There is no leading `-`. If the file goes missing, the unit fails to start, instead of starting with billing quietly off.
+5. Restart and check:
+
+ ```sh
+ systemctl daemon-reload && systemctl restart console.service
+ journalctl -u console.service -n 50
+ ```
+
+ If a variable is wrong, the console stops and names it. If so, fix the file and run `systemctl reset-failed console.service` before you start it again. Otherwise, wait for the readiness check to pass. `/billing/webhook` then stops answering 503, and the Dashboard's webhook page shows deliveries succeeding once there are events.
+
+To turn billing off again, set `CARLOS_BILLING=off` and restart. Nothing at Stripe changes.
+
+## 5. The dev rehearsal (outline step 9)
+
+Use test clocks, and the sandbox's test cards. Tick each line on dev:
+
+- [ ] `/upgrade` while signed out, through sign-up, to Checkout.
+- [ ] Personal with packs. Community at 4 members and at 12.
+- [ ] A declined pack raise, then paid from the portal. A resubmit refused while it is pending. A pending update left to expire.
+- [ ] A deleted pack restored and charged above its paid count.
+- [ ] A buy-back refused within 25 h of renewal, and allowed after it.
+- [ ] A delayed renewal webhook, followed by a pack request.
+- [ ] Member joins with a good card, a declining card and a dropped connection (check `Idempotent-Replayed`). Two joins at once. A join using an already-paid seat inside the margin.
+- [ ] A leave, then a rejoin. Match seats after a CLI removal.
+- [ ] Personal to Business (`pending_if_incomplete` with a price swap).
+- [ ] Stopping and resuming renewal.
+- [ ] Deletion refused while renewing, while collecting, and with an unresolved resume-renewal request, then allowed.
+- [ ] An expiry racing a completed Checkout.
+- [ ] A Checkout create with a lost response, continued from the page.
+- [ ] A 409 while a request is in flight.
+- [ ] An operator closing `operation_unresolved` from the Dashboard request log.
+- [ ] The renewal invoice read used by the late-restore check.
+- [ ] A failed renewal, then cancellation. Out-of-order events. `incomplete_expired`. Webhook secret rotation (with `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS`).
+- [ ] Readiness refusing a wrong price, an unlocked portal and a bad coupon, with backoff.
+- [ ] A house account at zero. The customer-currency lock.
+
+Also record the answers to the questions the code leaves open:
+
+- [ ] What shape Stripe returns for a single-currency price's expanded `currency_options` (`adapter.go:422-429`). Either shape passes.
+- [ ] Whether `name` was accepted in the portal's `allowed_updates` (4.2).
+- [ ] Which Dashboard row lets the key read `GET /v1/account` (4.3).
+
+## 6. Live, later, with Paul's approval
+
+Nothing in this section is done yet, and every step is Paul's. `scripts/stripe-setup.sh` has no live path on purpose. Live setup gets its own reviewed change once the rehearsal has passed.
+
+**Paul's switch-on condition (2026-10-27): existing users must not have to start paying.** So before the plan catalog goes live on flagship, every existing account is sponsored at its current usage:
+
+```sh
+carlos accounts plan --console https://<flagship console> --account <sqid> \
+ --set free --sponsored <sqid>-limits.json --reason "existing account"
+```
+
+Each `limits.json` holds that account's measured usage under the catalog's limit names (`running_things`, `disk_bytes`, `storage_bytes`, `email_per_day`, `bandwidth_bytes_month`, `awake_hours_month` and so on). The rule for measuring is spec §8.7: counts and sizes as measured on switch-on day; email, bandwidth and awake hours from the highest full month of the three before it. An account with no statement history gets Personal's caps. A sponsored limit may go above a ceiling, and Paul sees each of those before switch-on.
+
+There are two things to settle before then:
+
+- There is no tool yet to measure usage and write those files. Plans 1 lists "the sponsored-usage measurement tool" under part 4, and it has not been built.
+- `carlos accounts plan` only works once the console has a catalog (`internal/console/apiaccountplan.go:70`). Sponsoring therefore happens after the catalog is installed, but before any limit acts on an account. The order needs working out, for example with `CARLOS_PLAN_LIMITS=off` on the boxes in the meantime, and checking what the console's hourly warning pass does during that window.
+
+Then, in order:
+
+1. Spec §12 steps 1 to 4 are done: catalog shipped dormant, the dev rehearsal, flagship accounts sponsored and the catalog configured, a week of warnings watched, and the after-grace stages on.
+2. A new book version, marked `approved`, with the amounts Paul approves. A draft is never edited into an approved book. New version, new file, new price keys.
+3. The product tax codes, confirmed with the accountant (the sandbox uses `txcd_10103000`).
+4. Customer-facing text reviewed: product names (they appear on Checkout and on invoices), the coupon name if there is one, and the portal headline.
+5. Live setup, through its own reviewed change, against the live Carloku account: the same objects with the approved book's keys, the endpoint at `https://<flagship console>/billing/webhook`, retries set to cancel, and an `rk_live_` key with the same permissions.
+6. The flagship console's EnvironmentFile with `CARLOS_BILLING=live`, then a restart, a passing readiness check, and a first house-account Checkout at zero.
+7. Publish `https://<console>/upgrade?plan=<plan>&currency=<cur>`.
+
+## 7. If something is wrong
+
+- **The console refuses to start.** The log names the variable. Fix `/etc/carlos/billing.env`, run `systemctl reset-failed console.service` and start it again. Or set `CARLOS_BILLING=off`.
+- **The readiness check fails.** The log names the price key or the object, and the rule it broke. Run `scripts/stripe-setup.sh --check` to see the same thing from the Stripe side.
+- **A wrong object was made.** Archive it in the Dashboard (deactivate a portal configuration, delete a coupon, disable an endpoint), then run the script again. The script ignores archived objects, so it makes a new one. Prices and products that have been used cannot be deleted, only archived.
+- **Stripe refuses a new price because its lookup key is taken.** An older price still holds the key: archiving a product does not archive its prices, and an archived price may keep its key. Clear that price's lookup key in the Dashboard, then run again. The script never moves a lookup key itself.
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh
new file mode 100755
index 000000000..3be48c693
--- /dev/null
+++ b/scripts/stripe-setup.sh
@@ -0,0 +1,575 @@
+#!/usr/bin/env bash
+# shellcheck disable=SC2016 # the single-quoted $names are jq's, not the shell's
+#
+# stripe-setup.sh: one-time setup of the Stripe objects console billing
+# needs (plans 6c), in a Stripe sandbox or test mode only.
+#
+# It makes, if they are missing:
+# - one product per paid plan and per pack in the price book, with
+# metadata[carlos_product] = <plan> or pack/<pack>;
+# - one yearly price per product and currency, with lookup_key and
+# metadata[price_key] both set to the console's price key;
+# - the locked customer portal configuration, metadata[carlos_portal]=locked;
+# - the house coupon, metadata[carlos_coupon]=house;
+# - the webhook endpoint at $CONSOLE_URL/billing/webhook.
+# Then it prints the console's non-secret environment variables.
+#
+# Usage:
+# CONSOLE_URL=https://console.example.com scripts/stripe-setup.sh
+# Dry run. Sends nothing to Stripe: prints every command, in order.
+# CONSOLE_URL=... scripts/stripe-setup.sh --check
+# Read only. Checks the account is the sandbox, finds what exists,
+# checks it the way the console's readiness check does, and prints
+# what --apply would create.
+# CONSOLE_URL=... scripts/stripe-setup.sh --apply
+# As --check, then creates whatever is missing.
+#
+# Inputs (environment):
+# CONSOLE_URL required. https://host[:port], no path.
+# STRIPE_TAX_CODE product tax code. Default txcd_10103000 (the
+# sandbox's; the live code is the accountant's call).
+# STRIPE_ACCOUNT the account the CLI must be using. Default
+# acct_1UVFkoIiAD0xflDQ (the sandbox).
+# PRICE_BOOK the book file. Default
+# deploy/billing/pricebook-2026-10-27-v1.json.
+# PRICE_BOOK_PATH where the console box keeps the book, for the
+# printed CARLOS_PRICE_BOOK. Default
+# /etc/carlos/<book file name>.
+# PLAN_CATALOG_PATH the console box's catalog, for the printed
+# CARLOS_PLAN_CATALOG. Default /etc/carlos/plans.json.
+# PORTAL_RETURN_URL the portal's default return URL. Default
+# $CONSOLE_URL/.
+# PORTAL_HEADLINE optional portal headline, up to 60 characters.
+# PORTAL_CUSTOMER_UPDATES what a customer may edit in the portal, some of
+# "address name tax_id". Default all three.
+# PORTAL_PRIVACY_URL optional https privacy policy URL for the portal.
+# PORTAL_TERMS_URL optional https terms of service URL for the portal.
+# HOUSE_COUPON_NAME optional coupon name, up to 40 characters.
+# PRODUCT_NAME_<NAME> optional product name override, e.g.
+# PRODUCT_NAME_PERSONAL or PRODUCT_NAME_PACK_APPS.
+# STRIPE_PROJECT_NAME optional stripe CLI project (--project-name).
+#
+# Rules this script keeps:
+# - It never passes --live and has no live path. Live setup is a later,
+# separate decision that needs Paul's approval (the plans 6c runbook);
+# it gets its own reviewed change, not a flag here.
+# - It refuses to run against anything but the expected account in test
+# mode, and every object it reads or makes must say livemode false.
+# - It never deletes, archives or edits an object. An object that exists
+# but is wrong stops the run, naming what is wrong, for a person to fix.
+# Lookups see only live objects: active products, prices and portal
+# configurations, valid coupons, enabled endpoints. So once a wrong
+# object is archived in the Dashboard, the next run makes a new one.
+# - The webhook signing secret is printed once, to stderr, and is written
+# to no file.
+#
+# Needs bash, jq and the stripe CLI.
+set -euo pipefail
+
+readonly API_VERSION="2025-02-24.acacia"
+readonly WEBHOOK_EVENTS=(
+ checkout.session.completed
+ customer.subscription.created
+ customer.subscription.updated
+ customer.subscription.deleted
+ invoice.paid
+ invoice.payment_failed
+)
+readonly WEBHOOK_PATH="/billing/webhook"
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+die() { printf 'stripe-setup.sh: %s\n' "$*" >&2; exit 1; }
+warn() { printf 'stripe-setup.sh: warning: %s\n' "$*" >&2; }
+usage() { sed -n '4,/^set -euo/p' "${BASH_SOURCE[0]}" | sed -e '/^set -euo/d' -e 's/^# \{0,1\}//'; }
+
+mode="dry-run"
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -h | --help) usage; exit 0 ;;
+ --apply) mode="apply"; shift ;;
+ --check) mode="check"; shift ;;
+ --live) die "there is no live mode. Live setup is a separate, later decision (see the plans 6c runbook)" ;;
+ *) die "unknown argument: $1 (try --help)" ;;
+ esac
+done
+
+command -v jq >/dev/null || die "jq is needed"
+if [[ "$mode" != "dry-run" ]]; then
+ command -v stripe >/dev/null || die "the stripe CLI is needed"
+fi
+
+# ---------------------------------------------------------------------------
+# Inputs
+
+[[ -n "${CONSOLE_URL:-}" ]] || die "CONSOLE_URL is required, e.g. CONSOLE_URL=https://console.example.com"
+console_url="${CONSOLE_URL%/}"
+[[ "$console_url" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?$ ]] ||
+ die "CONSOLE_URL must be https://host or https://host:port, with no path"
+webhook_url="$console_url$WEBHOOK_PATH"
+
+tax_code="${STRIPE_TAX_CODE:-txcd_10103000}"
+[[ "$tax_code" =~ ^txcd_[0-9]{8}$ ]] || die "STRIPE_TAX_CODE must look like txcd_ and eight digits"
+
+account="${STRIPE_ACCOUNT:-acct_1UVFkoIiAD0xflDQ}"
+[[ "$account" =~ ^acct_[A-Za-z0-9]+$ ]] || die "STRIPE_ACCOUNT must look like acct_..."
+
+book_file="${PRICE_BOOK:-$here/../deploy/billing/pricebook-2026-10-27-v1.json}"
+[[ -r "$book_file" ]] || die "PRICE_BOOK $book_file cannot be read"
+book_path="${PRICE_BOOK_PATH:-/etc/carlos/$(basename "$book_file")}"
+catalog_path="${PLAN_CATALOG_PATH:-/etc/carlos/plans.json}"
+
+return_url="${PORTAL_RETURN_URL:-$console_url/}"
+headline="${PORTAL_HEADLINE:-}"
+privacy_url="${PORTAL_PRIVACY_URL:-}"
+terms_url="${PORTAL_TERMS_URL:-}"
+coupon_name="${HOUSE_COUPON_NAME:-}"
+read -r -a customer_updates <<<"${PORTAL_CUSTOMER_UPDATES:-address name tax_id}"
+((${#customer_updates[@]} > 0)) || die "PORTAL_CUSTOMER_UPDATES is empty"
+for u in "${customer_updates[@]}"; do
+ case "$u" in address | name | tax_id) ;; *) die "PORTAL_CUSTOMER_UPDATES may hold only address, name and tax_id, not $u" ;; esac
+done
+project="${STRIPE_PROJECT_NAME:-}"
+
+check_url() { [[ -z "$2" || "$2" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/%?=\&-]*)?$ ]] || die "$1 must be an https URL"; }
+check_text() { [[ "$2" != *[[:cntrl:]]* ]] || die "$1 has a control character"; ((${#2} <= $3)) || die "$1 is longer than $3 characters"; }
+check_url PORTAL_RETURN_URL "$return_url"
+check_url PORTAL_PRIVACY_URL "$privacy_url"
+check_url PORTAL_TERMS_URL "$terms_url"
+check_text PORTAL_HEADLINE "$headline" 60
+check_text HOUSE_COUPON_NAME "$coupon_name" 40
+[[ -z "$project" || "$project" =~ ^[A-Za-z0-9_-]+$ ]] || die "STRIPE_PROJECT_NAME must be letters, digits, - and _"
+
+# A key in the environment overrides the CLI's login. Refuse a live one.
+case "${STRIPE_API_KEY:-}" in
+ *_live_*) die "STRIPE_API_KEY holds a live key. This script runs in a sandbox or test mode only" ;;
+esac
+
+# ---------------------------------------------------------------------------
+# The price book: the one source of names, currencies and amounts.
+
+jq -e '
+ (.version | type == "string" and test("^[A-Za-z0-9._-]+$"))
+ and (.status == "draft" or .status == "approved")
+ and (.currencies | type == "array" and length > 0 and all(. == "usd" or . == "eur" or . == "gbp"))
+ and (.plans | type == "object") and (.packs | type == "object")
+ and ([.plans[], .packs[]] | all(type == "object" and all(.[]; type == "number" and . > 0 and . == floor)))
+' "$book_file" >/dev/null || die "$book_file is not a price book this script understands"
+
+book_version="$(jq -r .version "$book_file")"
+book_status="$(jq -r .status "$book_file")"
+read -r -a currencies <<<"$(jq -r '.currencies | join(" ")' "$book_file")"
+read -r -a plan_names <<<"$(jq -r '.plans | keys_unsorted | join(" ")' "$book_file")"
+read -r -a pack_names <<<"$(jq -r '.packs | keys_unsorted | join(" ")' "$book_file")"
+for c in "${currencies[@]}"; do
+ jq -e --arg c "$c" '[.plans[], .packs[]] | all(has($c))' "$book_file" >/dev/null ||
+ die "$book_file does not price everything in $c"
+done
+[[ " ${plan_names[*]} " != *" pack "* ]] || die "a paid plan may not be named pack"
+
+# ---------------------------------------------------------------------------
+# Printing and running commands
+
+readonly SQ="'\\''"
+quote() {
+ if [[ "$1" =~ ^[A-Za-z0-9_@%+=:,./-]+$ ]]; then
+ printf '%s' "$1"
+ else
+ printf "'%s'" "${1//\'/$SQ}"
+ fi
+}
+show() {
+ local first=1 w
+ for w in "$@"; do
+ if ((first)); then printf '%s' "$w"; first=0
+ elif [[ "$w" == -d ]]; then printf ' \\\n -d'
+ else printf ' %s' "$(quote "$w")"
+ fi
+ done
+ printf '\n'
+}
+
+# stripe_cmd fills the array cmd with one stripe CLI call.
+cmd=()
+stripe_cmd() {
+ local verb="$1" path="$2"
+ shift 2
+ cmd=(stripe "$verb" "$path" --stripe-version "$API_VERSION")
+ [[ -z "$project" ]] || cmd+=(--project-name "$project")
+ [[ "$verb" != post ]] || cmd+=(--confirm)
+ cmd+=("$@")
+}
+
+# call runs cmd and leaves the response in $out. It stops on a failed call
+# or a Stripe error. The response is never printed: a webhook endpoint's
+# carries its signing secret.
+out=""
+call() {
+ local rc=0
+ printf '+ '; show "${cmd[@]}"
+ out="$("${cmd[@]}")" || rc=$?
+ if jq -e 'type == "object" and has("error")' >/dev/null 2>&1 <<<"$out"; then
+ die "Stripe refused the call above: $(jq -r '.error | [.type, .code, .message] | map(select(. != null)) | join(": ")' <<<"$out")"
+ fi
+ ((rc == 0)) || die "the call above failed (exit $rc)"
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$out" || die "the call above did not answer with a JSON object"
+}
+
+# read_call is a read: printed in a dry run, run otherwise.
+read_call() {
+ stripe_cmd "$@"
+ if [[ "$mode" == "dry-run" ]]; then show "${cmd[@]}"; return 0; fi
+ call
+}
+
+# write_call is a create: printed in a dry run and in --check, run in --apply.
+# It returns 1 when it did not run.
+write_call() {
+ stripe_cmd "$@"
+ if [[ "$mode" != "apply" ]]; then show "${cmd[@]}"; return 1; fi
+ call
+}
+
+# list_all reads every page of a list into $out as one JSON array.
+list_all() {
+ local path="$1"
+ shift
+ local all="[]" after=""
+ while :; do
+ if [[ -n "$after" ]]; then
+ read_call get "$path" -d limit=100 -d "starting_after=$after" "$@"
+ else
+ read_call get "$path" -d limit=100 "$@"
+ fi
+ if [[ "$mode" == "dry-run" ]]; then out="[]"; return 0; fi
+ jq -e '.object == "list" and (.data | type == "array")' >/dev/null <<<"$out" || die "$path did not answer with a list"
+ jq -e '.data | all(.livemode == false)' >/dev/null <<<"$out" || die "$path returned a live-mode object. Stopping"
+ all="$(jq -c --argjson a "$all" '$a + .data' <<<"$out")"
+ jq -e '.has_more == true and (.data | length) > 0' >/dev/null <<<"$out" || break
+ after="$(jq -r '.data[-1].id' <<<"$out")"
+ done
+ out="$all"
+}
+
+# made_object checks a created object is in test mode and sets $id.
+id=""
+made_object() {
+ jq -e --arg p "$1" '.livemode == false and (.id | type == "string" and startswith($p))' >/dev/null <<<"$out" ||
+ die "the object just made is not a test-mode $1 object"
+ id="$(jq -r .id <<<"$out")"
+}
+
+ids='{}' # what the env block prints
+prices='{}' # price key -> price id
+remember() { ids="$(jq -c --arg k "$1" --arg v "$2" '. + {($k): $v}' <<<"$ids")"; }
+
+placeholder() { printf '<%s>' "$1"; }
+
+# ---------------------------------------------------------------------------
+# The console's readiness rules (internal/billingstripe/adapter.go), as jq.
+
+readonly PRICE_PROBLEM='
+ def own_options:
+ .currency as $c | .unit_amount as $a | .tax_behavior as $t
+ | (.currency_options // {}) as $o
+ | ($o | length) == 0
+ or (($o | length) == 1 and ($o | has($c))
+ and $o[$c].unit_amount == $a
+ and (($o[$c].tax_behavior // "") == "" or $o[$c].tax_behavior == $t));
+ if .active != true then "not active"
+ elif .livemode != false then "in live mode"
+ elif .product != $product then "on another product"
+ elif .currency != $currency then "in another currency"
+ elif .unit_amount != $amount then "its amount is not the one in the book"
+ elif (.recurring | type) != "object" then "not recurring"
+ elif .recurring.interval != "year" or .recurring.interval_count != 1 then "not billed once a year"
+ elif .recurring.usage_type != "licensed" then "not licensed"
+ elif .billing_scheme != "per_unit" then "not per unit"
+ elif .tax_behavior != "exclusive" then "not tax exclusive"
+ elif .transform_quantity != null then "has a quantity transform"
+ elif (own_options | not) then "has another currency option"
+ elif (.metadata.price_key // "") != $key then "its metadata price_key is not its key"
+ else "" end'
+
+readonly PORTAL_PROBLEM='
+ .features as $f
+ | if .active != true then "not active"
+ elif .livemode != false then "in live mode"
+ elif $f.payment_method_update.enabled != true then "payment method updates are off"
+ elif $f.invoice_history.enabled != true then "invoice history is off"
+ elif $f.subscription_update.enabled == true then "subscription updates are on"
+ elif $f.subscription_cancel.enabled == true then "cancellation is on"
+ elif ($f.subscription_pause.enabled // false) == true then "pause is on"
+ elif $f.customer_update.enabled == true
+ and ([$f.customer_update.allowed_updates[]? | select(. != "address" and . != "name" and . != "tax_id")] | length) > 0
+ then "customers may edit more than address, name and tax id"
+ else "" end'
+
+readonly COUPON_PROBLEM='
+ if .valid != true then "not valid"
+ elif .livemode != false then "in live mode"
+ elif .percent_off != 100 then "not 100% off"
+ elif .amount_off != null then "has an amount off"
+ elif .duration != "forever" then "not forever"
+ elif ((.applies_to.products // []) | length) > 0 then "limited to some products"
+ elif .max_redemptions != null then "has a redemption limit"
+ elif .redeem_by != null then "has a redemption deadline"
+ else "" end'
+
+readonly WEBHOOK_PROBLEM='
+ if .livemode != false then "in live mode"
+ elif .status != "enabled" then "not enabled"
+ elif .api_version != $version then "its API version is not \($version)"
+ elif (.enabled_events | sort) != ($events | sort) then "its events are not the six the console reads"
+ else "" end'
+
+# ---------------------------------------------------------------------------
+# 0. Preflight: the sandbox or test mode, nothing else.
+
+case "$mode" in
+ dry-run) echo "# stripe-setup.sh dry run: nothing below has been sent to Stripe." ;;
+ check) echo "# stripe-setup.sh --check: reads only." ;;
+ apply) echo "# stripe-setup.sh --apply: creates what is missing." ;;
+esac
+echo "# Book $book_version ($book_status): ${#plan_names[@]} plans, ${#pack_names[@]} packs, ${#currencies[@]} currencies."
+echo "# $(( ${#plan_names[@]} + ${#pack_names[@]} )) products, $(( (${#plan_names[@]} + ${#pack_names[@]}) * ${#currencies[@]} )) prices, API version $API_VERSION."
+echo
+echo "## Preflight: the CLI must be on $account in test mode"
+read_call get /v1/account
+if [[ "$mode" != "dry-run" ]]; then
+ got="$(jq -r '.id // ""' <<<"$out")"
+ [[ "$got" == "$account" ]] || die "the stripe CLI is on account ${got:-unknown}, not $account. Stopping"
+fi
+read_call get /v1/products -d limit=1
+if [[ "$mode" != "dry-run" ]]; then
+ jq -e '.object == "list" and (.data | all(.livemode == false))' >/dev/null <<<"$out" ||
+ die "the product list is not a test-mode list. Stopping"
+fi
+remember CARLOS_STRIPE_ACCOUNT "$account"
+echo
+
+# ---------------------------------------------------------------------------
+# 1. Products, 2. prices
+
+capitalise() { printf '%s%s' "$(printf '%s' "${1:0:1}" | tr '[:lower:]' '[:upper:]')" "${1:1}"; }
+
+# product_name sets $pname: PRODUCT_NAME_<NAME> if set, else "Personal" for
+# personal and "Apps pack" for pack/apps.
+pname=""
+product_name() { # <product metadata value>
+ local var
+ var="PRODUCT_NAME_$(printf '%s' "$1" | tr '[:lower:]/-' '[:upper:]__')"
+ pname="${!var:-}"
+ if [[ -z "$pname" ]]; then
+ case "$1" in
+ pack/*) pname="$(capitalise "${1#pack/}") pack" ;;
+ *) pname="$(capitalise "$1")" ;;
+ esac
+ fi
+ [[ -n "$pname" ]] || die "$var is empty"
+ check_text "$var" "$pname" 250
+}
+
+echo "## Products: metadata[carlos_product] names each one"
+list_all /v1/products
+all_products="$out"
+echo
+
+setup_product() { # <metadata value> <book section> <book name>
+ local meta="$1" section="$2" name="$3" found n pid made=0
+ echo "## Product $meta"
+ found="$(jq -c --arg m "$meta" '[.[] | select(.metadata.carlos_product == $m and .active == true)]' <<<"$all_products")"
+ n="$(jq length <<<"$found")"
+ if ((n > 1)); then die "$n active products have metadata[carlos_product]=$meta. Keep one, archive the others in the Dashboard, and run again"; fi
+ if ((n == 1)); then
+ pid="$(jq -r '.[0].id' <<<"$found")"
+ local tc
+ tc="$(jq -r '.[0].tax_code // "none"' <<<"$found")"
+ [[ "$tc" == "$tax_code" ]] || warn "product $meta ($pid) has tax code $tc, not $tax_code. This script does not change it"
+ echo "# exists: $pid"
+ else
+ echo "# none yet; this creates it:"
+ product_name "$meta"
+ if write_call post /v1/products -i "stripe-setup:product:$meta" \
+ -d "name=$pname" -d "tax_code=$tax_code" -d "metadata[carlos_product]=$meta"; then
+ made_object prod_
+ pid="$id"
+ made=1
+ echo "# created: $pid"
+ else
+ pid="$(placeholder "product $meta")"
+ fi
+ fi
+
+ local existing="[]"
+ if [[ "$mode" != "dry-run" && "$pid" == prod_* && "$made" == 0 ]]; then
+ list_all /v1/prices -d "product=$pid" -d "expand[]=data.currency_options"
+ existing="$out"
+ elif [[ "$mode" == "dry-run" ]]; then
+ list_all /v1/prices -d "product=$pid" -d "expand[]=data.currency_options"
+ fi
+
+ local cur key amount m problem prid
+ for cur in "${currencies[@]}"; do
+ if [[ "$section" == plans ]]; then key="$book_version/$name/$cur"; else key="$book_version/pack/$name/$cur"; fi
+ amount="$(jq -r --arg s "$section" --arg n "$name" --arg c "$cur" '.[$s][$n][$c]' "$book_file")"
+ echo "# price $key: $amount minor units a year"
+ found="$(jq -c --arg k "$key" '[.[] | select((.lookup_key == $k or .metadata.price_key == $k) and .active == true)]' <<<"$existing")"
+ m="$(jq length <<<"$found")"
+ if ((m > 1)); then die "$m active prices on $pid claim key $key. Archive the extra ones in the Dashboard and run again"; fi
+ if ((m == 1)); then
+ prid="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" ".[0] | $PRICE_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "price $key ($prid): $problem. The console would refuse it. Archive it in the Dashboard and run again"
+ [[ "$(jq -r '.[0].lookup_key // ""' <<<"$found")" == "$key" ]] || warn "price $key ($prid) has no lookup_key $key. The console does not read it"
+ echo "# exists: $prid"
+ elif write_call post /v1/prices -i "stripe-setup:price:$key" \
+ -d "product=$pid" -d "currency=$cur" -d "unit_amount=$amount" \
+ -d "recurring[interval]=year" -d "recurring[interval_count]=1" -d "recurring[usage_type]=licensed" \
+ -d billing_scheme=per_unit -d tax_behavior=exclusive \
+ -d "lookup_key=$key" -d "metadata[price_key]=$key"; then
+ made_object price_
+ prid="$id"
+ problem="$(jq -r --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" "$PRICE_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the price just made for $key ($prid): $problem. Stopping"
+ echo "# created: $prid"
+ else
+ prid="$(placeholder "price $key")"
+ fi
+ prices="$(jq -c --arg k "$key" --arg v "$prid" '. + {($k): $v}' <<<"$prices")"
+ done
+ echo
+}
+
+for p in "${plan_names[@]}"; do setup_product "$p" plans "$p"; done
+for p in "${pack_names[@]}"; do setup_product "pack/$p" packs "$p"; done
+
+# ---------------------------------------------------------------------------
+# 3. The locked portal configuration
+
+echo "## The locked portal configuration: metadata[carlos_portal]=locked"
+list_all /v1/billing_portal/configurations
+found="$(jq -c '[.[] | select(.metadata.carlos_portal == "locked" and .active == true)]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n active portal configurations have metadata[carlos_portal]=locked. Deactivate the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ portal="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r ".[0] | $PORTAL_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "portal configuration $portal: $problem. The console would refuse it. Fix it in the Dashboard, or deactivate it, and run again"
+ echo "# exists: $portal"
+else
+ echo "# none yet; this creates it:"
+ args=(
+ -d "features[payment_method_update][enabled]=true"
+ -d "features[invoice_history][enabled]=true"
+ -d "features[customer_update][enabled]=true"
+ -d "features[subscription_update][enabled]=false"
+ -d "features[subscription_cancel][enabled]=false"
+ -d "default_return_url=$return_url"
+ )
+ for u in "${customer_updates[@]}"; do args+=(-d "features[customer_update][allowed_updates][]=$u"); done
+ [[ -z "$headline" ]] || args+=(-d "business_profile[headline]=$headline")
+ [[ -z "$privacy_url" ]] || args+=(-d "business_profile[privacy_policy_url]=$privacy_url")
+ [[ -z "$terms_url" ]] || args+=(-d "business_profile[terms_of_service_url]=$terms_url")
+ args+=(-d "metadata[carlos_portal]=locked")
+ if write_call post /v1/billing_portal/configurations -i "stripe-setup:portal:locked" "${args[@]}"; then
+ made_object bpc_
+ portal="$id"
+ problem="$(jq -r "$PORTAL_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the portal configuration just made ($portal): $problem. Stopping"
+ echo "# created: $portal"
+ else
+ portal="$(placeholder "portal configuration")"
+ fi
+fi
+remember CARLOS_STRIPE_PORTAL_CONFIGURATION "$portal"
+echo
+
+# ---------------------------------------------------------------------------
+# 4. The house coupon
+
+echo "## The house coupon: metadata[carlos_coupon]=house"
+list_all /v1/coupons -d "expand[]=data.applies_to"
+found="$(jq -c '[.[] | select(.metadata.carlos_coupon == "house" and .valid == true)]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n valid coupons have metadata[carlos_coupon]=house. Delete the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ coupon="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r ".[0] | $COUPON_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "house coupon $coupon: $problem. The console would refuse it. Coupons cannot be changed: delete it in the Dashboard, then run again"
+ echo "# exists: $coupon"
+else
+ echo "# none yet; this creates it (no promotion code):"
+ args=(-d percent_off=100 -d duration=forever -d "expand[]=applies_to" -d "metadata[carlos_coupon]=house")
+ [[ -z "$coupon_name" ]] || args+=(-d "name=$coupon_name")
+ if write_call post /v1/coupons -i "stripe-setup:coupon:house" "${args[@]}"; then
+ jq -e '.livemode == false and (.id | type == "string" and test("^[A-Za-z0-9_-]{1,200}$"))' >/dev/null <<<"$out" ||
+ die "the coupon just made is not a test-mode coupon with a usable id"
+ coupon="$(jq -r .id <<<"$out")"
+ problem="$(jq -r "$COUPON_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the coupon just made ($coupon): $problem. Stopping"
+ echo "# created: $coupon"
+ else
+ coupon="$(placeholder "house coupon")"
+ fi
+fi
+remember CARLOS_STRIPE_HOUSE_COUPON "$coupon"
+echo
+
+# ---------------------------------------------------------------------------
+# 5. The webhook endpoint
+
+events_json="$(printf '%s\n' "${WEBHOOK_EVENTS[@]}" | jq -R . | jq -sc .)"
+echo "## The webhook endpoint: $webhook_url"
+list_all /v1/webhook_endpoints
+found="$(jq -c --arg u "$webhook_url" '[.[] | select(.url == $u and .status == "enabled")]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n enabled webhook endpoints point at $webhook_url. Delete the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ we="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" ".[0] | $WEBHOOK_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "webhook endpoint $we: $problem. Fix its events in the Dashboard, or, for a wrong API version (fixed when an endpoint is made), disable it and run again"
+ echo "# exists: $we. Its signing secret was shown when it was made."
+ echo "# If you do not have it, roll it in the Dashboard (Developers, Webhooks, the endpoint, Roll secret)."
+else
+ echo "# none yet; this creates it:"
+ args=(-d "url=$webhook_url")
+ for e in "${WEBHOOK_EVENTS[@]}"; do args+=(-d "enabled_events[]=$e"); done
+ args+=(-d "api_version=$API_VERSION" -d "description=console billing" -d "metadata[carlos_webhook]=billing")
+ if write_call post /v1/webhook_endpoints -i "stripe-setup:webhook:$webhook_url" "${args[@]}"; then
+ made_object we_
+ problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" "$WEBHOOK_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the webhook endpoint just made ($id): $problem. Stopping"
+ secret="$(jq -r '.secret // ""' <<<"$out")"
+ out=""
+ [[ "$secret" == whsec_* ]] || die "the new webhook endpoint ($id) came back without a signing secret. Roll its secret in the Dashboard"
+ echo "# created: $id. Its signing secret is on stderr, once."
+ {
+ echo
+ echo "CARLOS_STRIPE_WEBHOOK_SECRET=$secret"
+ echo " ^ The webhook signing secret. It is shown once and kept nowhere else."
+ echo " Put it in the console's EnvironmentFile now. Never put it in the repo, a ticket or a chat."
+ echo
+ } >&2
+ secret=""
+ fi
+fi
+echo
+
+# ---------------------------------------------------------------------------
+# The console's environment
+
+echo "## Console environment (non-secret). Paste into the console's EnvironmentFile."
+if [[ "$mode" != "apply" ]]; then
+ echo "# Values in <angle brackets> are ids --apply would create."
+fi
+echo "CARLOS_BILLING=test"
+echo "CARLOS_PLAN_CATALOG=$catalog_path"
+echo "CARLOS_PRICE_BOOK=$book_path"
+# Single quotes: systemd strips double quotes from an EnvironmentFile value.
+echo "CARLOS_BILLING_PRICES='$(jq -cS . <<<"$prices")'"
+jq -r 'to_entries[] | "\(.key)=\(.value)"' <<<"$ids"
+echo
+echo "## Secrets: set them by hand in the same file. Never in the repo."
+echo "# CARLOS_STRIPE_SECRET_KEY the rk_test_ restricted key made in the Dashboard (runbook, step 4)"
+echo "# CARLOS_STRIPE_WEBHOOK_SECRET the whsec_ signing secret, printed on stderr when the endpoint is made"