diff --git a/FAQ.md b/FAQ.md index 82ae94be..5c5c8a15 100644 --- a/FAQ.md +++ b/FAQ.md @@ -166,7 +166,7 @@ The runtime and model are free, open source (Apache-2.0) and need no API key or genclass.dev service are defined in `billing/plans.json`, which the collector and the pricing page read, and it defines three (since 2026-11-11). Free is what finds, shows and fixes the problems: the dashboard's problems for one person, 3 apps and the last 7 days, the coding-agent loop on your machine, and the GitHub App on public repositories. -Team, US$15 a developer a month, adds the GitHub App on private repositories, visitor analytics, forwarding, data +Team, US$50 a developer a month (US$15 in Canada), adds the GitHub App on private repositories, visitor analytics, forwarding, data export, 90 days of history and members. Enterprise, agreed by email, adds your own classifier, which GenClass trains, GenClass's models in its cloud, a year of history and contract terms. Your data is kept 90 days on every plan, so an upgrade shows what was counted before it. A collector you host yourself locks nothing. The pricing page shows the diff --git a/README.md b/README.md index 056cc428..580ed645 100644 --- a/README.md +++ b/README.md @@ -34,8 +34,8 @@ npx genclass # signs you in, starts Pro, adds GenClass to your app and walks y ``` Run it in your web app's folder and press Enter for each step: account, Pro, runtime, app plan, dashboard, test -workflow, GitHub App, coding agent, suggestions. The command comes with Pro: 3 days free, then US$15 a developer a -month. The card is asked for on Stripe when the trial starts, and nothing is charged if you cancel before the 3 days +workflow, GitHub App, coding agent, suggestions. The command comes with Pro: 3 days free, then US$50 a developer a +month (US$15 in Canada). The card is asked for on Stripe when the trial starts, and nothing is charged if you cancel before the 3 days end. Free stays on the website ([pricing](https://genclass.dev/pricing)). A step that does not fit your project is skipped, Enter also stops any wait, and running it again continues from where things are. It draws nothing on your pages. Then: @@ -204,7 +204,7 @@ GenClass's GitHub App puts what the runtime saw on the pull request it was seen the GenClass fixture, your workflow uploads the race files it writes, and the app posts one check and one comment: each finding with its test, the seeds it was flagged in and the evidence line. It reads those files and never your source code, it comments only where it is installed, and it is free on public repositories. Private repositories -come with Pro (US$15 a developer a month; [pricing](https://genclass.dev/pricing)). +come with Pro (US$50 a developer a month (US$15 in Canada); [pricing](https://genclass.dev/pricing)). > **Install** at (the app is GenClass.dev, ). With > no change to your tests, one workflow file is the whole setup: the check on your first pull request links to it, @@ -249,7 +249,7 @@ export const submitOrder = protect("checkout submit", (cart) => fetch("/api/orde - **Token and dashboard.** A token (`gc_` plus 22 letters and digits, public) groups your app's diagnostics under a private dashboard link (`https://genclass.dev/dashboard/...`). On Free the dashboard shows an app's totals for the - last 7 days, for one app in an account. Pro (US$15 a developer a month, up to 3 apps in an account) adds every + last 7 days, for one app in an account. Pro (US$50 a developer a month (US$15 in Canada), up to 3 apps in an account) adds every problem with its pages and a fix prompt, visitor analytics, forwarding, export, 90 days of history and team members; more apps come with Enterprise ([pricing](https://genclass.dev/pricing)). Plans bought before 13 November 2026 keep every app they cover (an app paid for on its own does not count toward Pro's 3); Free covers an account's oldest app diff --git a/billing/plans.json b/billing/plans.json index 7fc2c8b8..d0de0c43 100644 --- a/billing/plans.json +++ b/billing/plans.json @@ -1,5 +1,5 @@ { - "_about": "The one place GenClass plans are defined. telemetry-worker/src/plans.ts imports this file (limits, entitlements, Stripe lookup keys, the billing page) and genclass.dev's site reads it (the pricing page). Three plans since version 3 (2026-11-11): Free, Team (named Pro since 2026-11-12) and Enterprise; version 4 (2026-11-12) sold a plan per project; version 5 (2026-11-13, below) sells Pro for the account again. The history up to version 4 follows. Free is what finds, shows and fixes the problems: the open-source runtime with every mode and its on-device model, the coding-agent loop on the developer's machine, the dashboard's problems for an account's first 3 projects (the last 7 days shown; a 4th project on Free is locked until it has a plan), and 100 problems fixed live a month per project (limits.live_fixes_per_month; past it the runtime is told to observe only until the month ends) and genclass-dev[bot] on public repositories. Team is sold per project (per_project true: one Stripe subscription of quantity 1 per project, its metadata naming the project; everyone on the account's team sees it; telemetry-worker/src/stripe.ts) and adds what a team uses: genclass-dev[bot] on private repositories, visitor analytics, forwarding, export, 90 days of history and members. Enterprise is agreed by email: a null monthly price means the plan is not sold on the site, and an account gets it from GenClass's own grant (accounts.comp_until, set by hand to the end of the agreement; accounts.comp_plan names the plan granted, grant_plan when it is empty). The classifier a person from GenClass trains is in Enterprise only. retired_plans lists the plan ids GenClass sold before (Pro and Custom until 2026-10-19, Individual until 2026-10-22): their Stripe products and prices stay GenClass's own, so a subscription to one is still cancelled with its account, opens Manage billing and is reported to the owner while it bills, but it gives no plan (it reads as Free). The worker's Stripe code and scripts/stripe-setup.mjs sell any plan given a monthly price above 0, its stripe_lookup_keys and a stripe_tax_code. Prices are US cents (per project for a per_project plan, per seat for a per_seat plan); a null yearly price means no yearly option. limits.apps null means no plan limit (the worker still caps an account at 200 apps against abuse); limits.seats is how many people a plan that is not per_seat holds (null: no limit); limits.history_days is what the dashboard shows, and data is never deleted before 90 days whatever the plan, so the longer history is there the moment an account upgrades. Ingest never depends on the plan: an app's visitor analytics are counted while its plan leaves them out, and shown once it includes them. Pro (id team; named Team until 2026-11-12) has a trial: trial_days (3) days free at Checkout, a card taken up front and charged when it ends unless cancelled, once per account (telemetry-worker/src/billing.ts trialFor). Feature lines with available false are shown as coming next. The entitlement github_private is what lets genclass-dev[bot], the GitHub App, review an account's private repositories (telemetry-worker/src/github/entitlement.ts); public repositories are reviewed for everyone, whatever this file says. A self-hosted collector sets PLAN_GATES = \"open\" and gives every account the grant plan. managed_payments true would sell a plan through Stripe Managed Payments (only for fully automated digital products; telemetry-worker/README.md, Paid plans). `suggestions` (2026-11-12): what `genclass suggest` gives a plan (telemetry-worker/src/suggest.ts): `per_day`, model runs an account has a day, and `shown`, how many items of the plan it is shown (null: all); the measured checks themselves are free for everyone. Entitlements `problems` (the problem lists, pages, activity and fix prompts on the dashboard and in the genclass command; Free shows only the totals) and `ask` (genclass ask) were added 2026-11-12 (the owner's 'limit free fully'); a plan file without the key gives them. Version 5 (2026-11-13, the owner's call): Pro is bought for the account again, not per app, and per developer (per_seat: the subscription's quantity is how many developers, the owner included, US$15 each a month); it covers up to 3 apps (limits.apps) whatever the number of developers, the oldest first, and a later app waits on its plan page, where more apps are Enterprise's, by email. A subscription bought per project under version 4 still covers its app, is not counted in the 3 and holds the whole team (no seat count); an account subscription from before version 5 keeps covering the apps the account had when migration 0021 was applied (accounts.apps_kept) while it lasts. Free covers one app. GenClass's grants cover every app. The genclass command is Pro's (2026-11-13, the owner's 'make the entire CLI paid'): a CLI session without Pro, its trial or a paying team gets 402 from every /api/cli route but the overview and the account; Free is the website's, with the owner's words for its list: one app, a limited dashboard, the open-source basics, and (the owner's 'keep them free') the GitHub App on public repositories, the page check and 100 live fixes a month.", + "_about": "The one place GenClass plans are defined. telemetry-worker/src/plans.ts imports this file (limits, entitlements, Stripe lookup keys, the billing page) and genclass.dev's site reads it (the pricing page). Three plans since version 3 (2026-11-11): Free, Team (named Pro since 2026-11-12) and Enterprise; version 4 (2026-11-12) sold a plan per project; version 5 (2026-11-13, below) sells Pro for the account again. The history up to version 4 follows. Free is what finds, shows and fixes the problems: the open-source runtime with every mode and its on-device model, the coding-agent loop on the developer's machine, the dashboard's problems for an account's first 3 projects (the last 7 days shown; a 4th project on Free is locked until it has a plan), and 100 problems fixed live a month per project (limits.live_fixes_per_month; past it the runtime is told to observe only until the month ends) and genclass-dev[bot] on public repositories. Team is sold per project (per_project true: one Stripe subscription of quantity 1 per project, its metadata naming the project; everyone on the account's team sees it; telemetry-worker/src/stripe.ts) and adds what a team uses: genclass-dev[bot] on private repositories, visitor analytics, forwarding, export, 90 days of history and members. Enterprise is agreed by email: a null monthly price means the plan is not sold on the site, and an account gets it from GenClass's own grant (accounts.comp_until, set by hand to the end of the agreement; accounts.comp_plan names the plan granted, grant_plan when it is empty). The classifier a person from GenClass trains is in Enterprise only. retired_plans lists the plan ids GenClass sold before (Pro and Custom until 2026-10-19, Individual until 2026-10-22): their Stripe products and prices stay GenClass's own, so a subscription to one is still cancelled with its account, opens Manage billing and is reported to the owner while it bills, but it gives no plan (it reads as Free). The worker's Stripe code and scripts/stripe-setup.mjs sell any plan given a monthly price above 0, its stripe_lookup_keys and a stripe_tax_code. Prices are US cents (per project for a per_project plan, per seat for a per_seat plan); a null yearly price means no yearly option. limits.apps null means no plan limit (the worker still caps an account at 200 apps against abuse); limits.seats is how many people a plan that is not per_seat holds (null: no limit); limits.history_days is what the dashboard shows, and data is never deleted before 90 days whatever the plan, so the longer history is there the moment an account upgrades. Ingest never depends on the plan: an app's visitor analytics are counted while its plan leaves them out, and shown once it includes them. Pro (id team; named Team until 2026-11-12) has a trial: trial_days (3) days free at Checkout, a card taken up front and charged when it ends unless cancelled, once per account (telemetry-worker/src/billing.ts trialFor). Feature lines with available false are shown as coming next. The entitlement github_private is what lets genclass-dev[bot], the GitHub App, review an account's private repositories (telemetry-worker/src/github/entitlement.ts); public repositories are reviewed for everyone, whatever this file says. A self-hosted collector sets PLAN_GATES = \"open\" and gives every account the grant plan. managed_payments true would sell a plan through Stripe Managed Payments (only for fully automated digital products; telemetry-worker/README.md, Paid plans). `suggestions` (2026-11-12): what `genclass suggest` gives a plan (telemetry-worker/src/suggest.ts): `per_day`, model runs an account has a day, and `shown`, how many items of the plan it is shown (null: all); the measured checks themselves are free for everyone. Entitlements `problems` (the problem lists, pages, activity and fix prompts on the dashboard and in the genclass command; Free shows only the totals) and `ask` (genclass ask) were added 2026-11-12 (the owner's 'limit free fully'); a plan file without the key gives them. Version 5 (2026-11-13, the owner's call): Pro is bought for the account again, not per app, and per developer (per_seat: the subscription's quantity is how many developers, the owner included, US$15 each a month); it covers up to 3 apps (limits.apps) whatever the number of developers, the oldest first, and a later app waits on its plan page, where more apps are Enterprise's, by email. A subscription bought per project under version 4 still covers its app, is not counted in the 3 and holds the whole team (no seat count); an account subscription from before version 5 keeps covering the apps the account had when migration 0021 was applied (accounts.apps_kept) while it lasts. Free covers one app. GenClass's grants cover every app. The genclass command is Pro's (2026-11-13, the owner's 'make the entire CLI paid'): a CLI session without Pro, its trial or a paying team gets 402 from every /api/cli route but the overview and the account; Free is the website's, with the owner's words for its list: one app, a limited dashboard, the open-source basics, and (the owner's 'keep them free') the GitHub App on public repositories, the page check and 100 live fixes a month. Prices by country (2026-11-16, the owner's call): a plan's price_usd_cents and stripe_lookup_keys are what it costs everywhere but the countries its country_prices list (ISO 3166-1 alpha-2 codes, as Cloudflare reports the visitor's country). Pro is US$50 a developer a month everywhere but Canada, where it stays US$15 under the lookup key it was sold under before (genclass_team_monthly, so every subscription on it keeps its price). Checkout sells the price of the country the request comes from (telemetry-worker/src/plans.ts priceFor); a request with no country gets the plan's own price. A subscription keeps the price it was bought at. stripe_product (on a plan, for its own price, or on a country price) names the Stripe product that price is on; left out, the plan's main product genclass_. Pro's US$50 price is on genclass_team_world, because Stripe's Billing Portal allows only one monthly price per product for seat changes; both products are named GenClass Pro and carry metadata genclass_plan team.", "version": 5, "currency": "usd", "contact": "mehar@genclass.dev", @@ -35,8 +35,12 @@ "id": "team", "name": "Pro", "summary": "Everything for up to 3 apps, per developer.", - "price_usd_cents": { "monthly": 1500, "yearly": null }, - "stripe_lookup_keys": { "monthly": "genclass_team_monthly", "yearly": null }, + "price_usd_cents": { "monthly": 5000, "yearly": null }, + "stripe_lookup_keys": { "monthly": "genclass_team_world_monthly", "yearly": null }, + "stripe_product": "genclass_team_world", + "country_prices": [ + { "countries": ["CA"], "name": "Canada", "price_usd_cents": { "monthly": 1500, "yearly": null }, "stripe_lookup_keys": { "monthly": "genclass_team_monthly", "yearly": null } } + ], "stripe_tax_code": "txcd_10103001", "managed_payments": false, "per_seat": true, @@ -59,7 +63,7 @@ { "text": "Unlimited live fixes", "available": true }, { "text": "Data export and API", "available": true }, { "text": "90 days of history", "available": true }, - { "text": "Your team on it, $15 a developer", "available": true } + { "text": "Your team on it, priced per developer", "available": true } ] }, { diff --git a/docs/runtime/DASHBOARD.md b/docs/runtime/DASHBOARD.md index a02ea28b..618ddbd8 100644 --- a/docs/runtime/DASHBOARD.md +++ b/docs/runtime/DASHBOARD.md @@ -13,7 +13,7 @@ Each web app gets a **project key** (token: `gc_` + 22 letters and digits) that dashboard at genclass.dev. The key is public: it ships in your page and can only add telemetry to its app. Keep the dashboards in a GenClass account, or use one private link per app without an account. The dashboard is free for every app: what GenClass found, on which pages and what it did, for the last 7 days and up to 3 apps in an account. The Team -plan (US$15 a developer a month) adds visitor analytics, forwarding, export, 90 days of history, unlimited apps and +plan (US$50 a developer a month (US$15 in Canada)) adds visitor analytics, forwarding, export, 90 days of history, unlimited apps and members, who open your apps' dashboards with their own sign-in (Plan and billing, Team: make an invite link and send it; it works once, for 7 days). Enterprise adds a year of history and your own classifier, which a person from GenClass trains on your app's traffic, bug reports or labelled examples ([pricing](https://genclass.dev/pricing)). diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 79f1ae25..f907f2ee 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- **Pro's price by country**: before sign-in the command says Pro is 3 days free, then US$50 a developer a month + (US$15 in Canada). After sign-in it prints the price genclass.dev gives for where you are, as before. + ## 0.3.10 - **`genclass fix
`**: the findings genclass.dev's page check made on one page, handed to your coding agent diff --git a/packages/cli/README.md b/packages/cli/README.md index 57c29acd..563564e2 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -9,7 +9,7 @@ npx genclass Run it in your web app's folder. It shows where the project stands and walks you through the next step: one Enter per step. Stop at any point and run it again: it continues from what is true now. It comes with Pro: 3 days free, -then US$15 a developer a month. +then US$50 a developer a month (US$15 in Canada). ```text ╭─ GenClass ────────────────────────────────────────────── v0.3.7 ─╮ @@ -71,7 +71,7 @@ also a command of its own (`npx genclass problems`), so scripts and coding agent **The command comes with Pro.** Right after the sign-in, an account without Pro sees Pro's card, and Enter opens its checkout in the browser: 3 days free (one trial per account; the card is asked for on Stripe, and nothing is charged -if you cancel before they end), then US$15 a developer a month, for up to 3 apps in the account. More apps come with +if you cancel before they end), then US$50 a developer a month (US$15 in Canada), for up to 3 apps in the account. More apps come with Enterprise, by email. Every command but `login`, `logout`, `whoami`, `plan`, `upgrade`, `profile`, `status`, `remove`, `help` and `version` asks first. Without a terminal (`--yes`, `--json`, a coding agent) nothing is opened: one line with the checkout address, and exit code 1. Free stays on the website: one app's totals for the last 7 days. diff --git a/packages/cli/src/cli.mjs b/packages/cli/src/cli.mjs index b2a8e67e..bd6d782d 100644 --- a/packages/cli/src/cli.mjs +++ b/packages/cli/src/cli.mjs @@ -74,7 +74,7 @@ export function usage(cols = width()) { }; text("genclass: GenClass in your terminal. Set it up, see what it finds, have it fixed."); lines.push(""); - text("The genclass command comes with Pro: 3 days free, then $15 / developer / month, with a card on Stripe. Without Pro: login, logout, whoami, status, plan, upgrade, profile, remove, help. Free is on the website: https://genclass.dev", " "); + text("The genclass command comes with Pro: 3 days free, then $50 / developer / month ($15 in Canada), with a card on Stripe. Without Pro: login, logout, whoami, status, plan, upgrade, profile, remove, help. Free is on the website: https://genclass.dev", " "); const side = w >= 78; const col = 30; for (const [head, rows] of HELP) { diff --git a/packages/cli/src/state.mjs b/packages/cli/src/state.mjs index 7838f70f..29eb8e1d 100644 --- a/packages/cli/src/state.mjs +++ b/packages/cli/src/state.mjs @@ -70,7 +70,7 @@ export function hasPlaywright(cwd, project) { } /** What the command costs, said before the sign-in (the server says it in its own words once signed in). */ -export const PRO_TERMS = "The genclass command comes with Pro: 3 days free, then $15 / developer / month, card on Stripe."; +export const PRO_TERMS = "The genclass command comes with Pro: 3 days free, then $50 / developer / month ($15 in Canada)."; /** Free's limits as a few words ("3 apps, 7 days of history, your top 3 suggestions"), from the numbers the server sent. */ export function freeLimits(free) { @@ -199,7 +199,7 @@ export async function readState(o = {}, deps = {}) { // Pro: the price is said only to someone new (the 0.3.9 user stories: it was quoted to a payer after logout) why: creds || st.token ? `Opens ${host.overridden && !host.error ? new URL(host.host).host : "genclass.dev"} to sign you in again.` - : `Opens ${host.overridden && !host.error ? new URL(host.host).host : "genclass.dev"}. Then Pro: 3 days free, then $15 / developer / month, with a card on Stripe.`, + : `Opens ${host.overridden && !host.error ? new URL(host.host).host : "genclass.dev"}. Then Pro: 3 days free, then $50 / developer / month ($15 in Canada).`, more: `Your account is where your apps, their dashboards and your plan live. New here? It is made on that page. Nothing is typed in the terminal. ${PRO_TERMS} Free stays on the website: one app and its totals.`, run: "npx genclass login", human: "approve the sign-in in your browser", @@ -218,7 +218,7 @@ export async function readState(o = {}, deps = {}) { detail: !me ? creds || st.token ? "" - : "3 days free, then $15 / developer / month" + : "3 days free, then $50 / developer / month ($15 in Canada)" : cli && !cli.paid ? `${cli.price ?? cli.plan}${cli.trialDays ? `, ${cli.trialDays} days free` : ""}` : cli?.paid && cli.via === "team" diff --git a/packages/cli/test/actions.test.ts b/packages/cli/test/actions.test.ts index a313536e..b2bf0ce1 100644 --- a/packages/cli/test/actions.test.ts +++ b/packages/cli/test/actions.test.ts @@ -266,7 +266,7 @@ describe("genclass: the command line (src/cli.mjs, src/main.mjs)", () => { expect(lines.filter((l) => l.length > max), String(cols)).toEqual([]); expect(lines.join("\n")).toContain("npx genclass dashboard"); } - expect(usage(60)).toContain("$15 / developer / month"); + expect(usage(60).replace(/\s+/g, " ")).toContain("$50 / developer / month ($15 in Canada)"); // the browser opens only for someone at a terminal (none here: a coding agent, CI, a pipe), never with --no-browser expect(openBrowser("https://genclass.dev/account", {})).toBe(false); expect(openBrowser("https://genclass.dev/account", { noBrowser: true })).toBe(false); diff --git a/packages/cli/test/server-account.test.ts b/packages/cli/test/server-account.test.ts index 57ffca98..232a7f06 100644 --- a/packages/cli/test/server-account.test.ts +++ b/packages/cli/test/server-account.test.ts @@ -105,8 +105,8 @@ describe("genclass plan, team and apps (src/manage.mjs)", () => { // the paid plan's card, in the server's words, and (nobody at a terminal) where it starts: the genclass command is // Pro's, so the account's own checkout, its trial first expect(f).toContain("P R O"); - expect(f).toContain("$15 / developer / month"); - expect(f).toContain(`The genclass command comes with Pro ($15 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); + expect(f).toContain("$50 / developer / month"); + expect(f).toContain(`The genclass command comes with Pro ($50 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); expect(f).toContain("Apps and their plans Shop no plan chosen"); expect(JSON.parse((await said(() => plan({ ...me.o, json: true }, me.deps))).text)).toMatchObject({ ok: true, plan: { id: "free" }, limits: { apps: 1 }, offer: { plan: { id: "team" } }, cli: { paid: false, checkout_url: `${HOST}/account/billing?plan=pro&start=1`, trial_days: 3 } }); }); @@ -127,7 +127,7 @@ describe("genclass plan, team and apps (src/manage.mjs)", () => { expect(f).toContain("Signed in as ada@example.com"); expect(f).toContain("Plan Free (website only: the genclass command comes with Pro)"); expect(f).toContain("Apps and their plans Shop no plan chosen"); - expect(f).toContain("Start the 3-day free trial $15 / developer / month npx genclass upgrade"); + expect(f).toContain("Start the 3-day free trial $50 / developer / month npx genclass upgrade"); expect(f).toContain("Sign out npx genclass logout"); expect(JSON.parse((await said(() => profile({ ...me.o, json: true }, me.deps))).text)).toMatchObject({ ok: true, plan: { id: "free" }, apps: [{ name: "Shop", plan: { id: "free" } }], upgrade_url: `${HOST}/account/billing?plan=pro&start=1`, cli: { paid: false } }); // upgrade: Pro's card and its checkout, for the account (the genclass command is Pro's) @@ -151,7 +151,7 @@ describe("genclass plan, team and apps (src/manage.mjs)", () => { const me = await account(env); team3(sql, me.account.id); const f = flat((await said(() => plan(me.o, me.deps))).text); - expect(f).toContain("Plan Pro $15 / developer / month"); + expect(f).toContain("Plan Pro $50 / developer / month"); expect(f).toContain("Renews 2026-12-13"); // Pro is per developer (3 seats paid here) and covers up to 3 apps expect(f).toContain("People 1 of 3"); @@ -181,7 +181,7 @@ describe("genclass plan, team and apps (src/manage.mjs)", () => { const no = await said(() => team({ ...me.o, args: ["invite"] }, me.deps)); expect(no.code).toBe(1); // the genclass command is Pro's: the invite, like every command, says where Pro starts - expect(flat(no.text)).toContain(`The genclass command comes with Pro ($15 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); + expect(flat(no.text)).toContain(`The genclass command comes with Pro ($50 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); expect(flat(no.text)).toContain("npx genclass upgrade"); team3(sql, me.account.id); const made = await said(() => team({ ...me.o, args: ["invite"] }, me.deps)); @@ -227,7 +227,7 @@ describe("genclass plan, team and apps (src/manage.mjs)", () => { sql.db.prepare("UPDATE accounts SET subscription_status = 'trialing' WHERE id = ?").run(me.account.id); resetOwnerCache(); const p = flat((await said(() => plan(me.o, me.deps))).text); - expect(p).toContain("Trial until 2026-12-13. Then the first charge, $15 / developer / month, unless you cancel before."); + expect(p).toContain("Trial until 2026-12-13. Then the first charge, $50 / developer / month, unless you cancel before."); expect(p).not.toContain("Renews"); }); @@ -259,7 +259,7 @@ describe("genclass is Pro's: a view the server refuses with 402 says where Pro s const v = await said(() => analytics(me.o, me.deps)); expect(v.code).toBe(1); expect(tooWide(v.text)).toEqual([]); - expect(flat(v.text)).toContain(`The genclass command comes with Pro ($15 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); + expect(flat(v.text)).toContain(`The genclass command comes with Pro ($50 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); expect(flat(v.text)).toContain("npx genclass upgrade"); expect(v.text).not.toContain("Could not read the dashboard"); // the same needs_pro shape as the gate's (src/paywall.mjs needsProJson) @@ -292,7 +292,7 @@ describe("genclass connections (src/manage.mjs connections)", () => { expect(code).toBe(1); expect(tooWide(text)).toEqual([]); const f = flat(text); - expect(f).toContain(`The genclass command comes with Pro ($15 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); + expect(f).toContain(`The genclass command comes with Pro ($50 / developer / month): start your 3-day free trial at ${HOST}/account/billing?plan=pro&start=1`); expect(f).toContain("npx genclass upgrade"); expect(f).not.toContain("not set up"); // setting one up on Free: the same, said before anything is asked for @@ -507,11 +507,11 @@ describe("genclass ask (src/ask.mjs)", () => { const free = await account(env); const deps = { ...free.deps, readPrefs: () => ({ askTold: true }) }; // on Free, asking is Pro's: the answer says which plan, its trial and price, and the command that starts it - expect(await askModel(free.creds, { id: free.app.id, question: "How is it?" }, free.deps)).toMatchObject({ ok: false, status: 403, lock: { plan: "Pro", trialDays: 3, price: "$15 / developer / month" } }); + expect(await askModel(free.creds, { id: free.app.id, question: "How is it?" }, free.deps)).toMatchObject({ ok: false, status: 403, lock: { plan: "Pro", trialDays: 3, price: "$50 / developer / month" } }); const locked = await said(() => ask({ ...free.o, question: "How is it?" }, deps)); expect(locked.code).toBe(1); expect(tooWide(locked.text)).toEqual([]); - expect(flat(locked.text)).toContain("A question to the model comes with Pro. 3 days free, then $15 / developer / month. Cancel any time. Start: npx genclass upgrade"); + expect(flat(locked.text)).toContain("A question to the model comes with Pro. 3 days free, then $50 / developer / month. Cancel any time. Start: npx genclass upgrade"); const me = await pro(sql, free); expect(await askModel(me.creds, { id: me.app.id, question: "How is it?" }, me.deps)).toMatchObject({ ok: true, answer: null, why: "no-model" }); const none = await said(() => ask({ ...me.o, question: "How is it?" }, deps)); diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.ts index 9f1dcc32..4a6efec3 100644 --- a/packages/cli/test/server.test.ts +++ b/packages/cli/test/server.test.ts @@ -84,13 +84,13 @@ describe("genclass against the collector (src/api.mjs, telemetry-worker/src/cli. const deps = { runGit: () => null, fetchFn: through(env), now: now().getTime() }; // Free: the totals, and the way to the rest (the problems, their pages and the fix prompts are Pro's) const data = await fetchApp(me.creds, app.id, "7d", deps); - expect(data).toMatchObject({ ok: true, name: "shop", range: "7d", totals: { found: 2, checks: 0 }, problems: [], visitors: null, visitorsPlan: { plan: "Pro", upgradeUrl: `${HOST}/account/billing` }, problemsPlan: { plan: "Pro", trialDays: 3, price: "$15 / developer / month", upgradeUrl: `${HOST}/account/billing?project=${app.id}` }, dashboardUrl: `${HOST}/account/apps/${app.id}` }); + expect(data).toMatchObject({ ok: true, name: "shop", range: "7d", totals: { found: 2, checks: 0 }, problems: [], visitors: null, visitorsPlan: { plan: "Pro", upgradeUrl: `${HOST}/account/billing` }, problemsPlan: { plan: "Pro", trialDays: 3, price: "$50 / developer / month", upgradeUrl: `${HOST}/account/billing?project=${app.id}` }, dashboardUrl: `${HOST}/account/apps/${app.id}` }); let code = -1; const freeView = await printed(async () => (code = await dashboard({ cwd: dir }, deps))); expect(code).toBe(0); expect(freeView).toMatch(/Problems found\s+2/); expect(freeView.replace(/\s+/g, " ")).toContain("The problems, the pages they happen on and a fix prompt for each come with Pro. Free shows the totals."); - expect(freeView.replace(/\s+/g, " ")).toContain("3 days free, then $15 / developer / month. Cancel any time. Start: npx genclass upgrade"); + expect(freeView.replace(/\s+/g, " ")).toContain("3 days free, then $50 / developer / month. Cancel any time. Start: npx genclass upgrade"); expect(freeView).not.toContain("the same request went out twice"); // on Pro (here GenClass's grant for this app): every problem sql.db.prepare("UPDATE projects SET comp_until = '2027-12-31T00:00:00.000Z', comp_plan = 'team' WHERE id = ?").run(app.id); @@ -150,7 +150,7 @@ describe("genclass against the collector (src/api.mjs, telemetry-worker/src/cli. ideasLocked: 2, designsLocked: 1, upgradeUrl: `${HOST}/account/billing?plan=pro&from=cli`, - upgradePlan: { plan: "Pro", price: "$15 / developer / month", trialDays: 3 }, + upgradePlan: { plan: "Pro", price: "$50 / developer / month", trialDays: 3 }, limited: false, }; expect(free).toMatchObject({ ...shut, cachedAt: null, remainingToday: 2 }); diff --git a/packages/cli/test/state.test.ts b/packages/cli/test/state.test.ts index d11d56de..5146035a 100644 --- a/packages/cli/test/state.test.ts +++ b/packages/cli/test/state.test.ts @@ -216,8 +216,8 @@ describe("genclass: the state of a project (src/state.mjs header)", () => { const s = await readState({ cwd: dir, skip: ["account"] }, { runGit: noGit }); expect(s.next).toBeNull(); // before the sign-in, the first screen says what the command costs - expect(s.steps[0].why).toBe("Opens genclass.dev. Then Pro: 3 days free, then $15 / developer / month, with a card on Stripe."); - expect(s.steps[1].detail).toBe("3 days free, then $15 / developer / month"); + expect(s.steps[0].why).toBe("Opens genclass.dev. Then Pro: 3 days free, then $50 / developer / month ($15 in Canada)."); + expect(s.steps[1].detail).toBe("3 days free, then $50 / developer / month ($15 in Canada)"); // with Pro, a skipped step is not the next one signIn(); const fetchFn = fakeServer({ "GET /api/cli/overview": { json: overview({ plan: { id: "team", name: "Pro" }, cli: { paid: true, via: "plan" } }) } }).fetchFn; diff --git a/packages/cli/test/suggest.test.ts b/packages/cli/test/suggest.test.ts index 7dc0ae08..e7ebf8df 100644 --- a/packages/cli/test/suggest.test.ts +++ b/packages/cli/test/suggest.test.ts @@ -185,7 +185,7 @@ describe("genclass suggest: end to end (src/suggest/index.mjs header)", () => { const w = world(env, model); // Free: the first suggestion, and the rest counted, ideas and designs included, with Pro's trial const free = (await printed(async () => suggest({ cwd: dir, url: "https://shop.example", yes: true }, deps(w)))).replace(/\s+/g, " "); - expect(free).toMatch(/ PRO \d+ more suggestions for this app: \d+ from your checks, 2 ideas from the model, 1 website design inspired by sites like yours, each with a prompt for your coding agent\. 3 days free, then \$15 \/ developer \/ month\. Cancel any time\. Start: npx genclass upgrade/); + expect(free).toMatch(/ PRO \d+ more suggestions for this app: \d+ from your checks, 2 ideas from the model, 1 website design inspired by sites like yours, each with a prompt for your coding agent\. 3 days free, then \$50 \/ developer \/ month\. Cancel any time\. Start: npx genclass upgrade/); expect(free).not.toContain("A size guide for sleds"); expect(free).not.toContain("patagonia"); expect(runs).toBe(1); diff --git a/packages/runtime/README.md b/packages/runtime/README.md index 3ceb12df..63dec5e5 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -838,7 +838,7 @@ digits) that groups its diagnostics on a dashboard at genclass.dev, kept in a Ge then `connect`, `whoami`, `logout`) or behind one private link per app (anyone with the link can open it), which `init` saves in `.genclass.local` and `npx @genclass/runtime@beta dashboard` prints again (from `0.3.0-beta.2`; `--open` opens it). On Free the dashboard shows an app's totals for the last 7 days, for one app in an account, and -the `@genclass/mcp` server for coding agents is free. Pro, US$15 a developer a month for up to 3 apps in an account, +the `@genclass/mcp` server for coding agents is free. Pro, US$50 a developer a month (US$15 in Canada) for up to 3 apps in an account, adds every problem with its pages and a fix prompt, visitor analytics, forwarding, export, 90 days of history, team members and the `genclass` command; more apps, your own classifier, which a person from GenClass trains, and a year of history come with Enterprise ([pricing](https://genclass.dev/pricing)). Plans bought before 13 November 2026 keep diff --git a/scripts/stripe-setup.mjs b/scripts/stripe-setup.mjs index 9910df1f..0c8dd150 100644 --- a/scripts/stripe-setup.mjs +++ b/scripts/stripe-setup.mjs @@ -19,7 +19,10 @@ // 2. each plan's monthly price under its lookup key from billing/plans.json (all start with genclass_). Prices are // read only by those lookup keys; a key on another product's price stops the script. A changed amount gets a new // price: the old one is archived and keeps a genclass_..._retired_ lookup key, so its subscribers stay -// on it and on their plan (the worker reads a plan from a genclass_ lookup key and the product's metadata); +// on it and on their plan (the worker reads a plan from a genclass_ lookup key and the product's metadata). A +// plan's country prices (country_prices: Pro is US$15 in Canada and US$50 elsewhere, 2026-11-16) are made the +// same way; a price that names a product (stripe_product: Pro's own, genclass_team_world) is on that product, +// with the plan's name and metadata, because the Billing Portal's seat changes allow one monthly price a product; // 3. its webhook endpoint https://genclass.dev/api/billing/webhook with the description "GenClass billing", for the // events the worker handles and no others (the customer.subscription events, invoice.paid, charge.refunded and // charge.dispute.created; the worker reads only ids and amounts from the last three, which carry the buyer's @@ -96,9 +99,13 @@ function form(params) { * feature stays off, as before per-seat plans. */ export function seatUpdate(plans, made = {}) { + // a plan with country prices has a product for each price (the portal allows one monthly price a product): made[id] + // is then a list const products = plans - .filter((p) => (p.per_seat === true || p.per_app === true) && made[p.id] && !made[p.id].planned && made[p.id].prices.length) - .map((p) => ({ product: made[p.id].product, prices: made[p.id].prices })); + .filter((p) => p.per_seat === true || p.per_app === true) + .flatMap((p) => [].concat(made[p.id] ?? [])) + .filter((m) => !m.planned && m.prices.length) + .map((m) => ({ product: m.product, prices: m.prices })); return products.length ? { enabled: true, default_allowed_updates: ["quantity"], proration_behavior: "always_invoice", products } : { enabled: false }; } @@ -172,8 +179,12 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe // ------------------------------------------------------------------------------------------- read and check - /** GenClass's product for a plan: by its id, else (an earlier run) by a search on its metadata. Null: none yet. */ - async function findProduct(plan, id) { + /** + * GenClass's product for a plan: by its id, else (an earlier run, the plan's main product only: `others` is null for + * a product a price names, billing/plans.json stripe_product) by a search on its metadata, leaving out the products + * the plan's prices name (`others`). Null: none yet. + */ + async function findProduct(plan, id, others = []) { const byId = await stripe("GET", `/v1/products/${id}`, undefined, { missingOk: true }); if (byId) { if (byId.metadata?.genclass_plan !== plan.id) { @@ -181,9 +192,10 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe } return byId; } + if (others === null) return null; // the search returns only products with this metadata: nothing else in the account is read const found = ((await stripe("GET", "/v1/products/search", { query: `metadata['genclass_plan']:'${plan.id}'`, limit: 10 })).data ?? []).filter( - (p) => p.metadata?.genclass_plan === plan.id, + (p) => p.metadata?.genclass_plan === plan.id && !others.includes(p.id), ); if (found.length > 1) fail(`${found.length} products have metadata genclass_plan=${plan.id} (${found.map((p) => p.id).join(", ")}); archive all but one in the Stripe dashboard, then run this again. Nothing was changed.`); return found[0] ?? null; @@ -192,22 +204,37 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe async function readPlans() { const out = []; for (const plan of PLANS.plans.filter((p) => p.price_usd_cents.monthly > 0)) { - const id = `genclass_${plan.id}`; - const product = await findProduct(plan, id); - const prices = []; - for (const [interval, field] of [["month", "monthly"], ["year", "yearly"]]) { - const lookup = plan.stripe_lookup_keys[field]; - const cents = plan.price_usd_cents[field]; - if (!lookup || cents === null || cents === undefined) continue; - if (!lookup.startsWith(LOOKUP_PREFIX)) fail(`billing/plans.json: the lookup key ${lookup} must start with ${LOOKUP_PREFIX}`); - if (!TAX_CODE_RE.test(plan.stripe_tax_code ?? "")) fail(`billing/plans.json: the ${plan.name} plan needs a Stripe product tax code (stripe_tax_code, txcd_ and 8 digits)`); - const [price] = (await stripe("GET", "/v1/prices", { lookup_keys: [lookup], limit: 1 })).data ?? []; - if (price && price.product !== product?.id) { - fail(`the lookup key ${lookup} is on price ${price.id} of product ${price.product}, not on GenClass's product ${product?.id ?? id}; this script does not touch it. Nothing was changed.`); + const main = `genclass_${plan.id}`; + // the plan's own price, then its country prices (billing/plans.json country_prices: Pro is US$15 in Canada); a + // price that names a product (stripe_product) is on that one, the others on the plan's main product, because + // the Billing Portal's seat changes allow one monthly price a product + const groups = new Map(); + for (const entry of [plan, ...(plan.country_prices ?? [])]) { + const id = entry.stripe_product ?? main; + if (!id.startsWith(LOOKUP_PREFIX)) fail(`billing/plans.json: the product id ${id} must start with ${LOOKUP_PREFIX}`); + if (!groups.has(id)) groups.set(id, []); + groups.get(id).push(entry); + } + const named = [...groups.keys()].filter((id) => id !== main); + for (const [id, entries] of groups) { + const product = await findProduct(plan, id, id === main ? named : null); + const prices = []; + for (const entry of entries) { + for (const [interval, field] of [["month", "monthly"], ["year", "yearly"]]) { + const lookup = entry.stripe_lookup_keys?.[field]; + const cents = entry.price_usd_cents?.[field]; + if (!lookup || cents === null || cents === undefined) continue; + if (!lookup.startsWith(LOOKUP_PREFIX)) fail(`billing/plans.json: the lookup key ${lookup} must start with ${LOOKUP_PREFIX}`); + if (!TAX_CODE_RE.test(plan.stripe_tax_code ?? "")) fail(`billing/plans.json: the ${plan.name} plan needs a Stripe product tax code (stripe_tax_code, txcd_ and 8 digits)`); + const [price] = (await stripe("GET", "/v1/prices", { lookup_keys: [lookup], limit: 1 })).data ?? []; + if (price && price.product !== (product?.id ?? id)) { + fail(`the lookup key ${lookup} is on price ${price.id} of product ${price.product}, not on GenClass's product ${product?.id ?? id}; this script does not touch it. Nothing was changed.`); + } + prices.push({ interval, field, lookup, cents, price: price ?? null, label: entry === plan ? "" : ` (${entry.name})` }); + } } - prices.push({ interval, field, lookup, cents, price: price ?? null }); + out.push({ plan, id, product, prices }); } - out.push({ plan, id, product, prices }); } return out; } @@ -258,12 +285,14 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe would(`update product ${name} (${product.id}, tax code ${plan.stripe_tax_code})`); if (!DRY) product = await stripe("POST", `/v1/products/${product.id}`, { ...want, active: true, metadata: { genclass: MARK } }); } else say(`product ${name}: ${product.id}, unchanged`); - result[plan.id] = { product: product.id, planned: !!product.planned, prices: [] }; - for (const { interval, field, lookup, cents, price } of prices) { + // a plan with country prices on their own products has one entry for each product (seatUpdate) + const made = { product: product.id, planned: !!product.planned, prices: [] }; + result[plan.id] = result[plan.id] ? [].concat(result[plan.id], made) : made; + for (const { interval, field, lookup, cents, price, label } of prices) { const same = price && price.active && price.unit_amount === cents && price.currency === PLANS.currency && price.recurring?.interval === interval; if (same) { say(`price ${lookup}: ${price.id}, US$${cents / 100} per ${interval}, unchanged`); - result[plan.id].prices.push(price.id); + made.prices.push(price.id); continue; } if (price) { @@ -280,10 +309,10 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe currency: PLANS.currency, recurring: { interval }, lookup_key: lookup, - nickname: `${plan.name} ${field}`, + nickname: `${plan.name} ${field}${label}`, metadata: { genclass: MARK, genclass_plan: plan.id }, }); - result[plan.id].prices.push(created.id); + made.prices.push(created.id); } } return result; diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index 54577cce..dd9ab533 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -5,7 +5,7 @@ Cloudflare Worker that receives the default-on diagnostics batches from `@gencla a token and a private dashboard on genclass.dev, and that holds the optional accounts (Google, an email and a password, or GitHub, with passkeys as extra security) which keep several apps in one place and let `npx @genclass/runtime@beta login` connect an app ([Accounts](#accounts)). There are three plans (`billing/plans.json` version 5, since 2026-11-13): Free, one app with -its totals, on the website; Pro (plan id `team`), US$15 per developer a month for up to 3 apps, with the genclass +its totals, on the website; Pro (plan id `team`), US$50 per developer a month (US$15 in Canada) for up to 3 apps, with the genclass command, every problem, visitor analytics, forwarding, export, 90 days of history, private repositories for the GitHub App and members ([Teams](#teams)), 3 days free at the first Checkout; and Enterprise, by agreement, with more apps and your own classifier, which GenClass trains ([Paid plans](#paid-plans)). What was bought before 13 November @@ -534,9 +534,26 @@ npx --yes wrangler@4 d1 execute genclass-dashboard --remote --command " ## Paid plans +**Prices by country (2026-11-16, the owner's call).** Pro is US$50 a developer a month everywhere but Canada, where +it stays US$15. `billing/plans.json` gives Pro its own price (US$50, lookup key `genclass_team_world_monthly`, on the +Stripe product `genclass_team_world`, named by `stripe_product`) and `country_prices` (Canada: US$15 under +`genclass_team_monthly`, the key Pro was sold under before, on the product `genclass_team`). Checkout sells the price +of the country Cloudflare reports for the request (`request.cf.country`; `src/plans.ts` countryOf, priceFor) and +records it on the session (metadata `genclass_price`); an open Checkout page for another price, or one made before this +change, is closed and a new one made. A request with no country gets the plan's own price. The billing pages, the +plan pages and the genclass command's answers show the visitor's price; a message read later (the report email, the +seats message) says both ("$50 / developer / month ($15 in Canada)"). Every subscription keeps the price it was bought +at: the live subscription on `genclass_team_monthly` stays at US$15 wherever its buyer is. Both products are named +GenClass Pro with metadata `genclass_plan` team, because Stripe's Billing Portal allows one monthly price per product +for seat changes; the portal configuration lists each product with its own price. The country is the visitor's IP +address as Cloudflare sees it, so a VPN in Canada gets the Canadian price; nothing checks the card's country. +Promotion codes are typed on Stripe's Checkout page (`allow_promotion_codes`): `EFLAUNCH` (coupon "EF launch", 20% off +for as long as the subscription lasts, both Pro products, new customers only) was made in the live account on +2026-11-16. + **Version 5 (2026-11-13, the owner's calls; what follows below is the history it replaces where they differ).** Pro (id `team`) is bought for the account again, not per app, and per developer: `per_seat` true, the -subscription's quantity is how many developers (US$15 each a month), and it covers up to 3 apps (`limits.apps`) +subscription's quantity is how many developers (US$15 each a month then; see Prices by country below), and it covers up to 3 apps (`limits.apps`) whatever the number of developers, oldest first (`src/plans.ts` coverage, accessIn). An app past them is locked `pro_apps`: its plan page says more apps come with Enterprise, by email (a mailto button, no purchase). A subscription bought per project under version 4 still covers its own app (never locked) and gives the account diff --git a/telemetry-worker/src/auth.ts b/telemetry-worker/src/auth.ts index b341bb7f..18f39964 100644 --- a/telemetry-worker/src/auth.ts +++ b/telemetry-worker/src/auth.ts @@ -82,7 +82,7 @@ import { forgetAccount as forgetAccountGithub, unlinkProject } from "./github/st import { json, mediaType, readCapped } from "./http.js"; import { dashboardPage, ownEndpoint, securityHeaders, setupCommand } from "./pages.js"; import { DEVICE_FAILURES, DEVICE_MS, DUMMY_HASH, FAILURE_WINDOW_MS, FREE_FAILURES, MAX_DELAY_MS, PASSWORD_MAX, delayAfter, hashPassword, needsRehash, passwordProblem, verifyPassword, waitText } from "./password.js"; -import { accountAccess, accountBilling, canBuy, firstPlanWith, planParam, FREE, hasAnalytics, hasDashboard, hasProblems, keepDays, PAID_PLANS, pickRange, pitchLines, PLANS_FILE, priceText, problemsLock, projectAccess, viewRanges } from "./plans.js"; +import { accountAccess, accountBilling, canBuy, countryOf, firstPlanWith, planParam, FREE, hasAnalytics, hasDashboard, hasProblems, keepDays, PAID_PLANS, pickRange, pitchLines, PLANS_FILE, priceText, problemsLock, projectAccess, viewRanges } from "./plans.js"; import { trialFor } from "./billing.js"; import { activeOwners, appHome, forgetTeam, membershipsOf } from "./team.js"; import { cancelForDeletion } from "./stripe.js"; @@ -1987,7 +1987,7 @@ export async function routeAuth(request: Request, url: URL, path: string, env: E if (!view.projects.length && sold && canBuy(env, a.account) && (await accountAccess(c.db, a.account.id, env, c.now)).source === null) { view.trial = { plan: sold.name, - price: priceText(sold), + price: priceText(sold, countryOf(c.req)), days: (await trialFor(c.db, a.account.id, sold)) || null, features: pitchLines(sold), start: `/account/billing?plan=${encodeURIComponent(planParam(sold))}&start=1`, @@ -2111,7 +2111,7 @@ export async function routeAuth(request: Request, url: URL, path: string, env: E // visitor analytics are left out for a plan without them, and counted all the same (src/dashboard.ts stripAnalytics) const planUrl = `${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}`; const shown = hasAnalytics(access) ? s : stripAnalytics(s, { plan: firstPlanWith("analytics")?.name ?? null, upgrade_url: `${c.cfg.origin}/account/billing` }); - return json(200, { ...(hasProblems(access) ? shown : stripProblems(shown, problemsLock(planUrl))), usage, plan: { id: access.plan.id, name: access.plan.name, source: access.source }, plan_url: `${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}` }); + return json(200, { ...(hasProblems(access) ? shown : stripProblems(shown, problemsLock(planUrl, countryOf(c.req)))), usage, plan: { id: access.plan.id, name: access.plan.name, source: access.source }, plan_url: `${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}` }); } const fun = /^\/api\/account\/projects\/([^/]+)\/funnels$/.exec(path); if (fun) { diff --git a/telemetry-worker/src/billing-pages.ts b/telemetry-worker/src/billing-pages.ts index d57d1129..54979f57 100644 --- a/telemetry-worker/src/billing-pages.ts +++ b/telemetry-worker/src/billing-pages.ts @@ -30,6 +30,8 @@ import { PLANS_FILE, pitchLines, planById, + dollars, + priceFor, priceText, viewRanges, type Access, @@ -66,6 +68,8 @@ export interface BillingView { live: boolean; /** The key is a Stripe test key: no real money moves. */ testMode: boolean; + /** The visitor's country (src/plans.ts countryOf): the prices shown are its (priceFor); null or left out: the plan's own. */ + country?: string | null; /** Back from Stripe Checkout (?done=1). */ done: boolean; /** The plan chosen on the pricing page (?plan=). */ @@ -162,14 +166,14 @@ function statusLine(v: BillingView, plan: Plan): string { return `You are on the ${name} plan until ${day(b.current_period_end)}. It is cancelled and will not renew; you can resume it in Manage billing before then.`; } if (b.subscription_status === "trialing") { - return `You are on the ${name} plan, in a trial until ${day(b.current_period_end)}. When it ends your card is charged for the first month (${esc(priceText(plan))}). Cancel in Manage billing before then and nothing is charged; ${esc(plan.name)} then ends at once.`; + return `You are on the ${name} plan, in a trial until ${day(b.current_period_end)}. When it ends your card is charged for the first month (${esc(priceText(plan, v.country ?? null))}). Cancel in Manage billing before then and nothing is charged; ${esc(plan.name)} then ends at once.`; } if (plan.per_seat === true && v.access.seats !== null) { const n = v.access.seats; - const total = (plan.price_usd_cents.monthly ?? 0) * n; - return `You are on the ${name} plan with ${n} seat${n === 1 ? "" : "s"}, ${esc(priceText(plan))} ($${total % 100 ? (total / 100).toFixed(2) : String(total / 100)} a month). It renews on ${day(b.current_period_end)}. Add or remove seats in Manage billing.`; + const total = (priceFor(plan, v.country ?? null).price_usd_cents.monthly ?? 0) * n; + return `You are on the ${name} plan with ${n} seat${n === 1 ? "" : "s"}, ${esc(priceText(plan, v.country ?? null))} (${dollars(total)} a month). It renews on ${day(b.current_period_end)}. Add or remove seats in Manage billing.`; } - return `You are on the ${name} plan, ${esc(priceText(plan))}. It renews on ${day(b.current_period_end)}.`; + return `You are on the ${name} plan, ${esc(priceText(plan, v.country ?? null))}. It renews on ${day(b.current_period_end)}.`; } function planColumn(v: BillingView, p: Plan, current: Plan): string { @@ -206,7 +210,7 @@ function planColumn(v: BillingView, p: Plan, current: Plan): string { .join(""); const more = p.features.length - PITCH_SHOWN; const fold = more > 0 ? `
${more} more
` : ""; - return `

${esc(p.name)}

${esc(priceText(p))}

${esc(p.summary)}

    ${features}
${fold}
${act}
`; + return `

${esc(p.name)}

${esc(priceText(p, v.country ?? null))}

${esc(p.summary)}

    ${features}
${fold}
${act}
`; } /** The account's projects, each with its plan and the way to change it (its own page). */ @@ -226,7 +230,7 @@ function projectsSection(v: BillingView): string { .join(""); return `

Apps

What your plan covers
-

Free covers ${FREE_APPS === 1 ? "one app" : `${FREE_APPS} apps`}${PAID_PLANS[0] ? `; ${esc(PAID_PLANS[0].name)} covers ${PAID_PLANS[0].limits.apps ? `up to ${PAID_PLANS[0].limits.apps} apps` : "every app"}, ${esc(priceText(PAID_PLANS[0]))}` : ""}. More apps come with Enterprise.

+

Free covers ${FREE_APPS === 1 ? "one app" : `${FREE_APPS} apps`}${PAID_PLANS[0] ? `; ${esc(PAID_PLANS[0].name)} covers ${PAID_PLANS[0].limits.apps ? `up to ${PAID_PLANS[0].limits.apps} apps` : "every app"}, ${esc(priceText(PAID_PLANS[0], v.country ?? null))}` : ""}. More apps come with Enterprise.

${rows}
ProjectPlan
`; } @@ -256,6 +260,8 @@ export interface ProjectPlanView { trialDays?: number; live: boolean; testMode: boolean; + /** The visitor's country (src/plans.ts countryOf): the prices shown are its (priceFor); null or left out: the plan's own. */ + country?: string | null; /** Back from Stripe Checkout (?done=1). */ done: boolean; /** Open the checkout at once (?start=1, from the genclass command). */ @@ -317,10 +323,10 @@ export function projectPlanPage(nonce: string, v: ProjectPlanView): string { : proFull ? `Email us about Enterprise

Or remove an app you no longer use, and this one takes its place.

` : v.live - ? `${v.trialDays ? `

${v.trialDays} days free, then ${esc(priceText(offer!))}. Cancel before the trial ends and you pay nothing.

` : ""}` + ? `${v.trialDays ? `

${v.trialDays} days free, then ${esc(priceText(offer!, v.country ?? null))}. Cancel before the trial ends and you pay nothing.

` : ""}` : 'Paid plans are not on sale yet.'; const card = offer && a.source !== "open" - ? `

${esc(offer.name)}${covered ? ' Your plan' : ""}

${esc(priceText(offer))}

${features} + ? `

${esc(offer.name)}${covered ? ' Your plan' : ""}

${esc(priceText(offer, v.country ?? null))}

${features}
${action}
${a.locked || a.source !== null ? "" : `

Skip

diff --git a/telemetry-worker/src/billing.ts b/telemetry-worker/src/billing.ts index 21ee3184..c241b96a 100644 --- a/telemetry-worker/src/billing.ts +++ b/telemetry-worker/src/billing.ts @@ -43,6 +43,7 @@ import { accountPlan, canBuy, cleanSeats, + countryOf, entitled, MAX_SEATS, FREE, @@ -247,6 +248,7 @@ export async function routeBilling(request: Request, url: URL, path: string, env trialDays, live: canBuy(env, a.account), testMode: stripeMode(env) === "test", + country: countryOf(c.req), done: url.searchParams.get("done") === "1", go: start, fromCli, @@ -294,6 +296,7 @@ export async function routeBilling(request: Request, url: URL, path: string, env access, live: canBuy(env, a.account), testMode: stripeMode(env) === "test", + country: countryOf(c.req), done: url.searchParams.get("done") === "1", picked: picked?.id ?? null, go, @@ -467,13 +470,13 @@ async function checkout(c: C, f: Fetch): Promise { if (await foreignInvoice(c.env, f, customer.id, subs)) return refuseShared(c, f, account.id, customer.id, SHARED_INVOICE); // once the new subscription's first payment clears, the webhook refunds `held`'s unused time to its card and // cancels it; until then it stays - const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, switchFrom: held.id, seats }); + const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, switchFrom: held.id, seats, country: countryOf(c.req) }); return json(200, { url, switch: true }); } } // the first subscription starts with the plan's trial (trialFor), once per account const trialDays = customer.fresh || first ? await trialFor(c.db, a.account.id, plan, 0) : 0; - const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, fresh: customer.fresh, seats, trialDays, backTo, ...(next ? { next } : {}) }); + const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, fresh: customer.fresh, seats, trialDays, backTo, country: countryOf(c.req), ...(next ? { next } : {}) }); return json(200, { url, trial_days: trialDays || null }); } catch (e) { return stripeFail(e); @@ -572,7 +575,7 @@ async function checkoutProject(c: C, f: Fetch, a: Auth, plan: Plan, projectId: s // account has had one (trialFor), or another project's open Checkout already holds it const elsewhere = customer.fresh ? false : await openTrialElsewhere(c.env, f, customer.id, a.account.id, p.id).catch(() => true); const trialDays = elsewhere ? 0 : await trialFor(c.db, a.account.id, plan, first ? 0 : 1); - const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, fresh: customer.fresh, project: { id: p.id }, trialDays }); + const url = await checkoutSession(c.env, f, { account, customer: customer.id, plan, origin: c.cfg.origin, now: c.now, fresh: customer.fresh, project: { id: p.id }, trialDays, country: countryOf(c.req) }); return json(200, { url, trial_days: trialDays || null }); } catch (e) { return stripeFail(e); diff --git a/telemetry-worker/src/cli.ts b/telemetry-worker/src/cli.ts index b3b54fed..235f7174 100644 --- a/telemetry-worker/src/cli.ts +++ b/telemetry-worker/src/cli.ts @@ -55,7 +55,7 @@ import { isKind, KINDS } from "./forward.js"; import { githubApp } from "./github/config.js"; import { repoStatusForAccount } from "./github/http.js"; import { json } from "./http.js"; -import { accountAccess, accountBilling, accountProjectsAccess, appsCovered, better, planParam, canBuy, entitled, firstPaidWith, firstPlanWith, FREE, hasAnalytics, hasAsk, hasDashboard, hasProblems, PAID_PLANS, pickRange, priceText, problemsLock, projectAccess, viewRanges, type Access } from "./plans.js"; +import { accountAccess, accountBilling, accountProjectsAccess, appsCovered, better, planParam, canBuy, countryOf, entitled, firstPaidWith, firstPlanWith, FREE, hasAnalytics, hasAsk, hasDashboard, hasProblems, PAID_PLANS, pickRange, priceText, problemsLock, projectAccess, viewRanges, type Access } from "./plans.js"; import { liveFixUsage } from "./usage.js"; import { appKey, askModel, byWeight, claimRun, hasModel, keepAnswer, lastAnswer, MAX_SUGGEST_BYTES, readDigest, suggestionLimits, usedToday, type PlanItem, type SuggestAnswer } from "./suggest.js"; import { activeOwners, createInvite, isTeamError, membershipsOf, teamOf } from "./team.js"; @@ -132,7 +132,7 @@ async function cliJson(c: C, a: Auth): Promise<{ paid: true; via: "plan" | "team const via = await cliVia(c, a); if (via !== null) return { paid: true, via }; const plan = PAID_PLANS[0]!; - return { paid: false, plan: plan.name, price: priceText(plan), trial_days: (await trialFor(c.db, a.account.id, plan)) || null, checkout_url: `${c.cfg.origin}/account/billing?plan=${planParam(plan)}&start=1` }; + return { paid: false, plan: plan.name, price: priceText(plan, countryOf(c.req)), trial_days: (await trialFor(c.db, a.account.id, plan)) || null, checkout_url: `${c.cfg.origin}/account/billing?plan=${planParam(plan)}&start=1` }; } /** The routes that are Pro's for a CLI session: all but the overview and the account. */ @@ -191,7 +191,7 @@ async function offerFor(c: C, account: { id: string; email: string | null }, acc const trialDays = (await trialFor(c.db, account.id, plan)) || null; return { plan: { id: plan.id, name: plan.name }, - price: priceText(plan), + price: priceText(plan, countryOf(c.req)), summary: plan.summary, // the plan's own "N days free" line only while the account still has the trial features: plan.features.filter((f) => f.available && !/^Everything in /i.test(f.text) && (trialDays || !/days free/i.test(f.text))).map((f) => f.text).slice(0, 12), @@ -236,7 +236,7 @@ async function app(c: C): Promise { const planUrl = `${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}`; const seen = hasAnalytics(access) ? s : stripAnalytics(s, { plan: firstPlanWith("analytics")?.name ?? null, upgrade_url: `${c.cfg.origin}/account/billing` }); // Free sees the totals only: the problems, pages, activity and fix prompts come with Pro (the browser's rule too) - const view = hasProblems(access) ? seen : stripProblems(seen, problemsLock(planUrl)); + const view = hasProblems(access) ? seen : stripProblems(seen, problemsLock(planUrl, countryOf(c.req))); const usage = await liveFixUsage(c.db, p.token, access.plan, c.now).catch(() => null); return json(200, { ...view, recent: view.recent.slice(0, APP_RECENT), dashboard_url: projectJson(c, p).dashboard_url, usage, plan: { id: access.plan.id, name: access.plan.name, source: access.source }, plan_url: `${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}` }); } @@ -298,7 +298,7 @@ async function suggest(c: C): Promise { // the answer was kept from an earlier run (Free sees it again; a plan out of runs for the day sees its last) cached_at: created, upgrade_url: locked.length || hidden || limited ? `${c.cfg.origin}/account/billing?plan=${planParam(pro ?? PAID_PLANS[0]!)}&from=cli` : null, - upgrade_plan: pro ? { name: pro.name, price: priceText(pro), trial_days: pro.trial_days ?? null } : null, + upgrade_plan: pro ? { name: pro.name, price: priceText(pro, countryOf(c.req)), trial_days: pro.trial_days ?? null } : null, remaining_today: used === null ? Math.max(0, lim.per_day - (await usedToday(c.db, a.account.id, c.now))) : Math.max(0, lim.per_day - used), limited, }); @@ -340,7 +340,7 @@ async function account(c: C): Promise { const apps = await accountProjects(c, a.account.id); return json(200, { account: accountJson(a.account), - plan: { id: access.plan.id, name: access.plan.name, price: access.plan.id === FREE.id ? null : priceText(access.plan), summary: access.plan.summary }, + plan: { id: access.plan.id, name: access.plan.name, price: access.plan.id === FREE.id ? null : priceText(access.plan, countryOf(c.req)), summary: access.plan.summary }, // why the account has its plan now: "paid", "comp" (GenClass's own grant), "open" (this server's PLAN_GATES), or null on Free access: access.source, // the plan the account works under through a team when it is better than its own (workingAccess), else null: @@ -428,7 +428,7 @@ async function ask(c: C, f: Fetch): Promise { if (!hasDashboard(access)) return lockedJson(c, access, p.id); // asking about the app comes with Pro (plans.json entitlement `ask`): Free is told which plan, and where if (!hasAsk(access)) { - const lock = problemsLock(`${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}`); + const lock = problemsLock(`${c.cfg.origin}/account/billing?project=${encodeURIComponent(p.id ?? "")}`, countryOf(c.req)); return json(403, { ok: false, error: `asking about your app comes with ${lock.plan ?? "a paid plan"}`, locked: true, needs_plan: true, plan: lock.plan, upgrade_url: lock.upgrade_url, trial_days: lock.trial_days, price: lock.price }); } // the runs a day are the asker's, under the plan it works under (its team's for a member: workingAccess) diff --git a/telemetry-worker/src/collector.ts b/telemetry-worker/src/collector.ts index de654483..d35f8879 100644 --- a/telemetry-worker/src/collector.ts +++ b/telemetry-worker/src/collector.ts @@ -60,7 +60,7 @@ import { afterBatch } from "./paid.js"; import { dashboardPage, notFoundPage, openSourcePage, ownEndpoint, securityHeaders, setupCommand, setupPage, startPage } from "./pages.js"; import { lockedLink } from "./locked.js"; import { applyLock, linkSession, linkUnlocked, lockKind, lockedJson, readBody, readLock, routeLink, startPasskeyOptions, unlockPage } from "./link-lock.js"; -import { firstPlanWith, hasAnalytics, hasDashboard, hasProblems, pickRange, problemsLock, projectAccess, viewRanges } from "./plans.js"; +import { countryOf, firstPlanWith, hasAnalytics, hasDashboard, hasProblems, pickRange, problemsLock, projectAccess, viewRanges } from "./plans.js"; import { SAMPLE_PROJECT, SAMPLE_SECRET, sampleStats } from "./sample.js"; export const SCHEMA = "genclass-telemetry/1"; @@ -533,7 +533,7 @@ async function routeSite(request: Request, url: URL, path: string, env: Env, opt const s = await stats(env.DB, p, range, now); const seen = hasAnalytics(access) ? s : stripAnalytics(s, { plan: firstPlanWith("analytics")?.name ?? null, upgrade_url: upgradeUrl(env) }); // a private link's app has no account, so Free's rule: the totals only, and the way to an account with Pro - return json(200, hasProblems(access) ? seen : stripProblems(seen, problemsLock(upgradeUrl(env)))); + return json(200, hasProblems(access) ? seen : stripProblems(seen, problemsLock(upgradeUrl(env), countryOf(request)))); } if (path === "/start") { diff --git a/telemetry-worker/src/plans.ts b/telemetry-worker/src/plans.ts index 582cd459..d2003d3f 100644 --- a/telemetry-worker/src/plans.ts +++ b/telemetry-worker/src/plans.ts @@ -6,7 +6,7 @@ // price, a limit or an entitlement there, not here. Every check below reads the plan's entitlements and limits, so // nothing here names a plan but Free and the grant's (plans.json grant_plan). // - Since plans.json version 3 (2026-11-11) there are three plans. Free is what finds, shows and fixes the problems: the -// dashboard's problems for one person, 3 apps and the last 7 days shown. Team (US$15 a month per seat, sold on Stripe +// dashboard's problems for one person, 3 apps and the last 7 days shown. Team (US$15 a month per seat then, sold on Stripe // Checkout) adds visitor analytics, forwarding, export, 90 days shown, private repositories for the GitHub App and // members (src/team.ts). Enterprise (by agreement) adds the classifier a person trains (custom_model) and a year. // Individual, US$29 a month, ended on 2026-10-22: a stored "individual" reads as Free, while its Stripe prices stay @@ -21,6 +21,10 @@ // - A plan comes from accounts.plan, which src/stripe.ts derives from the Stripe subscription. Entitlements follow the // plan whatever the server's configuration, except that a plan bought in Stripe's test mode counts only while the // key is a test key (inMode): a test purchase never carries over to live. A live plan always counts. +// - Prices by country (2026-11-16): a plan's price_usd_cents and stripe_lookup_keys are what it costs everywhere but +// the countries its country_prices list (Pro: US$50 a developer a month, US$15 in Canada). Checkout sells the price +// of the country Cloudflare reports for the request (countryOf, priceFor); the screens show it (priceText). Every +// lookup key of a plan, its own or a country's, gives the plan (planByLookupKey), and a subscription keeps its price. // - A plan with a null monthly price (Enterprise) is not sold on the site: it is agreed by email, and an account gets // it from GenClass's own grant (accounts.comp_until, set by hand to the end of the agreement), which gives the plan // accounts.comp_plan names (plans.json grant_plan when it is empty or unknown). When an account has both a paid plan @@ -66,6 +70,13 @@ export interface Plan { /** US cents; monthly null: not sold on the site, agreed by email (byAgreement). */ price_usd_cents: { monthly: number | null; yearly: number | null }; stripe_lookup_keys: { monthly: string | null; yearly: string | null }; + /** + * Prices in some countries instead of the plan's own (2026-11-16: Pro is US$15 in Canada, US$50 elsewhere): Checkout + * sells the price of the country the request comes from (priceFor); every lookup key here gives the plan. + */ + country_prices?: CountryPrice[]; + /** The Stripe product the plan's own price is on (scripts/stripe-setup.mjs); left out: genclass_. */ + stripe_product?: string; /** The Stripe product tax code scripts/stripe-setup.mjs sets on the plan's product (null for Free). */ stripe_tax_code: string | null; /** Sold through Stripe Managed Payments (src/stripe.ts managedPayments): none today. */ @@ -93,6 +104,20 @@ export interface Plan { features: { text: string; available: boolean }[]; } +/** A plan's price in some countries (plans.json country_prices): ISO 3166-1 alpha-2 codes, as Cloudflare reports them. */ +export interface CountryPrice { + countries: string[]; + /** The countries in words, for "($15 in Canada)". */ + name: string; + price_usd_cents: { monthly: number | null; yearly: number | null }; + stripe_lookup_keys: { monthly: string | null; yearly: string | null }; + /** The Stripe product this price is on (scripts/stripe-setup.mjs); left out: the plan's genclass_. */ + stripe_product?: string; +} + +/** A price as plans.json writes one: a plan's own, or one of its country prices. */ +export type PlanPrice = Pick; + export interface PlansFile { version: number; currency: string; @@ -125,10 +150,32 @@ export const RETIRED_PLAN_IDS: readonly string[] = Array.isArray(PLANS_FILE.reti /** Every GenClass lookup key starts with this: plans.json's, and those of prices scripts/stripe-setup.mjs retired. */ export const LOOKUP_PREFIX = "genclass_"; -/** The plan a lookup_key from billing/plans.json sells (monthly or yearly), or null for any other key. */ +/** Every price a plan has: its own, then its country prices (plans.json country_prices). */ +export const planPrices = (plan: Plan): PlanPrice[] => [plan, ...(plan.country_prices ?? [])]; + +/** The plan a lookup_key from billing/plans.json sells (monthly or yearly, its own price or a country's), or null for any other key. */ export function planByLookupKey(key: unknown): Plan | null { if (typeof key !== "string" || !key) return null; - return PLANS.find((p) => p.stripe_lookup_keys.monthly === key || p.stripe_lookup_keys.yearly === key) ?? null; + return PLANS.find((p) => planPrices(p).some((x) => x.stripe_lookup_keys.monthly === key || x.stripe_lookup_keys.yearly === key)) ?? null; +} + +/** + * The visitor's country as Cloudflare reports it on the request (request.cf.country, ISO 3166-1 alpha-2, upper case), + * or null when there is none (a test, a local run). Tor's "T1" and an unknown "XX" are countries with no price of their own. + */ +export function countryOf(req: Request | null | undefined): string | null { + const cf = (req as { cf?: { country?: unknown } } | null | undefined)?.cf; + const c = typeof cf?.country === "string" ? cf.country.toUpperCase() : ""; + return /^[A-Z][A-Z0-9]$/.test(c) ? c : null; +} + +/** + * What a plan costs in this country: the country price that lists it (plans.json country_prices), else the plan's own + * (also when the country is not known). Checkout sells its lookup key; the screens show its price. + */ +export function priceFor(plan: Plan, country: string | null | undefined): PlanPrice { + const c = (country ?? "").toUpperCase(); + return (c && plan.country_prices?.find((x) => x.countries.includes(c))) || plan; } /** The paid plan named by a Stripe product's (or price's) metadata.genclass_plan (scripts/stripe-setup.mjs sets it). */ @@ -196,12 +243,23 @@ export function canBuy(env: Env, account: { id: string; email: string | null }): return list.some((x) => x === account.id || (!!email && x.toLowerCase() === email)); } -/** "$29 / month", "$15 / developer / month" (a per_seat plan), "$0", or "By agreement" for a plan agreed by email. */ -export function priceText(plan: Plan): string { - const c = plan.price_usd_cents.monthly; +/** US cents as dollars: "$50", "$12.50". */ +export const dollars = (cents: number): string => `$${cents % 100 ? (cents / 100).toFixed(2) : String(cents / 100)}`; + +/** + * "$29 / month", "$50 / developer / month" (a per_seat plan), "$0", or "By agreement" for a plan agreed by email, in + * the visitor's country (priceFor). `country` left out: the reader's country is not known (an email, a message read + * later), so a plan with country prices names them too: "$50 / developer / month ($15 in Canada)". null: the request + * had no country, so the plan's own price. + */ +export function priceText(plan: Plan, country?: string | null): string { + const unit = (c: number): string => `${dollars(c)}${plan.per_project === true ? " / project" : plan.per_seat === true ? " / developer" : ""} / month`; + const c = priceFor(plan, country).price_usd_cents.monthly; if (c === null) return "By agreement"; if (!c) return "$0"; - return `$${c % 100 ? (c / 100).toFixed(2) : String(c / 100)}${plan.per_project === true ? " / project" : plan.per_seat === true ? " / developer" : ""} / month`; + if (country !== undefined) return unit(c); + const others = (plan.country_prices ?? []).filter((x) => (x.price_usd_cents.monthly ?? 0) > 0).map((x) => `${dollars(x.price_usd_cents.monthly!)} in ${x.name}`); + return others.length ? `${unit(c)} (${others.join(", ")})` : unit(c); } /** @@ -436,9 +494,9 @@ export const hasProblems = (a: Access): boolean => a.plan.entitlements.problems /** genclass ask; a plan file without the key gives it. */ export const hasAsk = (a: Access): boolean => a.plan.entitlements.ask !== false; /** What a stats answer says when the problems are left out: the plan that shows them, its trial, and where to start it. */ -export const problemsLock = (upgradeUrl: string): { plan: string | null; upgrade_url: string; trial_days: number | null; price: string | null } => { +export const problemsLock = (upgradeUrl: string, country?: string | null): { plan: string | null; upgrade_url: string; trial_days: number | null; price: string | null } => { const p = firstPaidWith("problems"); - return { plan: p?.name ?? null, upgrade_url: upgradeUrl, trial_days: p?.trial_days ?? null, price: p ? priceText(p) : null }; + return { plan: p?.name ?? null, upgrade_url: upgradeUrl, trial_days: p?.trial_days ?? null, price: p ? priceText(p, country) : null }; }; /** The first plan on sale with an entitlement a plan file can leave out (problems, ask): for "comes with Pro". */ export const firstPaidWith = (e: "problems" | "ask"): Plan | null => PAID_PLANS.find((p) => p.entitlements[e] !== false) ?? null; diff --git a/telemetry-worker/src/stripe.ts b/telemetry-worker/src/stripe.ts index cd275f50..f0ac97b6 100644 --- a/telemetry-worker/src/stripe.ts +++ b/telemetry-worker/src/stripe.ts @@ -76,7 +76,7 @@ import type { Env } from "./collector.js"; import { randomBase62, sha256Hex, type D1Like } from "./dashboard.js"; import { json } from "./http.js"; -import { byQuantity, cleanSeats, entitled, LIVE_STATUSES, LOOKUP_PREFIX, MAX_SEATS, ownedPrice, pastDueLapsed, planById, PLANS, PLANS_FILE, planForPrice, stripeMode, type Billing, type Plan, type PlanId } from "./plans.js"; +import { byQuantity, cleanSeats, entitled, LIVE_STATUSES, LOOKUP_PREFIX, MAX_SEATS, ownedPrice, pastDueLapsed, planById, PLANS, PLANS_FILE, planForPrice, priceFor, stripeMode, type Billing, type Plan, type PlanId } from "./plans.js"; import { equalStrings } from "./webauthn.js"; export const STRIPE_API = "https://api.stripe.com"; @@ -406,11 +406,12 @@ export function managedPayments(env: Env, plan: Plan): boolean { export async function checkoutSession( env: Env, f: Fetch, - o: { account: BillingAccount; customer: string; plan: Plan; origin: string; now: Date; fresh?: boolean; switchFrom?: string; seats?: number; project?: { id: string }; trialDays?: number; backTo?: string; next?: string }, + o: { account: BillingAccount; customer: string; plan: Plan; origin: string; now: Date; fresh?: boolean; switchFrom?: string; seats?: number; project?: { id: string }; trialDays?: number; backTo?: string; next?: string; country?: string | null }, ): Promise { // free days only on a first subscription (the caller decides), never on a switch, and only what Stripe allows (1 to 730) const trialDays = !o.switchFrom && Number.isInteger(o.trialDays) && o.trialDays! >= 1 && o.trialDays! <= 730 ? o.trialDays! : 0; - const lookup = o.plan.stripe_lookup_keys.monthly; + // the price of the buyer's country (plans.json country_prices: Pro is US$15 in Canada), else the plan's own + const lookup = priceFor(o.plan, o.country).stripe_lookup_keys.monthly; if (!lookup) throw new StripeError(`the ${o.plan.name} plan has no monthly price`, 400); // a plan sold per seat: the quantity is the seats asked for, and the buyer can still change it on Stripe's page const perSeat = byQuantity(o.plan); @@ -425,6 +426,8 @@ export async function checkoutSession( if ((x.metadata?.genclass_project ?? undefined) !== o.project?.id) continue; const same = x.metadata?.genclass_plan === o.plan.id && + // a page for another country's price is closed, and so is one made before prices by country (no genclass_price) + x.metadata?.genclass_price === lookup && (x.metadata?.genclass_switch_from ?? undefined) === o.switchFrom && x.metadata?.genclass_trial !== "1" && (x.metadata?.genclass_trial_days ?? "0") === String(trialDays) && @@ -465,7 +468,7 @@ export async function checkoutSession( // back from a switch, the page waits for the new plan success_url: backId ? `${back}&done=1` : `${o.origin}/account/billing?done=1${o.switchFrom ? `&to=${o.plan.id}` : ""}${next ? `&next=${encodeURIComponent(next)}` : ""}`, cancel_url: next ? `${o.origin}${next}` : back, - metadata: { ...mark, genclass_plan: o.plan.id, ...(next ? { genclass_next: next } : {}), ...(perSeat ? { genclass_seats: String(seats) } : {}), ...(trialDays ? { genclass_trial_days: String(trialDays) } : {}) }, + metadata: { ...mark, genclass_plan: o.plan.id, genclass_price: lookup, ...(next ? { genclass_next: next } : {}), ...(perSeat ? { genclass_seats: String(seats) } : {}), ...(trialDays ? { genclass_trial_days: String(trialDays) } : {}) }, // a card (or another payment method) up front payment_method_collection: "always", // the "Add promotion code" field: codes made in the Stripe dashboard (Product catalog, Coupons) for GenClass's prices @@ -473,7 +476,7 @@ export async function checkoutSession( subscription_data: { metadata: mark, billing_mode: { type: "flexible" }, ...(trialDays ? { trial_period_days: trialDays } : {}) }, managed_payments: managedPayments(env, o.plan) ? { enabled: true } : undefined, }, - `genclass-checkout-${o.account.id}${o.project ? `-p-${o.project.id}` : ""}-${o.plan.id}${perSeat ? `-x${seats}` : ""}-${Math.floor(o.now.getTime() / 60_000)}${from}${after}${trialDays ? `-t${trialDays}` : ""}`, + `genclass-checkout-${o.account.id}${o.project ? `-p-${o.project.id}` : ""}-${o.plan.id}${lookup !== o.plan.stripe_lookup_keys.monthly ? `-k-${lookup}` : ""}${perSeat ? `-x${seats}` : ""}-${Math.floor(o.now.getTime() / 60_000)}${from}${after}${trialDays ? `-t${trialDays}` : ""}`, ); } catch (e) { priceCache.delete(lookup); // the cached price may have been replaced since diff --git a/telemetry-worker/test/account-helpers.ts b/telemetry-worker/test/account-helpers.ts index d9d9ddea..588e175d 100644 --- a/telemetry-worker/test/account-helpers.ts +++ b/telemetry-worker/test/account-helpers.ts @@ -54,6 +54,8 @@ export interface CallOpts { fetch?: Fetch; /** The pause the handler asks for before a second try (default: no wait at all). */ wait?: (ms: number) => Promise; + /** The visitor's country, as Cloudflare puts it on the request (request.cf.country); left out: none. */ + country?: string; } export async function call(env: Env, method: string, path: string, o: CallOpts = {}): Promise { @@ -64,7 +66,9 @@ export async function call(env: Env, method: string, path: string, o: CallOpts = if (o.cookie) headers.cookie = o.cookie; if (o.bearer) headers.authorization = `Bearer ${o.bearer}`; const body = o.body === undefined ? undefined : typeof o.body === "string" ? o.body : JSON.stringify(o.body); - return handle(new Request(`${ORIGIN}${path}`, { method, headers, body }), env, { now: () => clock, fetch: o.fetch, wait: o.wait ?? (async () => undefined) }); + const req = new Request(`${ORIGIN}${path}`, { method, headers, body }); + if (o.country) Object.defineProperty(req, "cf", { value: { country: o.country } }); + return handle(req, env, { now: () => clock, fetch: o.fetch, wait: o.wait ?? (async () => undefined) }); } /** The password the helper accounts sign up with. */ @@ -360,12 +364,13 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon return { fetch, calls, other, customers, subs, sessions, invoices, refunds, charges, paymentIntents, portal, genclassCustomer }; } -/** The GenClass prices the fake Stripe knows by lookup key: the fixture's (Pro, Custom), the retired Individual and the real plans' Team. */ +/** The GenClass prices the fake Stripe knows by lookup key: the fixture's (Pro, Custom), the retired Individual and the real plans' Pro (Canada's price and everyone else's). */ const KNOWN_PRICES: Record = { genclass_pro_monthly: { plan: "pro", id: "price_pro000001" }, genclass_custom_monthly: { plan: "custom", id: "price_custom0001" }, genclass_individual_monthly: { plan: "individual", id: "price_indiv00001" }, genclass_team_monthly: { plan: "team", id: "price_team000001" }, + genclass_team_world_monthly: { plan: "team", id: "price_teamworld1" }, }; /** A price as a subscription fetched with its products expanded shows it: GenClass's carry product metadata genclass_plan. */ diff --git a/telemetry-worker/test/cli-account.test.ts b/telemetry-worker/test/cli-account.test.ts index 050ca3a8..c8d788b3 100644 --- a/telemetry-worker/test/cli-account.test.ts +++ b/telemetry-worker/test/cli-account.test.ts @@ -118,7 +118,7 @@ describe("genclass command: GET /api/cli/account and POST /api/cli/team/invite", // nothing of how the account signs in or pays expect(JSON.stringify(j)).not.toMatch(/stripe|customer|password|passkey/i); // the genclass command is Pro's where Pro is sold: the account says so, and every other route answers 402 - expect(j.cli).toEqual({ paid: false, plan: "Pro", price: "$15 / developer / month", trial_days: 3, checkout_url: "https://genclass.dev/account/billing?plan=pro&start=1" }); + expect(j.cli).toEqual({ paid: false, plan: "Pro", price: "$50 / developer / month", trial_days: 3, checkout_url: "https://genclass.dev/account/billing?plan=pro&start=1" }); const no = await send(env, "POST", "/api/cli/team/invite", me.bearer, {}); expect(no.status).toBe(402); expect(await no.json()).toMatchObject(NEEDS_PRO); @@ -135,7 +135,7 @@ describe("genclass command: GET /api/cli/account and POST /api/cli/team/invite", const me = await cliUser(env); team(sql, me.account.id, 3); const j = await json(get(env, "/api/cli/account", me.bearer)); - expect(j.plan).toMatchObject({ id: "team", name: "Pro", price: "$15 / developer / month" }); + expect(j.plan).toMatchObject({ id: "team", name: "Pro", price: "$50 / developer / month" }); // Pro is per developer since plans.json version 5: the seats paid for, and up to 3 apps for the account expect([j.access, j.limits.seats, j.limits.apps, j.limits.history_days]).toEqual(["paid", 3, 3, 90]); expect(j.includes).toEqual({ analytics: true, forwarding: true, export: true, private_repositories: true }); @@ -312,7 +312,7 @@ describe("genclass command: POST /api/cli/ask (src/ask.ts)", () => { plan: "Pro", upgrade_url: `https://genclass.dev/account/billing?project=${app.id}`, trial_days: 3, - price: "$15 / developer / month", + price: "$50 / developer / month", }); expect(model.calls).toEqual([]); expect(sql.rows("SELECT * FROM suggest_usage")).toEqual([]); @@ -461,7 +461,7 @@ describe("the genclass command is Pro's (src/cli.ts cliPaid; the owner's call of needs_pro: true, paid: false, plan: "Pro", - price: "$15 / developer / month", + price: "$50 / developer / month", trial_days: 3, checkout_url: CHECKOUT, }; @@ -520,7 +520,7 @@ describe("the genclass command is Pro's (src/cli.ts cliPaid; the owner's call of const { env, sql: db, me } = await freeUser(); setPlan(db, me.account.id, "free", { subscription_id: "sub_old0000001", subscription_status: "canceled" }); const r = await get(env, "/api/cli/overview", me.bearer); - expect((await r.json() as any).cli).toEqual({ paid: false, plan: "Pro", price: "$15 / developer / month", trial_days: null, checkout_url: CHECKOUT }); + expect((await r.json() as any).cli).toEqual({ paid: false, plan: "Pro", price: "$50 / developer / month", trial_days: null, checkout_url: CHECKOUT }); const no = await send(env, "POST", "/api/cli/suggest", me.bearer, {}); expect(await no.json()).toMatchObject({ error: `the genclass command comes with Pro: ${CHECKOUT}`, trial_days: null }); }); diff --git a/telemetry-worker/test/cli.test.ts b/telemetry-worker/test/cli.test.ts index 852dd431..7ed4cde6 100644 --- a/telemetry-worker/test/cli.test.ts +++ b/telemetry-worker/test/cli.test.ts @@ -69,7 +69,7 @@ describe("genclass command: GET /api/cli/overview (src/cli.ts)", () => { expect(offered.offer).toEqual({ // the plan id stays team; its name is Pro since 2026-11-12 plan: { id: "team", name: "Pro" }, - price: "$15 / developer / month", + price: "$50 / developer / month", summary: teamPlan.summary, features: teamPlan.features.filter((f) => f.available && !/^Everything in /.test(f.text)).map((f) => f.text).slice(0, 12), // Pro is the account's (plans.json version 5), bought on the plan page of its first app on Free @@ -247,7 +247,7 @@ describe("genclass command: POST /api/cli/suggest (src/suggest.ts header)", () = cached_at: null, // the plan page that starts Pro from the command, and what Pro is upgrade_url: "https://genclass.dev/account/billing?plan=pro&from=cli", - upgrade_plan: { name: "Pro", price: "$15 / developer / month", trial_days: 3 }, + upgrade_plan: { name: "Pro", price: "$50 / developer / month", trial_days: 3 }, remaining_today: 3, limited: false, }); @@ -399,7 +399,7 @@ describe("genclass command: POST /api/cli/suggest (src/suggest.ts header)", () = designs_locked: 2, cached_at: null, upgrade_url: "https://genclass.dev/account/billing?plan=pro&from=cli", - upgrade_plan: { name: "Pro", price: "$15 / developer / month", trial_days: 3 }, + upgrade_plan: { name: "Pro", price: "$50 / developer / month", trial_days: 3 }, remaining_today: 2, limited: false, }); @@ -543,7 +543,7 @@ describe("genclass command: GET /api/cli/app (src/cli.ts)", () => { expect(j.recent).toEqual([]); expect(j.typeSeries.every((b: any) => Object.keys(b.counts).join() === "problems")).toBe(true); expect(j.typeSeries.reduce((n: number, b: any) => n + b.counts.problems, 0)).toBe(1); - expect(j.locked.problems).toEqual({ plan: "Pro", upgrade_url: `https://genclass.dev/account/billing?project=${app.id}`, trial_days: 3, price: "$15 / developer / month" }); + expect(j.locked.problems).toEqual({ plan: "Pro", upgrade_url: `https://genclass.dev/account/billing?project=${app.id}`, trial_days: 3, price: "$50 / developer / month" }); expect(JSON.stringify(j)).not.toContain("/checkout"); // nothing a page typed, and no session of the account expect(JSON.stringify(j)).not.toContain("SECRET PAGE TEXT"); diff --git a/telemetry-worker/test/country-prices.test.ts b/telemetry-worker/test/country-prices.test.ts new file mode 100644 index 00000000..e0019488 --- /dev/null +++ b/telemetry-worker/test/country-prices.test.ts @@ -0,0 +1,127 @@ +// Prices by country (billing/plans.json country_prices, the owner's call of 2026-11-16): Pro is US$50 a developer a +// month everywhere but Canada, where it stays US$15 under the lookup key it was sold under before +// (genclass_team_monthly). Checkout sells the price of the country Cloudflare reports for the request (request.cf.country); +// a request with no country gets the plan's own price; every lookup key of the plan gives Pro; the screens show the +// visitor's price, and a message read later (an email) names both. +import { beforeEach, describe, expect, it } from "vitest"; +import { resetTokenCache } from "../src/dashboard.js"; +import { resetOwnerCache } from "../src/paid.js"; +import { countryOf, planById, planByLookupKey, planForPrice, priceFor, priceText, problemsLock } from "../src/plans.js"; +import { CLI_ACCOUNT_FROM } from "../src/cli.js"; +import { resetStripeCache } from "../src/stripe.js"; +import { call, cliToken, createApp, fakeStripe, GENCLASS_PORTAL, price, resetClock, setNow, setup, signedIn, WEBHOOK_SECRET } from "./account-helpers.js"; + +const LIVE = { STRIPE_SECRET_KEY: "sk_live_fake", STRIPE_WEBHOOK_SECRET: WEBHOOK_SECRET, STRIPE_PORTAL_CONFIGURATION: GENCLASS_PORTAL }; +const PRO = planById("team"); + +beforeEach(() => { + resetClock(); + resetTokenCache(); + resetOwnerCache(); + resetStripeCache(); +}); + +async function buyer() { + const t = setup(LIVE); + const a = await signedIn(t.env); + const s = fakeStripe(); + t.sql.db.prepare("UPDATE accounts SET stripe_customer_id = 'cus_ada0000001', stripe_mode = 'live' WHERE id = ?").run(a.account.id); + s.genclassCustomer("cus_ada0000001", a.account.id); + await createApp(t.env, a.cookie, "Shop"); + return { ...t, ...a, s }; +} +const sessionsOf = (s: ReturnType) => s.calls.filter((c) => c.method === "POST" && c.url.pathname === "/v1/checkout/sessions").map((c) => Object.fromEntries(c.form!)); + +describe("prices by country (billing/plans.json country_prices)", () => { + it("Pro is $50 a developer a month, $15 in Canada; both lookup keys give Pro", () => { + expect(PRO.price_usd_cents.monthly).toBe(5000); + expect(priceFor(PRO, "CA")).toMatchObject({ price_usd_cents: { monthly: 1500 }, stripe_lookup_keys: { monthly: "genclass_team_monthly" } }); + for (const c of ["US", "GB", "IN", "XX", "T1", null, undefined]) expect(priceFor(PRO, c).stripe_lookup_keys.monthly, String(c)).toBe("genclass_team_world_monthly"); + expect(priceFor(PRO, "ca").price_usd_cents.monthly).toBe(1500); + expect(planByLookupKey("genclass_team_monthly")?.id).toBe("team"); + expect(planByLookupKey("genclass_team_world_monthly")?.id).toBe("team"); + // a price on either Pro product is GenClass's Pro + expect(planForPrice(price("genclass_team_world_monthly", { product: "genclass_team_world" }))?.id).toBe("team"); + expect(planForPrice(price("genclass_team_monthly"))?.id).toBe("team"); + }); + + it("the price text: the visitor's country's, the plan's own without one, both for a reader whose country is not known", () => { + expect(priceText(PRO, "CA")).toBe("$15 / developer / month"); + expect(priceText(PRO, "US")).toBe("$50 / developer / month"); + expect(priceText(PRO, null)).toBe("$50 / developer / month"); + expect(priceText(PRO)).toBe("$50 / developer / month ($15 in Canada)"); + expect(priceText(planById("free"), "CA")).toBe("$0"); + expect(priceText(planById("enterprise"), "CA")).toBe("By agreement"); + expect(problemsLock("https://genclass.dev/account/billing", "CA").price).toBe("$15 / developer / month"); + }); + + it("countryOf reads Cloudflare's request.cf.country, and nothing else", () => { + const req = (cf?: unknown) => { + const r = new Request("https://genclass.dev/"); + if (cf !== undefined) Object.defineProperty(r, "cf", { value: cf }); + return r; + }; + expect(countryOf(req({ country: "CA" }))).toBe("CA"); + expect(countryOf(req({ country: "us" }))).toBe("US"); + expect(countryOf(req({ country: "T1" }))).toBe("T1"); + for (const cf of [undefined, null, {}, { country: "" }, { country: "Canada" }, { country: 1 }]) expect(countryOf(req(cf)), JSON.stringify(cf)).toBeNull(); + expect(countryOf(null)).toBeNull(); + // a header saying Canada is not Cloudflare's word + expect(countryOf(new Request("https://genclass.dev/", { headers: { "cf-ipcountry": "CA" } }))).toBeNull(); + }); + + it("Checkout from Canada sells the $15 price, from anywhere else the $50 one, and says which on the session", async () => { + for (const [country, priceId, key] of [["CA", "price_team000001", "genclass_team_monthly"], ["US", "price_teamworld1", "genclass_team_world_monthly"], [undefined, "price_teamworld1", "genclass_team_world_monthly"]] as const) { + resetStripeCache(); + const b = await buyer(); + const r = await call(b.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: b.cookie, fetch: b.s.fetch, ...(country ? { country } : {}) }); + expect(r.status, String(country)).toBe(200); + const [form] = sessionsOf(b.s); + expect(form, String(country)).toMatchObject({ "line_items[0][price]": priceId, "metadata[genclass_plan]": "team", "metadata[genclass_price]": key, allow_promotion_codes: "true" }); + // Stripe was asked for that price by its lookup key only + const asked = b.s.calls.filter((c) => c.method === "GET" && c.url.pathname === "/v1/prices").map((c) => c.url.searchParams.get("lookup_keys[0]")); + expect(asked, String(country)).toEqual([key]); + } + }); + + it("an open Checkout page for the other country's price, or one made before prices by country, is closed, not reused", async () => { + const b = await buyer(); + expect((await call(b.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: b.cookie, fetch: b.s.fetch, country: "CA" })).status).toBe(200); + const first = [...b.s.sessions.values()][0] as any; + expect(first.metadata.genclass_price).toBe("genclass_team_monthly"); + // the same country again: the same page + const again = (await (await call(b.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: b.cookie, fetch: b.s.fetch, country: "CA" })).json()) as any; + expect(again.url).toBe(first.url); + // from elsewhere: the Canadian page is closed and a $50 one made + const other = (await (await call(b.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: b.cookie, fetch: b.s.fetch, country: "DE" })).json()) as any; + expect(other.url).not.toBe(first.url); + expect(b.s.calls.some((c) => c.method === "POST" && c.url.pathname === `/v1/checkout/sessions/${first.id}/expire`)).toBe(true); + expect(sessionsOf(b.s).at(-1)).toMatchObject({ "line_items[0][price]": "price_teamworld1", "metadata[genclass_price]": "genclass_team_world_monthly" }); + // a page from before (no genclass_price) is closed too + const old = [...b.s.sessions.values()].at(-1) as any; + delete old.metadata.genclass_price; + const after = (await (await call(b.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: b.cookie, fetch: b.s.fetch, country: "DE" })).json()) as any; + expect(after.url).not.toBe(old.url); + }); + + it("the billing page and the genclass command show the visitor's price", async () => { + const b = await buyer(); + const ca = await (await call(b.env, "GET", "/account/billing", { cookie: b.cookie, country: "CA" })).text(); + expect(ca).toContain('

$15 / developer / month

'); + expect(ca).not.toContain("$50"); + const us = await (await call(b.env, "GET", "/account/billing", { cookie: b.cookie, country: "US" })).text(); + expect(us).toContain('

$50 / developer / month

'); + expect(us).not.toContain("$15 /"); + // the genclass command, on a new account approved after the approval page listed the account route + setNow(new Date(Date.parse(CLI_ACCOUNT_FROM) + 3_600_000)); + const t = setup(LIVE); + const me = await signedIn(t.env, "grace@example.com"); + const token = await cliToken(t.env, me.cookie); + for (const [country, want] of [["CA", "$15 / developer / month"], ["FR", "$50 / developer / month"]] as const) { + const res = await call(t.env, "GET", "/api/cli/account", { bearer: token, origin: null, country }); + const cli = (await res.json()) as any; + expect(res.status, JSON.stringify(cli)).toBe(200); + expect(cli.cli.price, country).toBe(want); + } + }); +}); diff --git a/telemetry-worker/test/pages.test.ts b/telemetry-worker/test/pages.test.ts index 2cf455ec..c304092b 100644 --- a/telemetry-worker/test/pages.test.ts +++ b/telemetry-worker/test/pages.test.ts @@ -655,7 +655,7 @@ describe("dashboard page: interaction analytics (docs/runtime/ANALYTICS.md secti const { doc, text, hidden, close } = await render(st); expect(hidden("prolock")).toBe(false); expect(text("#prolock b")).toBe("Free shows the totals"); - expect(text("#prolockmsg")).toBe("Every problem, the pages it happens on, what GenClass did about it and a fix prompt for your coding agent come with Pro. 3 days free, then $15 / developer / month. Cancel any time."); + expect(text("#prolockmsg")).toBe("Every problem, the pages it happens on, what GenClass did about it and a fix prompt for your coding agent come with Pro. 3 days free, then $50 / developer / month ($15 in Canada). Cancel any time."); expect(doc.getElementById("prolocka")!.getAttribute("href")).toBe("https://genclass.dev/account/billing?project=p1"); expect(text("#prolocka")).toBe("Start your 3-day free trial"); // the lists give way to the banner, so an empty list never reads as "no problems" diff --git a/telemetry-worker/test/plans.test.ts b/telemetry-worker/test/plans.test.ts index 4635a968..d8e086b2 100644 --- a/telemetry-worker/test/plans.test.ts +++ b/telemetry-worker/test/plans.test.ts @@ -54,12 +54,14 @@ describe("billing/plans.json: the one source of plans", () => { expect(PLANS.map((p) => p.name)).toEqual(["Free", "Pro", "Enterprise"]); const [free, team, enterprise] = PLANS; expect(free!.price_usd_cents).toEqual({ monthly: 0, yearly: null }); - // US$15 a developer a month, for up to 3 apps (the owner, 2026-11-13; a project a month the day before) - expect(team!.price_usd_cents).toEqual({ monthly: 1500, yearly: null }); + // US$50 a developer a month (US$15 in Canada, 2026-11-16; US$15 everywhere from 2026-11-13), for up to 3 apps + expect(team!.price_usd_cents).toEqual({ monthly: 5000, yearly: null }); + expect(team!.country_prices).toEqual([{ countries: ["CA"], name: "Canada", price_usd_cents: { monthly: 1500, yearly: null }, stripe_lookup_keys: { monthly: "genclass_team_monthly", yearly: null } }]); + expect(team!.stripe_product).toBe("genclass_team_world"); expect(enterprise!.price_usd_cents).toEqual({ monthly: null, yearly: null }); expect(PLANS.map((p) => p.stripe_lookup_keys)).toEqual([ { monthly: null, yearly: null }, - { monthly: "genclass_team_monthly", yearly: null }, + { monthly: "genclass_team_world_monthly", yearly: null }, { monthly: null, yearly: null }, ]); // Free: finds and fixes the problems and shows their totals, for one person and one app (version 5); the problem @@ -77,7 +79,7 @@ describe("billing/plans.json: the one source of plans", () => { expect(PLANS.map((p) => p.per_project === true)).toEqual([false, false, false]); expect(PLANS.map((p) => p.apps_per_unit)).toEqual([undefined, undefined, undefined]); expect(team!.summary).toBe("Everything for up to 3 apps, per developer."); - expect(team!.features.map((x) => x.text)).toEqual(expect.arrayContaining(["Up to 3 apps", "The genclass command in your terminal", "Your team on it, $15 a developer"])); + expect(team!.features.map((x) => x.text)).toEqual(expect.arrayContaining(["Up to 3 apps", "The genclass command in your terminal", "Your team on it, priced per developer"])); expect(enterprise!.features.map((x) => x.text)).toContain("More than 3 apps"); expect(team!.limits).toEqual({ apps: 3, history_days: 90, seats: null, live_fixes_per_month: null }); expect(team!.entitlements).toEqual({ dashboard: true, forwarding: true, export: true, analytics: true, custom_model: false, github_private: true, problems: true, ask: true }); @@ -106,9 +108,10 @@ describe("billing/plans.json: the one source of plans", () => { expect(GRANT_PLAN.id).toBe("enterprise"); expect(FREE.id).toBe("free"); expect(priceText(free!)).toBe("$0"); - expect(priceText(team!)).toBe("$15 / developer / month"); + expect(priceText(team!)).toBe("$50 / developer / month ($15 in Canada)"); expect(priceText(enterprise!)).toBe("By agreement"); expect(planByLookupKey("genclass_team_monthly")?.id).toBe("team"); + expect(planByLookupKey("genclass_team_world_monthly")?.id).toBe("team"); // Individual (until 2026-10-22) and the plans before it name no plan any more for (const k of ["genclass_individual_monthly", "genclass_pro_monthly"]) expect(planByLookupKey(k), k).toBeNull(); expect(viewRanges(free!)).toEqual(["24h", "7d"]); @@ -134,7 +137,7 @@ describe("billing/plans.json: the one source of plans", () => { // the plan an upgrade names: the first one on sale with it expect(firstPaidWith("problems")?.id).toBe("team"); expect(firstPaidWith("ask")?.id).toBe("team"); - expect(problemsLock("https://genclass.dev/account/billing?project=p1")).toEqual({ plan: "Pro", upgrade_url: "https://genclass.dev/account/billing?project=p1", trial_days: 3, price: "$15 / developer / month" }); + expect(problemsLock("https://genclass.dev/account/billing?project=p1")).toEqual({ plan: "Pro", upgrade_url: "https://genclass.dev/account/billing?project=p1", trial_days: 3, price: "$50 / developer / month ($15 in Canada)" }); // the per-seat plans of version 3 (test/fixtures/plans-v3-seats.json) say nothing of them: every plan gives them const v3 = (SEATS_JSON as any).plans as Plan[]; expect(v3.every((p) => !("problems" in p.entitlements) && !("ask" in p.entitlements))).toBe(true); @@ -236,7 +239,7 @@ describe("the dashboard is free: every app opens it, with an account or without" // Free sees the totals: the problem lists, pages and latest events come with Pro, from the app's plan page expect(stats.locked).toEqual({ analytics: { plan: "Pro", upgrade_url: "https://genclass.dev/account/billing" }, - problems: { plan: "Pro", upgrade_url: `https://genclass.dev/account/billing?project=${apps[0]!.id}`, trial_days: 3, price: "$15 / developer / month" }, + problems: { plan: "Pro", upgrade_url: `https://genclass.dev/account/billing?project=${apps[0]!.id}`, trial_days: 3, price: "$50 / developer / month" }, }); expect([stats.breakdowns, stats.recent]).toEqual([{}, []]); const denied = async (r: Promise, what: string) => { @@ -295,7 +298,7 @@ describe("the dashboard is free: every app opens it, with an account or without" expect(st.totals.detections, range).toBe(1); if (locked) { // the app has no account: the way to Pro is the plans page - expect(st.locked.problems).toEqual({ plan: "Pro", upgrade_url: "https://genclass.dev/account/billing", trial_days: 3, price: "$15 / developer / month" }); + expect(st.locked.problems).toEqual({ plan: "Pro", upgrade_url: "https://genclass.dev/account/billing", trial_days: 3, price: "$50 / developer / month" }); expect([st.breakdowns, st.recent]).toEqual([{}, []]); } else { expect(st.locked).toBeUndefined(); @@ -353,7 +356,7 @@ describe("the old trial stays gone; Pro's 3 days free are offered on the plan pa // the app's plan page, for an account that has never had a subscription: the trial, and what follows it const eligible = pages.find(([p]) => p.startsWith("/account/billing?project="))![1]; expect(eligible).toContain('data-plan="team" data-pick>Start your 3-day free trial'); - expect(eligible).toContain('

3 days free, then $15 / developer / month. Cancel before the trial ends and you pay nothing.

'); + expect(eligible).toContain('

3 days free, then $50 / developer / month. Cancel before the trial ends and you pay nothing.

'); expect(visible(eligible)).not.toMatch(/—|!/); const planPage = () => text(call(env, "GET", `/account/billing?project=${app.id}`, { cookie })); const noTrial = (html: string, why: string) => { @@ -474,8 +477,8 @@ describe("Pro (id team) is the one plan sold on the site, for the account; Enter const live = "STRIPE_SECRET_KEY" in keys; expect(page).toContain(live ? "You are on the Free plan.

" : "You are on the Free plan. Paid plans are not on sale yet.

"); expect(page).toContain("grid-template-columns:repeat(3,minmax(0,1fr))"); - expect(page).toContain('

$15 / developer / month

'); - expect(page).toMatch(/Your team on it, \$15 a developer<\/li>/); // folded behind "N more" on a phone only + expect(page).toContain('

$50 / developer / month

'); + expect(page).toMatch(/Your team on it, priced per developer<\/li>/); // folded behind "N more" on a phone only expect(page).toContain("
  • More than 3 apps
  • "); expect(page.match(/
  • Your own classifier/g)).toHaveLength(1); // bought for the account here, with how many developers (no project to choose first) @@ -499,7 +502,7 @@ describe("Pro (id team) is the one plan sold on the site, for the account; Enter const a = await signedIn(t.env); setPlan(t.sql, a.account.id, "team", { stripe_customer_id: "cus_b000000001", stripe_mode: "live", seats: 3, subscription_id: "sub_b000000001", subscription_status: "active", current_period_end: "2026-11-13T12:00:00.000Z" }); const page = await text(call(t.env, "GET", "/account/billing", { cookie: a.cookie })); - expect(page).toContain('You are on the Pro plan with 3 seats, $15 / developer / month ($45 a month). It renews on . Add or remove seats in Manage billing.'); + expect(page).toContain('You are on the Pro plan with 3 seats, $50 / developer / month ($150 a month). It renews on . Add or remove seats in Manage billing.'); expect(page).toContain('Your plan'); const open = setup({ PLAN_GATES: "open" }); const b = await signedIn(open.env); diff --git a/telemetry-worker/test/project-plans.test.ts b/telemetry-worker/test/project-plans.test.ts index 970e1aa1..b16cac2c 100644 --- a/telemetry-worker/test/project-plans.test.ts +++ b/telemetry-worker/test/project-plans.test.ts @@ -1,4 +1,4 @@ -// Pro for the account again (billing/plans.json version 5, the owner's decision of 2026-11-13): Pro is US$15 a +// Pro for the account again (billing/plans.json version 5, the owner's decision of 2026-11-13): Pro was US$15 a // developer a month for up to 3 of the account's apps (oldest first), everyone on its team included; more apps are // Enterprise's, by email. Free covers one app and 100 problems fixed live a month, after which the runtime is told to // observe only. A subscription bought per project under version 4 still gives the account Pro (and its 3 apps), and @@ -66,9 +66,11 @@ async function withApps(names: string[], over: Record = {}) { } describe("plans.json version 5: Pro for the account, per developer, up to 3 apps", () => { - it("Pro is $15 a developer a month, sold by seats, for up to 3 apps; Free covers one app and 100 live fixes a month", () => { + it("Pro is $50 a developer a month ($15 in Canada), sold by seats, for up to 3 apps; Free covers one app and 100 live fixes a month", () => { const [free, team, enterprise] = PLANS; - expect(priceText(team!)).toBe("$15 / developer / month"); + expect(priceText(team!)).toBe("$50 / developer / month ($15 in Canada)"); + expect(priceText(team!, null)).toBe("$50 / developer / month"); + expect(priceText(team!, "CA")).toBe("$15 / developer / month"); expect(team!.per_project).toBeUndefined(); expect(team!.per_seat).toBe(true); expect(team!.apps_per_unit).toBeUndefined(); @@ -221,7 +223,7 @@ describe("checkout for the account (POST /api/billing/checkout { plan, seats?, p mode: "subscription", customer: "cus_ada0000001", client_reference_id: b.account.id, - "line_items[0][price]": "price_team000001", + "line_items[0][price]": "price_teamworld1", "line_items[0][quantity]": "1", "line_items[0][adjustable_quantity][enabled]": "true", "line_items[0][adjustable_quantity][minimum]": "1", @@ -660,7 +662,7 @@ describe("an app past what the plan covers waits on its plan page (Free: one app it("the billing page lists each app with its plan and sells Pro for the account", async () => { const t = await withApps(["Shop", "Blog"]); const page = await text(call(t.env, "GET", "/account/billing", { cookie: t.cookie })); - expect(page).toContain('

    $15 / developer / month

    '); + expect(page).toContain('

    $50 / developer / month

    '); expect(page).toContain('data-plan="team">Upgrade to Pro'); expect(page).not.toContain("Choose a project"); expect(page).toContain('id="projects"'); @@ -680,7 +682,7 @@ describe("an app past what the plan covers waits on its plan page (Free: one app expect(one).not.toContain("Choose its plan to go on"); expect(one).not.toContain("Problems fixed live this month"); // the card: the name, the price, the first 5 lines, the rest folded under "N more"; no summary repeating the price - expect(one).toContain('

    Pro

    $15 / developer / month

    • Up to 3 apps
    • The genclass command in your terminal
    • '); + expect(one).toContain('

      Pro

      $50 / developer / month

      • Up to 3 apps
      • The genclass command in your terminal
      • '); const lines = pitchLines(PLANS[1]!); expect(one).toContain(`
        ${lines.length - 5} more
          ${lines.slice(5).map((l) => `
        • ${l.replace(/'/g, "'")}
        • `).join("")}
        `); expect(one).not.toContain("
      • Everything in Free
      • "); @@ -688,7 +690,7 @@ describe("an app past what the plan covers waits on its plan page (Free: one app expect(one).not.toContain('

        '); // an account that has never had a subscription starts with Pro's 3 days free (billing.ts trialFor) expect(one).toContain(''); - expect(one).toContain('

        3 days free, then $15 / developer / month. Cancel before the trial ends and you pay nothing.

        '); + expect(one).toContain('

        3 days free, then $50 / developer / month. Cancel before the trial ends and you pay nothing.

        '); expect(one).not.toContain('type="button" data-continue>'); expect(one).not.toContain('Your plan'); // Free is the small way on: a very small link under the big card, and a popup that asks why before it goes on @@ -878,9 +880,9 @@ describe("the website: a new account's first screen is Pro's trial, with a tiny expect(home.status).toBe(200); const page = await home.text(); expect(page).toContain('

        Start your 3-day free trial

        '); - expect(page).toContain('

        Pro, $15 / developer / month

        '); + expect(page).toContain('

        Pro, $50 / developer / month

        '); expect(page).toContain('Start your 3-day free trial'); - expect(page).toContain("

        3 days free, then $15 / developer / month. Cancel before the trial ends and you pay nothing.

        "); + expect(page).toContain("

        3 days free, then $50 / developer / month. Cancel before the trial ends and you pay nothing.

        "); // 5 lines shown, the rest folded, and no summary repeating the price (the owner, 2026-11-13: less written) expect(page).toContain(`
        ${pitchLines(PLANS[1]!).length - 5} more`); expect(page).not.toContain("Everything for up to 3 apps, per developer."); diff --git a/telemetry-worker/test/stripe-setup-country.test.ts b/telemetry-worker/test/stripe-setup-country.test.ts new file mode 100644 index 00000000..15e517f3 --- /dev/null +++ b/telemetry-worker/test/stripe-setup-country.test.ts @@ -0,0 +1,142 @@ +import { fileURLToPath } from "node:url"; +import { beforeAll, describe, expect, it } from "vitest"; +import { planForPrice } from "../src/plans.js"; + +// scripts/stripe-setup.mjs on the real billing/plans.json, whose Pro has a price by country (2026-11-16: US$50 a +// developer a month, US$15 in Canada). Each price is on its own product, both named GenClass Pro with metadata +// genclass_plan team (the Billing Portal's seat changes allow one monthly price a product): Canada's on the plan's +// main product genclass_team under the key it was sold under before, everyone else's on genclass_team_world, which +// plans.json names (stripe_product). A run against an account that already has them changes nothing. + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let setup: any; +beforeAll(async () => { + process.env.GENCLASS_PLANS_FILE = fileURLToPath(new URL("../../billing/plans.json", import.meta.url)); + setup = await import("../../scripts/stripe-setup.mjs"); +}); + +type Obj = Record; + +function fields(body: string): Obj { + const out: Obj = {}; + for (const [k, v] of new URLSearchParams(body)) { + const arr = /^([a-z_]+)\[\d+\]$/.exec(k); + if (arr) (out[arr[1]!] ??= []).push(v); + else out[k] = v; + } + return out; +} +const meta = (body: Obj): Obj => Object.fromEntries(Object.entries(body).filter(([k]) => k.startsWith("metadata[")).map(([k, v]) => [k.slice(9, -1), v])); + +/** A small fake Stripe account: products, prices, webhook endpoints and portal configurations, nothing else. */ +function account() { + const products = new Map(); + const prices = new Map(); + const endpoints = new Map(); + const portal = new Map([["bpc_default00001", { id: "bpc_default00001", is_default: true, active: true, metadata: {} }]]); + const calls: { method: string; url: URL; body: Obj }[] = []; + let n = 0; + const ok = (j: unknown, status = 200) => new Response(JSON.stringify(j), { status, headers: { "content-type": "application/json" } }); + const fetch = async (input: string, init: RequestInit = {}) => { + const url = new URL(input); + const method = init.method ?? "GET"; + const body = method === "POST" ? fields(String(init.body ?? "")) : {}; + calls.push({ method, url, body }); + const p = url.pathname; + const q = url.searchParams; + let m: RegExpExecArray | null; + if (method === "GET" && p === "/v1/products/search") { + const want = /^metadata\['genclass_plan'\]:'([a-z]+)'$/.exec(q.get("query") ?? "")![1]; + return ok({ data: [...products.values()].filter((x) => x.metadata?.genclass_plan === want), has_more: false }); + } + if ((m = /^\/v1\/products\/([^/]+)$/.exec(p))) { + const x = products.get(m[1]!); + if (!x) return ok({ error: { code: "resource_missing" } }, 404); + if (method === "POST") Object.assign(x, { name: body.name ?? x.name, description: body.description ?? x.description, statement_descriptor: body.statement_descriptor ?? x.statement_descriptor, tax_code: body.tax_code ?? x.tax_code }); + return ok(x); + } + if (method === "POST" && p === "/v1/products") { + const x = { id: body.id, object: "product", active: true, name: body.name, description: body.description, statement_descriptor: body.statement_descriptor, tax_code: body.tax_code, metadata: meta(body) }; + products.set(x.id, x); + return ok(x); + } + if (method === "GET" && p === "/v1/prices") return ok({ data: [...prices.values()].filter((x) => x.lookup_key === q.get("lookup_keys[0]")).slice(0, 1), has_more: false }); + if (method === "POST" && p === "/v1/prices") { + const x = { id: `price_gc${String(++n).padStart(6, "0")}`, object: "price", product: body.product, unit_amount: Number(body.unit_amount), currency: body.currency, recurring: { interval: body["recurring[interval]"] }, lookup_key: body.lookup_key, nickname: body.nickname, active: true, metadata: meta(body) }; + prices.set(x.id, x); + return ok(x); + } + if (method === "GET" && p === "/v1/webhook_endpoints") return ok({ data: [...endpoints.values()], has_more: false }); + if (method === "POST" && p === "/v1/webhook_endpoints") { + const x = { id: `we_gc${++n}`, url: body.url, description: body.description, enabled_events: body.enabled_events, api_version: body.api_version, status: "enabled", metadata: meta(body) }; + endpoints.set(x.id, x); + return ok({ ...x, secret: "whsec_fresh" }); + } + if (method === "GET" && p === "/v1/billing_portal/configurations") { + const d = q.get("is_default"); + return ok({ data: [...portal.values()].filter((c) => d === null || String(c.is_default) === d), has_more: false }); + } + if (method === "POST" && p === "/v1/billing_portal/configurations") { + const x = { id: `bpc_gc${++n}`, is_default: false, active: true, metadata: meta(body), form: body }; + portal.set(x.id, x); + return ok(x); + } + if (method === "POST" && (m = /^\/v1\/billing_portal\/configurations\/([^/]+)$/.exec(p))) { + const x = portal.get(m[1]!)!; + x.form = body; + return ok(x); + } + return ok({ error: { message: `fake Stripe has no ${method} ${p}` } }, 404); + }; + return { products, prices, portal, calls, fetch }; +} + +async function run(a: ReturnType) { + const from = a.calls.length; + await setup.main({ argv: [], env: { STRIPE_SECRET_KEY: "sk_test_fake" }, fetch: a.fetch, log: () => undefined, putSecret: async () => true }); + return a.calls.slice(from).filter((c) => c.method !== "GET"); +} + +describe("scripts/stripe-setup.mjs: prices by country (billing/plans.json country_prices)", () => { + it("Pro: Canada's US$15 on genclass_team, everyone else's US$50 on genclass_team_world, both seat-changeable in the portal", async () => { + const a = account(); + await run(a); + expect([...a.products.values()].map((x) => [x.id, x.name, x.metadata.genclass_plan, x.tax_code])).toEqual([ + ["genclass_team_world", "GenClass Pro", "team", "txcd_10103001"], + ["genclass_team", "GenClass Pro", "team", "txcd_10103001"], + ]); + const made = [...a.prices.values()].map((x) => [x.lookup_key, x.product, x.unit_amount, x.currency, x.recurring.interval, x.nickname]); + expect(made).toEqual([ + ["genclass_team_world_monthly", "genclass_team_world", 5000, "usd", "month", "Pro monthly"], + ["genclass_team_monthly", "genclass_team", 1500, "usd", "month", "Pro monthly (Canada)"], + ]); + // the worker reads both as Pro + for (const x of a.prices.values()) expect(planForPrice({ ...x, product: a.products.get(x.product) })?.id).toBe("team"); + // the portal: one product per price, each its own price only + const ours = [...a.portal.values()].find((c) => c.metadata.genclass === "1")!; + const form = new URLSearchParams(Object.entries(ours.form as Obj).flatMap(([k, v]) => (Array.isArray(v) ? v.map((x) => [k, x]) : [[k, v]])) as [string, string][]); + const products = [...form.entries()].filter(([k]) => /^features\[subscription_update\]\[products\]\[\d+\]\[product\]$/.test(k)).map(([, v]) => v); + expect(products).toEqual(["genclass_team_world", "genclass_team"]); + }); + + it("a second run changes no product or price", async () => { + const a = account(); + await run(a); + const again = await run(a); + expect(again.filter((c) => c.url.pathname.startsWith("/v1/products") || c.url.pathname.startsWith("/v1/prices"))).toEqual([]); + }); + + it("a product the plans name is found by its id only: an earlier product of the plan is never taken for it", async () => { + const a = account(); + // an earlier run's product of Pro with an id Stripe chose (found by the metadata search) holds Canada's price + a.products.set("prod_earlier00001", { id: "prod_earlier00001", object: "product", active: true, name: "GenClass Pro", description: "Everything for up to 3 apps, per developer.", statement_descriptor: "GENCLASS", tax_code: "txcd_10103001", metadata: { genclass: "1", genclass_plan: "team" } }); + a.prices.set("price_earlier0001", { id: "price_earlier0001", object: "price", product: "prod_earlier00001", unit_amount: 1500, currency: "usd", recurring: { interval: "month" }, lookup_key: "genclass_team_monthly", active: true, metadata: { genclass: "1", genclass_plan: "team" } }); + await run(a); + expect(a.products.has("genclass_team")).toBe(false); + expect(a.products.get("genclass_team_world")?.metadata.genclass_plan).toBe("team"); + expect([...a.prices.values()].filter((x) => x.active).map((x) => [x.lookup_key, x.product])).toEqual([ + ["genclass_team_monthly", "prod_earlier00001"], + ["genclass_team_world_monthly", "genclass_team_world"], + ]); + }); +});