Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(billing): add scheduled plan notices and billing lab (#7865)
Peter Chinman0717635a36bd
diff --git a/.sqlx/query-1603df291e3d62f08cb38af3f118b2bb25f306bbba797fbd70ce375e45562322.json b/.sqlx/query-1603df291e3d62f08cb38af3f118b2bb25f306bbba797fbd70ce375e45562322.jsondeleted file mode 100644index 228fa013a5..0000000000--- a/.sqlx/query-1603df291e3d62f08cb38af3f118b2bb25f306bbba797fbd70ce375e45562322.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id, COALESCE(SUM(\n COALESCE(\n total::float8,\n (input_tokens::float8 / 1000000.0) * $4\n + (output_tokens::float8 / 1000000.0) * $5\n + (cache_read_input_tokens::float8 / 1000000.0) * $6\n + (cache_write_input_tokens::float8 / 1000000.0) * $7\n )\n ), 0)::float8 AS \"usd!\"\n FROM ai_usage\n WHERE user_id = ANY($1)\n AND created_at >= $2\n AND created_at < $3\n AND count_usage = TRUE\n GROUP BY user_id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "usd!",- "type_info": "Float8"- }- ],- "parameters": {- "Left": [- "TextArray",- "Timestamptz",- "Timestamptz",- "Float8",- "Float8",- "Float8",- "Float8"- ]- },- "nullable": [- false,- null- ]- },- "hash": "1603df291e3d62f08cb38af3f118b2bb25f306bbba797fbd70ce375e45562322"-}diff --git a/.sqlx/query-4477a86a50518e2a048fd8300fc50b565ed649f2523633c261cc132a95557ca4.json b/.sqlx/query-4477a86a50518e2a048fd8300fc50b565ed649f2523633c261cc132a95557ca4.jsonnew file mode 100644index 0000000000..568ddbb48b--- /dev/null+++ b/.sqlx/query-4477a86a50518e2a048fd8300fc50b565ed649f2523633c261cc132a95557ca4.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO ai_billing_account (user_id) VALUES ($1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4477a86a50518e2a048fd8300fc50b565ed649f2523633c261cc132a95557ca4"+}diff --git a/.sqlx/query-4788516149d3331fa694676df88497a599d9fa21e276434aa6fe777991cbd8c9.json b/.sqlx/query-4788516149d3331fa694676df88497a599d9fa21e276434aa6fe777991cbd8c9.jsonnew file mode 100644index 0000000000..69a72460a5--- /dev/null+++ b/.sqlx/query-4788516149d3331fa694676df88497a599d9fa21e276434aa6fe777991cbd8c9.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT user_id, payer_id, subscription_id, period_start, period_end, policy FROM ai_billing_usage_period\n WHERE user_id = $1 AND period_start <= $2 AND period_end > $2\n AND NOT EXISTS (\n SELECT 1 FROM ai_billing_plan_change AS reset\n WHERE reset.user_id = ai_billing_usage_period.user_id\n AND reset.period_start = ai_billing_usage_period.period_start\n AND (reset.new_plan = 'max' AND reset.changed_at <= $2\n OR reset.previous_plan = 'max' AND reset.changed_at > reset.period_start\n AND NOT EXISTS (SELECT 1 FROM ai_billing_plan_change AS earlier\n WHERE earlier.user_id = reset.user_id AND earlier.period_start = reset.period_start\n AND earlier.changed_at < reset.changed_at))\n )",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "payer_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "subscription_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "period_start",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "period_end",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "policy",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "4788516149d3331fa694676df88497a599d9fa21e276434aa6fe777991cbd8c9"+}diff --git a/.sqlx/query-593aa81e11a7ab0c9ef40225fb3890bb137509fd4635eaa5944db3c24d3c486b.json b/.sqlx/query-593aa81e11a7ab0c9ef40225fb3890bb137509fd4635eaa5944db3c24d3c486b.jsonnew file mode 100644index 0000000000..86b4b5f3b5--- /dev/null+++ b/.sqlx/query-593aa81e11a7ab0c9ef40225fb3890bb137509fd4635eaa5944db3c24d3c486b.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT effective_at, member_plans FROM subscription_plan_schedule WHERE id = $1 AND subscription_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "effective_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "member_plans",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "593aa81e11a7ab0c9ef40225fb3890bb137509fd4635eaa5944db3c24d3c486b"+}diff --git a/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.json b/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.jsonnew file mode 100644index 0000000000..89ab941a64--- /dev/null+++ b/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens)\n VALUES ($1, 'chat', $2, 'legacy-model', 1000000, 1000000)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0"+}diff --git a/.sqlx/query-6b4e7c66c526999588ba3cd6e28a753686363434b474181c6511702fba18984e.json b/.sqlx/query-6b4e7c66c526999588ba3cd6e28a753686363434b474181c6511702fba18984e.jsonnew file mode 100644index 0000000000..e900610fb3--- /dev/null+++ b/.sqlx/query-6b4e7c66c526999588ba3cd6e28a753686363434b474181c6511702fba18984e.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT user_id FROM ai_billing_usage_period WHERE user_id = ANY($1)\n AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2\n AND NOT EXISTS (\n SELECT 1 FROM ai_billing_plan_change AS change\n WHERE change.user_id = ai_billing_usage_period.user_id\n AND change.period_start = ai_billing_usage_period.period_start\n AND change.changed_at < $3\n AND (change.new_plan = 'max' OR change.previous_plan = 'max' AND change.changed_at > change.period_start)\n )",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "6b4e7c66c526999588ba3cd6e28a753686363434b474181c6511702fba18984e"+}diff --git a/.sqlx/query-7461c824736b6cf927c3b8ad03aa6212bca7e5ca60b57da2038a8b0d15d87601.json b/.sqlx/query-7461c824736b6cf927c3b8ad03aa6212bca7e5ca60b57da2038a8b0d15d87601.jsonnew file mode 100644index 0000000000..a0bbefae5c--- /dev/null+++ b/.sqlx/query-7461c824736b6cf927c3b8ad03aa6212bca7e5ca60b57da2038a8b0d15d87601.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE ai_usage SET created_at = $2 WHERE id = (SELECT id FROM ai_usage WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "7461c824736b6cf927c3b8ad03aa6212bca7e5ca60b57da2038a8b0d15d87601"+}diff --git a/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.json b/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.jsonnew file mode 100644index 0000000000..417b14c176--- /dev/null+++ b/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status, accounting_policy)\n VALUES ($1, $2, $3, 105, 'paid', 'public_allowance_v1')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e"+}diff --git a/.sqlx/query-78beb1a2b480da66fb5a5c767ccae3a4abd54f516aad873c17ae37342cb142fa.json b/.sqlx/query-78beb1a2b480da66fb5a5c767ccae3a4abd54f516aad873c17ae37342cb142fa.jsonnew file mode 100644index 0000000000..2d12434c1d--- /dev/null+++ b/.sqlx/query-78beb1a2b480da66fb5a5c767ccae3a4abd54f516aad873c17ae37342cb142fa.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_billing_plan_change\n (user_id, period_start, changed_at, previous_plan, new_plan,\n previous_included_cost_cents, new_included_cost_cents)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (user_id, period_start, changed_at, previous_plan, new_plan) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Text",+ "Text",+ "Int8",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "78beb1a2b480da66fb5a5c767ccae3a4abd54f516aad873c17ae37342cb142fa"+}diff --git a/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.json b/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.jsonnew file mode 100644index 0000000000..7c40a440bf--- /dev/null+++ b/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens,\n total, created_at, count_usage)\n VALUES ($1, 'chat', $2, 'test-model', 0, 0, 1.0, $3, $4)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76"+}diff --git a/.sqlx/query-a50cfc5a5bcd0675c29e39963cc969e7de230b342469d949a3a524e91f4b5e99.json b/.sqlx/query-a50cfc5a5bcd0675c29e39963cc969e7de230b342469d949a3a524e91f4b5e99.jsonnew file mode 100644index 0000000000..e4e084df65--- /dev/null+++ b/.sqlx/query-a50cfc5a5bcd0675c29e39963cc969e7de230b342469d949a3a524e91f4b5e99.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "WITH history AS MATERIALIZED (\n SELECT user_id, changed_at, previous_plan, new_plan,\n previous_included_cost_cents, new_included_cost_cents\n FROM ai_billing_plan_change\n WHERE user_id = ANY($1) AND period_start = $2 AND changed_at < $3\n), boundaries AS (\n SELECT requested.user_id, $2::timestamptz AS start\n FROM UNNEST($1::text[]) AS requested(user_id)\n UNION\n SELECT user_id, changed_at FROM history\n), intervals AS (\n SELECT user_id, start,\n LEAD(start, 1, $3) OVER (PARTITION BY user_id ORDER BY start) AS end\n FROM boundaries\n), usage_segments AS (\n SELECT interval.user_id, interval.start,\n COALESCE(SUM(COALESCE(\n usage.total::float8,\n usage.input_tokens::float8 / 1000000.0 * $4\n + usage.output_tokens::float8 / 1000000.0 * $5\n + usage.cache_read_input_tokens::float8 / 1000000.0 * $6\n + usage.cache_write_input_tokens::float8 / 1000000.0 * $7\n )), 0)::float8 AS usd,\n EXISTS (\n SELECT 1 FROM ai_billing_usage_period AS policy\n WHERE policy.user_id = interval.user_id AND policy.period_start = $2\n AND policy.policy = 'public_allowance_v1'\n ) AS public_funding\n FROM intervals AS interval\n LEFT JOIN ai_usage AS usage\n ON usage.user_id = interval.user_id\n AND usage.created_at >= interval.start AND usage.created_at < interval.end\n AND usage.count_usage = TRUE\n GROUP BY interval.user_id, interval.start\n)\nSELECT TRUE AS \"is_plan_change!\", user_id AS \"user_id!\", changed_at AS \"start!\",\n previous_plan AS \"previous_plan?\", new_plan AS \"new_plan?\",\n previous_included_cost_cents, new_included_cost_cents,\n NULL::float8 AS \"usd?\", NULL::boolean AS \"public_funding?\"\nFROM history\nUNION ALL\nSELECT FALSE, user_id, start, NULL::text, NULL::text,\n NULL::bigint, NULL::bigint, usd, public_funding\nFROM usage_segments\nORDER BY \"user_id!\", \"start!\", \"is_plan_change!\" DESC, \"previous_plan?\", \"new_plan?\"\n",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "is_plan_change!",+ "type_info": "Bool"+ },+ {+ "ordinal": 1,+ "name": "user_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "start!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "previous_plan?",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "new_plan?",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "previous_included_cost_cents",+ "type_info": "Int8"+ },+ {+ "ordinal": 6,+ "name": "new_included_cost_cents",+ "type_info": "Int8"+ },+ {+ "ordinal": 7,+ "name": "usd?",+ "type_info": "Float8"+ },+ {+ "ordinal": 8,+ "name": "public_funding?",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Timestamptz",+ "Timestamptz",+ "Float8",+ "Float8",+ "Float8",+ "Float8"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "a50cfc5a5bcd0675c29e39963cc969e7de230b342469d949a3a524e91f4b5e99"+}diff --git a/.sqlx/query-cc20f902b9d7bbba6c10722be138edf3841aca4bbe8f1994a249430a388cb6d1.json b/.sqlx/query-cc20f902b9d7bbba6c10722be138edf3841aca4bbe8f1994a249430a388cb6d1.jsonnew file mode 100644index 0000000000..1ccf9a0ff2--- /dev/null+++ b/.sqlx/query-cc20f902b9d7bbba6c10722be138edf3841aca4bbe8f1994a249430a388cb6d1.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy) VALUES ($1, $1, 'sub_test', $2, $3, 'public_allowance_v1')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "cc20f902b9d7bbba6c10722be138edf3841aca4bbe8f1994a249430a388cb6d1"+}diff --git a/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.json b/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.jsonnew file mode 100644index 0000000000..43dbb6e867--- /dev/null+++ b/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM ai_billing_usage_observation",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491"+}diff --git a/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.json b/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.jsonnew file mode 100644index 0000000000..82f38da2f6--- /dev/null+++ b/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b"+}diff --git a/.sqlx/query-ea9699f158d8430269b28e8d986ae4f453b335df009b120fc9a38925da14fd7e.json b/.sqlx/query-ea9699f158d8430269b28e8d986ae4f453b335df009b120fc9a38925da14fd7e.jsonnew file mode 100644index 0000000000..60c19ecd69--- /dev/null+++ b/.sqlx/query-ea9699f158d8430269b28e8d986ae4f453b335df009b120fc9a38925da14fd7e.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, 'sub_team', $2, $3)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "ea9699f158d8430269b28e8d986ae4f453b335df009b120fc9a38925da14fd7e"+}diff --git a/.sqlx/query-f3c3ebc7e9ef14262161957ed9a02091b8106d1ed6772bfe60cafd47dbe3a620.json b/.sqlx/query-f3c3ebc7e9ef14262161957ed9a02091b8106d1ed6772bfe60cafd47dbe3a620.jsonnew file mode 100644index 0000000000..e46443e297--- /dev/null+++ b/.sqlx/query-f3c3ebc7e9ef14262161957ed9a02091b8106d1ed6772bfe60cafd47dbe3a620.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, $2, $3, $4)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "f3c3ebc7e9ef14262161957ed9a02091b8106d1ed6772bfe60cafd47dbe3a620"+}diff --git a/Cargo.lock b/Cargo.lockindex 8b3d2095f6..815ae7bad2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -19138,6 +19138,7 @@ dependencies = ["url","utoipa","uuid",+ "wiremock","workspace-hack",]diff --git a/apps/web/billing-lab.html b/apps/web/billing-lab.htmlnew file mode 100644index 0000000000..55e982ffc4--- /dev/null+++ b/apps/web/billing-lab.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en" data-platform="browser" data-touch-device="false">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Billing Lab · Macro</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/features/billing-lab/entry.tsx"></script>+ </body>+</html>diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0567e175c7..5043852c05 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -7,6 +7,7 @@"dev": "bun run dev:prepare && bun run dev:server","dev:prepare": "just ensure-cache-wasm && just ensure-agent-fold-wasm && just ensure-database-sql-wasm && just ensure-pptx-engine-wasm && just ensure-docx-engine-wasm && just ensure-fig-engine-wasm && just ensure-psd-engine-wasm && just ensure-ai-engine-wasm","dev:server": "vite -c vite.config.ts",+ "dev:billing": "vite -c vite.config.ts --open /billing-lab.html","build": "vite build -c vite.config.ts && bun run postbuild:semver && bun run postbuild:bundle-manifest","postbuild:semver": "echo $npm_package_version+$(git rev-parse --short HEAD) > ./dist/semver.txt","postbuild:bundle-manifest": "bun ./scripts/write-bundle-manifest.mjs",diff --git a/apps/web/src/features/billing-lab/README.md b/apps/web/src/features/billing-lab/README.mdnew file mode 100644index 0000000000..6ed95f2f5c--- /dev/null+++ b/apps/web/src/features/billing-lab/README.md@@ -0,0 +1,108 @@+# Billing Lab++A local workspace for reviewing the real Billing settings, Usage settings,+credit purchase, Auto-Reload, and usage-limit UI with deterministic fixtures.+It runs without signing in, a local backend, or Stripe credentials.++From `apps/web`:++```sh+bun run dev:billing+```++Open `/billing-lab.html` on the URL printed by Vite. If another worktree uses the+default port, choose a free one with `PORT=3003 bun run dev:billing`.+`MACRO_DEV_HTTPS=false` uses HTTP. You can also open the lab from a local app's+**Settings → Usage → Developer tools → Open Billing Lab**.++## Try Max → Pro++1. Select **Max → Pro at renewal** to start with a scheduled downgrade.+2. Max and its included usage stay active. Billing shows the scheduled Pro+ downgrade and its effective date.+3. Switch to the Usage preview to inspect the current allowance, or choose+ **Keep Max plan** in Billing to cancel the downgrade without resetting usage.+4. Reset the scenario if you canceled, then choose **Advance to renewal**.+ The plan becomes Pro and included usage+ resets; prepaid credits carry over.++**Max → Pro at renewal** starts with the downgrade already scheduled. The+timeline exposes the same state and also offers **Cancel scheduled change**.++## Other states and actions++The 20 presets cover Free/Pro/Max, a scheduled cancellation, exhausted+allowances, prepaid credits, paused reloads, spending limits, payment failures,+team members and owners, unlimited access, loading, errors, and pre-launch UI.+Controls advance time, change the usage percentage and credit balance, and+open the actual usage-limit dialog. **Fail the next billing request** injects+one request failure so the existing error and retry UI can be reviewed.++Purchases and payment management open an explicitly simulated flow. Choose+**Complete simulation** to apply its fixture transition, or cancel. Automatic+reload settings update the fixture; the lab does not run automatic charges or+meter AI requests. **Reset** restores the selected preset. **Copy scenario+link** shares the preset, not subsequent edits; refresh also restores it.++## Monthly reload limit notice++Choose **Monthly reload limit reached**. The lab opens Usage with a $50 monthly+cap already spent. The shared notice banner puts the amount in its title and+the reset date on the right. Try both full width and compact layout.++**Adjust limit** opens the real Auto-Reload dialog. Raising the cap clears the+notice while keeping this month's spend. **Add credits** opens the real purchase+dialog; manually purchased credits do not change auto-reload spend. Advancing+into November resets reload spend. Reload budgets use UTC calendar months,+independently of subscription renewal.++Live settings use the same banner with authoritative monthly reload commitments+and reset facts from the API. Paid and pending reloads, plus failed invoices that+can still collect, consume the cap; manual credit purchases do not. The notice+also appears when the remaining cap cannot fund the $0.50 minimum reload.+A limit-reached state does not imply existing credits or the included allowance+are exhausted. Older backends without budget facts show no cap notice.++## Team credit controls++The **Teams** group opens directly to Usage settings. **Mixed-plan team owner**+starts with a shared $25 credit balance and automatic reload enabled for four+seats (one Max, three Pro). Use **Add more** to purchase shared credits, or+**Automatic reload** to configure the minimum balance, target balance, monthly+spending cap, and payment method through the real application dialogs.+The section is labeled **Team Usage Credits** with “Credits are shared by your+entire team.” Purchase and auto-reload dialogs repeat the shared-team scope.++Try **Team credits exhausted**, **Team reload paused**, and **Team monthly reload+limit** to review empty-balance, payment-recovery, and cap-reached states. Complete+the simulated payment-method flow and save reload settings to test recovery.+Manual purchases increase the shared balance without consuming the reload cap.+Request failures and calendar-month resets work for these scenarios too.++Owners use **Settings → Usage** for shared credit controls in the live app;+Team settings manages seats. The included-usage meter is always the viewer's+own seat allowance, not a pooled team allowance. **Team-paid Max member** shows+the team-managed notice without the balance, purchase, or reload controls.+The lab simulates one viewer at a time; it does not meter other members' AI+activity or run automatic charges. Its fixture budget follows the same decoder+and cap status used by live Usage settings.++## Boundaries++Billing and Usage views receive injected capabilities. The lab uses the same+usage-summary decoder as the app, with no API clients, login, remote mutations,+or hosted payment navigation. Team-settings navigation is recorded locally.++The simulator's allowances and transitions are UI fixtures, not a billing+policy test or production price catalog. Backend and Stripe integration tests+remain responsible for real entitlement changes, invoices, proration, and+webhook handling.++The standalone HTML entry is excluded from Vite's production build inputs.+Rendering additionally requires `import.meta.hot`, the app's local-only gate.++Run fixture and action tests from `apps/web`:++```sh+bun run test src/features/billing-lab+```diff --git a/apps/web/src/features/billing-lab/core/billing-simulation.test.ts b/apps/web/src/features/billing-lab/core/billing-simulation.test.tsnew file mode 100644index 0000000000..8a00249ddd--- /dev/null+++ b/apps/web/src/features/billing-lab/core/billing-simulation.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest';+import {+ advanceDays,+ changePlan,+ createScenario,+ includedCents,+ parseScenario,+ renew,+ setUsage,+} from './billing-simulation';++describe('billing-cycle UI fixtures', () => {+ it('keeps Max and its usage until the scheduled Pro renewal', () => {+ const max = createScenario('max');+ const scheduled = changePlan(max, 'premium');+ expect(scheduled.tier).toBe('max');+ expect(scheduled.scheduledPlan).toBe('premium');+ expect(scheduled.usedCents).toBe(max.usedCents);+ expect(scheduled.periodEnd).toBe(max.periodEnd);+ const renewed = renew(scheduled);+ expect(renewed.tier).toBe('premium');+ expect(renewed.scheduledPlan).toBeUndefined();+ expect(renewed.usedCents).toBe(0);+ expect(renewed.periodStart).toBe(max.periodEnd);+ });++ it('cancels a downgrade by keeping Max without resetting usage', () => {+ const before = createScenario('max-to-pro');+ const canceled = changePlan(before, 'max');+ expect(canceled.tier).toBe('max');+ expect(canceled.scheduledPlan).toBeUndefined();+ expect(canceled.usedCents).toBe(before.usedCents);+ expect(canceled.periodEnd).toBe(before.periodEnd);+ });++ it('upgrades Pro immediately and preserves the cycle and credits', () => {+ const before = createScenario('credits');+ const upgraded = changePlan(before, 'max');+ expect(upgraded.tier).toBe('max');+ expect(upgraded.usedCents).toBe(0);+ expect(upgraded.creditBalanceCents).toBe(before.creditBalanceCents);+ expect(upgraded.periodStart).toBe(before.periodStart);+ expect(upgraded.periodEnd).toBe(before.periodEnd);+ });++ it('carries prepaid credits into the next cycle', () => {+ const before = createScenario('credits');+ const after = renew(before);+ expect(after.creditBalanceCents).toBe(before.creditBalanceCents);+ expect(after.usedCents).toBe(0);+ expect(after.periodEnd).toBe('2026-12-01T12:00:00.000Z');+ });++ it('applies a scheduled cancellation at renewal', () => {+ const before = createScenario('canceling');+ expect(before.tier).toBe('premium');+ expect(renew(before).tier).toBe('free');+ });++ it('crosses renewal boundaries when advancing the clock', () => {+ const after = advanceDays(createScenario('max-to-pro'), 50);+ expect(after.tier).toBe('premium');+ expect(after.now).toBe('2026-12-04T12:00:00.000Z');+ expect(after.periodStart).toBe('2026-12-01T12:00:00.000Z');+ expect(after.periodEnd).toBe('2027-01-01T12:00:00.000Z');+ });++ it('does not let a team member change a paid seat', () => {+ const member = createScenario('team-member');+ expect(changePlan(member, 'premium')).toEqual(member);+ });++ it('keeps the owner allowance scoped to their own seat', () => {+ const owner = createScenario('team-owner');+ expect(includedCents(owner)).toBe(includedCents(createScenario('max')));+ expect(owner.usedCents / includedCents(owner)).toBe(0.75);+ expect(setUsage(owner, 100).usedCents).toBe(20_000);+ });++ it('uses the right limit state for free, paid, and funded accounts', () => {+ expect(setUsage(createScenario('free'), 100).blockedReason).toBe(+ 'free_allowance_exhausted'+ );+ expect(setUsage(createScenario('pro'), 100).blockedReason).toBe(+ 'allowance_exhausted'+ );+ expect(+ setUsage(createScenario('credits'), 100).blockedReason+ ).toBeUndefined();+ expect(+ setUsage(createScenario('unlimited'), 100).blockedReason+ ).toBeUndefined();+ });++ it('resets reload spend at the UTC month boundary, independently of subscription renewal', () => {+ const capped = {+ ...createScenario('spending-limit'),+ periodStart: '2026-09-20T12:00:00.000Z',+ periodEnd: '2026-10-20T12:00:00.000Z',+ };+ const renewed = renew(capped);+ expect(renewed.reloadSpentCents).toBe(5_000);+ expect(renewed.periodEnd).toBe('2026-11-20T12:00:00.000Z');+ const nextMonth = advanceDays(renewed, 12);+ expect(nextMonth.now).toBe('2026-11-01T12:00:00.000Z');+ expect(nextMonth.reloadSpentCents).toBe(0);+ expect(nextMonth.periodEnd).toBe(renewed.periodEnd);+ expect(nextMonth.autoReload.enabled).toBe(true);+ });++ it('handles unknown scenario links with the downgrade example', () => {+ expect(parseScenario('not-a-scenario')).toBe('max-to-pro');+ expect(parseScenario('payment-failed')).toBe('payment-failed');+ });+});diff --git a/apps/web/src/features/billing-lab/core/billing-simulation.ts b/apps/web/src/features/billing-lab/core/billing-simulation.tsnew file mode 100644index 0000000000..0e67343b19--- /dev/null+++ b/apps/web/src/features/billing-lab/core/billing-simulation.ts@@ -0,0 +1,386 @@+import { match } from 'ts-pattern';+import type { PlanTier } from '../../paywall/plans';+import type { AutoReloadSettings } from '../../usage/core/usage';+import { DEFAULT_AUTO_RELOAD } from '../../usage/core/usage';++/** Deliberately fixed fixture values; production pricing still comes from the API. */+export const FIXTURE_ALLOWANCES: Record<PlanTier, number> = {+ free: 100,+ premium: 2_000,+ max: 20_000,+};++export const SCENARIOS = [+ {+ id: 'max-to-pro',+ group: 'Plan changes',+ title: 'Max → Pro at renewal',+ description:+ 'A downgrade is scheduled. Max access and usage stay in place until renewal.',+ },+ {+ id: 'max',+ group: 'Plan changes',+ title: 'Max, mid-cycle',+ description: 'Inspect Max access and usage during an active billing cycle.',+ },+ {+ id: 'pro',+ group: 'Plan changes',+ title: 'Pro, ready to upgrade',+ description:+ 'Upgrade to Max and inspect the fresh allowance without moving the renewal date.',+ },+ {+ id: 'canceling',+ group: 'Plan changes',+ title: 'Subscription ending',+ description:+ 'Paid access lasts until renewal, then the account becomes Free.',+ },+ {+ id: 'free',+ group: 'Usage & credits',+ title: 'Free account',+ description: 'Preview the plan cards, free allowance, and upgrade flow.',+ },+ {+ id: 'free-exhausted',+ group: 'Usage & credits',+ title: 'Free limit reached',+ description: 'The free allowance is exhausted. View the upgrade prompt.',+ },+ {+ id: 'pro-exhausted',+ group: 'Usage & credits',+ title: 'Pro limit reached',+ description: 'Included AI is exhausted and no credits remain.',+ },+ {+ id: 'credits',+ group: 'Usage & credits',+ title: 'Using additional credits',+ description:+ 'Included usage is exhausted. A prepaid balance keeps AI available.',+ },+ {+ id: 'reload-paused',+ group: 'Usage & credits',+ title: 'Automatic reload paused',+ description:+ 'A reload payment failed. Inspect the paused state and retry controls.',+ },+ {+ id: 'spending-limit',+ group: 'Usage & credits',+ title: 'Monthly reload limit reached',+ description:+ 'A monthly auto-reload cap is reached. Adjust the limit, add credits, or wait for reset.',+ },+ {+ id: 'payment-failed',+ group: 'Usage & credits',+ title: 'Usage payment failed',+ description: 'Preview the payment-failure message and payment-method flow.',+ },+ {+ id: 'team-member',+ group: 'Teams',+ title: 'Team-paid Max member',+ description:+ 'The team pays for this seat; billing controls belong to the owner.',+ },+ {+ id: 'team-owner',+ group: 'Teams',+ title: 'Mixed-plan team owner',+ description:+ 'Manage shared credits and automatic reload for one Max seat and three Pro seats. Included usage is per seat.',+ },+ {+ id: 'team-owner-exhausted',+ group: 'Teams',+ title: 'Team credits exhausted',+ description:+ 'The owner has exhausted their included usage and the shared credit balance is empty. Buy credits or enable automatic reload.',+ },+ {+ id: 'team-owner-reload-paused',+ group: 'Teams',+ title: 'Team reload paused',+ description:+ 'A reload on the owner’s card failed. Update payment methods and save the team’s reload settings to retry.',+ },+ {+ id: 'team-owner-spending-limit',+ group: 'Teams',+ title: 'Team monthly reload limit',+ description:+ 'The team’s $50 monthly auto-reload cap is spent. The owner can raise it or buy shared credits manually.',+ },+ {+ id: 'unlimited',+ group: 'Access & loading',+ title: 'Unlimited access',+ description: 'Inspect the unlimited allowance and hidden credit controls.',+ },+ {+ id: 'loading',+ group: 'Access & loading',+ title: 'Loading usage',+ description: 'The usage summary has not arrived yet.',+ },+ {+ id: 'error',+ group: 'Access & loading',+ title: 'Usage unavailable',+ description: 'Inspect the error state and Try again action.',+ },+ {+ id: 'before-launch',+ group: 'Access & loading',+ title: 'Before billing launch',+ description: 'Inspect disabled usage controls before launch.',+ },+] as const;++export type ScenarioId = (typeof SCENARIOS)[number]['id'];+export type LimitReason =+ | 'allowance_exhausted'+ | 'free_allowance_exhausted'+ | 'overage_limit_reached'+ | 'overage_payment_failed';+export type BillingSimulation = {+ scenario: ScenarioId;+ tier: PlanTier;+ scheduledPlan?: PlanTier;+ now: string;+ periodStart: string;+ periodEnd: string;+ usedCents: number;+ creditBalanceCents: number;+ creditsConsumedCents: number;+ role: 'solo' | 'owner' | 'member';+ unlimited: boolean;+ status: 'ready' | 'loading' | 'error' | 'before-launch';+ blockedReason?: LimitReason;+ overageEnabled: boolean;+ overageSuspended: boolean;+ overageLimitCents: number;+ autoReload: AutoReloadSettings;+ reloadSuspended: boolean;+ reloadSpentCents: number;+};++export function parseScenario(value: string | null): ScenarioId {+ return (+ SCENARIOS.find((scenario) => scenario.id === value)?.id ?? 'max-to-pro'+ );+}++export function includedCents(state: BillingSimulation): number {+ // The live summary reports the viewer's seat allowance, not a pooled team quota.+ return FIXTURE_ALLOWANCES[state.tier];+}++export function createScenario(scenario: ScenarioId): BillingSimulation {+ const state: BillingSimulation = {+ scenario,+ tier: 'premium',+ now: '2026-10-15T12:00:00.000Z',+ periodStart: '2026-10-01T12:00:00.000Z',+ periodEnd: '2026-11-01T12:00:00.000Z',+ usedCents: 1_000,+ creditBalanceCents: 0,+ creditsConsumedCents: 0,+ role: 'solo',+ unlimited: false,+ status: 'ready',+ overageEnabled: false,+ overageSuspended: false,+ overageLimitCents: 5_000,+ autoReload: { ...DEFAULT_AUTO_RELOAD },+ reloadSuspended: false,+ reloadSpentCents: 0,+ };+ const teamOwner: BillingSimulation = {+ ...state,+ tier: 'max',+ role: 'owner',+ usedCents: 15_000,+ creditBalanceCents: 2_500,+ overageEnabled: true,+ autoReload: {+ ...state.autoReload,+ enabled: true,+ monthlySpendLimitCents: 5_000,+ },+ };+ return match(scenario)+ .returnType<BillingSimulation>()+ .with('max-to-pro', () => ({+ ...state,+ tier: 'max',+ usedCents: 12_000,+ scheduledPlan: 'premium',+ }))+ .with('max', () => ({ ...state, tier: 'max', usedCents: 12_000 }))+ .with('canceling', () => ({ ...state, scheduledPlan: 'free' }))+ .with('free', () => ({ ...state, tier: 'free', usedCents: 45 }))+ .with('free-exhausted', () => ({+ ...state,+ tier: 'free',+ usedCents: 100,+ blockedReason: 'free_allowance_exhausted',+ }))+ .with('pro-exhausted', () => ({+ ...state,+ usedCents: 2_000,+ blockedReason: 'allowance_exhausted',+ }))+ .with('credits', () => ({+ ...state,+ usedCents: 2_000,+ creditBalanceCents: 2_500,+ }))+ .with('reload-paused', () => ({+ ...state,+ usedCents: 2_000,+ overageEnabled: true,+ reloadSuspended: true,+ autoReload: { ...state.autoReload, enabled: true },+ }))+ .with('spending-limit', () => ({+ ...state,+ usedCents: 2_000,+ overageEnabled: true,+ autoReload: {+ ...state.autoReload,+ enabled: true,+ monthlySpendLimitCents: 5_000,+ },+ reloadSpentCents: 5_000,+ blockedReason: 'allowance_exhausted',+ }))+ .with('payment-failed', () => ({+ ...state,+ usedCents: 2_000,+ overageEnabled: true,+ overageSuspended: true,+ blockedReason: 'overage_payment_failed',+ reloadSuspended: true,+ autoReload: { ...state.autoReload, enabled: true },+ }))+ .with('team-member', () => ({+ ...state,+ tier: 'max',+ role: 'member',+ usedCents: 12_000,+ }))+ .with('team-owner', () => teamOwner)+ .with('team-owner-exhausted', () => ({+ ...teamOwner,+ usedCents: FIXTURE_ALLOWANCES.max,+ creditBalanceCents: 0,+ overageEnabled: false,+ autoReload: { ...teamOwner.autoReload, enabled: false },+ blockedReason: 'allowance_exhausted',+ }))+ .with('team-owner-reload-paused', () => ({+ ...teamOwner,+ usedCents: FIXTURE_ALLOWANCES.max,+ creditBalanceCents: 0,+ reloadSuspended: true,+ blockedReason: 'allowance_exhausted',+ }))+ .with('team-owner-spending-limit', () => ({+ ...teamOwner,+ usedCents: FIXTURE_ALLOWANCES.max,+ creditBalanceCents: 500,+ reloadSpentCents: 5_000,+ }))+ .with('unlimited', () => ({ ...state, tier: 'max', unlimited: true }))+ .with('loading', () => ({ ...state, status: 'loading' }))+ .with('error', () => ({ ...state, status: 'error' }))+ .with('before-launch', () => ({ ...state, status: 'before-launch' }))+ .with('pro', () => state)+ .exhaustive();+}++/** UI fixture transitions only; the backend remains the billing-policy authority. */+export function changePlan(+ state: BillingSimulation,+ tier: PlanTier+): BillingSimulation {+ if (state.role === 'member') return state;+ if (tier === state.tier) return { ...state, scheduledPlan: undefined };+ const upgrading = state.tier === 'free' || tier === 'max';+ if (!upgrading) return { ...state, scheduledPlan: tier };+ return {+ ...state,+ tier,+ scheduledPlan: undefined,+ usedCents: 0,+ blockedReason: undefined,+ };+}++export function renew(state: BillingSimulation): BillingSimulation {+ const nextEnd = new Date(state.periodEnd);+ nextEnd.setUTCMonth(nextEnd.getUTCMonth() + 1);+ return {+ ...state,+ tier: state.scheduledPlan ?? state.tier,+ scheduledPlan: undefined,+ now: state.periodEnd,+ reloadSpentCents:+ state.periodEnd.slice(0, 7) === state.now.slice(0, 7)+ ? state.reloadSpentCents+ : 0,+ periodStart: state.periodEnd,+ periodEnd: nextEnd.toISOString(),+ usedCents: 0,+ creditsConsumedCents: 0,+ blockedReason: undefined,+ };+}++export function advanceDays(+ state: BillingSimulation,+ days: number+): BillingSimulation {+ const now = new Date(state.now);+ now.setUTCDate(now.getUTCDate() + days);+ let next = state;+ while (now.getTime() >= Date.parse(next.periodEnd)) next = renew(next);+ return {+ ...next,+ now: now.toISOString(),+ reloadSpentCents:+ now.toISOString().slice(0, 7) === next.now.slice(0, 7)+ ? next.reloadSpentCents+ : 0,+ };+}++export function setUsage(+ state: BillingSimulation,+ percentage: number+): BillingSimulation {+ const usedCents = Math.round(+ (includedCents(state) * Math.min(100, Math.max(0, percentage))) / 100+ );+ return {+ ...state,+ usedCents,+ blockedReason:+ usedCents >= includedCents(state) &&+ state.creditBalanceCents === 0 &&+ !state.overageEnabled &&+ !state.unlimited+ ? state.tier === 'free'+ ? 'free_allowance_exhausted'+ : 'allowance_exhausted'+ : undefined,+ };+}diff --git a/apps/web/src/features/billing-lab/create-billing-lab.test.ts b/apps/web/src/features/billing-lab/create-billing-lab.test.tsnew file mode 100644index 0000000000..0d29a6c375--- /dev/null+++ b/apps/web/src/features/billing-lab/create-billing-lab.test.ts@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createBillingLab } from './create-billing-lab';++describe('billing lab actions', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('adds credits only after the simulated checkout completes', async () => {+ const lab = createBillingLab('credits');+ const checkout = lab.usage.checkout.start(2_500);+ await vi.runAllTimersAsync();+ await checkout;+ expect(lab.payment()).toEqual({ kind: 'credits', amountCents: 2_500 });+ expect(lab.state().creditBalanceCents).toBe(2_500);+ const payment = lab.completePayment();+ await vi.runAllTimersAsync();+ await payment;+ expect(lab.state().creditBalanceCents).toBe(5_000);+ expect(lab.payment()).toBeUndefined();+ });++ it('fails one checkout without changing the balance, then permits a retry', async () => {+ const lab = createBillingLab('pro');+ lab.setFailNext(true);+ const failed = expect(lab.usage.checkout.start(2_500)).rejects.toThrow(+ 'Simulated billing request failure'+ );+ await vi.runAllTimersAsync();+ await failed;+ expect(lab.state().creditBalanceCents).toBe(0);+ expect(lab.payment()).toBeUndefined();+ expect(lab.failNext()).toBe(false);+ expect(lab.pending()).toBe(false);+ const retry = lab.usage.checkout.start(2_500);+ await vi.runAllTimersAsync();+ await retry;+ expect(lab.payment()?.kind).toBe('credits');+ });++ it('keeps manual purchases outside the reload budget and preserves spend when raising the cap', async () => {+ const lab = createBillingLab('spending-limit');+ expect(lab.usage.autoReload.budget?.()).toEqual({+ limitCents: 5_000,+ spentCents: 5_000,+ resetsAt: '2026-11-01T00:00:00.000Z',+ limitReached: true,+ });+ const checkout = lab.usage.checkout.start(2_500);+ await vi.runAllTimersAsync();+ await checkout;+ const complete = lab.completePayment();+ await vi.runAllTimersAsync();+ await complete;+ expect(lab.state().creditBalanceCents).toBe(2_500);+ expect(lab.usage.autoReload.budget?.()?.spentCents).toBe(5_000);+ const save = lab.usage.autoReload.save({+ ...lab.state().autoReload,+ monthlySpendLimitCents: 10_000,+ });+ await vi.runAllTimersAsync();+ await save;+ expect(lab.usage.autoReload.budget?.()).toMatchObject({+ limitCents: 10_000,+ spentCents: 5_000,+ });+ });++ it('rejects billing actions for a team-paid member without opening a payment flow or changing settings', async () => {+ const lab = createBillingLab('team-member');+ await expect(lab.usage.checkout.start(2_500)).rejects.toThrow(+ 'Credit purchase unavailable'+ );+ await expect(+ lab.usage.autoReload.save({ ...lab.state().autoReload, enabled: true })+ ).rejects.toThrow('Auto-Reload unavailable');+ await expect(lab.usage.paymentMethods.open()).rejects.toThrow(+ 'Payment methods unavailable'+ );+ expect(lab.payment()).toBeUndefined();+ expect(lab.pending()).toBe(false);+ expect(lab.state().autoReload.enabled).toBe(false);+ });++ it.each([+ 'team-owner',+ 'team-owner-exhausted',+ 'team-owner-reload-paused',+ 'team-owner-spending-limit',+ ] as const)(+ 'lets the payer manage shared credits in %s',+ async (scenario) => {+ const lab = createBillingLab(scenario);+ expect(lab.surface()).toBe('usage');+ expect(lab.usage.summary()?.billingAccess).toBe('payer');+ expect(lab.billing.teamSeatDescription()).toBe(+ '4 users • 3 Pro seats, 1 Max seat'+ );+ const before = lab.state().creditBalanceCents;+ const spent = lab.state().reloadSpentCents;+ const checkout = lab.usage.checkout.start(2_500);+ await vi.runAllTimersAsync();+ await checkout;+ const complete = lab.completePayment();+ await vi.runAllTimersAsync();+ await complete;+ expect(lab.state().creditBalanceCents).toBe(before + 2_500);+ expect(lab.state().reloadSpentCents).toBe(spent);+ expect(lab.notice()).toBe('Credits added to the shared team balance');+ const save = lab.usage.autoReload.save({+ enabled: true,+ minimumBalanceCents: 1_000,+ targetBalanceCents: 10_000,+ monthlySpendLimitCents: 10_000,+ });+ await vi.runAllTimersAsync();+ await save;+ expect(lab.state().autoReload.monthlySpendLimitCents).toBe(10_000);+ expect(lab.state().reloadSuspended).toBe(false);+ expect(lab.state().role).toBe('owner');+ }+ );++ it('discards an in-flight plan change after selecting another scenario', async () => {+ const lab = createBillingLab('pro');+ const upgrade = lab.billing.changePlan('max');+ lab.selectScenario('free');+ await vi.runAllTimersAsync();+ await upgrade;+ expect(lab.state().tier).toBe('free');+ expect(lab.state().usedCents).toBe(45);+ expect(lab.events()).toEqual([]);+ expect(lab.pending()).toBe(false);+ });++ it('retains a failed payment for retry without activating the subscription', async () => {+ const lab = createBillingLab('free');+ const checkout = lab.billing.checkout('max');+ await vi.runAllTimersAsync();+ await checkout;+ lab.setFailNext(true);+ const failed = expect(lab.completePayment()).rejects.toThrow();+ await vi.runAllTimersAsync();+ await failed;+ expect(lab.state().tier).toBe('free');+ expect(lab.payment()?.kind).toBe('subscription');+ const retry = lab.completePayment();+ await vi.runAllTimersAsync();+ await retry;+ expect(lab.state().tier).toBe('max');+ expect(lab.state().usedCents).toBe(0);+ expect(lab.payment()).toBeUndefined();+ });+});diff --git a/apps/web/src/features/billing-lab/create-billing-lab.ts b/apps/web/src/features/billing-lab/create-billing-lab.tsnew file mode 100644index 0000000000..beb74ed743--- /dev/null+++ b/apps/web/src/features/billing-lab/create-billing-lab.ts@@ -0,0 +1,297 @@+import { createSignal } from 'solid-js';+import { PLAN_BY_TIER } from '../paywall/plans';+import type { BillingContext } from '../settings/context/billing-context';+import type { UsageContext } from '../usage/context/usage-context';+import { toUsageSummary } from '../usage/queries/usage-summary';+import {+ advanceDays,+ type BillingSimulation,+ changePlan,+ createScenario,+ includedCents,+ renew,+ type ScenarioId,+ setUsage,+} from './core/billing-simulation';+import { fixtureSnapshot } from './queries/fixture-snapshot';++export type LabSurface = 'billing' | 'usage';+export type LabPayment =+ | { kind: 'credits'; amountCents: number }+ | { kind: 'subscription'; tier: 'premium' | 'max' }+ | { kind: 'methods' };++const defaultSurface = (scenario: ScenarioId): LabSurface =>+ scenario.startsWith('team-') || scenario === 'spending-limit'+ ? 'usage'+ : 'billing';++export function createBillingLab(initial: ScenarioId) {+ const [state, setState] = createSignal(createScenario(initial));+ const [surface, setSurface] = createSignal<LabSurface>(+ defaultSurface(initial)+ );+ const [pending, setPending] = createSignal(false);+ const [failNext, setFailNext] = createSignal(false);+ const [notice, setNotice] = createSignal('');+ const [limitOpen, setLimitOpen] = createSignal(false);+ const [payment, setPayment] = createSignal<LabPayment>();+ const [events, setEvents] = createSignal<+ { id: number; at: string; label: string }[]+ >([]);+ let generation = 0;+ let nextEvent = 0;+ const record = (label: string) => {+ setNotice(label);+ setEvents((previous) =>+ [{ id: ++nextEvent, at: state().now, label }, ...previous].slice(0, 12)+ );+ };+ const update = (+ apply: (state: BillingSimulation) => BillingSimulation,+ label: string+ ) => {+ setState(apply);+ record(label);+ };+ const selectScenario = (scenario: ScenarioId) => {+ generation++;+ setState(createScenario(scenario));+ setSurface(defaultSurface(scenario));+ setPending(false);+ setFailNext(false);+ setLimitOpen(false);+ setPayment(undefined);+ setEvents([]);+ setNotice('');+ };+ const perform = async (label: string, action: () => void) => {+ const current = generation;+ setPending(true);+ try {+ await new Promise<void>((resolve) => setTimeout(resolve, 300));+ if (generation !== current) return;+ if (failNext()) {+ setFailNext(false);+ record(`${label} failed — simulated request error`);+ throw new Error('Simulated billing request failure');+ }+ action();+ } finally {+ if (generation === current) setPending(false);+ }+ };+ const openPayment = (value: LabPayment) => {+ setPayment(value);+ record('Opened simulated payment flow');+ };+ const startBillingPayment = async (value: LabPayment) => {+ try {+ await perform('Payment flow', () => openPayment(value));+ } catch {+ // Billing's simulated failure is visible in the lab notice.+ }+ };+ const billing: BillingContext = {+ tier: () => state().tier,+ renewalDate: () => state().periodEnd,+ scheduledChange: () => {+ const plan = state().scheduledPlan;+ return plan ? { plan, effectiveAt: state().periodEnd } : undefined;+ },+ hasPaid: () => state().tier !== 'free',+ aiUsageBilling: () => state().status !== 'before-launch',+ teamRole: () =>+ state().role === 'solo'+ ? undefined+ : state().role === 'owner'+ ? 'owner'+ : 'member',+ teamSeatDescription: () =>+ state().role === 'owner'+ ? '4 users • 3 Pro seats, 1 Max seat'+ : undefined,+ billedThroughTeam: () => state().role === 'member',+ isOwnerOrSolo: () => state().role !== 'member',+ canManageSubscription: () => state().role !== 'member',+ canChangePlan: () => state().role !== 'member',+ changingPlan: pending,+ checkout: (tier) => startBillingPayment({ kind: 'subscription', tier }),+ manage: () => startBillingPayment({ kind: 'methods' }),+ openTeamSettings: () =>+ record('Team settings navigation requested (simulated)'),+ changePlan: async (tier) => {+ try {+ await perform('Plan change', () => {+ const previous = state();+ const next = changePlan(previous, tier);+ setState(next);+ record(+ next.scheduledPlan+ ? `${PLAN_BY_TIER[tier].name} scheduled for renewal; ${PLAN_BY_TIER[previous.tier].name} stays active`+ : previous.tier === tier+ ? 'Scheduled change canceled; active plan and usage preserved'+ : `${PLAN_BY_TIER[tier].name} active; included usage reset`+ );+ });+ } catch {+ // The lab notice exposes the simulated failure; no remote mutation runs.+ }+ },+ };+ const manageable = () =>+ state().role !== 'member' && state().tier !== 'free' && !state().unlimited;+ const usage: UsageContext = {+ available: () => state().status !== 'before-launch',+ summary: () =>+ state().status === 'loading' || state().status === 'error'+ ? undefined+ : toUsageSummary(fixtureSnapshot(state())),+ loading: () => state().status === 'loading',+ failed: () => state().status === 'error',+ refresh: () =>+ update(+ (value) => ({ ...value, status: 'ready' }),+ 'Usage summary loaded'+ ),+ checkout: {+ pending,+ supportedAmounts: () => [2_500, 5_000, 10_000],+ start: async (amountCents) => {+ if (!manageable()) throw new Error('Credit purchase unavailable');+ await perform('Credit checkout', () =>+ openPayment({ kind: 'credits', amountCents })+ );+ return 'billing-lab:checkout';+ },+ },+ autoReload: {+ settings: () => state().autoReload,+ budget: () => usage.summary()?.autoReload.budget,+ available: manageable,+ pending,+ suspended: () => state().reloadSuspended,+ preview: () => false,+ save: async (settings) => {+ if (!manageable()) throw new Error('Auto-Reload unavailable');+ await perform('Automatic reload update', () =>+ update(+ (value) => ({+ ...value,+ autoReload: settings,+ overageEnabled: settings.enabled,+ reloadSuspended: false,+ overageSuspended: false,+ }),+ 'Automatic reload settings saved'+ )+ );+ },+ },+ paymentMethods: {+ pending,+ open: async () => {+ if (!manageable()) throw new Error('Payment methods unavailable');+ await perform('Payment methods', () =>+ openPayment({ kind: 'methods' })+ );+ return 'billing-lab:payment-methods';+ },+ },+ existingUsageBilling: {+ pending,+ turnOff: async () =>+ await perform('Usage billing update', () =>+ update(+ (value) => ({+ ...value,+ overageEnabled: false,+ overageSuspended: false,+ autoReload: { ...value.autoReload, enabled: false },+ }),+ 'Usage billing turned off'+ )+ ),+ },+ // Payment completion is explicit in the lab; never navigate to a hosted URL.+ navigateToPayment: () => {},+ openPlans: () => setSurface('billing'),+ };++ return {+ state,+ surface,+ setSurface,+ pending,+ failNext,+ setFailNext,+ notice,+ events,+ limitOpen,+ setLimitOpen,+ payment,+ setPayment,+ billing,+ usage,+ selectScenario,+ setUsage: (percentage: number) =>+ setState((value) => setUsage(value, percentage)),+ setCredits: (cents: number) =>+ setState((value) => ({+ ...value,+ creditBalanceCents: cents,+ blockedReason: cents > 0 ? undefined : value.blockedReason,+ })),+ advance: (days: number) =>+ update(+ (value) => advanceDays(value, days),+ `Advanced ${days} day${days === 1 ? '' : 's'}`+ ),+ renew: () => update(renew, 'Billing cycle renewed; included usage reset'),+ cancelChange: () =>+ update(+ (value) => ({ ...value, scheduledPlan: undefined }),+ 'Scheduled change canceled; active plan and usage preserved'+ ),+ exhaust: () =>+ update((value) => setUsage(value, 100), 'Included usage exhausted'),+ completePayment: async () => {+ const selected = payment();+ if (!selected) return;+ await perform('Payment', () => {+ if (selected.kind === 'credits')+ update(+ (value) => ({+ ...value,+ creditBalanceCents:+ value.creditBalanceCents + selected.amountCents,+ blockedReason: undefined,+ }),+ state().role === 'owner'+ ? 'Credits added to the shared team balance'+ : 'Credits added to the simulated account'+ );+ if (selected.kind === 'subscription')+ update(+ (value) => changePlan(value, selected.tier),+ 'Simulated subscription activated'+ );+ if (selected.kind === 'methods')+ update(+ (value) => ({+ ...value,+ reloadSuspended: false,+ overageSuspended: false,+ blockedReason: undefined,+ }),+ 'Simulated payment method updated'+ );+ setPayment(undefined);+ });+ },+ percentage: () =>+ Math.round((state().usedCents / includedCents(state())) * 100),+ };+}++export type BillingLab = ReturnType<typeof createBillingLab>;diff --git a/apps/web/src/features/billing-lab/entry.tsx b/apps/web/src/features/billing-lab/entry.tsxnew file mode 100644index 0000000000..58b3f54c07--- /dev/null+++ b/apps/web/src/features/billing-lab/entry.tsx@@ -0,0 +1,36 @@+import '../../index.css';+import '@fontsource-variable/inter';+import '@fontsource-variable/roboto-mono';+import { applyTheme, resolveActiveThemeId } from '@theme/utils/themeUtils';+import { onCleanup } from 'solid-js';+import { render } from 'solid-js/web';+import { parseScenario, type ScenarioId } from './core/billing-simulation';+import { createBillingLab } from './create-billing-lab';+import { BillingLabView } from './views/billing-lab';++function BillingLab() {+ const lab = createBillingLab(+ parseScenario(new URLSearchParams(window.location.search).get('scenario'))+ );+ const onSelect = (scenario: ScenarioId) => {+ lab.selectScenario(scenario);+ const url = new URL(window.location.href);+ url.searchParams.set('scenario', scenario);+ window.history.pushState({}, '', url);+ };+ const onPopState = () =>+ lab.selectScenario(+ parseScenario(new URLSearchParams(window.location.search).get('scenario'))+ );+ window.addEventListener('popstate', onPopState);+ onCleanup(() => window.removeEventListener('popstate', onPopState));+ return <BillingLabView lab={lab} onSelect={onSelect} />;+}++// This HTML entry is deliberately absent from Vite's production build inputs.+// HMR is the same local-only gate used by the app's other local developer tools.+if (import.meta.hot) {+ applyTheme(resolveActiveThemeId());+ const root = document.getElementById('root');+ if (root) render(() => <BillingLab />, root);+}diff --git a/apps/web/src/features/billing-lab/queries/fixture-snapshot.ts b/apps/web/src/features/billing-lab/queries/fixture-snapshot.tsnew file mode 100644index 0000000000..6dd507dac8--- /dev/null+++ b/apps/web/src/features/billing-lab/queries/fixture-snapshot.ts@@ -0,0 +1,54 @@+import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';+import { MIN_RELOAD_CENTS } from '../../usage/core/usage';+import {+ type BillingSimulation,+ includedCents,+} from '../core/billing-simulation';++/** Adapt local fixture facts to the same decoder used by the live Usage view. */+export function fixtureSnapshot(state: BillingSimulation): AiUsageSnapshot {+ const included = includedCents(state);+ const now = new Date(state.now);+ const limit = state.autoReload.monthlySpendLimitCents;+ return {+ tier: state.tier,+ unlimited: state.unlimited,+ payer: 'billing-lab',+ can_manage_billing: state.role !== 'member',+ seats: state.role === 'solo' ? 1 : 4,+ period_start: state.periodStart,+ period_end: state.periodEnd,+ included_cents: included,+ used_cents: state.usedCents,+ remaining_cents: Math.max(0, included - state.usedCents),+ credit_balance_cents: state.creditBalanceCents,+ credits_shared_with_team: state.role !== 'solo',+ credits_consumed_cents: state.creditsConsumedCents,+ overage_enabled: state.overageEnabled,+ overage_limit_cents: state.overageLimitCents,+ overage_charged_cents:+ state.blockedReason === 'overage_limit_reached'+ ? state.overageLimitCents+ : 0,+ overage_suspended: state.overageSuspended,+ uncovered_cents: 0,+ blocked_reason: state.blockedReason,+ auto_reload: {+ minimum_balance_cents: state.autoReload.minimumBalanceCents,+ target_balance_cents: state.autoReload.targetBalanceCents,+ monthly_spend_limit_cents: state.autoReload.monthlySpendLimitCents,+ monthly_budget:+ limit === null+ ? null+ : {+ committed_cents: state.reloadSpentCents,+ resets_at: new Date(+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)+ ).toISOString(),+ limit_reached: limit - state.reloadSpentCents < MIN_RELOAD_CENTS,+ },+ suspended: state.reloadSuspended,+ active: state.autoReload.enabled && !state.reloadSuspended,+ },+ };+}diff --git a/apps/web/src/features/billing-lab/views/billing-lab.tsx b/apps/web/src/features/billing-lab/views/billing-lab.tsxnew file mode 100644index 0000000000..5e64757f49--- /dev/null+++ b/apps/web/src/features/billing-lab/views/billing-lab.tsx@@ -0,0 +1,591 @@+import ArrowClockwiseIcon from '@phosphor/arrow-clockwise.svg';+import ArrowRightIcon from '@phosphor/arrow-right.svg';+import CalendarIcon from '@phosphor/calendar-blank.svg';+import FlaskIcon from '@phosphor/flask.svg';+import { Button, Dialog, Layer, Surface } from '@ui';+import { createSignal, For, type JSX, Show } from 'solid-js';+import { match } from 'ts-pattern';+import { AiUsageLimitDialogView } from '../../paywall/components/ai-usage-limit-dialog';+import { PLAN_BY_TIER } from '../../paywall/plans';+import { BillingSettingsView } from '../../settings/views/billing-settings';+import { formatCreditBalance } from '../../usage/core/usage';+import { UsageSettingsView } from '../../usage/views/usage-settings';+import { SCENARIOS, type ScenarioId } from '../core/billing-simulation';+import type { BillingLab, LabPayment } from '../create-billing-lab';++function ControlSection(props: { title: string; children: JSX.Element }) {+ return (+ <section class="flex flex-col gap-4 border-t border-edge-muted pt-5">+ <h3 class="text-xs font-medium tracking-wide text-ink-muted">+ {props.title}+ </h3>+ {props.children}+ </section>+ );+}++function Metric(props: { label: string; value: string; detail: string }) {+ return (+ <div class="min-w-0 rounded-xl border border-edge-muted bg-surface p-4">+ <p class="text-[11px] text-ink-muted">{props.label}</p>+ <p class="mt-1 text-xl font-medium tracking-tight text-ink">+ {props.value}+ </p>+ <p class="mt-1 truncate text-[11px] text-ink-extra-muted">+ {props.detail}+ </p>+ </div>+ );+}++function PaymentSummary(props: { payment: LabPayment }) {+ return (+ <p>+ {match(props.payment)+ .with(+ { kind: 'credits' },+ (payment) =>+ `Add ${formatCreditBalance(payment.amountCents)} in usage credits`+ )+ .with(+ { kind: 'subscription' },+ (payment) => `Start a ${PLAN_BY_TIER[payment.tier].name} subscription`+ )+ .with(+ { kind: 'methods' },+ () =>+ 'Update the payment method and clear the simulated payment failure.'+ )+ .exhaustive()}+ </p>+ );+}++const dateLabel = (value: string) =>+ new Date(value).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ });++export function BillingLabView(props: {+ lab: BillingLab;+ onSelect: (id: ScenarioId) => void;+}) {+ const lab = props.lab;+ const [compact, setCompact] = createSignal(false);+ const [paymentError, setPaymentError] = createSignal<string>();+ const [copied, setCopied] = createSignal(false);+ const selectedScenario = () =>+ SCENARIOS.find((scenario) => scenario.id === lab.state().scenario)!;+ const cycleProgress = () =>+ Math.min(+ 100,+ Math.max(+ 0,+ ((Date.parse(lab.state().now) - Date.parse(lab.state().periodStart)) /+ (Date.parse(lab.state().periodEnd) -+ Date.parse(lab.state().periodStart))) *+ 100+ )+ );+ const remainingDays = () =>+ Math.ceil(+ (Date.parse(lab.state().periodEnd) - Date.parse(lab.state().now)) /+ 86_400_000+ );+ const copyLink = async () => {+ try {+ await navigator.clipboard.writeText(window.location.href);+ setCopied(true);+ } catch {+ setCopied(false);+ }+ };+ const completePayment = async () => {+ setPaymentError(undefined);+ try {+ await lab.completePayment();+ } catch {+ setPaymentError('Simulated payment failed. Try again or cancel.');+ }+ };++ return (+ <Layer depth={1}>+ <div class="h-screen overflow-y-auto bg-panel text-ink font-sans">+ <header class="flex flex-wrap items-center justify-between gap-4 border-b border-edge-muted bg-surface px-6 py-4">+ <div class="flex items-center gap-3">+ <div class="flex size-10 items-center justify-center rounded-xl border border-accent/20 bg-accent/10 text-accent">+ <FlaskIcon class="size-5" />+ </div>+ <div>+ <h1 class="text-base font-semibold tracking-tight">+ Billing Lab+ </h1>+ <p class="mt-0.5 text-xs text-ink-muted">+ A workspace for every moment in the billing cycle+ </p>+ </div>+ </div>+ <div class="flex items-center gap-3">+ <span class="flex items-center gap-1.5 rounded-full border border-success/20 bg-success/5 px-2.5 py-1 text-[11px] text-success">+ <span class="size-1.5 rounded-full bg-success" />+ Local simulation+ </span>+ <Button variant="ghost" size="sm" onClick={() => void copyLink()}>+ {copied() ? 'Scenario link copied' : 'Copy scenario link'}+ </Button>+ </div>+ </header>+ <div class="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[240px_minmax(0,1fr)_280px]">+ <aside class="flex flex-col gap-5 border-b border-edge-muted bg-surface/60 p-5 lg:border-b-0 lg:border-r">+ <div class="flex items-center justify-between">+ <h2 class="text-xs font-semibold tracking-wide text-ink-muted">+ SCENARIOS+ </h2>+ <span class="font-mono text-[10px] text-ink-extra-muted">+ {SCENARIOS.length} states+ </span>+ </div>+ <For+ each={[...new Set(SCENARIOS.map((scenario) => scenario.group))]}+ >+ {(group) => (+ <section class="flex flex-col gap-1">+ <h3 class="mb-2 text-[11px] text-ink-extra-muted">{group}</h3>+ <For+ each={SCENARIOS.filter(+ (scenario) => scenario.group === group+ )}+ >+ {(scenario) => (+ <button+ type="button"+ aria-pressed={lab.state().scenario === scenario.id}+ class="flex items-center justify-between gap-2 rounded-lg border border-transparent px-3 py-2.5 text-left text-xs transition-colors hover:bg-active focus-visible:outline-2 focus-visible:outline-accent"+ classList={{+ 'bg-accent/8 !border-accent/20 text-accent':+ lab.state().scenario === scenario.id,+ 'text-ink-muted':+ lab.state().scenario !== scenario.id,+ }}+ onClick={() => {+ setPaymentError(undefined);+ setCopied(false);+ props.onSelect(scenario.id);+ }}+ >+ {scenario.title}+ <Show when={lab.state().scenario === scenario.id}>+ <ArrowRightIcon class="size-3 shrink-0" />+ </Show>+ </button>+ )}+ </For>+ </section>+ )}+ </For>+ <p class="mt-auto rounded-lg bg-active p-3 text-[11px] leading-relaxed text-ink-extra-muted">+ Every control changes a local fixture. No account, payment, or+ subscription is changed.+ </p>+ </aside>++ <main class="flex min-w-0 flex-col gap-5 p-5 xl:p-8">+ <div class="flex items-start justify-between gap-4">+ <div>+ <p class="mb-2 text-[11px] font-medium tracking-wider text-accent">+ BILLING CYCLE / {selectedScenario().group.toUpperCase()}+ </p>+ <h2 class="text-2xl font-medium tracking-tight">+ {selectedScenario().title}+ </h2>+ <p class="mt-2 max-w-xl text-sm leading-relaxed text-ink-muted">+ {selectedScenario().description}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ label="Reset scenario"+ onClick={() => {+ lab.selectScenario(lab.state().scenario);+ setPaymentError(undefined);+ }}+ >+ <ArrowClockwiseIcon class="size-3.5" />+ Reset+ </Button>+ </div>+ <div class="grid grid-cols-2 gap-3 xl:grid-cols-4">+ <Metric+ label="Active plan"+ value={PLAN_BY_TIER[lab.state().tier].name}+ detail={+ lab.state().role === 'member'+ ? 'Paid by team'+ : lab.state().role === 'owner'+ ? '4 seats • mixed plans'+ : 'Personal subscription'+ }+ />+ <Metric+ label="Included usage"+ value={+ lab.state().unlimited ? 'Unlimited' : `${lab.percentage()}%`+ }+ detail={+ lab.state().unlimited+ ? 'No monthly limit'+ : lab.state().role !== 'solo'+ ? 'Your seat’s usage this cycle'+ : 'Used in this billing cycle'+ }+ />+ <Metric+ label={lab.state().role === 'solo' ? 'Credits' : 'Team credits'}+ value={formatCreditBalance(lab.state().creditBalanceCents)}+ detail={+ lab.state().role === 'solo'+ ? 'Prepaid balance carries over'+ : 'Shared balance • managed by owner'+ }+ />+ <Metric+ label="Next renewal"+ value={dateLabel(lab.state().periodEnd)}+ detail={`${remainingDays()} days from simulated today`}+ />+ </div>++ <section+ class="rounded-xl border border-edge-muted bg-surface p-5"+ aria-label="Billing cycle timeline"+ >+ <div class="flex flex-wrap items-center justify-between gap-2 text-xs">+ <span class="flex items-center gap-2 font-medium">+ <CalendarIcon class="size-4 text-ink-muted" />+ Current billing cycle+ </span>+ <span class="text-ink-muted">+ Today: {dateLabel(lab.state().now)},{' '}+ {new Date(lab.state().now).getUTCFullYear()}+ </span>+ </div>+ <div class="relative my-5 h-1.5 rounded-full bg-active">+ <div+ class="h-full rounded-full bg-accent/70"+ style={{ width: `${cycleProgress()}%` }}+ />+ <span+ class="absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface bg-accent ring-2 ring-accent/15"+ style={{ left: `${cycleProgress()}%` }}+ />+ </div>+ <div class="flex justify-between text-[11px] text-ink-muted">+ <span>{dateLabel(lab.state().periodStart)} · cycle starts</span>+ <span>{dateLabel(lab.state().periodEnd)} · renews</span>+ </div>+ <Show when={lab.state().scheduledPlan}>+ {(plan) => (+ <div class="mt-4 flex flex-wrap items-center justify-between gap-3 rounded-lg bg-accent/5 px-3 py-2.5 text-xs">+ <span>+ {PLAN_BY_TIER[lab.state().tier].name} stays active until{' '}+ {dateLabel(lab.state().periodEnd)}.{' '}+ <strong class="font-medium">+ {PLAN_BY_TIER[plan()].name} starts at renewal.+ </strong>+ </span>+ <button+ type="button"+ class="text-link hover:text-link-hover disabled:opacity-50"+ disabled={lab.pending()}+ onClick={lab.cancelChange}+ >+ Cancel scheduled change+ </button>+ </div>+ )}+ </Show>+ </section>++ <section+ class="flex min-h-[680px] min-w-0 flex-col overflow-hidden rounded-xl border border-edge-muted bg-surface shadow-sm"+ aria-label="Live application preview"+ >+ <div class="flex flex-wrap items-center justify-between gap-3 border-b border-edge-muted p-2.5">+ <div+ class="flex items-center gap-1"+ role="group"+ aria-label="Preview surface"+ >+ <For each={['billing', 'usage'] as const}>+ {(surface) => (+ <button+ type="button"+ aria-pressed={lab.surface() === surface}+ class="rounded-lg px-4 py-2 text-xs font-medium hover:bg-active focus-visible:outline-2 focus-visible:outline-accent"+ classList={{+ 'bg-active text-ink': lab.surface() === surface,+ 'text-ink-muted': lab.surface() !== surface,+ }}+ onClick={() => lab.setSurface(surface)}+ >+ {surface === 'billing'+ ? 'Billing settings'+ : 'Usage settings'}+ </button>+ )}+ </For>+ </div>+ <div class="flex items-center gap-2 text-[11px] text-ink-extra-muted">+ <span>Real app components</span>+ <button+ type="button"+ aria-pressed={compact()}+ class="rounded-md border border-edge-muted px-2 py-1 text-ink-muted hover:bg-active"+ onClick={() => setCompact(!compact())}+ >+ {compact() ? 'Compact' : 'Full width'}+ </button>+ </div>+ </div>+ <div+ class="mx-auto h-[720px] w-full min-w-0 overflow-hidden transition-[max-width]"+ style={{ 'max-width': compact() ? '420px' : 'none' }}+ >+ <Show+ when={lab.surface() === 'billing'}+ fallback={<UsageSettingsView context={lab.usage} />}+ >+ <BillingSettingsView context={lab.billing} />+ </Show>+ </div>+ </section>+ <Show when={lab.notice()}>+ <p+ class="rounded-lg border border-edge-muted bg-surface px-4 py-3 text-xs text-ink-muted"+ role="status"+ >+ {lab.notice()}+ </p>+ </Show>+ </main>++ <aside class="flex flex-col gap-5 border-t border-edge-muted bg-surface/60 p-5 lg:border-l lg:border-t-0">+ <div>+ <h2 class="text-xs font-semibold tracking-wide text-ink-muted">+ CONTROLS+ </h2>+ <p class="mt-2 text-[11px] leading-relaxed text-ink-extra-muted">+ Move time, change usage, then inspect the app.+ </p>+ </div>+ <ControlSection title="Time travel">+ <div class="grid grid-cols-2 gap-2">+ <Button+ variant="outline"+ size="sm"+ disabled={lab.pending()}+ onClick={() => lab.advance(1)}+ >+ +1 day+ </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={lab.pending()}+ onClick={() => lab.advance(7)}+ >+ +7 days+ </Button>+ </div>+ <Button+ variant="accent"+ size="sm"+ disabled={lab.pending()}+ onClick={lab.renew}+ >+ Advance to renewal+ <ArrowRightIcon class="size-3.5" />+ </Button>+ <p class="text-[11px] leading-relaxed text-ink-extra-muted">+ Renewal applies the scheduled plan and resets included usage.+ Credits carry over.+ </p>+ </ControlSection>+ <ControlSection title="Usage & balance">+ <label class="flex flex-col gap-3 text-xs">+ <span class="flex justify-between">+ Included usage+ <span class="font-mono text-ink-muted">+ {lab.percentage()}%+ </span>+ </span>+ <input+ type="range"+ min="0"+ max="100"+ step="1"+ value={lab.percentage()}+ aria-label="Included usage percent"+ class="w-full accent-accent"+ onInput={(event) =>+ lab.setUsage(Number(event.currentTarget.value))+ }+ />+ </label>+ <Button variant="outline" size="sm" onClick={lab.exhaust}>+ Exhaust included usage+ </Button>+ <label class="flex flex-col gap-2 text-xs">+ Credit balance ($)+ <input+ type="number"+ min="0"+ max="100000"+ step="1"+ value={lab.state().creditBalanceCents / 100}+ class="rounded-lg border border-edge-muted bg-panel px-3 py-2 text-sm outline-none focus:border-accent"+ onInput={(event) => {+ const amount = event.currentTarget.valueAsNumber;+ if (Number.isFinite(amount))+ lab.setCredits(+ Math.round(Math.max(0, Math.min(100000, amount)) * 100)+ );+ }}+ />+ </label>+ </ControlSection>+ <ControlSection title="Dialogs & requests">+ <Button+ variant="outline"+ size="sm"+ onClick={() => lab.setLimitOpen(true)}+ >+ Open usage-limit dialog+ </Button>+ <label class="flex items-center gap-2 text-xs text-ink-muted">+ <input+ type="checkbox"+ class="accent-accent"+ checked={lab.failNext()}+ onChange={(event) =>+ lab.setFailNext(event.currentTarget.checked)+ }+ />+ Fail the next billing request+ </label>+ <p class="text-[11px] leading-relaxed text-ink-extra-muted">+ Purchases open a simulated checkout. Complete or fail them to+ inspect success and error states.+ </p>+ </ControlSection>+ <ControlSection title="Event history">+ <Show+ when={lab.events().length > 0}+ fallback={+ <p class="text-[11px] leading-relaxed text-ink-extra-muted">+ Select a scenario, then try an action. Changes will appear+ here.+ </p>+ }+ >+ <ol class="flex flex-col gap-4">+ <For each={lab.events()}>+ {(event) => (+ <li class="flex gap-2.5">+ <span class="mt-1 size-1.5 shrink-0 rounded-full bg-accent/60" />+ <div>+ <p class="text-[11px] leading-relaxed text-ink-muted">+ {event.label}+ </p>+ <time class="mt-1 block font-mono text-[10px] text-ink-extra-muted">+ {dateLabel(event.at)}+ </time>+ </div>+ </li>+ )}+ </For>+ </ol>+ </Show>+ </ControlSection>+ </aside>+ </div>+ </div>++ <AiUsageLimitDialogView+ open={lab.limitOpen()}+ code={`ai_${lab.state().blockedReason ?? (lab.state().tier === 'free' ? 'free_allowance_exhausted' : 'allowance_exhausted')}`}+ freePlan={lab.state().tier === 'free'}+ usage={{+ percentage: lab.percentage(),+ periodEnd: lab.state().periodEnd,+ unlimited: lab.state().unlimited,+ }}+ previewNotice="Billing Lab · simulated account"+ onClose={() => lab.setLimitOpen(false)}+ onOpenSettings={() => {+ lab.setLimitOpen(false);+ lab.setSurface(lab.state().tier === 'free' ? 'billing' : 'usage');+ }}+ />+ <Dialog+ open={!!lab.payment()}+ onOpenChange={(open) => {+ if (!open) {+ lab.setPayment(undefined);+ setPaymentError(undefined);+ }+ }}+ position="center"+ class="w-120"+ >+ <Surface depth={2} class="rounded-xl">+ <div class="flex flex-col gap-5 p-6">+ <div>+ <Dialog.Title class="text-xl font-medium">+ {lab.payment()?.kind === 'methods'+ ? 'Simulated payment methods'+ : 'Simulated checkout'}+ </Dialog.Title>+ <Dialog.Description class="mt-2 text-sm text-ink-muted">+ This flow stays in Billing Lab. No charge will be made.+ </Dialog.Description>+ </div>+ <Show when={lab.payment()}>+ {(payment) => (+ <div class="rounded-lg bg-active p-4 text-sm">+ <PaymentSummary payment={payment()} />+ </div>+ )}+ </Show>+ <Show when={paymentError()}>+ <p class="text-sm text-failure" role="alert">+ {paymentError()}+ </p>+ </Show>+ <div class="flex justify-end gap-2">+ <Button+ variant="ghost"+ onClick={() => {+ lab.setPayment(undefined);+ setPaymentError(undefined);+ }}+ >+ Cancel+ </Button>+ <Button+ variant="accent"+ disabled={lab.pending()}+ onClick={() => void completePayment()}+ >+ {lab.pending() ? 'Processing…' : 'Complete simulation'}+ </Button>+ </div>+ </div>+ </Surface>+ </Dialog>+ </Layer>+ );+}diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsxindex 5330fa3f5a..d1a0a29ffa 100644--- a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx@@ -7,19 +7,10 @@ import {} from '@core/constant/featureFlags';import { useSettingsState } from '@core/constant/SettingsState';import { useAiBillingSummaryQuery } from '@queries/auth';-import type { AiDenyCode } from '@service-auth/ai-billing-types';-import { Button, Dialog, Surface } from '@ui';-import { Show, Suspense } from 'solid-js';-import { MonthlyLimit } from '../usage/components/monthly-limit';+import { Suspense } from 'solid-js';import { isUsageAvailable, monthlyUsagePercent } from '../usage/core/usage';import { useAiUsagePreview } from './ai-usage-preview';--const TITLES: Record<AiDenyCode, string> = {- ai_allowance_exhausted: "You've used this month's included AI",- ai_free_allowance_exhausted: "You've used this month's free AI",- ai_overage_limit_reached: "You've hit your AI spending limit",- ai_overage_payment_failed: 'Your last AI usage charge failed',-};+import { AiUsageLimitDialogView } from './components/ai-usage-limit-dialog';/*** Shown when the backend refuses an AI request with a billing code. Shows the@@ -42,83 +33,38 @@ export function AiUsageLimitDialog() {usageLimitCode() === 'ai_free_allowance_exhausted' ||usageSnapshot()?.tier === 'free';- const title = () => TITLES[usageLimitCode() ?? 'ai_allowance_exhausted'];-+ const usage = () => {+ const snapshot = usageSnapshot();+ return snapshot+ ? {+ percentage: monthlyUsagePercent(+ snapshot.used_cents,+ snapshot.included_cents+ ),+ periodEnd: snapshot.period_end,+ unlimited: snapshot.unlimited,+ }+ : undefined;+ };return (- <Dialog- open={usageLimitOpen() && available()}- onOpenChange={(open) => !open && hideUsageLimit()}- position="center"- class="w-160"- >- <Surface depth={2} class="rounded-xl">- <section class="flex flex-col gap-5 p-6 font-sans">- <div class="flex flex-col gap-1">- <Dialog.Title class="text-xl font-semibold text-ink">- {title()}- </Dialog.Title>- <Dialog.Description class="text-sm text-ink-extra-muted">- {freePlan()- ? 'Subscribe to a paid plan to keep going.'- : usageSnapshot()- ? 'Add additional credits to keep going.'- : 'Check your plan and usage options to keep going.'}- </Dialog.Description>- </div>-- <Show when={usagePreview.active()}>- <p class="text-xs text-ink-muted" role="status">- Developer preview:{' '}- {usagePreview.plan() === 'free' ? 'Free' : 'paid'} plan. No- account billing has changed.- </p>- </Show>-- {/* The summary is a suspending query resource; keep its- suspension inside the dialog rather than the route boundary. */}- <Suspense fallback={null}>- <Show when={usageSnapshot()}>- {(snapshot) => (- <div class="flex flex-col gap-4 rounded-lg bg-active p-4">- <MonthlyLimit- percentage={monthlyUsagePercent(- snapshot().used_cents,- snapshot().included_cents- )}- periodEnd={snapshot().period_end}- unlimited={snapshot().unlimited}- />- </div>- )}- </Show>- </Suspense>-- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">- <Button- variant={freePlan() ? 'accent' : 'ghost'}- depth={3}- class="px-3 py-1.5"- onClick={() => {- const target = freePlan() ? 'Billing' : 'Usage';- hideUsageLimit();- openSettings(target);- }}- >- {freePlan() ? 'View plans' : 'Open usage settings'}- </Button>- <div class="flex gap-2 sm:justify-end">- <Button- variant="ghost"- depth={3}- class="px-3 py-1.5"- onClick={hideUsageLimit}- >- Dismiss- </Button>- </div>- </div>- </section>- </Surface>- </Dialog>+ <Suspense fallback={null}>+ <AiUsageLimitDialogView+ open={usageLimitOpen() && available()}+ code={usageLimitCode() ?? undefined}+ freePlan={freePlan()}+ usage={usage()}+ previewNotice={+ usagePreview.active()+ ? `Developer preview: ${usagePreview.plan() === 'free' ? 'Free' : 'paid'} plan. No account billing has changed.`+ : undefined+ }+ onClose={hideUsageLimit}+ onOpenSettings={() => {+ const target = freePlan() ? 'Billing' : 'Usage';+ hideUsageLimit();+ openSettings(target);+ }}+ />+ </Suspense>);}diff --git a/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsx b/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsxnew file mode 100644index 0000000000..fffbbee67c--- /dev/null+++ b/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsx@@ -0,0 +1,92 @@+import type { AiDenyCode } from '@service-auth/ai-billing-types';+import { Button, Dialog, Surface } from '@ui';+import { Show, Suspense } from 'solid-js';+import { MonthlyLimit } from '../../usage/components/monthly-limit';++const TITLES: Record<AiDenyCode, string> = {+ ai_allowance_exhausted: "You've used this month's included AI",+ ai_free_allowance_exhausted: "You've used this month's free AI",+ ai_overage_limit_reached: "You've hit your AI spending limit",+ ai_overage_payment_failed: 'Your last AI usage charge failed',+};++export type AiUsageLimitDialogProps = {+ open: boolean;+ code?: AiDenyCode;+ freePlan: boolean;+ usage?: { percentage: number; periodEnd: string; unlimited: boolean };+ previewNotice?: string;+ onClose: () => void;+ onOpenSettings: () => void;+};++export function AiUsageLimitDialogView(props: AiUsageLimitDialogProps) {+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => !open && props.onClose()}+ position="center"+ class="w-160"+ >+ <Surface depth={2} class="rounded-xl">+ <section class="flex flex-col gap-5 p-6 font-sans">+ <div class="flex flex-col gap-1">+ <Dialog.Title class="text-xl font-semibold text-ink">+ {TITLES[props.code ?? 'ai_allowance_exhausted']}+ </Dialog.Title>+ <Dialog.Description class="text-sm text-ink-extra-muted">+ {props.freePlan+ ? 'Subscribe to a paid plan to keep going.'+ : props.usage+ ? 'Add additional credits to keep going.'+ : 'Check your plan and usage options to keep going.'}+ </Dialog.Description>+ </div>++ <Show when={props.previewNotice}>+ <p class="text-xs text-ink-muted" role="status">+ {props.previewNotice}+ </p>+ </Show>++ {/* The summary is a suspending query resource; keep its+ suspension inside the dialog rather than the route boundary. */}+ <Suspense fallback={null}>+ <Show when={props.usage}>+ {(snapshot) => (+ <div class="flex flex-col gap-4 rounded-lg bg-active p-4">+ <MonthlyLimit+ percentage={snapshot().percentage}+ periodEnd={snapshot().periodEnd}+ unlimited={snapshot().unlimited}+ />+ </div>+ )}+ </Show>+ </Suspense>++ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <Button+ variant={props.freePlan ? 'accent' : 'ghost'}+ depth={3}+ class="px-3 py-1.5"+ onClick={props.onOpenSettings}+ >+ {props.freePlan ? 'View plans' : 'Open usage settings'}+ </Button>+ <div class="flex gap-2 sm:justify-end">+ <Button+ variant="ghost"+ depth={3}+ class="px-3 py-1.5"+ onClick={props.onClose}+ >+ Dismiss+ </Button>+ </div>+ </div>+ </section>+ </Surface>+ </Dialog>+ );+}diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsxindex 4814660891..5bee9230bf 100644--- a/apps/web/src/features/settings/Billing.tsx+++ b/apps/web/src/features/settings/Billing.tsx@@ -10,7 +10,9 @@ import {useAiBillingSummaryQuery,useChangePlanMutation,useCreateCheckoutSessionMutation,+ useSubscriptionStatusQuery,} from '@queries/auth';+import { queryReadyGate } from '@queries/gate';import { useCurrentTeamQuery } from '@queries/team/teams';import type { PaidPlan } from '@service-auth/ai-billing-types';import { stripeServiceClient } from '@service-stripe/client';@@ -52,6 +54,10 @@ function LiveBilling(props: { controls?: JSX.Element }) {const effectiveHasPaid = () =>hasPaid() || (summary.isSuccess && summary.data.tier !== 'free');+ const subscriptionStatus = useSubscriptionStatusQuery({+ enabled: effectiveHasPaid,+ });+const canManageSubscription = createMemo(() => {return permissions()?.includes(PERMISSION_IDS.WRITE_STRIPE_SUBSCRIPTION);});@@ -112,14 +118,17 @@ function LiveBilling(props: { controls?: JSX.Element }) {const handleChangePlan = async (plan: PaidPlan) => {try {+ const previousTier = state().tier;await changePlan.mutateAsync({ plan });analytics.track('plan_changed', { plan });toast.success(- plan === 'max'- ? aiUsageBilling().enabled- ? 'Upgraded to Max. Your larger AI allowance applies right away.'- : 'Upgraded to Max.'- : 'Switched to Pro.'+ plan === previousTier+ ? `Keeping your ${plan === 'max' ? 'Max' : 'Pro'} plan. Your scheduled downgrade is canceled.`+ : plan === 'max'+ ? aiUsageBilling().enabled+ ? 'Upgraded to Max. Your larger AI allowance applies right away.'+ : 'Upgraded to Max.'+ : 'Pro will start at your next renewal. You keep Max until then.');} catch (error) {console.error(error);@@ -140,6 +149,19 @@ function LiveBilling(props: { controls?: JSX.Element }) {<BillingSettingsViewstate={state()}controls={props.controls}+ renewalDate={+ queryReadyGate(subscriptionStatus)+ ? (subscriptionStatus.data.renewalDate ?? undefined)+ : undefined+ }+ scheduledChange={+ queryReadyGate(subscriptionStatus)+ ? (subscriptionStatus.data.scheduledChange ?? undefined)+ : undefined+ }+ subscriptionStatusFailed={subscriptionStatus.isError}+ onRefreshStatus={() => void subscriptionStatus.refetch()}+ onKeepPlan={(plan) => void handleChangePlan(plan)}onManage={() => void handleManage()}onSelectPlan={(plan) =>void (effectiveHasPaid()diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 665201c630..716dc69fc6 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -1,4 +1,3 @@-import { PLANS } from '@app/features/paywall/plans';import { SlackImport } from '@app/features/slack-import/slack-import';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { toast } from '@core/component/Toast/Toast';@@ -87,6 +86,7 @@ import {Switch,} from 'solid-js';import { z } from 'zod';+import { TeamSeatPlanSelect } from './components/team-seat-plan-select';import { ConnectAction } from './integration-ui';import {IntegrationRow,@@ -167,23 +167,6 @@ function RoleSelect(props: {);}-type PlanOption = { value: PaidPlan; label: string; description: string };--/** Every paid plan a seat can be moved to, cheapest first. */-function planOptionsFor(aiUsageBilling: boolean): PlanOption[] {- return PLANS.flatMap((plan) =>- plan.tier === 'free'- ? []- : [- {- value: plan.tier,- label: plan.name,- description: `$${plan.price}${aiUsageBilling && plan.tier === 'max' ? ' · 10× usage' : ''}`,- },- ]- );-}-/*** The plan a member's seat is billed at. Until the generated `TeamMember`* schema carries `plan`, read it defensively; every seat starts on Pro.@@ -193,63 +176,6 @@ function memberPlan(member: TeamMember): PaidPlan {return plan === 'max' ? 'max' : 'premium';}-function PlanSelect(props: {- value: PaidPlan;- onChange: (plan: PaidPlan) => void;- disabled?: boolean;-}) {- const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);- const options = () => planOptionsFor(aiUsageBilling().enabled);- const selectedOption = () =>- options().find((option) => option.value === props.value) ?? options()[0];-- return (- <Select<PlanOption>- options={options()}- value={selectedOption()}- onChange={(opt) => opt && props.onChange(opt.value)}- optionValue="value"- optionTextValue="label"- gutter={4}- placement="bottom-end"- disabled={props.disabled}- itemComponent={(itemProps: { item: CollectionNode<PlanOption> }) => (- <Select.Item- item={itemProps.item}- class="flex items-center justify-between gap-3 px-2 py-1.5 text-sm rounded-xs hover:bg-hover outline-none data-highlighted:bg-hover"- >- <Select.ItemLabel class="flex flex-col">- <span>{itemProps.item.rawValue.label}</span>- <span class="text-xs text-ink-muted">- {itemProps.item.rawValue.description}- </span>- </Select.ItemLabel>- <Select.ItemIndicator>- <CheckIcon class="size-3" />- </Select.ItemIndicator>- </Select.Item>- )}- >- <Select.Trigger- as={Button}- class="rounded-xs px-1 py-0.5 text-xs -ml-1 data-expanded:bg-ink/10"- disabled={props.disabled}- aria-label="Seat plan"- >- <Select.Value<PlanOption>>- {(state) => state.selectedOption().label}- </Select.Value>- <CaretDownIcon class="size-3 text-ink-muted shrink-0" />- </Select.Trigger>- <Select.Portal>- <Select.Content class="menu-surface z-action-menu min-w-40 p-1">- <Select.Listbox />- </Select.Content>- </Select.Portal>- </Select>- );-}-const emailSchema = z.string().email();type InviteEntry = { email: string };@@ -420,10 +346,12 @@ function MemberRow(props: {showPlan: boolean;canEditPlan: boolean;planPending: boolean;+ pendingDowngrade: boolean;onRemove: () => void;onRoleChange: (role: TeamRole) => void;onPlanChange: (plan: PaidPlan) => void;}) {+ const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);const displayName = () => getDisplayName(tryMacroId(props.member.user_id));const isMemberOwner = () => props.member.role === TeamRole.owner;const email = () => {@@ -463,10 +391,12 @@ function MemberRow(props: {</span>}>- <PlanSelect+ <TeamSeatPlanSelectvalue={memberPlan(props.member)}onChange={props.onPlanChange}disabled={props.planPending}+ aiUsageBilling={aiUsageBilling().enabled}+ pendingDowngrade={props.pendingDowngrade}/></Show></Show>@@ -1562,6 +1492,29 @@ function TeamManagement(props: {</label></Show>+ <Show+ when={+ showSeatPlans() &&+ isAdminOrOwner() &&+ !teamQuery.data?.team.enterprise &&+ teamQuery.data?.scheduled_seat_plans == null+ }+ >+ <div+ class="flex items-center gap-2 text-xs text-ink-muted"+ role="status"+ >+ <span>Couldn't load scheduled plan changes.</span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => teamQuery.refetch()}+ >+ Try again+ </Button>+ </div>+ </Show>+<Showwhen={!teamQuery.isLoading}fallback={@@ -1596,9 +1549,12 @@ function TeamManagement(props: {showPlan={showSeatPlans()}canEditPlan={isAdminOrOwner()}planPending={planMovePending()}+ pendingDowngrade={+ teamQuery.data?.scheduled_seat_plans?.[member.user_id]+ ?.plan === 'premium'+ }onPlanChange={(plan) => {- if (!props.teamId || plan === memberPlan(member))- return;+ if (!props.teamId) return;setMemberPlanMutation.mutate({teamId: props.teamId,userId: member.user_id,diff --git a/apps/web/src/features/settings/components/billing-settings-view.tsx b/apps/web/src/features/settings/components/billing-settings-view.tsxindex 07781a6dab..ccbe9a9181 100644--- a/apps/web/src/features/settings/components/billing-settings-view.tsx+++ b/apps/web/src/features/settings/components/billing-settings-view.tsx@@ -1,5 +1,6 @@import { type PaidPlanTier, PLAN_BY_TIER } from '@app/features/paywall/plans';import { plural } from '@core/util/string';+import CalendarIcon from '@phosphor/calendar-blank.svg';import EnvelopeIcon from '@phosphor/envelope.svg';import { Button, Layer } from '@ui';import { For, type JSX, Match, Show, Switch } from 'solid-js';@@ -10,10 +11,31 @@ import { BillingPlanCard, PlanFeatures } from './billing-plan-card';export function BillingSettingsView(props: {state: BillingState;controls?: JSX.Element;+ renewalDate?: string;+ scheduledChange?: { plan: 'free' | 'premium' | 'max'; effectiveAt: string };+ subscriptionStatusFailed?: boolean;+ onRefreshStatus?: () => void;+ onKeepPlan?: (plan: PaidPlanTier) => void;+ teamSeatDescription?: string;onManage: () => void;onSelectPlan: (plan: PaidPlanTier) => void;onTeamSettings?: JSX.EventHandler<HTMLAnchorElement, MouseEvent>;}) {+ const formatDate = (value: string | undefined) => {+ if (!value) return;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return;+ return date.toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ });+ };+ const scheduledChange = () => {+ const change = props.scheduledChange;+ const date = formatDate(change?.effectiveAt);+ return change && date ? { ...change, date } : undefined;+ };return (<SettingsPagetitle="Billing"@@ -76,24 +98,35 @@ export function BillingSettingsView(props: {when={props.state.hasPaid &&props.state.teamRole === 'owner' &&- props.state.teamPlans+ (props.teamSeatDescription || props.state.teamPlans)}>- {(plans) => (- <p class="text-ink-extra-muted text-xs">- {plans().length} {plural('user', plans().length)} •{' '}- {describeSeatPlans(plans())} • set each seat's plan in{' '}- <a- class="text-link hover:text-link-hover"- href="/app/settings/team"- onClick={props.onTeamSettings}- >- Team settings- </a>- </p>- )}+ <p class="text-ink-extra-muted text-xs">+ {props.teamSeatDescription ||+ `${props.state.teamPlans?.length} ${plural('user', props.state.teamPlans?.length ?? 0)} • ${describeSeatPlans(props.state.teamPlans ?? [])}`}{' '}+ • set each seat's plan in{' '}+ <a+ class="text-link hover:text-link-hover"+ href="/app/settings/team"+ onClick={props.onTeamSettings}+ >+ Team settings+ </a>+ </p></Match></Switch>+ <Show+ when={props.state.hasPaid && formatDate(props.renewalDate)}+ >+ {(date) => (+ <p class="text-xs text-ink-extra-muted">+ {scheduledChange()?.plan === 'free'+ ? 'Your subscription ends on '+ : 'Your current billing period ends on '}+ {date()}.+ </p>+ )}+ </Show></div><Show when={props.state.canChangePlan && props.state.hasPaid}>@@ -116,20 +149,62 @@ export function BillingSettingsView(props: {</ul></section></SettingsCard>+ <Show when={props.subscriptionStatusFailed}>+ <div+ class="flex flex-wrap items-center gap-3 px-4 text-xs text-ink-muted"+ role="status"+ >+ <p>Couldn't load your renewal details.</p>+ <Button variant="ghost" size="sm" onClick={props.onRefreshStatus}>+ Try again+ </Button>+ </div>+ </Show>+ <Show when={scheduledChange()}>+ {(change) => (+ <SettingsCard>+ <div class="flex flex-wrap items-center gap-3 p-4" role="status">+ <CalendarIcon class="size-4 shrink-0 text-ink-muted" />+ <p class="min-w-0 flex-1 text-sm text-ink">+ {change().plan === 'free'+ ? 'Your subscription cancellation'+ : `Your downgrade to ${PLAN_BY_TIER[change().plan].name}`}{' '}+ is scheduled for {change().date}.+ </p>+ <Show+ when={+ props.state.canChangePlan && props.state.tier !== 'free'+ }+ >+ <Button+ variant="outline"+ size="sm"+ depth={2}+ disabled={props.state.pending}+ onClick={() => {+ const tier = props.state.tier;+ if (tier !== 'free') props.onKeepPlan?.(tier);+ }}+ >+ Keep {PLAN_BY_TIER[props.state.tier].name} plan+ </Button>+ </Show>+ </div>+ </SettingsCard>+ )}+ </Show></section>- <Show when={props.state.canChangePlan}>+ <Show when={props.state.canChangePlan && props.state.tier !== 'max'}><sectiondata-settings-target="upgrade"tabIndex={-1}class="@container/plan-options flex scroll-mt-4 flex-col gap-4 outline-none"><h2 class="text-base font-medium text-ink">- {props.state.tier === 'max'- ? 'Change plan'- : props.state.hasPaid && props.state.aiUsageEnabled- ? 'Need more AI?'- : 'Upgrade'}+ {props.state.hasPaid && props.state.aiUsageEnabled+ ? 'Need more AI?'+ : 'Upgrade'}</h2><divclass="grid grid-cols-1 gap-6"diff --git a/apps/web/src/features/settings/components/team-seat-plan-select.test.tsx b/apps/web/src/features/settings/components/team-seat-plan-select.test.tsxnew file mode 100644index 0000000000..4177c6a1ff--- /dev/null+++ b/apps/web/src/features/settings/components/team-seat-plan-select.test.tsx@@ -0,0 +1,63 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { TeamSeatPlanSelect } from './team-seat-plan-select';++afterEach(cleanup);++it('only offers Keep Max for an active Max seat with a pending downgrade', () => {+ const keep = vi.fn();+ const { unmount } = render(() => {+ const [pending, setPending] = createSignal(true);+ return (+ <TeamSeatPlanSelect+ value="max"+ aiUsageBilling={true}+ pendingDowngrade={pending()}+ onChange={(plan) => {+ keep(plan);+ setPending(false);+ }}+ />+ );+ });+ fireEvent.click(screen.getByRole('button', { name: 'Keep Max' }));+ expect(keep).toHaveBeenCalledWith('max');+ expect(screen.queryByRole('button', { name: 'Keep Max' })).toBeNull();+ unmount();+ render(() => (+ <TeamSeatPlanSelect+ value="premium"+ aiUsageBilling={true}+ pendingDowngrade={true}+ onChange={keep}+ />+ ));+ expect(screen.queryByRole('button', { name: 'Keep Max' })).toBeNull();+});++it('hides Keep Max when no downgrade is confirmed and disables it during a change', () => {+ const { unmount } = render(() => (+ <TeamSeatPlanSelect+ value="max"+ aiUsageBilling={true}+ pendingDowngrade={false}+ onChange={() => {}}+ />+ ));+ expect(screen.queryByRole('button', { name: 'Keep Max' })).toBeNull();+ unmount();+ render(() => (+ <TeamSeatPlanSelect+ value="max"+ aiUsageBilling={true}+ pendingDowngrade={true}+ disabled={true}+ onChange={() => {}}+ />+ ));+ expect(+ (screen.getByRole('button', { name: 'Keep Max' }) as HTMLButtonElement)+ .disabled+ ).toBe(true);+});diff --git a/apps/web/src/features/settings/components/team-seat-plan-select.tsx b/apps/web/src/features/settings/components/team-seat-plan-select.tsxnew file mode 100644index 0000000000..58c69cb862--- /dev/null+++ b/apps/web/src/features/settings/components/team-seat-plan-select.tsx@@ -0,0 +1,95 @@+import { PLANS } from '@app/features/paywall/plans';+import type { CollectionNode } from '@kobalte/core';+import { Select } from '@kobalte/core/select';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import type { PaidPlan } from '@service-auth/ai-billing-types';+import { Button } from '@ui';+import { Show } from 'solid-js';++type PlanOption = { value: PaidPlan; label: string; description: string };++/** Every paid plan a seat can be moved to, cheapest first. */+function planOptionsFor(aiUsageBilling: boolean): PlanOption[] {+ return PLANS.flatMap((plan) =>+ plan.tier === 'free'+ ? []+ : [+ {+ value: plan.tier,+ label: plan.name,+ description: `$${plan.price}${aiUsageBilling && plan.tier === 'max' ? ' · 10× usage' : ''}`,+ },+ ]+ );+}++export function TeamSeatPlanSelect(props: {+ value: PaidPlan;+ onChange: (plan: PaidPlan) => void;+ disabled?: boolean;+ aiUsageBilling: boolean;+ pendingDowngrade: boolean;+}) {+ const options = () => planOptionsFor(props.aiUsageBilling);+ const selectedOption = () =>+ options().find((option) => option.value === props.value) ?? options()[0];++ return (+ <div class="flex items-center gap-2">+ <Select<PlanOption>+ options={options()}+ value={selectedOption()}+ onChange={(opt) => opt && props.onChange(opt.value)}+ optionValue="value"+ optionTextValue="label"+ gutter={4}+ placement="bottom-end"+ disabled={props.disabled}+ itemComponent={(itemProps: { item: CollectionNode<PlanOption> }) => (+ <Select.Item+ item={itemProps.item}+ class="flex items-center justify-between gap-3 px-2 py-1.5 text-sm rounded-xs hover:bg-hover outline-none data-highlighted:bg-hover"+ >+ <Select.ItemLabel class="flex flex-col">+ <span>{itemProps.item.rawValue.label}</span>+ <span class="text-xs text-ink-muted">+ {itemProps.item.rawValue.description}+ </span>+ </Select.ItemLabel>+ <Select.ItemIndicator>+ <CheckIcon class="size-3" />+ </Select.ItemIndicator>+ </Select.Item>+ )}+ >+ <Select.Trigger+ as={Button}+ class="rounded-xs px-1 py-0.5 text-xs -ml-1 data-expanded:bg-ink/10"+ disabled={props.disabled}+ aria-label="Seat plan"+ >+ <Select.Value<PlanOption>>+ {(state) => state.selectedOption().label}+ </Select.Value>+ <CaretDownIcon class="size-3 text-ink-muted shrink-0" />+ </Select.Trigger>+ <Select.Portal>+ <Select.Content class="menu-surface z-action-menu min-w-40 p-1">+ <Select.Listbox />+ </Select.Content>+ </Select.Portal>+ </Select>+ <Show when={props.value === 'max' && props.pendingDowngrade}>+ <Button+ size="sm"+ variant="outline"+ disabled={props.disabled}+ onClick={() => props.onChange('max')}+ >+ Keep Max+ </Button>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/settings/context/billing-context.ts b/apps/web/src/features/settings/context/billing-context.tsnew file mode 100644index 0000000000..32af2b517a--- /dev/null+++ b/apps/web/src/features/settings/context/billing-context.ts@@ -0,0 +1,26 @@+import type { Accessor } from 'solid-js';+import type { PaidPlanTier, PlanTier } from '../../paywall/plans';++/** Billing presentation capabilities, supplied by the app or the local sandbox. */+export type BillingContext = {+ tier: Accessor<PlanTier>;+ renewalDate: Accessor<string | undefined>;+ subscriptionStatusFailed?: Accessor<boolean>;+ refreshStatus?: () => void;+ scheduledChange: Accessor<+ { plan: PlanTier; effectiveAt: string } | undefined+ >;+ hasPaid: Accessor<boolean>;+ aiUsageBilling: Accessor<boolean>;+ teamRole: Accessor<'owner' | 'member' | undefined>;+ teamSeatDescription: Accessor<string | undefined>;+ billedThroughTeam: Accessor<boolean>;+ isOwnerOrSolo: Accessor<boolean>;+ canManageSubscription: Accessor<boolean>;+ canChangePlan: Accessor<boolean>;+ changingPlan: Accessor<boolean>;+ checkout: (plan: PaidPlanTier) => Promise<void>;+ changePlan: (plan: PaidPlanTier) => Promise<void>;+ manage: () => Promise<void>;+ openTeamSettings?: () => void;+};diff --git a/apps/web/src/features/settings/views/billing-settings.test.tsx b/apps/web/src/features/settings/views/billing-settings.test.tsxnew file mode 100644index 0000000000..eff2f0ce73--- /dev/null+++ b/apps/web/src/features/settings/views/billing-settings.test.tsx@@ -0,0 +1,94 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import type { BillingContext } from '../context/billing-context';+import { BillingSettingsView } from './billing-settings';++afterEach(cleanup);++function context(overrides: Partial<BillingContext> = {}): BillingContext {+ return {+ tier: () => 'max',+ renewalDate: () => '2026-11-01T12:00:00Z',+ scheduledChange: () => ({+ plan: 'premium',+ effectiveAt: '2026-11-01T12:00:00Z',+ }),+ hasPaid: () => true,+ aiUsageBilling: () => true,+ teamRole: () => undefined,+ teamSeatDescription: () => undefined,+ billedThroughTeam: () => false,+ isOwnerOrSolo: () => true,+ canManageSubscription: () => true,+ canChangePlan: () => true,+ changingPlan: () => false,+ checkout: async () => {},+ changePlan: async () => {},+ manage: async () => {},+ ...overrides,+ };+}++it('shows the future Pro date while Max remains current, and cancels using Max', () => {+ const keep = vi.fn();+ render(() => {+ const [change, setChange] = createSignal<+ { plan: 'premium'; effectiveAt: string } | undefined+ >({ plan: 'premium', effectiveAt: '2026-11-01T12:00:00Z' });+ return (+ <BillingSettingsView+ context={context({+ scheduledChange: change,+ changePlan: async (plan) => {+ keep(plan);+ setChange(undefined);+ },+ })}+ />+ );+ });+ expect(screen.getByRole('heading', { name: 'Max plan' })).toBeTruthy();+ expect(+ screen.getByText(/Your downgrade to Pro is scheduled/).textContent+ ).toContain('Nov 1, 2026');+ expect(screen.queryByRole('button', { name: 'Switch to Pro' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Keep Max plan' }));+ expect(keep).toHaveBeenCalledWith('max');+ expect(screen.queryByText(/Your downgrade to Pro/)).toBeNull();+ expect(screen.queryByRole('button', { name: 'Switch to Pro' })).toBeNull();+});++it('keeps a pending notice visible during mutation and hides the action from team members', () => {+ const { unmount } = render(() => (+ <BillingSettingsView context={context({ changingPlan: () => true })} />+ ));+ expect(+ (screen.getByRole('button', { name: 'Keep Max plan' }) as HTMLButtonElement)+ .disabled+ ).toBe(true);+ unmount();+ render(() => (+ <BillingSettingsView context={context({ canChangePlan: () => false })} />+ ));+ expect(screen.getByText(/Your downgrade to Pro is scheduled/)).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Keep Max plan' })).toBeNull();+});++it('offers a retry when subscription state fails instead of inventing a renewal date', () => {+ const refresh = vi.fn();+ render(() => (+ <BillingSettingsView+ context={context({+ scheduledChange: () => undefined,+ renewalDate: () => undefined,+ subscriptionStatusFailed: () => true,+ refreshStatus: refresh,+ })}+ />+ ));+ expect(screen.queryByText(/Your current billing period ends/)).toBeNull();+ expect(screen.queryByText(/Your downgrade/)).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));+ expect(refresh).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/settings/views/billing-settings.tsx b/apps/web/src/features/settings/views/billing-settings.tsxnew file mode 100644index 0000000000..7233219673--- /dev/null+++ b/apps/web/src/features/settings/views/billing-settings.tsx@@ -0,0 +1,37 @@+import { BillingSettingsView as BillingView } from '../components/billing-settings-view';+import type { BillingContext } from '../context/billing-context';++export const BillingSettingsView = (props: { context: BillingContext }) => (+ <BillingView+ state={{+ tier: props.context.tier(),+ hasPaid: props.context.hasPaid(),+ aiUsageEnabled: props.context.aiUsageBilling(),+ teamRole: props.context.teamRole(),+ billedThroughTeam: props.context.billedThroughTeam(),+ canManageSubscription: props.context.canManageSubscription(),+ canChangePlan: props.context.canChangePlan(),+ pending: props.context.changingPlan(),+ }}+ renewalDate={props.context.renewalDate()}+ scheduledChange={props.context.scheduledChange()}+ subscriptionStatusFailed={props.context.subscriptionStatusFailed?.()}+ onRefreshStatus={props.context.refreshStatus}+ teamSeatDescription={props.context.teamSeatDescription()}+ onKeepPlan={(plan) => void props.context.changePlan(plan)}+ onManage={() => void props.context.manage()}+ onSelectPlan={(plan) =>+ void (props.context.hasPaid()+ ? props.context.changePlan(plan)+ : props.context.checkout(plan))+ }+ onTeamSettings={+ props.context.openTeamSettings+ ? (event) => {+ event.preventDefault();+ props.context.openTeamSettings?.();+ }+ : undefined+ }+ />+);diff --git a/apps/web/src/features/usage/components/auto-reload-dialog.tsx b/apps/web/src/features/usage/components/auto-reload-dialog.tsxindex 8b909e4cfa..2a9cc6c9cf 100644--- a/apps/web/src/features/usage/components/auto-reload-dialog.tsx+++ b/apps/web/src/features/usage/components/auto-reload-dialog.tsx@@ -3,6 +3,7 @@ import { Button, Dialog, InputGroup, Surface, TextField } from '@ui';import { Show } from 'solid-js';export function AutoReloadDialog(props: {+ sharedWithTeam?: boolean;enabled: boolean;minimum: string;target: string;@@ -47,6 +48,11 @@ export function AutoReloadDialog(props: {Set balance thresholds and a monthly spending limit for automaticcredit purchases.</Dialog.Description>+ <Show when={props.sharedWithTeam}>+ <p class="text-sm text-ink-muted">+ Auto-reload adds credits to your team’s shared balance.+ </p>+ </Show><TextField value={props.minimum} onChange={props.onMinimum}><TextField.Label>Minimum balance</TextField.Label><TextField.Description>diff --git a/apps/web/src/features/usage/components/auto-reload-limit-notice.tsx b/apps/web/src/features/usage/components/auto-reload-limit-notice.tsxnew file mode 100644index 0000000000..71daf07428--- /dev/null+++ b/apps/web/src/features/usage/components/auto-reload-limit-notice.tsx@@ -0,0 +1,68 @@+import CalendarIcon from '@phosphor/calendar-blank.svg';+import { Button } from '@ui';+import { Show } from 'solid-js';+import { type AutoReloadBudget, formatCreditBalance } from '../core/usage';++/** Shared presentation; monthly facts must come from an authoritative source or an explicit fixture. */+export function AutoReloadLimitNotice(props: {+ budget: AutoReloadBudget;+ canManage: boolean;+ pending: boolean;+ onAdjust: (trigger: HTMLButtonElement) => void;+ onAddCredits: (trigger: HTMLButtonElement) => void;+}) {+ const resetDate = () =>+ new Date(props.budget.resetsAt).toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ });+ return (+ <div+ role="status"+ class="flex flex-col gap-3 rounded-xl border border-accent/20 bg-accent/5 p-4 text-left"+ >+ <div class="flex items-start justify-between gap-4">+ <div class="flex min-w-0 items-start gap-2">+ <CalendarIcon class="mt-0.5 size-4 shrink-0 text-accent" />+ <p class="text-sm font-medium text-ink">+ Monthly auto-reload {formatCreditBalance(props.budget.limitCents)}{' '}+ limit reached+ </p>+ </div>+ <span class="shrink-0 pt-0.5 text-xs text-ink-muted">+ resets {resetDate()}+ </span>+ </div>+ <Show+ when={props.canManage}+ fallback={+ <p class="text-xs text-ink-muted">+ Ask your team owner to adjust the limit or add credits.+ </p>+ }+ >+ <div class="flex flex-wrap gap-2">+ <Button+ size="sm"+ variant="outline"+ depth={3}+ disabled={props.pending}+ onClick={(event) => props.onAdjust(event.currentTarget)}+ >+ Adjust limit+ </Button>+ <Button+ size="sm"+ variant="ghost"+ depth={3}+ disabled={props.pending}+ onClick={(event) => props.onAddCredits(event.currentTarget)}+ >+ Add credits+ </Button>+ </div>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/usage/components/credit-purchase-dialog.tsx b/apps/web/src/features/usage/components/credit-purchase-dialog.tsxindex 766277d414..bfddfb6dff 100644--- a/apps/web/src/features/usage/components/credit-purchase-dialog.tsx+++ b/apps/web/src/features/usage/components/credit-purchase-dialog.tsx@@ -4,6 +4,7 @@ import { createUniqueId, For, Show } from 'solid-js';import { formatCreditBalance } from '../core/usage';export function CreditPurchaseDialog(props: {+ sharedWithTeam?: boolean;selection: number | 'other';customAmount: string;amountCents: number | undefined;@@ -41,7 +42,9 @@ export function CreditPurchaseDialog(props: {Need more usage?</Dialog.Title><Dialog.Description class="mt-1 text-sm text-ink-muted">- Choose an amount to start. You can always buy more later.+ {props.sharedWithTeam+ ? 'These credits are shared by your entire team.'+ : 'Choose an amount to start. You can always buy more later.'}</Dialog.Description></header><fieldset class="grid grid-cols-2 gap-3 sm:grid-cols-4">@@ -81,7 +84,9 @@ export function CreditPurchaseDialog(props: {</Show><div class="rounded-xl border border-edge-muted p-4 text-sm text-ink"><div class="flex justify-between gap-4">- <span>Usage credits</span>+ <span>+ {props.sharedWithTeam ? 'Team usage credits' : 'Usage credits'}+ </span><span>{formatCreditBalance(props.amountCents ?? 0)}</span></div><div class="mt-4 flex justify-between gap-4 border-t border-edge-muted pt-4">diff --git a/apps/web/src/features/usage/context/usage-context.ts b/apps/web/src/features/usage/context/usage-context.tsindex 31b6961f9e..717ebfa5bb 100644--- a/apps/web/src/features/usage/context/usage-context.ts+++ b/apps/web/src/features/usage/context/usage-context.ts@@ -1,5 +1,6 @@import type { Accessor } from 'solid-js';import type {+ AutoReloadBudget,AutoReloadSettings,UsagePreviewPlan,UsageSummary,@@ -19,6 +20,8 @@ export type UsageContext = {};autoReload: {settings: Accessor<AutoReloadSettings>;+ /** Authoritative calendar-month cap commitments, or explicit lab fixtures. */+ budget?: Accessor<AutoReloadBudget | undefined>;available: Accessor<boolean>;pending: Accessor<boolean>;/** The last automatic reload failed to charge; saving retries. */@@ -37,6 +40,7 @@ export type UsageContext = {navigateToPayment: (url: string) => void;openPlans: () => void;developer?: {+ openBillingLab?: () => void;active: Accessor<boolean>;plan: Accessor<UsagePreviewPlan | undefined>;beforeLaunch: Accessor<boolean>;diff --git a/apps/web/src/features/usage/core/usage.ts b/apps/web/src/features/usage/core/usage.tsindex 5419dfc453..678b932b3c 100644--- a/apps/web/src/features/usage/core/usage.ts+++ b/apps/web/src/features/usage/core/usage.ts@@ -3,9 +3,14 @@ export type UsageSummary = {periodEnd: string;unlimited: boolean;creditBalanceCents: number;+ creditScope: 'personal' | 'team';billingAccess: 'free' | 'payer' | 'team-member';existingUsageBilling?: { limitCents: number; suspended: boolean };- autoReload: { settings: AutoReloadSettings; suspended: boolean };+ autoReload: {+ settings: AutoReloadSettings;+ suspended: boolean;+ budget?: AutoReloadBudget;+ };};export type UsagePreviewPlan = 'free' | 'paid';@@ -87,3 +92,12 @@ export function validateAutoReload(return `Monthly spend limit must be at least ${formatCreditBalance(MIN_MONTHLY_SPEND_LIMIT_CENTS)}, or leave it blank.`;}}++/** Reload purchases use UTC calendar months, independently of subscription renewal. */+export type AutoReloadBudget = {+ /** Authoritative cap status, including insufficient room for the minimum charge. */+ limitReached?: boolean;+ spentCents: number;+ limitCents: number;+ resetsAt: string;+};diff --git a/apps/web/src/features/usage/queries/usage-summary.test.ts b/apps/web/src/features/usage/queries/usage-summary.test.tsindex 2f85591f3d..11e5de2a19 100644--- a/apps/web/src/features/usage/queries/usage-summary.test.ts+++ b/apps/web/src/features/usage/queries/usage-summary.test.ts@@ -24,6 +24,22 @@ const snapshot: AiUsageSnapshot = {};describe('usage billing access', () => {+ it('uses authoritative credit scope for a single-seat team and preserves the older-backend fallback', () => {+ expect(+ toUsageSummary({+ ...snapshot,+ tier: 'max',+ credits_shared_with_team: true,+ })+ ).toMatchObject({ billingAccess: 'payer', creditScope: 'team' });+ expect(+ toUsageSummary({ ...snapshot, seats: 4, credits_shared_with_team: false })+ .creditScope+ ).toBe('personal');+ expect(toUsageSummary({ ...snapshot, seats: 4 }).creditScope).toBe('team');+ expect(toUsageSummary(snapshot).creditScope).toBe('personal');+ });+it('marks a Free payer as ineligible for credit purchases', () => {expect(toUsageSummary(snapshot)).toMatchObject({billingAccess: 'free',@@ -64,12 +80,52 @@ describe('usage billing access', () => {it.each(['premium', 'max'] as const)('lets a %s payer purchase credits',(tier) => {- expect(toUsageSummary({ ...snapshot, tier }).billingAccess).toBe('payer');+ expect(toUsageSummary({ ...snapshot, tier })).toMatchObject({+ billingAccess: 'payer',+ creditScope: 'personal',+ });+ expect(toUsageSummary({ ...snapshot, tier, seats: 4 })).toMatchObject({+ billingAccess: 'payer',+ creditScope: 'team',+ });});});describe('automatic reload', () => {+ it('decodes authoritative calendar-month budget facts and keeps legacy responses unknown', () => {+ const auto_reload = {+ minimum_balance_cents: 1_000,+ target_balance_cents: 10_000,+ monthly_spend_limit_cents: 5_000,+ suspended: false,+ active: true,+ };+ expect(+ toUsageSummary({ ...snapshot, tier: 'max', auto_reload }).autoReload+ .budget+ ).toBeUndefined();+ expect(+ toUsageSummary({+ ...snapshot,+ tier: 'max',+ auto_reload: {+ ...auto_reload,+ monthly_budget: {+ committed_cents: 4_951,+ resets_at: '2026-11-01T00:00:00Z',+ limit_reached: true,+ },+ },+ }).autoReload.budget+ ).toEqual({+ spentCents: 4_951,+ limitCents: 5_000,+ resetsAt: '2026-11-01T00:00:00Z',+ limitReached: true,+ });+ });+it('treats usage billing as the opt-in and reads thresholds from the backend', () => {expect(toUsageSummary({diff --git a/apps/web/src/features/usage/queries/usage-summary.ts b/apps/web/src/features/usage/queries/usage-summary.tsindex 828e71cddb..86114d9c78 100644--- a/apps/web/src/features/usage/queries/usage-summary.ts+++ b/apps/web/src/features/usage/queries/usage-summary.ts@@ -17,6 +17,16 @@ function toAutoReload(snapshot: AiUsageSnapshot): UsageSummary['autoReload'] {return {settings: { ...thresholds, enabled: snapshot.overage_enabled },suspended: reload?.suspended ?? false,+ ...(reload?.monthly_budget && reload.monthly_spend_limit_cents !== null+ ? {+ budget: {+ spentCents: reload.monthly_budget.committed_cents,+ limitCents: reload.monthly_spend_limit_cents,+ resetsAt: reload.monthly_budget.resets_at,+ limitReached: reload.monthly_budget.limit_reached,+ },+ }+ : {}),};}@@ -29,6 +39,10 @@ export function toUsageSummary(snapshot: AiUsageSnapshot): UsageSummary {periodEnd: snapshot.period_end,unlimited: snapshot.unlimited,creditBalanceCents: snapshot.credit_balance_cents,+ creditScope:+ (snapshot.credits_shared_with_team ?? snapshot.seats > 1)+ ? 'team'+ : 'personal',existingUsageBilling:snapshot.tier !== 'free' &&(snapshot.overage_enabled || snapshot.overage_suspended)diff --git a/apps/web/src/features/usage/usage.tsx b/apps/web/src/features/usage/usage.tsxindex a1a6f7d984..cc1384bec6 100644--- a/apps/web/src/features/usage/usage.tsx+++ b/apps/web/src/features/usage/usage.tsx@@ -94,6 +94,7 @@ export function Usage() {},},autoReload: {+ budget: () => usageSummary()?.autoReload.budget,settings: () => {if (autoReloadPreview()) return previewSettings();return usageSummary()?.autoReload.settings ?? DEFAULT_AUTO_RELOAD;@@ -151,6 +152,11 @@ export function Usage() {},developer: DEV_MODE_ENV? {+ openBillingLab: LOCAL_ONLY+ ? () => {+ window.open('/billing-lab.html', '_blank', 'noopener');+ }+ : undefined,active: usagePreview.active,plan: usagePreview.plan,beforeLaunch: usagePreview.beforeLaunch,diff --git a/apps/web/src/features/usage/views/auto-reload.tsx b/apps/web/src/features/usage/views/auto-reload.tsxindex 0130624c38..1e8a95c115 100644--- a/apps/web/src/features/usage/views/auto-reload.tsx+++ b/apps/web/src/features/usage/views/auto-reload.tsx@@ -55,6 +55,7 @@ export function AutoReloadView(props: {};return (<AutoReloadDialog+ sharedWithTeam={props.context.summary()?.creditScope === 'team'}enabled={props.context.autoReload.settings().enabled}minimum={form.minimum()}target={form.target()}diff --git a/apps/web/src/features/usage/views/credit-purchase.tsx b/apps/web/src/features/usage/views/credit-purchase.tsxindex a6cdc0bdc0..46ef19fbed 100644--- a/apps/web/src/features/usage/views/credit-purchase.tsx+++ b/apps/web/src/features/usage/views/credit-purchase.tsx@@ -44,6 +44,7 @@ export function CreditPurchaseView(props: {try {const url = await props.context.checkout.start(amount);props.context.navigateToPayment(url);+ props.onClose();} catch (error) {const needsPlan = thrownResultErrorHasCode(error, 'PAID_PLAN_REQUIRED');setSubscriptionRequired(needsPlan);@@ -56,6 +57,7 @@ export function CreditPurchaseView(props: {};return (<CreditPurchaseDialog+ sharedWithTeam={props.context.summary()?.creditScope === 'team'}selection={selection()}customAmount={customAmount()}amountCents={amountCents()}diff --git a/apps/web/src/features/usage/views/usage-settings.test.tsx b/apps/web/src/features/usage/views/usage-settings.test.tsxnew file mode 100644index 0000000000..f68b4e658e--- /dev/null+++ b/apps/web/src/features/usage/views/usage-settings.test.tsx@@ -0,0 +1,210 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { createBillingLab } from '../../billing-lab/create-billing-lab';+import { fixtureSnapshot } from '../../billing-lab/queries/fixture-snapshot';+import { toUsageSummary } from '../queries/usage-summary';+import { UsageSettingsView } from './usage-settings';++beforeEach(() => vi.spyOn(window, 'scrollTo').mockImplementation(() => {}));+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++it.each(['spending-limit', 'team-owner-spending-limit'] as const)(+ 'lets the monthly cap notice open the real reload and credit dialogs in %s',+ (scenario) => {+ const lab = createBillingLab(scenario);+ render(() => <UsageSettingsView context={lab.usage} />);+ expect(+ screen.getByText('Monthly auto-reload $50 limit reached')+ ).toBeTruthy();+ expect(screen.getByText('resets Nov 1')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Adjust limit' }));+ expect(screen.getByRole('dialog', { name: 'Auto-Reload' })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Close Auto-Reload' }));+ fireEvent.click(screen.getByRole('button', { name: 'Add credits' }));+ expect(+ screen.getByRole('dialog', { name: 'Need more usage?' })+ ).toBeTruthy();+ }+);++it('lets a team owner recover a failed reload through the real controls', async () => {+ const lab = createBillingLab('team-owner-reload-paused');+ render(() => <UsageSettingsView context={lab.usage} />);+ expect(+ screen.getByText(/Paused — payment failed\. Update your payment/)+ ).toBeTruthy();+ fireEvent.click(+ screen.getByRole('button', { name: 'Configure Automatic reload' })+ );+ expect(screen.getByRole('dialog', { name: 'Auto-Reload' })).toBeTruthy();+ fireEvent.click(+ screen.getByRole('button', { name: 'Manage payment methods' })+ );+ await waitFor(() => expect(lab.payment()).toEqual({ kind: 'methods' }));+ await lab.completePayment();+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(lab.usage.autoReload.settings().enabled).toBe(true);+ expect(lab.usage.autoReload.suspended()).toBe(false);+});++it('does not infer a monthly cap-reached status without spend facts', () => {+ const lab = createBillingLab('spending-limit');+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ autoReload: { ...lab.usage.autoReload, budget: undefined },+ }}+ />+ ));+ expect(+ screen.queryByText('Monthly auto-reload $50 limit reached')+ ).toBeNull();+ expect(screen.queryByRole('button', { name: 'Adjust limit' })).toBeNull();+});++it('shows a live decoded cap notice when the remaining budget cannot fund a minimum reload', () => {+ const lab = createBillingLab('pro');+ const snapshot = {+ ...fixtureSnapshot(lab.state()),+ overage_enabled: true,+ auto_reload: {+ minimum_balance_cents: 1_000,+ target_balance_cents: 10_000,+ monthly_spend_limit_cents: 5_000,+ suspended: false,+ active: true,+ monthly_budget: {+ committed_cents: 4_951,+ resets_at: '2026-11-01T00:00:00Z',+ limit_reached: true,+ },+ },+ };+ const summary = () => toUsageSummary(snapshot);+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ summary,+ autoReload: {+ ...lab.usage.autoReload,+ settings: () => summary().autoReload.settings,+ budget: () => summary().autoReload.budget,+ },+ }}+ />+ ));+ expect(+ screen.getByText('Monthly auto-reload $50 limit reached')+ ).toBeTruthy();+ expect(screen.getByText('resets Nov 1')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Adjust limit' })).toBeTruthy();+});++it('removes the cap notice when the simulated calendar month resets', () => {+ const lab = createBillingLab('spending-limit');+ render(() => <UsageSettingsView context={lab.usage} />);+ expect(+ screen.getByText('Monthly auto-reload $50 limit reached')+ ).toBeTruthy();+ lab.advance(20);+ expect(+ screen.queryByText('Monthly auto-reload $50 limit reached')+ ).toBeNull();+ expect(lab.usage.autoReload.settings().enabled).toBe(true);+});++it('shows team-paid members only a team-managed notice for usage credits', () => {+ const lab = createBillingLab('team-member');+ render(() => <UsageSettingsView context={lab.usage} />);+ expect(+ screen.getByText('Usage credits are managed by your team.')+ ).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Add more' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Add credits' })).toBeNull();+ expect(screen.queryByText(/credits remaining/)).toBeNull();+ expect(screen.queryByText('Automatic reload')).toBeNull();+ expect(screen.queryByRole('button', { name: /Automatic reload/ })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Adjust limit' })).toBeNull();+ expect(screen.queryByRole('dialog')).toBeNull();+});++it.each(['pro', 'team-owner'] as const)(+ 'preserves credit purchases for a %s payer',+ (scenario) => {+ const lab = createBillingLab(scenario);+ render(() => <UsageSettingsView context={lab.usage} />);+ if (scenario === 'team-owner') {+ expect(+ screen.getByText('This is your personal monthly usage limit.')+ ).toBeTruthy();+ expect(screen.getByText('Team Usage Credits')).toBeTruthy();+ expect(+ screen.getByText('Credits are shared by your entire team.')+ ).toBeTruthy();+ expect(screen.getByText('Shared team balance')).toBeTruthy();+ expect(+ screen.getByText('Reloads credits for your entire team.')+ ).toBeTruthy();+ } else {+ expect(+ screen.queryByText('This is your personal monthly usage limit.')+ ).toBeNull();+ expect(screen.queryByText('Team Usage Credits')).toBeNull();+ expect(screen.getByText('Current balance')).toBeTruthy();+ }+ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ expect(+ screen.getByRole('dialog', { name: 'Need more usage?' })+ ).toBeTruthy();+ if (scenario === 'team-owner') {+ expect(+ screen.getByText('These credits are shared by your entire team.')+ ).toBeTruthy();+ expect(screen.getByText('Team usage credits')).toBeTruthy();+ fireEvent.click(+ screen.getByRole('button', { name: 'Close credit purchase' })+ );+ fireEvent.click(+ screen.getByRole('button', { name: 'Configure Automatic reload' })+ );+ expect(+ screen.getByText(+ 'Auto-reload adds credits to your team’s shared balance.'+ )+ ).toBeTruthy();+ }+ }+);++it('keeps team credit labels and the personal allowance explanation for an owner with one seat', () => {+ const lab = createBillingLab('team-owner');+ const snapshot = { ...fixtureSnapshot(lab.state()), seats: 1 };+ render(() => (+ <UsageSettingsView+ context={{ ...lab.usage, summary: () => toUsageSummary(snapshot) }}+ />+ ));+ expect(+ screen.getByText('This is your personal monthly usage limit.')+ ).toBeTruthy();+ expect(screen.getByText('Team Usage Credits')).toBeTruthy();+ expect(+ screen.getByText('Credits are shared by your entire team.')+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ expect(+ screen.getByText('These credits are shared by your entire team.')+ ).toBeTruthy();+});diff --git a/apps/web/src/features/usage/views/usage-settings.tsx b/apps/web/src/features/usage/views/usage-settings.tsxindex cf1f74d1c7..b68d7698b7 100644--- a/apps/web/src/features/usage/views/usage-settings.tsx+++ b/apps/web/src/features/usage/views/usage-settings.tsx@@ -6,6 +6,7 @@ import {SettingsRow,SettingsSection,} from '../../settings/primitives';+import { AutoReloadLimitNotice } from '../components/auto-reload-limit-notice';import { MonthlyLimit } from '../components/monthly-limit';import { UsageInfoDialog } from '../components/usage-info-dialog';import type { UsageContext } from '../context/usage-context';@@ -17,25 +18,44 @@ export function UsageSettingsView(props: { context: UsageContext }) {const [infoOpen, setInfoOpen] = createSignal(false);const [purchaseOpen, setPurchaseOpen] = createSignal(false);const [autoReloadOpen, setAutoReloadOpen] = createSignal(false);- const [billingError, setBillingError] = createSignal<string>();// Controlled dialogs have no Dialog.Trigger; restore their actual opener on close.let infoTrigger: HTMLButtonElement | undefined;let purchaseTrigger: HTMLButtonElement | undefined;let autoReloadTrigger: HTMLButtonElement | undefined;- const turnOffUsageBilling = async () => {- if (- props.context.developer?.active() ||- props.context.autoReload.preview() ||- props.context.existingUsageBilling.pending()- )- return;- setBillingError(undefined);- try {- await props.context.existingUsageBilling.turnOff();- } catch {- setBillingError("Couldn't turn off usage billing. Please try again.");- }+ const reloadLimit = () => {+ const budget = props.context.autoReload.budget?.();+ return props.context.autoReload.settings().enabled &&+ !props.context.autoReload.suspended() &&+ budget &&+ (budget.limitReached ?? budget.spentCents >= budget.limitCents)+ ? budget+ : undefined;};+ const reloadLimitNotice = () => (+ <Show when={reloadLimit()}>+ {(budget) => (+ <AutoReloadLimitNotice+ budget={budget()}+ canManage={+ props.context.summary()?.billingAccess === 'payer' &&+ props.context.autoReload.available()+ }+ pending={+ props.context.autoReload.pending() ||+ props.context.checkout.pending()+ }+ onAdjust={(trigger) => {+ autoReloadTrigger = trigger;+ setAutoReloadOpen(true);+ }}+ onAddCredits={(trigger) => {+ purchaseTrigger = trigger;+ setPurchaseOpen(true);+ }}+ />+ )}+ </Show>+ );return (<SettingsPage title="Usage"><Show when={!props.context.available()}>@@ -92,6 +112,17 @@ export function UsageSettingsView(props: { context: UsageContext }) {infoTrigger = button;}}/>+ <Show+ when={+ summary().billingAccess === 'payer' &&+ summary().creditScope === 'team' &&+ !summary().unlimited+ }+ >+ <p class="mt-3 text-xs text-ink-muted">+ This is your personal monthly usage limit.+ </p>+ </Show></div></SettingsCard><Show@@ -124,108 +155,117 @@ export function UsageSettingsView(props: { context: UsageContext }) {}><SettingsSection- title="Usage Credits"- description="Buy credits or turn on automatic reload to continue using Macro AI when you reach usage limits"+ title={+ summary().creditScope === 'team' &&+ summary().billingAccess === 'payer'+ ? 'Team Usage Credits'+ : 'Usage Credits'+ }+ description={+ summary().billingAccess === 'team-member'+ ? undefined+ : summary().creditScope === 'team'+ ? 'Credits are shared by your entire team.'+ : 'Buy credits or turn on automatic reload to continue using Macro AI when you reach usage limits'+ }>- <SettingsCard>- <SettingsRow- label={- <span class="font-medium">- {formatCreditBalance(summary().creditBalanceCents)}{' '}- credits remaining- </span>- }- description="Current balance"- >- <Button- ref={(button) => {- purchaseTrigger = button;- }}- variant="outline"- depth={3}- size="sm"- class="rounded-full px-4"- onClick={() => setPurchaseOpen(true)}- >- Add more- </Button>- </SettingsRow>- <SettingsRow label="Automatic reload">- <button- ref={(button) => {- autoReloadTrigger = button;- }}- type="button"- aria-label="Configure Automatic reload"- aria-haspopup="dialog"- aria-expanded={autoReloadOpen()}- class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2"- classList={{- 'bg-accent':- props.context.autoReload.settings().enabled,- 'bg-ink-muted/40':- !props.context.autoReload.settings().enabled,- }}- onClick={() => setAutoReloadOpen(true)}- >- <span- aria-hidden="true"- class={cn(- 'absolute left-0.5 size-4 rounded-full bg-surface transition-transform',- props.context.autoReload.settings().enabled &&- 'translate-x-4'- )}- />- <span class="sr-only">- Currently{' '}- {props.context.autoReload.settings().enabled- ? 'on'- : 'off'}- </span>- </button>- </SettingsRow>- </SettingsCard>- </SettingsSection>- </Show>- <Show when={summary().existingUsageBilling}>- {(billing) => (- <SettingsSection- title="Existing usage billing"- description="Usage past your plan and credits is billed to your card. While it is on, credits reload automatically when your balance drops below your minimum."- >- <SettingsCard>- <SettingsRow- label={- billing().suspended- ? 'Usage billing paused'- : 'Usage billing enabled'- }- description={`Limit: ${formatCreditBalance(billing().limitCents)} per period`}- >- <Show when={summary().billingAccess === 'payer'}>- <Button- variant="outline"- depth={3}- size="sm"- disabled={- props.context.existingUsageBilling.pending() ||- props.context.developer?.active() ||- props.context.autoReload.preview()+ <Show+ when={summary().billingAccess === 'team-member'}+ fallback={+ <>+ {reloadLimitNotice()}+ <SettingsCard>+ <SettingsRow+ label={+ <span class="font-medium">+ {formatCreditBalance(+ summary().creditBalanceCents+ )}{' '}+ credits remaining+ </span>+ }+ description={+ summary().creditScope === 'team'+ ? 'Shared team balance'+ : 'Current balance'}- onClick={() => void turnOffUsageBilling()}>- Turn off usage billing- </Button>- </Show>- </SettingsRow>- </SettingsCard>- <Show when={billingError()}>- <p class="text-sm text-failure" role="alert">- {billingError()}+ <Show when={summary().billingAccess === 'payer'}>+ <Button+ ref={(button) => {+ purchaseTrigger = button;+ }}+ variant="outline"+ depth={3}+ size="sm"+ class="rounded-full px-4"+ onClick={() => setPurchaseOpen(true)}+ >+ Add more+ </Button>+ </Show>+ </SettingsRow>+ <SettingsRow+ label="Automatic reload"+ description={+ props.context.autoReload.suspended() ? (+ <span role="status" class="text-failure">+ Paused — payment failed. Update your payment+ method, then save to retry.+ </span>+ ) : summary().creditScope === 'team' ? (+ 'Reloads credits for your entire team.'+ ) : undefined+ }+ >+ <button+ ref={(button) => {+ autoReloadTrigger = button;+ }}+ type="button"+ aria-label="Configure Automatic reload"+ aria-haspopup="dialog"+ aria-expanded={autoReloadOpen()}+ class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2 disabled:opacity-50"+ classList={{+ 'bg-accent':+ props.context.autoReload.settings().enabled,+ 'bg-ink-muted/40':+ !props.context.autoReload.settings().enabled,+ }}+ onClick={() => setAutoReloadOpen(true)}+ >+ <span+ aria-hidden="true"+ class={cn(+ 'absolute left-0.5 size-4 rounded-full bg-surface transition-transform',+ props.context.autoReload.settings().enabled &&+ 'translate-x-4'+ )}+ />+ <span class="sr-only">+ {props.context.autoReload.suspended()+ ? 'Paused after a failed payment. Setting currently '+ : reloadLimit()+ ? 'Monthly limit reached. Setting currently '+ : 'Currently '}+ {props.context.autoReload.settings().enabled+ ? 'on'+ : 'off'}+ </span>+ </button>+ </SettingsRow>+ </SettingsCard>+ </>+ }+ >+ <SettingsCard>+ <p class="p-4 text-sm text-ink-muted">+ Usage credits are managed by your team.</p>- </Show>- </SettingsSection>- )}+ </SettingsCard>+ </Show>+ </SettingsSection></Show></>)}@@ -239,6 +279,19 @@ export function UsageSettingsView(props: { context: UsageContext }) {><SettingsCard><div class="flex flex-col gap-3 p-4">+ <Show when={developer().openBillingLab}>+ {(open) => (+ <Button+ variant="accent"+ depth={3}+ size="sm"+ class="self-start"+ onClick={open()}+ >+ Open Billing Lab+ </Button>+ )}+ </Show><div class="flex flex-wrap gap-2"><Buttonvariant={diff --git a/apps/web/src/lib/queries/auth/ai-billing.ts b/apps/web/src/lib/queries/auth/ai-billing.tsindex 4c7ee683e3..db27286177 100644--- a/apps/web/src/lib/queries/auth/ai-billing.ts+++ b/apps/web/src/lib/queries/auth/ai-billing.ts@@ -77,6 +77,37 @@ export function invalidateAiBillingSummary() {});}+/** Renewal and scheduled downgrade, read only while Billing settings needs it. */+function subscriptionStatusQueryOptions(enabled: boolean) {+ return {+ queryKey: authKeys.subscriptionStatus.queryKey,+ queryFn: async () =>+ await throwOnErr(() => authServiceClient.getSubscriptionStatus()),+ enabled,+ staleTime: AI_BILLING_SUMMARY_STALE_TIME,+ throwOnError: false,+ retry: 1,+ };+}++export function useSubscriptionStatusQuery(+ options?: UseAiBillingSummaryQueryOptions+) {+ return useQuery(() =>+ subscriptionStatusQueryOptions(+ typeof options?.enabled === 'function'+ ? options.enabled()+ : (options?.enabled ?? true)+ )+ );+}++export function invalidateSubscriptionStatus() {+ return queryClient.invalidateQueries({+ queryKey: authKeys.subscriptionStatus.queryKey,+ });+}+/** Turn usage billing (overage) on or off with a per-period cap. */export function useUpdateAiOverageMutation() {return useMutation(() => ({@@ -130,10 +161,11 @@ export function useChangePlanMutation() {return useMutation(() => ({mutationFn: async (args: { plan: PaidPlan }) =>await throwOnErr(async () => await authServiceClient.changePlan(args)),- onSuccess: () => {- // Roles flip via webhook shortly after; refetch both views.+ onSuccess: async () => {+ // Roles flip via webhook; the scheduled change is available immediately.void invalidateUserInfo();void invalidateAiBillingSummary();+ await invalidateSubscriptionStatus();},}));}diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.tsindex b51b8f9793..e784d064ce 100644--- a/apps/web/src/lib/queries/auth/index.ts+++ b/apps/web/src/lib/queries/auth/index.ts@@ -6,11 +6,13 @@ export {} from '@core/context/user';export {invalidateAiBillingSummary,+ invalidateSubscriptionStatus,useAiBillingPlansQuery,useAiBillingSummaryQuery,useChangePlanMutation,useCreateAiCreditCheckoutMutation,useIncludedAiCentsByTier,+ useSubscriptionStatusQuery,useUpdateAiAutoReloadMutation,useUpdateAiOverageMutation,} from './ai-billing';diff --git a/apps/web/src/lib/queries/auth/keys.ts b/apps/web/src/lib/queries/auth/keys.tsindex 231195e113..06e004d16f 100644--- a/apps/web/src/lib/queries/auth/keys.ts+++ b/apps/web/src/lib/queries/auth/keys.ts@@ -3,6 +3,7 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';export const authKeys = createQueryKeys('auth', {aiBillingPlans: null,aiBillingSummary: null,+ subscriptionStatus: null,codexStatus: null,codexEnvironments: null,codexLogin: (attemptId: string) => ({ queryKey: [attemptId] }),diff --git a/apps/web/src/lib/queries/team/members.ts b/apps/web/src/lib/queries/team/members.tsindex 1b8864510b..10a5142050 100644--- a/apps/web/src/lib/queries/team/members.ts+++ b/apps/web/src/lib/queries/team/members.ts@@ -5,7 +5,10 @@ import { authServiceClient } from '@service-auth/client';import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';import { useMutation } from '@tanstack/solid-query';-import { invalidateAiBillingSummary } from '../auth';+import {+ invalidateAiBillingSummary,+ invalidateSubscriptionStatus,+} from '../auth';import { queryClient } from '../client';import { type MutationCallbacks, withCallbacks } from '../utils';@@ -88,8 +91,7 @@ type SetTeamMemberPlanCallbacks = MutationCallbacks</*** Move one member's seat between Pro and Max. Team admins only; the- * team's subscription is re-billed (prorated) and that seat's AI allowance- * changes at once, so the billing summary is refreshed too.+ * Max upgrades apply immediately with proration; Pro downgrades start at renewal.*/export function useSetTeamMemberPlanMutation(callbacks?: SetTeamMemberPlanCallbacks@@ -104,8 +106,11 @@ export function useSetTeamMemberPlanMutation(onSuccess: (_data, { teamId, plan }) => {invalidateTeam(teamId);void invalidateAiBillingSummary();+ void invalidateSubscriptionStatus();toast.success(- plan === 'max' ? 'Seat moved to Max' : 'Seat moved to Pro'+ plan === 'max'+ ? 'Max applies immediately. Any pending downgrade is canceled.'+ : 'Pro is scheduled for the next renewal. This seat keeps Max until then.');},diff --git a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.tsindex 314d270b2a..172df6cb49 100644--- a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts+++ b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts@@ -31,6 +31,12 @@ export interface AiAutoReloadSnapshot {target_balance_cents: number;/** Most reloaded per UTC calendar month; `null` when there is no limit. */monthly_spend_limit_cents: number | null;+ /** Authoritative UTC-month cap commitments; absent on older backends. */+ monthly_budget?: {+ committed_cents: number;+ resets_at: string;+ limit_reached: boolean;+ } | null;/** Reloads are paused after a failed reload charge. */suspended: boolean;/** Overage is on and reloads are not suspended. */@@ -49,6 +55,8 @@ export interface AiUsageSnapshot {used_cents: number;credits_consumed_cents: number;credit_balance_cents: number;+ /** Team billing scope, independent of seat count; absent on older backends. */+ credits_shared_with_team?: boolean;overage_enabled: boolean;overage_limit_cents: number;overage_charged_cents: number;@@ -86,6 +94,9 @@ export interface AiPlanCatalog {export type PaidPlan = 'premium' | 'max';+/** Authoritative renewal and pending change from GET /user/stripe/plan. */+export type { SubscriptionStatus } from './generated/schemas/subscriptionStatus';+/*** A team member with the plan their seat is billed at. Mirrors the auth* service's `TeamMember` once `plan` lands in the generated schema.diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex edbf4283bb..ca391d8452 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -18,6 +18,7 @@ import type {AiPlanCatalog,AiUsageSnapshot,PaidPlan,+ SubscriptionStatus,TeamMemberPlan,} from './ai-billing-types';import { fetchWithAuth as _fetchWithAuth } from './fetch';@@ -699,8 +700,8 @@ export const authServiceClient = {},/**- * Moves the active subscription to another paid plan. Proration is invoiced- * immediately; roles and the AI allowance follow from the Stripe webhook.+ * Upgrades immediately, schedules downgrades for renewal, or keeps the active+ * plan by canceling its pending downgrade.*/async changePlan(args: { plan: PaidPlan }) {return (@@ -711,6 +712,13 @@ export const authServiceClient = {).map((result) => result.plan);},+ async getSubscriptionStatus() {+ return await fetchWithAuth<SubscriptionStatus>(+ `${authHost}/user/stripe/plan`,+ { method: 'GET' }+ );+ },+// AI billing: allowance, credits, overage.async getAiBillingSummary() {return await fetchWithAuth<AiUsageSnapshot>(diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex c7369ccd2e..e78b7a9fa7 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -82,6 +82,7 @@ import type {SsoLoginParams,SsoRequiredResponse,StripeSessionResponse,+ SubscriptionStatus,Team,TeamInvitesResponse,TeamMember,@@ -5556,14 +5557,72 @@ export const createCheckoutSessionV2 = async (};/**- * On a team billed per seat this moves only the caller's seat (team admins-and the owner may do so; teammates' seats are managed from team-settings). Members of a free team, and solo subscribers, get the price on-their own subscription's seat item swapped. The proration is invoiced-immediately either way; roles and the AI allowance follow at once on a-team and from the `customer.subscription.updated` webhook for a personal-subscription.- * @summary Moves the caller's own seat between paid plans.+ * @summary Read subscription state for the authenticated user's seat.+ */+export type getSubscriptionStatusResponse200 = {+ data: SubscriptionStatus;+ status: 200;+};++export type getSubscriptionStatusResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type getSubscriptionStatusResponse409 = {+ data: ErrorResponse;+ status: 409;+};++export type getSubscriptionStatusResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type getSubscriptionStatusResponseSuccess =+ getSubscriptionStatusResponse200 & {+ headers: Headers;+ };+export type getSubscriptionStatusResponseError = (+ | getSubscriptionStatusResponse401+ | getSubscriptionStatusResponse409+ | getSubscriptionStatusResponse500+) & {+ headers: Headers;+};++export type getSubscriptionStatusResponse =+ | getSubscriptionStatusResponseSuccess+ | getSubscriptionStatusResponseError;++export const getGetSubscriptionStatusUrl = () => {+ return `/user/stripe/plan`;+};++export const getSubscriptionStatus = async (+ options?: RequestInit+): Promise<getSubscriptionStatusResponse> => {+ const res = await fetch(getGetSubscriptionStatusUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getSubscriptionStatusResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getSubscriptionStatusResponse;+};++/**+ * @summary Changes the caller's paid plan. Upgrades are prorated immediately;+downgrades retain the active plan until renewal. Selecting the active plan+cancels a pending downgrade without charging or resetting usage.*/export type changePlanResponse200 = {data: ChangePlanResponse;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.tsnew file mode 100644index 0000000000..74d0a6e001--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Calendar-month commitments that consume the payer's automatic reload cap.+ */+export interface AutoReloadMonthlyBudget {+ /** Reloads paid, pending, or failed with an invoice that can still collect.+Customer cents; manual credit purchases do not count. */+ committed_cents: number;+ /** Remaining cap cannot fund the minimum automatic reload charge. */+ limit_reached: boolean;+ /** Start of the next UTC calendar month, independently of subscription renewal. */+ resets_at: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.tsindex e898f17007..a4183badf3 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts@@ -4,6 +4,7 @@* authentication_service* OpenAPI spec version: 0.1.0*/+import type { AutoReloadSnapshotMonthlyBudget } from './autoReloadSnapshotMonthlyBudget';import type { AutoReloadSnapshotMonthlySpendLimitCents } from './autoReloadSnapshotMonthlySpendLimitCents';/**@@ -14,6 +15,7 @@ export interface AutoReloadSnapshot {active: boolean;/** Reload once the effective balance drops below this, in customer cents. */minimum_balance_cents: number;+ monthly_budget?: AutoReloadSnapshotMonthlyBudget;/** Most reloaded per UTC calendar month, in customer cents. `null` whenthere is no limit. */monthly_spend_limit_cents?: AutoReloadSnapshotMonthlySpendLimitCents;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshotMonthlyBudget.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshotMonthlyBudget.tsnew file mode 100644index 0000000000..56d532e777--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshotMonthlyBudget.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { AutoReloadMonthlyBudget } from './autoReloadMonthlyBudget';++export type AutoReloadSnapshotMonthlyBudget = null | AutoReloadMonthlyBudget;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex 34ad3546cd..e94a40a2a2 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -9,7 +9,9 @@ export * from './aBGroup';export * from './aiBillingErrorBody';export * from './appleLoginRequest';export * from './autoReloadDefaults';+export * from './autoReloadMonthlyBudget';export * from './autoReloadSnapshot';+export * from './autoReloadSnapshotMonthlyBudget';export * from './autoReloadSnapshotMonthlySpendLimitCents';export * from './changePlanRequest';export * from './changePlanResponse';@@ -173,6 +175,7 @@ export * from './putUserNameQueryParamsFirstName';export * from './putUserNameQueryParamsLastName';export * from './redeemGtmInviteLinkRequest';export * from './resendFusionauthVerifyUserEmailRequest';+export * from './scheduledSeatPlan';export * from './seatPlan';export * from './sendInviteBody';export * from './sendMobileWelcomeEmailRequest';@@ -180,6 +183,9 @@ export * from './sendMobileWelcomeEmailResponse';export * from './ssoLoginParams';export * from './ssoRequiredResponse';export * from './stripeSessionResponse';+export * from './subscriptionStatus';+export * from './subscriptionStatusRenewalDate';+export * from './subscriptionStatusScheduledChange';export * from './team';export * from './teamAutoJoinDomain';export * from './teamDefaultLinkShare';@@ -189,6 +195,8 @@ export * from './teamMember';export * from './teamPlan';export * from './teamRole';export * from './teamWithMembers';+export * from './teamWithMembersScheduledSeatPlans';+export * from './teamWithMembersScheduledSeatPlansAnyOf';export * from './toggleAutoJoinDomainResponse';export * from './toggleAutoJoinDomainResponseAutoJoinDomain';export * from './toggleNonAdminInvitesResponse';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/scheduledSeatPlan.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/scheduledSeatPlan.tsnew file mode 100644index 0000000000..642c4cb870--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/scheduledSeatPlan.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { SeatPlan } from './seatPlan';++/**+ * A seat's future plan in the subscription's currently attached schedule.+ */+export interface ScheduledSeatPlan {+ /** Provider-confirmed time when the future phase starts. */+ effectiveAt: string;+ /** Plan that takes effect at renewal. */+ plan: SeatPlan;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatus.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatus.tsnew file mode 100644index 0000000000..1065551ac8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatus.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { SubscriptionStatusRenewalDate } from './subscriptionStatusRenewalDate';+import type { SubscriptionStatusScheduledChange } from './subscriptionStatusScheduledChange';++/**+ * Current renewal and scheduled change; empty for accounts without a subscription.+ */+export interface SubscriptionStatus {+ /** Provider-confirmed subscription renewal date. */+ renewalDate?: SubscriptionStatusRenewalDate;+ scheduledChange?: SubscriptionStatusScheduledChange;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusRenewalDate.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusRenewalDate.tsnew file mode 100644index 0000000000..31a26b7628--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusRenewalDate.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider-confirmed subscription renewal date.+ */+export type SubscriptionStatusRenewalDate = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusScheduledChange.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusScheduledChange.tsnew file mode 100644index 0000000000..7bd2d6ee17--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/subscriptionStatusScheduledChange.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { ScheduledSeatPlan } from './scheduledSeatPlan';++export type SubscriptionStatusScheduledChange = null | ScheduledSeatPlan;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembers.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembers.tsindex c1c30c4d48..cb1b428b93 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembers.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembers.ts@@ -7,6 +7,7 @@import type { Team } from './team';import type { TeamMember } from './teamMember';+import type { TeamWithMembersScheduledSeatPlans } from './teamWithMembersScheduledSeatPlans';/*** A team with its members@@ -14,6 +15,9 @@ import type { TeamMember } from './teamMember';export interface TeamWithMembers {/** The members of the team */members: TeamMember[];+ /** Provider-confirmed pending seat changes, keyed by member user ID.+Only available to paid-team admins and owners; empty means no pending changes. */+ scheduled_seat_plans?: TeamWithMembersScheduledSeatPlans;/** The team */team: Team;}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlans.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlans.tsnew file mode 100644index 0000000000..48bf2933a7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlans.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamWithMembersScheduledSeatPlansAnyOf } from './teamWithMembersScheduledSeatPlansAnyOf';++/**+ * Provider-confirmed pending seat changes, keyed by member user ID.+Only available to paid-team admins and owners; empty means no pending changes.+ */+export type TeamWithMembersScheduledSeatPlans =+ TeamWithMembersScheduledSeatPlansAnyOf | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlansAnyOf.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlansAnyOf.tsnew file mode 100644index 0000000000..0fcebc5a35--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembersScheduledSeatPlansAnyOf.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { ScheduledSeatPlan } from './scheduledSeatPlan';++/**+ * Provider-confirmed pending seat changes, keyed by member user ID.+Only available to paid-team admins and owners; empty means no pending changes.+ */+export type TeamWithMembersScheduledSeatPlansAnyOf = {+ [key: string]: ScheduledSeatPlan;+};diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.tsindex 317f7bb8d0..57f926ceed 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts@@ -23,6 +23,8 @@ reloads are not suspended. */credit_balance_cents: number;/** Shared payer credits already applied to this period, in customer cents. */credits_consumed_cents: number;+ /** Whether prepaid credits belong to the team, including a team with one seat. */+ credits_shared_with_team: boolean;/** Included AI for this user's seat this period, in cents at provider cost. */included_cents: number;/** Shared overage charged so far this period, in customer cents. */diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 23c9831b11..2ea9d10496 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -4630,10 +4630,56 @@}},"/user/stripe/plan": {+ "get": {+ "tags": ["user::stripe::subscription_status"],+ "summary": "Read subscription state for the authenticated user's seat.",+ "operationId": "get_subscription_status",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubscriptionStatus"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "More than one active subscription",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },"post": {"tags": ["user::stripe::change_plan"],- "summary": "Moves the caller's own seat between paid plans.",- "description": "On a team billed per seat this moves only the caller's seat (team admins\nand the owner may do so; teammates' seats are managed from team\nsettings). Members of a free team, and solo subscribers, get the price on\ntheir own subscription's seat item swapped. The proration is invoiced\nimmediately either way; roles and the AI allowance follow at once on a\nteam and from the `customer.subscription.updated` webhook for a personal\nsubscription.",+ "summary": "Changes the caller's paid plan. Upgrades are prorated immediately;\ndowngrades retain the active plan until renewal. Selecting the active plan\ncancels a pending downgrade without charging or resetting usage.","operationId": "change_plan","requestBody": {"content": {@@ -4697,7 +4743,7 @@}},"409": {- "description": "Already on this plan, or more than one active subscription",+ "description": "More than one active subscription","content": {"application/json": {"schema": {@@ -4874,6 +4920,27 @@}}},+ "AutoReloadMonthlyBudget": {+ "type": "object",+ "description": "Calendar-month commitments that consume the payer's automatic reload cap.",+ "required": ["committed_cents", "resets_at", "limit_reached"],+ "properties": {+ "committed_cents": {+ "type": "integer",+ "format": "int64",+ "description": "Reloads paid, pending, or failed with an invoice that can still collect.\nCustomer cents; manual credit purchases do not count."+ },+ "limit_reached": {+ "type": "boolean",+ "description": "Remaining cap cannot fund the minimum automatic reload charge."+ },+ "resets_at": {+ "type": "string",+ "format": "date-time",+ "description": "Start of the next UTC calendar month, independently of subscription renewal."+ }+ }+ },"AutoReloadSnapshot": {"type": "object","description": "The payer's automatic reload settings, as shown in Billing settings.",@@ -4893,6 +4960,17 @@"format": "int64","description": "Reload once the effective balance drops below this, in customer cents."},+ "monthly_budget": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AutoReloadMonthlyBudget",+ "description": "Present for paid finite accounts with a configured monthly cap."+ }+ ]+ },"monthly_spend_limit_cents": {"type": ["integer", "null"],"format": "int64",@@ -6561,6 +6639,22 @@}}},+ "ScheduledSeatPlan": {+ "type": "object",+ "description": "A seat's future plan in the subscription's currently attached schedule.",+ "required": ["plan", "effectiveAt"],+ "properties": {+ "effectiveAt": {+ "type": "string",+ "format": "date-time",+ "description": "Provider-confirmed time when the future phase starts."+ },+ "plan": {+ "$ref": "#/components/schemas/SeatPlan",+ "description": "Plan that takes effect at renewal."+ }+ }+ },"SeatPlan": {"type": "string","description": "The paid plan a seat is billed at. Every member of a paying team has one;\na team may mix them, and its Stripe subscription carries one seat item per\nplan in use.",@@ -6618,6 +6712,28 @@}}},+ "SubscriptionStatus": {+ "type": "object",+ "description": "Current renewal and scheduled change; empty for accounts without a subscription.",+ "properties": {+ "renewalDate": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Provider-confirmed subscription renewal date."+ },+ "scheduledChange": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ScheduledSeatPlan",+ "description": "Future downgrade for the caller's seat, if still pending."+ }+ ]+ }+ }+ },"Team": {"type": "object","description": "The Team struct",@@ -6780,6 +6896,16 @@},"description": "The members of the team"},+ "scheduled_seat_plans": {+ "type": ["object", "null"],+ "description": "Provider-confirmed pending seat changes, keyed by member user ID.\nOnly available to paid-team admins and owners; empty means no pending changes.",+ "additionalProperties": {+ "$ref": "#/components/schemas/ScheduledSeatPlan"+ },+ "propertyNames": {+ "type": "string"+ }+ },"team": {"$ref": "#/components/schemas/Team","description": "The team"@@ -6864,6 +6990,7 @@"used_cents","credits_consumed_cents","credit_balance_cents",+ "credits_shared_with_team","overage_enabled","overage_limit_cents","overage_charged_cents",@@ -6902,6 +7029,10 @@"format": "int64","description": "Shared payer credits already applied to this period, in customer cents."},+ "credits_shared_with_team": {+ "type": "boolean",+ "description": "Whether prepaid credits belong to the team, including a team with one seat."+ },"included_cents": {"type": "integer","format": "int64",diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rsindex 692f27ab65..34df46f7f0 100644--- a/crates/agent_inmem/src/testing.rs+++ b/crates/agent_inmem/src/testing.rs@@ -47,6 +47,14 @@ pub(crate) fn disabled_admission() -> std::sync::Arc<dyn AiAdmissionService> {struct UnavailableBilling;impl ai_billing::domain::BillingService for UnavailableBilling {+ async fn change_plan(+ &self,+ _: &MacroUserIdStr<'_>,+ _: ai_billing::domain::plan_change::PlanChange,+ ) -> ai_billing::domain::Result<()> {+ panic!("this use case must not change plans")+ }+async fn check_allowance(&self,_: &MacroUserIdStr<'_>,diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex a28364ea6a..196fa37e75 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -6,6 +6,7 @@ pub mod financial;pub mod ledger;pub mod models;pub mod period;+pub mod plan_change;pub mod policy;pub mod ports;pub mod pricing;diff --git a/crates/ai_billing/src/domain/admission/test.rs b/crates/ai_billing/src/domain/admission/test.rsindex d665bd33ef..cd56a72f61 100644--- a/crates/ai_billing/src/domain/admission/test.rs+++ b/crates/ai_billing/src/domain/admission/test.rs@@ -21,6 +21,14 @@ impl FakeBilling {}impl BillingService for FakeBilling {+ async fn change_plan(+ &self,+ _: &MacroUserIdStr<'_>,+ _: crate::domain::plan_change::PlanChange,+ ) -> BillingResult<()> {+ panic!("this use case must not change plans")+ }+async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> BillingResult<AllowanceDecision> {assert_eq!(user.as_ref(), "macro|[email protected]");self.calls.fetch_add(1, Ordering::SeqCst);diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rsindex 22575deecc..2f933bea43 100644--- a/crates/ai_billing/src/domain/ledger.rs+++ b/crates/ai_billing/src/domain/ledger.rs@@ -39,7 +39,8 @@ mod test;use super::models::{AllowanceDecision, AutoReloadSnapshot, AutoReloadThresholds, BillingPeriod, BillingSettings,- DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS, PeriodLedger, PlanTier, UsageSnapshot,+ DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS, PayerScope, PeriodLedger, PlanTier,+ UsageSnapshot,};use super::pricing::AiPricing;use macro_user_id::user_id::MacroUserIdStr;@@ -196,6 +197,7 @@ pub fn build_snapshot(used_cents: used_cost_cents,credits_consumed_cents: ledger.credits_consumed_cents,credit_balance_cents,+ credits_shared_with_team: !matches!(entitlement.scope, PayerScope::Personal),overage_enabled: settings.overage_enabled,overage_limit_cents: settings.overage_limit_cents,overage_charged_cents: ledger.overage_charged_cents,@@ -204,6 +206,7 @@ pub fn build_snapshot(minimum_balance_cents: settings.auto_reload.minimum_cents,target_balance_cents: settings.auto_reload.target_cents,monthly_spend_limit_cents: settings.auto_reload.monthly_limit_cents,+ monthly_budget: None,suspended: settings.auto_reload_suspended_at.is_some(),active: settings.auto_reload_active(),},diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rsindex 80aab755d9..8d154e8b70 100644--- a/crates/ai_billing/src/domain/ledger/test.rs+++ b/crates/ai_billing/src/domain/ledger/test.rs@@ -530,6 +530,37 @@ fn unlimited_is_never_blocked() {assert_eq!(s.remaining_cents, i64::MAX);}+#[test]+fn credit_scope_follows_team_ownership_even_with_only_one_seat() {+ let owner = user("[email protected]");+ let mut entitlement = Entitlement::personal(owner.clone(), PlanTier::Max);+ for (scope, shared) in [+ (PayerScope::Personal, false),+ (+ PayerScope::TeamOwner {+ team_id: macro_uuid::generate_uuid_v7(),+ },+ true,+ ),+ ] {+ entitlement.scope = scope;+ let snapshot = build_snapshot(+ &owner,+ &entitlement,+ &BillingSettings::default(),+ BillingPeriod::calendar_month(Utc::now()),+ 0,+ 0,+ PeriodLedger::default(),+ 2_500,+ AiPricing::testing(),+ );+ assert_eq!(snapshot.seats, 1);+ assert!(snapshot.can_manage_billing);+ assert_eq!(snapshot.credits_shared_with_team, shared);+ }+}+#[test]fn team_member_is_not_the_payer() {let owner = user("[email protected]");@@ -556,6 +587,7 @@ fn team_member_is_not_the_payer() {AiPricing::testing(),);assert!(!s.can_manage_billing);+ assert!(s.credits_shared_with_team);assert_eq!(s.seats, 2);assert_eq!(s.included_cents, 10_000);}diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex abe4ee7deb..306d91e6f5 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -349,6 +349,11 @@ pub struct SeatUsage {pub user: MacroUserIdStr<'static>,/// Usage in cents at provider cost.pub used_cents: i64,+ /// Total historical overage across paid allowance intervals, when plan+ /// history exists. Earlier included costs never become debt on downgrade;+ /// upgrades preserve old overage and previously consumed credits.+ /// Without history, the service applies the current seat allowance.+ pub chargeable_cost_cents: Option<i64>,}/// A user's resolved plan and payer.@@ -616,6 +621,18 @@ pub enum AllowanceDecision {Deny(DenyReason),}+/// Calendar-month commitments that consume the payer's automatic reload cap.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct AutoReloadMonthlyBudget {+ /// Reloads paid, pending, or failed with an invoice that can still collect.+ /// Customer cents; manual credit purchases do not count.+ pub committed_cents: i64,+ /// Start of the next UTC calendar month, independently of subscription renewal.+ pub resets_at: DateTime<Utc>,+ /// Remaining cap cannot fund the minimum automatic reload charge.+ pub limit_reached: bool,+}+/// The payer's automatic reload settings, as shown in Billing settings.#[derive(Debug, Clone, Serialize, ToSchema)]pub struct AutoReloadSnapshot {@@ -626,6 +643,8 @@ pub struct AutoReloadSnapshot {/// Most reloaded per UTC calendar month, in customer cents. `null` when/// there is no limit.pub monthly_spend_limit_cents: Option<i64>,+ /// Present for paid finite accounts with a configured monthly cap.+ pub monthly_budget: Option<AutoReloadMonthlyBudget>,/// Whether reloads are paused after a failed reload charge.pub suspended: bool,/// Whether reloads will fire: the payer opted in and reloads are not suspended.@@ -659,6 +678,8 @@ pub struct UsageSnapshot {pub credits_consumed_cents: i64,/// Shared prepaid credit balance, in customer cents.pub credit_balance_cents: i64,+ /// Whether prepaid credits belong to the team, including a team with one seat.+ pub credits_shared_with_team: bool,/// Legacy API name for the automatic reload opt-in. Never authorizes direct charges.pub overage_enabled: bool,/// Per-period overage cap, in customer cents.diff --git a/crates/ai_billing/src/domain/plan_change.rs b/crates/ai_billing/src/domain/plan_change.rsnew file mode 100644index 0000000000..e208a3c402--- /dev/null+++ b/crates/ai_billing/src/domain/plan_change.rs@@ -0,0 +1,131 @@+//! Usage resets for verified paid-plan changes.++use chrono::{DateTime, Utc};++use super::{BillingPeriod, PlanTier};++#[cfg(test)]+mod test;++/// A plan transition with its original occurrence time and subscription interval.+/// Retaining these facts makes delayed/replayed webhooks use the same baseline.+#[derive(Debug, Clone, Copy)]+pub struct PlanChange {+ /// Plan before the change.+ pub from: PlanTier,+ /// Plan after the change.+ pub to: PlanTier,+ /// When the provider or team service changed the plan.+ pub at: DateTime<Utc>,+ /// Billing interval containing the change; renewal dates remain unchanged.+ pub period: BillingPeriod,+}++impl PlanChange {+ /// Whether the destination gives a higher plan than the source.+ pub fn is_upgrade(from: PlanTier, to: PlanTier) -> bool {+ matches!(+ (from, to),+ (PlanTier::Free, PlanTier::Premium | PlanTier::Max)+ | (PlanTier::Premium, PlanTier::Max)+ )+ }++ /// Only actual transitions within the original interval become history.+ pub fn is_valid(self) -> bool {+ self.from != self.to && self.period.start <= self.at && self.at < self.period.end+ }++ /// Whether this transition can establish a new allowance baseline.+ pub fn resets_usage(self) -> bool {+ Self::is_upgrade(self.from, self.to) && self.is_valid()+ }+}++/// Immutable plan facts and the configured allowances at the time of the change.+#[derive(Debug, Clone, Copy)]+pub struct RecordedPlanChange {+ /// Original transition, including its occurrence time and billing interval.+ pub change: PlanChange,+ /// Previous paid allowance; Free cannot accrue overage.+ pub previous_included_cents: Option<i64>,+ /// Destination paid allowance; Free cannot accrue overage.+ pub new_included_cents: Option<i64>,+}++/// Counted provider costs grouped by a plan boundary, including empty intervals.+#[derive(Debug, Clone, Copy)]+pub struct PlanUsageSegment {+ /// Interval start, either the period start or a recorded transition.+ pub start: DateTime<Utc>,+ /// Provider cost in dollars; rounding applies to cumulative usage.+ pub usd: f64,+}++/// Usage and historical liability after applying a seat's plan history.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PlanUsage {+ /// Current allowance consumption since the most recent eligible upgrade.+ pub used_cents: i64,+ /// Total cost liability across all paid legacy intervals, including old overage.+ pub chargeable_cents: i64,+}++fn rank(tier: PlanTier) -> u8 {+ match tier {+ PlanTier::Free => 0,+ PlanTier::Premium => 1,+ PlanTier::Max => 2,+ }+}++/// Apply immutable history in occurrence order, independent of delivery order.+/// Returning to an already held plan retains consumption. Each paid interval+/// charges only usage newly exceeding its allowance, never reclassifying old use.+pub fn meter_plan_usage(+ changes: &[RecordedPlanChange],+ segments: &[PlanUsageSegment],+ public_funding: bool,+) -> PlanUsage {+ let Some(first) = changes.first() else {+ return PlanUsage {+ used_cents: super::cost_cents(segments.iter().map(|s| s.usd).sum()),+ chargeable_cents: 0,+ };+ };+ let mut highest = if first.change.at == first.change.period.start {+ 0+ } else {+ rank(first.change.from)+ };+ let mut allowance = first.previous_included_cents;+ let mut legacy = !public_funding+ || (first.change.from == PlanTier::Max && first.change.at > first.change.period.start);+ let mut usd = 0.0;+ let mut chargeable_cents = 0;+ let mut next = 0;+ for segment in segments {+ while let Some(record) = changes.get(next).filter(|r| r.change.at <= segment.start) {+ if record.change.at > record.change.period.start {+ highest = highest.max(rank(record.change.from));+ }+ if record.change.resets_usage() && rank(record.change.to) > highest {+ usd = 0.0;+ }+ highest = highest.max(rank(record.change.to));+ allowance = record.new_included_cents;+ legacy |= record.change.to == PlanTier::Max;+ next += 1;+ }+ let before = super::cost_cents(usd);+ usd += segment.usd;+ if legacy && let Some(included) = allowance {+ chargeable_cents +=+ (super::cost_cents(usd) - included).max(0) - (before - included).max(0);+ }+ }+ PlanUsage {+ used_cents: super::cost_cents(usd),+ chargeable_cents,+ }+}diff --git a/crates/ai_billing/src/domain/plan_change/test.rs b/crates/ai_billing/src/domain/plan_change/test.rsnew file mode 100644index 0000000000..476aab9e74--- /dev/null+++ b/crates/ai_billing/src/domain/plan_change/test.rs@@ -0,0 +1,143 @@+use super::*;+use chrono::Duration;++fn record(from: PlanTier, to: PlanTier, seconds: i64) -> RecordedPlanChange {+ let start = DateTime::from_timestamp(1_800_000_000, 0).unwrap();+ let allowance = |plan| match plan {+ PlanTier::Free => None,+ PlanTier::Premium => Some(2_000),+ PlanTier::Max => Some(10_000),+ };+ RecordedPlanChange {+ change: PlanChange {+ from,+ to,+ at: start + Duration::seconds(seconds),+ period: BillingPeriod {+ start,+ end: start + Duration::days(30),+ },+ },+ previous_included_cents: allowance(from),+ new_included_cents: allowance(to),+ }+}+fn segment(seconds: i64, usd: f64) -> PlanUsageSegment {+ PlanUsageSegment {+ start: record(PlanTier::Free, PlanTier::Premium, seconds).change.at,+ usd,+ }+}+#[test]+fn free_pro_max_each_new_highest_resets_and_preserves_prior_overage() {+ let changes = [+ record(PlanTier::Free, PlanTier::Premium, 10),+ record(PlanTier::Premium, PlanTier::Max, 20),+ ];+ let costs = [segment(0, 80.0), segment(10, 22.0), segment(20, 105.0)];+ assert_eq!(+ meter_plan_usage(&changes, &costs, false),+ PlanUsage {+ used_cents: 10_500,+ chargeable_cents: 700+ }+ );+ assert_eq!(+ meter_plan_usage(&changes, &costs, true),+ PlanUsage {+ used_cents: 10_500,+ chargeable_cents: 500+ }+ );+}+#[test]+fn max_pro_max_cannot_replenish_or_reclassify_prior_max_costs() {+ let changes = [+ record(PlanTier::Max, PlanTier::Premium, 10),+ record(PlanTier::Premium, PlanTier::Max, 20),+ ];+ assert_eq!(+ meter_plan_usage(+ &changes,+ &[segment(0, 80.0), segment(10, 0.0), segment(20, 0.0)],+ false+ ),+ PlanUsage {+ used_cents: 8_000,+ chargeable_cents: 0+ }+ );+ assert_eq!(+ meter_plan_usage(+ &changes,+ &[segment(0, 80.0), segment(10, 1.0), segment(20, 25.0)],+ false+ ),+ PlanUsage {+ used_cents: 10_600,+ chargeable_cents: 700+ }+ );+}+#[test]+fn max_free_max_retains_consumption_without_charging_free_costs() {+ let changes = [+ record(PlanTier::Max, PlanTier::Free, 10),+ record(PlanTier::Free, PlanTier::Max, 20),+ ];+ assert_eq!(+ meter_plan_usage(+ &changes,+ &[segment(0, 80.0), segment(10, 5.0), segment(20, 20.0)],+ false+ ),+ PlanUsage {+ used_cents: 10_500,+ chargeable_cents: 500+ }+ );+}+#[test]+fn previous_cycle_max_does_not_block_a_new_cycle_pro_max_upgrade() {+ let changes = [+ record(PlanTier::Max, PlanTier::Premium, 0),+ record(PlanTier::Premium, PlanTier::Max, 10),+ ];+ assert_eq!(+ meter_plan_usage(&changes, &[segment(0, 15.0), segment(10, 2.0)], false),+ PlanUsage {+ used_cents: 200,+ chargeable_cents: 0+ }+ );+}+#[test]+fn repeated_upgrade_fact_cannot_reset_new_usage() {+ let changes = [+ record(PlanTier::Premium, PlanTier::Max, 10),+ record(PlanTier::Premium, PlanTier::Max, 20),+ ];+ assert_eq!(+ meter_plan_usage(+ &changes,+ &[segment(0, 15.0), segment(10, 2.0), segment(20, 1.0)],+ false+ ),+ PlanUsage {+ used_cents: 300,+ chargeable_cents: 0+ }+ );+}++#[test]+fn renewal_downgrade_starts_fresh_public_pro_funding() {+ let changes = [record(PlanTier::Max, PlanTier::Premium, 0)];+ assert_eq!(+ meter_plan_usage(&changes, &[segment(0, 22.0)], true),+ PlanUsage {+ used_cents: 2_200,+ chargeable_cents: 0+ }+ );+}diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex 7dfada00d3..d03a7fad99 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -74,12 +74,14 @@ pub trait EntitlementSource: Send + Sync + 'static {/// Reads recorded, metered AI usage at provider cost.pub trait UsageReader: Send + Sync + 'static {- /// Usage in cost cents for each of `users` within `period`.+ /// Usage since the latest new-highest-plan baseline in cost cents for each seat.+ /// Historical plan changes supply an explicit cumulative liability for settlement.////// Only rows with the persisted `count_usage = TRUE` decision consume a user's/// allowance, credits, or overage. Historical and uncounted rows remain available/// for cost tracking. The period is inclusive at the start and exclusive at the end;- /// users with no counted rows are omitted, and an empty user list returns no rows.+ /// users with no counted rows or prior overage are omitted, and an empty list+ /// returns no rows. Upgrade history does not delete or reclassify recorded costs.fn usage_cost_cents_by_user(&self,users: &[MacroUserIdStr<'static>],@@ -141,12 +143,28 @@ pub trait BillingRepo: Send + Sync + 'static {seats: Vec<SeatAllowance>,) -> impl Future<Output = Result<Vec<SeatAllowance>>> + Send;+ /// Record an immutable transition, including downgrades, for chronological+ /// metering. Replays preserve the original facts and subsequent usage.+ fn record_plan_change(+ &self,+ user: &MacroUserIdStr<'_>,+ record: super::plan_change::RecordedPlanChange,+ ) -> impl Future<Output = Result<()>> + Send;+/// The payer's settings (defaults when no row exists).fn settings(&self,payer: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<BillingSettings>> + Send;+ /// Reload commitments charged against a UTC calendar-month cap. Includes+ /// pending reloads and failed invoices that may still collect; excludes manual purchases.+ fn credit_reload_committed_cents(+ &self,+ payer: &MacroUserIdStr<'_>,+ month: BillingPeriod,+ ) -> impl Future<Output = Result<i64>> + Send;+/// Set overage on/off and the cap. Clears any suspension.fn update_overage(&self,@@ -523,6 +541,15 @@ impl SettlementTrigger for NoOpSettlementTrigger {/// (`ai_usage::domain::ports::InvocationFunding`) backed by the reservation and/// allocation rules in [`super::policy`]. It must never also enter legacy settlement.pub trait BillingService: Send + Sync + 'static {+ /// Apply a verified transition. Only a new highest plan in the billing+ /// period resets usage;+ /// recorded costs, prepaid credits and existing charges remain intact.+ fn change_plan(+ &self,+ user: &MacroUserIdStr<'_>,+ change: super::plan_change::PlanChange,+ ) -> impl Future<Output = Result<()>> + Send;+/// May `user` start another AI request?////// Admission is a read of the position at this instant; usage isdiff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 293040b4ff..fd42b278bc 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -6,10 +6,11 @@ mod test;use super::ledger::{SettlementPolicy, build_snapshot, decide};use super::models::{- AiUsageBilling, AllowanceDecision, AllowanceStore, AutoReloadThresholds, BillingError,- BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS, CreditReloadStatus, Entitlement,- OVERAGE_CHARGE_THRESHOLD_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger,- Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,+ AiUsageBilling, AllowanceDecision, AllowanceStore, AutoReloadMonthlyBudget,+ AutoReloadThresholds, BillingError, BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS,+ CreditReloadStatus, Entitlement, MIN_STRIPE_CHARGE_CENTS, OVERAGE_CHARGE_THRESHOLD_CENTS,+ OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, Result, SeatAllowance,+ SeatUsage, SubscriptionScope, UsageSnapshot,};use super::period::{PeriodSync, SubscriptionPeriod};use super::ports::{@@ -138,7 +139,13 @@ fn usage_for(user: &MacroUserIdStr<'_>, usage: &[SeatUsage]) -> i64 {fn chargeable_cost_cents(seats: &[SeatAllowance], usage: &[SeatUsage]) -> i64 {seats.iter()- .map(|seat| (usage_for(&seat.user, usage) - seat.included_cents).max(0))+ .map(|seat| {+ usage+ .iter()+ .find(|usage| usage.user == seat.user)+ .and_then(|usage| usage.chargeable_cost_cents)+ .unwrap_or_else(|| (usage_for(&seat.user, usage) - seat.included_cents).max(0))+ }).sum()}@@ -720,6 +727,40 @@ where{type Err = BillingError;+ async fn change_plan(+ &self,+ member: &MacroUserIdStr<'_>,+ change: teams::domain::open_seat_release::SeatPlanChange,+ ) -> Result<()> {+ let from = change+ .from+ .map(Into::into)+ .unwrap_or(super::models::PlanTier::Free);+ let to = change.to.into();+ if from == to {+ return Ok(());+ }+ let period = if let Some((start, end)) = change.period {+ BillingPeriod { start, end }+ } else {+ let entitlement = self.entitlements.entitlement(member).await?;+ let settings = self.repo.settings(&entitlement.payer).await?;+ self.usage_period(&entitlement, settings.period_anchor, change.at)+ .await+ };+ BillingService::change_plan(+ self,+ member,+ super::plan_change::PlanChange {+ from,+ to,+ at: change.at,+ period,+ },+ )+ .await+ }+#[tracing::instrument(skip(self), err)]async fn release(&self, team_id: Uuid, member: &MacroUserIdStr<'_>) -> Result<()> {self.release_at(team_id, member, Utc::now()).await@@ -733,6 +774,33 @@ whereR: BillingRepo,P: PaymentGateway,{+ #[tracing::instrument(skip(self), err)]+ async fn change_plan(+ &self,+ user: &MacroUserIdStr<'_>,+ change: super::plan_change::PlanChange,+ ) -> Result<()> {+ if change.is_valid() {+ self.repo+ .record_plan_change(+ user,+ super::plan_change::RecordedPlanChange {+ change,+ previous_included_cents: change+ .from+ .is_paid()+ .then(|| change.from.included_ai_cents_per_seat(self.pricing)),+ new_included_cents: change+ .to+ .is_paid()+ .then(|| change.to.included_ai_cents_per_seat(self.pricing)),+ },+ )+ .await?;+ }+ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {if !self.enforcement.is_enabled() {@@ -748,8 +816,24 @@ where#[tracing::instrument(skip(self), err)]async fn snapshot(&self, user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {- let position = self.position(user, Utc::now()).await?;+ let now = Utc::now();+ let position = self.position(user, now).await?;let mut snapshot = self.snapshot_at(user, &position).await?;+ // Summary-only read; allowance enforcement does not need monthly reload facts.+ if position.entitlement.is_metered()+ && let Some(limit) = position.settings.auto_reload.monthly_limit_cents+ {+ let month = BillingPeriod::calendar_month(now);+ let committed_cents = self+ .repo+ .credit_reload_committed_cents(&position.entitlement.payer, month)+ .await?;+ snapshot.auto_reload.monthly_budget = Some(AutoReloadMonthlyBudget {+ committed_cents,+ resets_at: month.end,+ limit_reached: limit.saturating_sub(committed_cents) < MIN_STRIPE_CHARGE_CENTS,+ });+ }// Keep the summary consistent with the configured allowance gate.if !self.enforcement.is_enabled() {snapshot.blocked_reason = None;diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 7ed0b7c25e..6113dcff2b 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -139,6 +139,7 @@ impl UsageReader for FakeUsage {user: MacroUserIdStr::try_from(user).map_err(|error| BillingError::Storage(error.into()))?,used_cents,+ chargeable_cost_cents: None,})}).collect()@@ -175,14 +176,28 @@ struct RepoState {charges: Vec<FakeCharge>,suspended: bool,reloads: Vec<FakeReload>,+ reload_budget_payers: Vec<String>,auto_reload_suspended: bool,allowances: HashMap<DateTime<Utc>, PeriodAllowance>,+ usage_resets: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,releases: Vec<(String, DateTime<Utc>, String)>,activated_seats: Vec<String>,period_writes: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,}impl RepoState {+ fn reload_committed_cents(&self, month: BillingPeriod) -> i64 {+ self.reloads+ .iter()+ .filter(|reload| {+ (reload.status != CreditReloadStatus::Failed || reload.invoice.is_some())+ && month.start <= reload.created_at+ && reload.created_at < month.end+ })+ .map(|reload| reload.amount_cents)+ .sum()+ }+fn ledger(&self, period_start: DateTime<Utc>) -> PeriodLedger {PeriodLedger {credits_consumed_cents: self.consumed.get(&period_start).copied().unwrap_or(0),@@ -245,6 +260,16 @@ impl FakeRepo {}impl BillingRepo for FakeRepo {+ async fn credit_reload_committed_cents(+ &self,+ payer: &MacroUserIdStr<'_>,+ month: BillingPeriod,+ ) -> Result<i64> {+ let mut state = self.state.lock().unwrap();+ state.reload_budget_payers.push(payer.as_ref().to_string());+ Ok(state.reload_committed_cents(month))+ }+async fn legacy_seats(&self,_payer: &MacroUserIdStr<'_>,@@ -261,6 +286,19 @@ impl BillingRepo for FakeRepo {Ok(seats)}+ async fn record_plan_change(+ &self,+ user: &MacroUserIdStr<'_>,+ record: crate::domain::plan_change::RecordedPlanChange,+ ) -> Result<()> {+ self.state.lock().unwrap().usage_resets.push((+ user.to_string(),+ record.change.period.start,+ record.change.at,+ ));+ Ok(())+ }+async fn settings(&self, _payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {let s = self.state.lock().unwrap();let mut settings = s.settings.clone();@@ -569,16 +607,7 @@ impl BillingRepo for FakeRepo {let ledger = s.ledger(period_start);let covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;let month = BillingPeriod::calendar_month(now);- let spent_this_month_cents = s- .reloads- .iter()- .filter(|r| {- r.status != CreditReloadStatus::Failed- && month.start <= r.created_at- && r.created_at < month.end- })- .map(|r| r.amount_cents)- .sum();+ let spent_this_month_cents = s.reload_committed_cents(month);let amount_cents = plan_reload(ReloadState {credit_balance_cents: s.balance,@@ -951,6 +980,7 @@ async fn policy_activation_during_analytics_read_cannot_double_bill() {.map(|user| SeatUsage {user: user.clone(),used_cents: 100_000,+ chargeable_cost_cents: None,}).collect())}@@ -1362,6 +1392,83 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {assert_eq!(snap.included_cents, 2_000);}+#[tokio::test]+async fn summary_reports_calendar_month_commitments_and_minimum_reload_cap_status() {+ let (service, repo, _, _) = premium_service(0);+ let payer = user("[email protected]");+ let now = Utc::now();+ let month = BillingPeriod::calendar_month(now);+ {+ let mut state = repo.state.lock().unwrap();+ state.settings.auto_reload.monthly_limit_cents = Some(5_000);+ for (amount_cents, status, invoice, created_at) in [+ (2_500, CreditReloadStatus::Paid, Some("in_paid"), now),+ (2_000, CreditReloadStatus::Pending, None, now),+ (450, CreditReloadStatus::Failed, Some("in_retry"), now),+ (10_000, CreditReloadStatus::Failed, None, now),+ (+ 10_000,+ CreditReloadStatus::Paid,+ Some("in_old"),+ month.start - chrono::Duration::seconds(1),+ ),+ (10_000, CreditReloadStatus::Paid, Some("in_next"), month.end),+ ] {+ state.reloads.push(FakeReload {+ id: macro_uuid::generate_uuid_v7(),+ amount_cents,+ status,+ invoice: invoice.map(str::to_string),+ created_at,+ });+ }+ }+ // Manual credit balance does not consume the reload cap.+ repo.set_balance(50_000);+ let snapshot = service.snapshot(&payer).await.unwrap();+ let budget = snapshot.auto_reload.monthly_budget.unwrap();+ assert_eq!(budget.committed_cents, 4_950);+ assert_eq!(budget.resets_at, month.end);+ assert!(+ !budget.limit_reached,+ "exactly the minimum reload still fits"+ );+ repo.state.lock().unwrap().reloads.push(FakeReload {+ id: macro_uuid::generate_uuid_v7(),+ amount_cents: 1,+ status: CreditReloadStatus::Paid,+ invoice: Some("in_last_cent".to_string()),+ created_at: now,+ });+ let budget = service+ .snapshot(&payer)+ .await+ .unwrap()+ .auto_reload+ .monthly_budget+ .unwrap();+ assert_eq!(budget.committed_cents, 4_951);+ assert!(budget.limit_reached);+ let reads = repo.state.lock().unwrap().reload_budget_payers.len();+ service.check_allowance(&payer).await.unwrap();+ assert_eq!(repo.state.lock().unwrap().reload_budget_payers.len(), reads);+ repo.state+ .lock()+ .unwrap()+ .settings+ .auto_reload+ .monthly_limit_cents = None;+ assert!(+ service+ .snapshot(&payer)+ .await+ .unwrap()+ .auto_reload+ .monthly_budget+ .is_none()+ );+}+#[tokio::test]async fn team_seats_keep_allowances_separate_and_share_credits() {let owner = user("[email protected]");@@ -1382,6 +1489,12 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {let usage = FakeUsage::default();usage.add(&member, Utc::now(), 3_000);let repo = FakeRepo::default();+ repo.state+ .lock()+ .unwrap()+ .settings+ .auto_reload+ .monthly_limit_cents = Some(5_000);let service = BillingServiceImpl::new(entitlements,usage,@@ -1398,6 +1511,26 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {let member_snapshot = service.snapshot(&member).await.unwrap();assert_eq!(member_snapshot.used_cents, 3_000);assert_eq!(member_snapshot.included_cents, 2_000);+ assert_eq!(+ owner_snapshot+ .auto_reload+ .monthly_budget+ .unwrap()+ .committed_cents,+ 0+ );+ assert_eq!(+ member_snapshot+ .auto_reload+ .monthly_budget+ .unwrap()+ .committed_cents,+ 0+ );+ assert_eq!(+ repo.state.lock().unwrap().reload_budget_payers,+ vec![owner.as_ref().to_string(); 2]+ );assert_eq!(member_snapshot.blocked_reason,Some(DenyReason::AllowanceExhausted)@@ -3176,3 +3309,194 @@ async fn release_rolls_an_ended_anchor_when_the_entitlement_read_fails() {)]);}++#[tokio::test]+async fn only_valid_transitions_are_recorded_in_the_original_period() {+ use crate::domain::plan_change::PlanChange;+ let (svc, repo, _, _, _, payer, _, current) = anchored_premium(1_500);+ let at = current.start + chrono::Duration::seconds(1);+ for (from, to) in [+ (PlanTier::Free, PlanTier::Free),+ (PlanTier::Premium, PlanTier::Free),+ (PlanTier::Max, PlanTier::Free),+ (PlanTier::Max, PlanTier::Premium),+ (PlanTier::Max, PlanTier::Max),+ (PlanTier::Premium, PlanTier::Premium),+ ] {+ BillingService::change_plan(+ &svc,+ &payer,+ PlanChange {+ from,+ to,+ at,+ period: current,+ },+ )+ .await+ .unwrap();+ }+ for at in [current.start - chrono::Duration::seconds(1), current.end] {+ BillingService::change_plan(+ &svc,+ &payer,+ PlanChange {+ from: PlanTier::Premium,+ to: PlanTier::Max,+ at,+ period: current,+ },+ )+ .await+ .unwrap();+ }+ assert_eq!(repo.state.lock().unwrap().usage_resets.len(), 3);+ repo.state.lock().unwrap().usage_resets.clear();+ for (from, to) in [+ (PlanTier::Free, PlanTier::Premium),+ (PlanTier::Free, PlanTier::Max),+ (PlanTier::Premium, PlanTier::Max),+ ] {+ BillingService::change_plan(+ &svc,+ &payer,+ PlanChange {+ from,+ to,+ at,+ period: current,+ },+ )+ .await+ .unwrap();+ }+ assert_eq!(+ repo.state.lock().unwrap().usage_resets,+ vec![(payer.to_string(), current.start, at); 3]+ );+}++#[test]+fn prior_overage_remains_covered_separately_from_the_reset_max_allowance() {+ let user = user("[email protected]");+ let seats = [SeatAllowance {+ user: user.clone(),+ included_cents: 10_000,+ }];+ let usage = [SeatUsage {+ user,+ used_cents: 10_500,+ chargeable_cost_cents: Some(700),+ }];+ // An existing 200-cent settlement covers the old Pro overage; the next+ // settlement must still book the 500 cents newly incurred on Max.+ assert_eq!(chargeable_cost_cents(&seats, &usage), 700);+}++#[sqlx::test(migrator = "macro_db_migrator::MACRO_DB_MIGRATIONS")]+async fn all_plan_upgrades_reset_the_real_snapshot_and_gate(pool: sqlx::PgPool) {+ for (from, to) in [+ (PlanTier::Free, PlanTier::Premium),+ (PlanTier::Free, PlanTier::Max),+ (PlanTier::Premium, PlanTier::Max),+ ] {+ assert_upgrade_resets_snapshot_and_gate(pool.clone(), from, to).await;+ }+}++async fn assert_upgrade_resets_snapshot_and_gate(pool: sqlx::PgPool, from: PlanTier, to: PlanTier) {+ use crate::domain::plan_change::PlanChange;+ use crate::outbound::{PgBillingRepo, PgUsageReader};+ use ai_usage::outbound::PgUsageRepo;+ use ai_usage::{+ AiFeature, CompletionUsage, ModelPricing, Price, Usage, UsageAmount, UsageRepo,+ };+ let payer = user(&format!("upgrade-{from:?}-{to:?}@x.com"));+ let ents = FakeEntitlements::default().with(Entitlement::personal(payer.clone(), from));+ let pricing = AiPricing::testing();+ let svc = BillingServiceImpl::new(+ ents.clone(),+ PgUsageReader::new(pool.clone()),+ PgBillingRepo::new(pool.clone(), pricing),+ FakePayments::default(),+ pricing,+ )+ .with_enforcement(AiUsageEnforcement::Enabled);+ // PostgreSQL stores timestamps at microsecond precision.+ let now = DateTime::from_timestamp_micros(Utc::now().timestamp_micros()).unwrap();+ let period = BillingPeriod {+ start: now - chrono::Duration::days(1),+ end: now + chrono::Duration::days(29),+ };+ svc.sync_period(&payer, period.start, period.end, None)+ .await+ .unwrap();+ let usage_repo = PgUsageRepo::new(pool.clone());+ let mut usage = CompletionUsage {+ feature: AiFeature::Chat,+ user: payer.clone(),+ entity: None,+ cost: Usage {+ amount: UsageAmount::Tokens {+ input: 1_000_000,+ output: 0,+ cache_read: 0,+ cache_write: 0,+ },+ model: "upgrade-test".into(),+ price: Some(Price {+ pricing: ModelPricing::Tokens {+ input: 20.0,+ output: 0.0,+ cache_read: None,+ cache_write: None,+ },+ total: 20.0,+ }),+ created_at: now - chrono::Duration::seconds(1),+ },+ };+ usage_repo.insert_usage(&usage, true).await.unwrap();+ // Usage writes use the database clock, so place this fixture explicitly.+ sqlx::query!("UPDATE ai_usage SET created_at = $2 WHERE id = (SELECT id FROM ai_usage WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1)", payer.as_ref(), usage.cost.created_at)+ .execute(&pool).await.unwrap();+ assert_eq!(svc.snapshot(&payer).await.unwrap().used_cents, 2_000);+ assert!(matches!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Deny(_)+ ));+ ents.set(Entitlement::personal(payer.clone(), to));+ let change = PlanChange {+ from,+ to,+ at: now,+ period,+ };+ BillingService::change_plan(&svc, &payer, change)+ .await+ .unwrap();+ let snapshot = svc.snapshot(&payer).await.unwrap();+ assert_eq!(snapshot.used_cents, 0);+ assert_eq!(+ snapshot.included_cents,+ to.included_ai_cents_per_seat(pricing)+ );+ assert_eq!(+ (snapshot.period_start, snapshot.period_end),+ (period.start, period.end)+ );+ assert!(matches!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Allow+ ));+ usage.cost.created_at = now;+ usage.cost.price.as_mut().unwrap().total = 2.0;+ usage_repo.insert_usage(&usage, true).await.unwrap();+ // Usage writes use the database clock, so place this fixture explicitly.+ sqlx::query!("UPDATE ai_usage SET created_at = $2 WHERE id = (SELECT id FROM ai_usage WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1)", payer.as_ref(), usage.cost.created_at)+ .execute(&pool).await.unwrap();+ BillingService::change_plan(&svc, &payer, change)+ .await+ .unwrap();+ assert_eq!(svc.snapshot(&payer).await.unwrap().used_cents, 200);+}diff --git a/crates/ai_billing/src/domain/sweep/test.rs b/crates/ai_billing/src/domain/sweep/test.rsindex 9f882fab0a..7228502cfe 100644--- a/crates/ai_billing/src/domain/sweep/test.rs+++ b/crates/ai_billing/src/domain/sweep/test.rs@@ -74,6 +74,14 @@ struct FakeBilling {}impl BillingService for FakeBilling {+ async fn change_plan(+ &self,+ _user: &MacroUserIdStr<'_>,+ _change: crate::domain::plan_change::PlanChange,+ ) -> Result<()> {+ unreachable!()+ }+async fn settle(&self, user: &MacroUserIdStr<'_>) -> Result<()> {self.settled.lock().unwrap().push(user.to_string());if self.fail_for.as_deref() == Some(user.as_ref()) {diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rsindex 84c0ac9c93..28f4581b47 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs@@ -54,6 +54,29 @@ fn invalid_payer(e: impl std::fmt::Display) -> BillingError {BillingError::Storage(anyhow::anyhow!("invalid payer id: {e}"))}+async fn reload_committed_cents(+ conn: &mut sqlx::PgConnection,+ payer: &str,+ month: BillingPeriod,+) -> Result<i64> {+ sqlx::query_scalar!(+ r#"+ SELECT COALESCE(SUM(amount_cents), 0)::bigint AS "spent!"+ FROM ai_credit_reload+ WHERE user_id = $1+ AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)+ AND created_at >= $2+ AND created_at < $3+ "#,+ payer,+ month.start,+ month.end,+ )+ .fetch_one(conn)+ .await+ .map_err(storage)+}+async fn book_credit_reload(conn: &mut sqlx::PgConnection,payer: &MacroUserIdStr<'_>,@@ -93,7 +116,14 @@ impl BillingRepo for PgBillingRepo {// must never route V1 analytics into a new owner's legacy settlement.let activated = sqlx::query_scalar!("SELECT user_id FROM ai_billing_usage_period WHERE user_id = ANY($1)- AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2",+ AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2+ AND NOT EXISTS (+ SELECT 1 FROM ai_billing_plan_change AS change+ WHERE change.user_id = ai_billing_usage_period.user_id+ AND change.period_start = ai_billing_usage_period.period_start+ AND change.changed_at < $3+ AND (change.new_plan = 'max' OR change.previous_plan = 'max' AND change.changed_at > change.period_start)+ )",&users,period.start,period.end,@@ -105,6 +135,35 @@ impl BillingRepo for PgBillingRepo {Ok(seats)}+ async fn record_plan_change(+ &self,+ user: &MacroUserIdStr<'_>,+ record: crate::domain::plan_change::RecordedPlanChange,+ ) -> Result<()> {+ let previous_plan = plan_name(record.change.from);+ let new_plan = plan_name(record.change.to);+ sqlx::query!(+ r#"+ INSERT INTO ai_billing_plan_change+ (user_id, period_start, changed_at, previous_plan, new_plan,+ previous_included_cost_cents, new_included_cost_cents)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (user_id, period_start, changed_at, previous_plan, new_plan) DO NOTHING+ "#,+ user.as_ref(),+ record.change.period.start,+ record.change.at,+ previous_plan,+ new_plan,+ record.previous_included_cents,+ record.new_included_cents,+ )+ .execute(&self.pool)+ .await+ .map_err(storage)?;+ Ok(())+ }+async fn settings(&self, payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {let row = sqlx::query!(r#"@@ -138,6 +197,15 @@ impl BillingRepo for PgBillingRepo {.unwrap_or_default())}+ async fn credit_reload_committed_cents(+ &self,+ payer: &MacroUserIdStr<'_>,+ month: BillingPeriod,+ ) -> Result<i64> {+ let mut conn = self.pool.acquire().await.map_err(storage)?;+ reload_committed_cents(&mut conn, payer.as_ref(), month).await+ }+async fn update_overage(&self,payer: &MacroUserIdStr<'_>,@@ -928,22 +996,7 @@ impl BillingRepo for PgBillingRepo {// A failed reload that reached Stripe may still be collected by its// retries, so it counts against the limit like a pending one.let month = BillingPeriod::calendar_month(now);- let spent_this_month_cents = sqlx::query_scalar!(- r#"- SELECT COALESCE(SUM(amount_cents), 0)::bigint AS "spent!"- FROM ai_credit_reload- WHERE user_id = $1- AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)- AND created_at >= $2- AND created_at < $3- "#,- payer,- month.start,- month.end,- )- .fetch_one(&mut *tx)- .await- .map_err(storage)?;+ let spent_this_month_cents = reload_committed_cents(&mut tx, payer, month).await?;let amount_cents = plan_reload(ReloadState {@@ -1164,3 +1217,11 @@ fn parse_seat_allowances(}).collect()}++fn plan_name(plan: crate::domain::PlanTier) -> &'static str {+ match plan {+ crate::domain::PlanTier::Free => "free",+ crate::domain::PlanTier::Premium => "premium",+ crate::domain::PlanTier::Max => "max",+ }+}diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rsindex 4dd6312c46..4b9ae73690 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs@@ -835,6 +835,13 @@ async fn reserve_credit_reload_honors_the_monthly_limit_including_pending_rows(p.unwrap().expect("reload reserved");assert_eq!(first.amount_cents, 10_000);+ let month = BillingPeriod::calendar_month(now);+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), month)+ .await+ .unwrap(),+ 10_000+ );// Pending rows count against the limit, so once Stripe resolves this one// only 2_000 of room is left.repo.finish_credit_reload(first.id, Some("in_1"), CreditReloadStatus::Paid)@@ -857,6 +864,18 @@ async fn reserve_credit_reload_honors_the_monthly_limit_including_pending_rows(p.is_none());assert_eq!(reload_rows(&pool).await, 2);+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), month)+ .await+ .unwrap(),+ 12_000+ );+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), BillingPeriod::calendar_month(month.end))+ .await+ .unwrap(),+ 0+ );// A failed reload does not count; a reload from last month does not either.sqlx::query!(@@ -876,6 +895,12 @@ async fn reserve_credit_reload_honors_the_monthly_limit_including_pending_rows(prepo.finish_credit_reload(third.id, None, CreditReloadStatus::Failed).await.unwrap();+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), month)+ .await+ .unwrap(),+ 10_000+ );// Suspension is what stops reloads after a failure, not the ledger.enable_auto_reload(&repo, &thresholds(Some(12_000))).await;let fourth = repo@@ -960,6 +985,12 @@ async fn reserve_credit_reload_retries_a_failed_reload_on_its_open_invoice(pool:.await.unwrap();repo.suspend_auto_reload(&payer()).await.unwrap();+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), BillingPeriod::calendar_month(now))+ .await+ .unwrap(),+ 10_000+ );assert!(repo.reserve_credit_reload(&payer(), period_start, 0, now).awaitdiff --git a/crates/ai_billing/src/outbound/pg_funding_repo.rs b/crates/ai_billing/src/outbound/pg_funding_repo.rsindex d849c12b47..699f877b0c 100644--- a/crates/ai_billing/src/outbound/pg_funding_repo.rs+++ b/crates/ai_billing/src/outbound/pg_funding_repo.rs@@ -112,7 +112,17 @@ async fn read_period() -> FinancialResult<Option<FundingPeriod>> {let row = sqlx::query!("SELECT user_id, payer_id, subscription_id, period_start, period_end, policy FROM ai_billing_usage_period- WHERE user_id = $1 AND period_start <= $2 AND period_end > $2",+ WHERE user_id = $1 AND period_start <= $2 AND period_end > $2+ AND NOT EXISTS (+ SELECT 1 FROM ai_billing_plan_change AS reset+ WHERE reset.user_id = ai_billing_usage_period.user_id+ AND reset.period_start = ai_billing_usage_period.period_start+ AND (reset.new_plan = 'max' AND reset.changed_at <= $2+ OR reset.previous_plan = 'max' AND reset.changed_at > reset.period_start+ AND NOT EXISTS (SELECT 1 FROM ai_billing_plan_change AS earlier+ WHERE earlier.user_id = reset.user_id AND earlier.period_start = reset.period_start+ AND earlier.changed_at < reset.changed_at))+ )",seat, at,).fetch_optional(conn).await?;row.map(|r| {diff --git a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs b/crates/ai_billing/src/outbound/pg_funding_repo/test.rsindex 776c508498..c128b14b85 100644--- a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs@@ -1084,3 +1084,133 @@ async fn domain_facade_rejects_exemption_and_exclusion_on_billable_funding(pool:};assert!(service.finalize(record).await.is_err());}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn max_upgrade_stops_using_the_old_pro_funding_policy_but_preserves_history(pool: PgPool) {+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());+ let billing = PgBillingRepo::new(pool, AiPricing::testing());+ let (rollout, baseline) = rollout_observation();+ repo.observe(&rollout, baseline.clone(), true)+ .await+ .unwrap();+ let renewal = next_renewal(baseline);+ repo.observe(&rollout, renewal.clone(), true).await.unwrap();+ let period = renewal.subscription.period;+ let at = period.start + Duration::days(1);+ billing+ .reset_usage(+ &user("seat"),+ period.start,+ at,+ Some(2_000),+ crate::domain::PlanTier::Max,+ )+ .await+ .unwrap();+ assert!(repo.period(user("seat"), at).await.unwrap().is_none());+ assert_eq!(+ repo.period(user("seat"), at - Duration::seconds(1))+ .await+ .unwrap()+ .unwrap()+ .policy,+ UsagePolicy::PublicAllowanceV1+ );+ let seats = vec![SeatAllowance {+ user: user("seat"),+ included_cents: 10_000,+ }];+ assert_eq!(+ billing+ .legacy_seats(&user("payer"), period, seats.clone())+ .await+ .unwrap(),+ seats+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn free_to_pro_upgrade_preserves_the_new_public_funding_policy(pool: PgPool) {+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());+ let billing = PgBillingRepo::new(pool, AiPricing::testing());+ let (rollout, baseline) = rollout_observation();+ repo.observe(&rollout, baseline.clone(), true)+ .await+ .unwrap();+ let renewal = next_renewal(baseline);+ repo.observe(&rollout, renewal.clone(), true).await.unwrap();+ let period = renewal.subscription.period;+ let at = period.start + Duration::days(1);+ billing+ .reset_usage(+ &user("seat"),+ period.start,+ at,+ None,+ crate::domain::PlanTier::Premium,+ )+ .await+ .unwrap();+ assert_eq!(+ repo.period(user("seat"), at).await.unwrap().unwrap().policy,+ UsagePolicy::PublicAllowanceV1+ );+ assert!(+ billing+ .legacy_seats(+ &user("payer"),+ period,+ vec![SeatAllowance {+ user: user("seat"),+ included_cents: 2_000,+ }]+ )+ .await+ .unwrap()+ .is_empty()+ );+}++trait UpgradeFixture {+ async fn reset_usage(+ &self,+ user: &MacroUserIdStr<'_>,+ start: chrono::DateTime<Utc>,+ at: chrono::DateTime<Utc>,+ previous: Option<i64>,+ to: crate::domain::PlanTier,+ ) -> crate::domain::Result<()>;+}+impl UpgradeFixture for crate::outbound::PgBillingRepo {+ async fn reset_usage(+ &self,+ user: &MacroUserIdStr<'_>,+ start: chrono::DateTime<Utc>,+ at: chrono::DateTime<Utc>,+ previous: Option<i64>,+ to: crate::domain::PlanTier,+ ) -> crate::domain::Result<()> {+ use crate::domain::{BillingRepo, PlanTier};+ self.record_plan_change(+ user,+ crate::domain::plan_change::RecordedPlanChange {+ change: crate::domain::plan_change::PlanChange {+ from: if previous.is_some() {+ PlanTier::Premium+ } else {+ PlanTier::Free+ },+ to,+ at,+ period: crate::domain::BillingPeriod {+ start,+ end: start + chrono::Duration::days(30),+ },+ },+ previous_included_cents: previous,+ new_included_cents: Some(if to == PlanTier::Max { 10_000 } else { 2_000 }),+ },+ )+ .await+ }+}diff --git a/crates/ai_billing/src/outbound/pg_usage_reader.rs b/crates/ai_billing/src/outbound/pg_usage_reader.rsindex cddbbd9029..8fa39c7a8a 100644--- a/crates/ai_billing/src/outbound/pg_usage_reader.rs+++ b/crates/ai_billing/src/outbound/pg_usage_reader.rs@@ -3,9 +3,13 @@#[cfg(test)]mod test;-use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, cost_cents};+use crate::domain::plan_change::{+ PlanChange, PlanUsageSegment, RecordedPlanChange, meter_plan_usage,+};+use crate::domain::{BillingError, BillingPeriod, PlanTier, Result, SeatUsage, UsageReader};use macro_user_id::user_id::MacroUserIdStr;use sqlx::PgPool;+use std::collections::HashMap;/// Counted rows recorded before a model had pricing carry a NULL total. Price/// them at the Opus 5 rate rather than for free; `set_pricing` backfills them later.@@ -44,24 +48,10 @@ impl UsageReader for PgUsageReader {return Ok(Vec::new());}let ids: Vec<String> = users.iter().map(|u| u.as_ref().to_string()).collect();- let rows = sqlx::query!(- r#"- SELECT user_id, COALESCE(SUM(- COALESCE(- total::float8,- (input_tokens::float8 / 1000000.0) * $4- + (output_tokens::float8 / 1000000.0) * $5- + (cache_read_input_tokens::float8 / 1000000.0) * $6- + (cache_write_input_tokens::float8 / 1000000.0) * $7- )- ), 0)::float8 AS "usd!"- FROM ai_usage- WHERE user_id = ANY($1)- AND created_at >= $2- AND created_at < $3- AND count_usage = TRUE- GROUP BY user_id- "#,+ // One statement gives history and usage the same database snapshot,+ // even when a webhook records another transition during this read.+ let rows = sqlx::query_file!(+ "src/outbound/pg_usage_reader/usage.sql",&ids,period.start,period.end,@@ -73,15 +63,72 @@ impl UsageReader for PgUsageReader {.fetch_all(&self.pool).await.map_err(|e| BillingError::Storage(e.into()))?;- rows.into_iter()- .map(|row| {- let user = MacroUserIdStr::try_from(row.user_id)- .map_err(|error| BillingError::Storage(error.into()))?;- Ok(SeatUsage {- user,- used_cents: cost_cents(row.usd),- })- })- .collect()+ let mut changes: HashMap<String, Vec<RecordedPlanChange>> = HashMap::new();+ let mut segments: HashMap<String, (bool, Vec<PlanUsageSegment>)> = HashMap::new();+ for row in rows {+ match (+ row.is_plan_change,+ row.previous_plan,+ row.new_plan,+ row.usd,+ row.public_funding,+ ) {+ (true, Some(from), Some(to), None, None) => {+ changes+ .entry(row.user_id)+ .or_default()+ .push(RecordedPlanChange {+ change: PlanChange {+ from: parse_plan(&from)?,+ to: parse_plan(&to)?,+ at: row.start,+ period,+ },+ previous_included_cents: row.previous_included_cost_cents,+ new_included_cents: row.new_included_cost_cents,+ });+ }+ (false, None, None, Some(usd), Some(public)) => {+ segments+ .entry(row.user_id)+ .or_insert_with(|| (public, Vec::new()))+ .1+ .push(PlanUsageSegment {+ start: row.start,+ usd,+ });+ }+ _ => {+ return Err(BillingError::Storage(anyhow::anyhow!(+ "invalid plan usage row"+ )));+ }+ }+ }+ let mut result = Vec::new();+ for (id, (public, segments)) in segments {+ let history = changes.get(&id).map(Vec::as_slice).unwrap_or_default();+ let usage = meter_plan_usage(history, &segments, public);+ if usage.used_cents == 0 && usage.chargeable_cents == 0 {+ continue;+ }+ result.push(SeatUsage {+ user: MacroUserIdStr::try_from(id).map_err(|e| BillingError::Storage(e.into()))?,+ used_cents: usage.used_cents,+ chargeable_cost_cents: (!history.is_empty()).then_some(usage.chargeable_cents),+ });+ }+ Ok(result)+ }+}++fn parse_plan(plan: &str) -> Result<PlanTier> {+ match plan {+ "free" => Ok(PlanTier::Free),+ "premium" => Ok(PlanTier::Premium),+ "max" => Ok(PlanTier::Max),+ _ => Err(BillingError::Storage(anyhow::anyhow!(+ "invalid recorded plan"+ ))),}}diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs b/crates/ai_billing/src/outbound/pg_usage_reader/test.rsindex 202ba64d5f..a763b83e7e 100644--- a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs+++ b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs@@ -112,11 +112,13 @@ async fn aggregates_only_persisted_counted_rows_for_requested_seats(pool: PgPoolvec![SeatUsage {user: first.clone(),- used_cents: 400+ used_cents: 400,+ chargeable_cost_cents: None,},SeatUsage {user: second,- used_cents: 3_300+ used_cents: 3_300,+ chargeable_cost_cents: None,},]);@@ -134,7 +136,8 @@ async fn aggregates_only_persisted_counted_rows_for_requested_seats(pool: PgPool.unwrap(),vec![SeatUsage {user: first,- used_cents: 400+ used_cents: 400,+ chargeable_cost_cents: None,}]);}@@ -173,7 +176,8 @@ async fn billing_period_includes_start_and_excludes_end(pool: PgPool) {usage,vec![SeatUsage {user,- used_cents: 200+ used_cents: 200,+ chargeable_cost_cents: None,}]);}@@ -237,6 +241,7 @@ async fn free_features_are_recorded_but_only_chat_and_editing_are_metered(pool:vec![SeatUsage {user,used_cents: 600,+ chargeable_cost_cents: None,}]);}@@ -284,6 +289,7 @@ async fn unpriced_free_features_are_excluded_from_fallback_billing(pool: PgPool)vec![SeatUsage {user,used_cents: 1_000,+ chargeable_cost_cents: None,}]);}@@ -334,6 +340,7 @@ async fn priced_cache_tokens_count_through_the_stored_total(pool: PgPool) {vec![SeatUsage {user,used_cents: 1_175,+ chargeable_cost_cents: None,}]);}@@ -375,6 +382,429 @@ async fn unpriced_cache_tokens_fall_back_to_the_opus_5_cache_rates(pool: PgPool)vec![SeatUsage {user,used_cents: 1_175,+ chargeable_cost_cents: None,}]);}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn upgrade_resets_only_the_seat_and_replays_preserve_new_usage(pool: PgPool) {+ use crate::domain::AiPricing;+ use crate::outbound::PgBillingRepo;+ let first = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let second = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = Utc::now();+ for user in [&first, &second] {+ let mut usage = completion(user.clone(), AiFeature::Chat, 15.0);+ usage.cost.created_at = at - Duration::seconds(1);+ insert_upgrade_usage(&pool, &usage).await;+ }+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ billing+ .reset_usage(+ &first,+ period.start,+ at,+ Some(2_000),+ crate::domain::PlanTier::Max,+ )+ .await+ .unwrap();+ let reader = PgUsageReader::new(pool.clone());+ assert!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&first), period)+ .await+ .unwrap()+ .is_empty()+ );+ assert_eq!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&second), period)+ .await+ .unwrap()[0]+ .used_cents,+ 1_500+ );+ let mut new_usage = completion(first.clone(), AiFeature::Chat, 2.0);+ new_usage.cost.created_at = at; // Reset includes the boundary instant.+ insert_upgrade_usage(&pool, &new_usage).await;+ for _ in 0..2 {+ billing+ .reset_usage(+ &first,+ period.start,+ at,+ Some(2_000),+ crate::domain::PlanTier::Max,+ )+ .await+ .unwrap();+ assert_eq!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&first), period)+ .await+ .unwrap()[0]+ .used_cents,+ 200+ );+ }+ // Audit history and stored counting decisions are untouched.+ assert_eq!(+ PgUsageRepo::new(pool.clone())+ .query_usage(&UsageApiParams {+ include_users: vec![first.clone()],+ ..Default::default()+ })+ .await+ .unwrap()+ .len(),+ 2+ );+ let next = BillingPeriod {+ start: period.end,+ end: period.end + Duration::days(30),+ };+ new_usage.cost.created_at = next.start;+ insert_upgrade_usage(&pool, &new_usage).await;+ assert_eq!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&first), next)+ .await+ .unwrap()[0]+ .used_cents,+ 200+ );+ // A replay with a newer timestamp cannot replenish an already held Max plan.+ billing+ .reset_usage(+ &first,+ period.start,+ at + Duration::seconds(1),+ Some(2_000),+ crate::domain::PlanTier::Max,+ )+ .await+ .unwrap();+ assert_eq!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&first), period)+ .await+ .unwrap()+ .first()+ .unwrap()+ .used_cents,+ 200+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn reset_preserves_prior_overage_without_reusing_spent_credits(pool: PgPool) {+ use crate::domain::AiPricing;+ use crate::outbound::PgBillingRepo;+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = Utc::now();+ let mut usage = completion(user.clone(), AiFeature::Chat, 22.0);+ usage.cost.created_at = at - Duration::seconds(1);+ insert_upgrade_usage(&pool, &usage).await;+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ billing+ .reset_usage(+ &user,+ period.start,+ at,+ Some(2_000),+ crate::domain::PlanTier::Max,+ )+ .await+ .unwrap();+ let reader = PgUsageReader::new(pool.clone());+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 0);+ assert_eq!(position[0].chargeable_cost_cents, Some(200));+ usage.cost.created_at = at;+ usage.cost.price.as_mut().unwrap().total = 105.0;+ insert_upgrade_usage(&pool, &usage).await;+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 10_500);+ assert_eq!(position[0].chargeable_cost_cents, Some(700));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn free_upgrade_discards_usage_without_creating_billable_overage(pool: PgPool) {+ use crate::domain::AiPricing;+ use crate::outbound::PgBillingRepo;+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = Utc::now();+ let mut usage = completion(user.clone(), AiFeature::Chat, 22.0);+ usage.cost.created_at = at - Duration::seconds(1);+ insert_upgrade_usage(&pool, &usage).await;+ PgBillingRepo::new(pool.clone(), AiPricing::testing())+ .reset_usage(+ &user,+ period.start,+ at,+ None,+ crate::domain::PlanTier::Premium,+ )+ .await+ .unwrap();+ let reader = PgUsageReader::new(pool.clone());+ assert!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap()+ .is_empty()+ );+ usage.cost.created_at = at;+ usage.cost.price.as_mut().unwrap().total = 2.0;+ insert_upgrade_usage(&pool, &usage).await;+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 200);+ assert_eq!(position[0].chargeable_cost_cents, Some(0));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn sequential_free_pro_max_upgrades_do_not_double_bill_public_funded_usage(pool: PgPool) {+ use crate::domain::{AiPricing, PlanTier};+ use crate::outbound::PgBillingRepo;+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = Utc::now();+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ sqlx::query!(+ "INSERT INTO ai_billing_account (user_id) VALUES ($1)",+ user.as_ref()+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!("INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy) VALUES ($1, $1, 'sub_test', $2, $3, 'public_allowance_v1')", user.as_ref(), period.start, period.end).execute(&pool).await.unwrap();+ billing+ .reset_usage(+ &user,+ period.start,+ at - Duration::seconds(2),+ None,+ PlanTier::Premium,+ )+ .await+ .unwrap();+ let mut usage = completion(user.clone(), AiFeature::Chat, 22.0);+ usage.cost.created_at = at - Duration::seconds(1);+ insert_upgrade_usage(&pool, &usage).await;+ billing+ .reset_usage(&user, period.start, at, Some(2_000), PlanTier::Max)+ .await+ .unwrap();+ let reader = PgUsageReader::new(pool.clone());+ assert!(+ reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap()+ .is_empty()+ );+ usage.cost.created_at = at;+ usage.cost.price.as_mut().unwrap().total = 2.0;+ insert_upgrade_usage(&pool, &usage).await;+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 200);+ assert_eq!(position[0].chargeable_cost_cents, Some(0));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn batched_usage_preserves_each_change_at_a_shared_boundary(pool: PgPool) {+ use crate::domain::{AiPricing, BillingRepo, PlanTier};+ use crate::outbound::PgBillingRepo;++ let upgraded = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let unchanged = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let empty = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let outside = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = period.start + Duration::seconds(10);+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());++ // Insert in reverse order: both transitions must survive the shared boundary,+ // and neither may turn the earlier Free usage into paid overage.+ for (from, to, old, new) in [+ (PlanTier::Premium, PlanTier::Max, Some(2_000), 10_000),+ (PlanTier::Free, PlanTier::Premium, None, 2_000),+ ] {+ billing+ .record_plan_change(+ &upgraded,+ RecordedPlanChange {+ change: PlanChange {+ from,+ to,+ at,+ period,+ },+ previous_included_cents: old,+ new_included_cents: Some(new),+ },+ )+ .await+ .unwrap();+ }+ billing+ .reset_usage(&empty, period.start, at, None, PlanTier::Premium)+ .await+ .unwrap();+ for (user, total, created_at) in [+ (&upgraded, 22.0, at - Duration::seconds(1)),+ (&upgraded, 25.0, at),+ (&unchanged, 1.0, at),+ (&outside, 100.0, at),+ ] {+ let mut usage = completion(user.clone(), AiFeature::Chat, total);+ usage.cost.created_at = created_at;+ insert_upgrade_usage(&pool, &usage).await;+ }++ let mut usage = PgUsageReader::new(pool)+ .usage_cost_cents_by_user(&[unchanged.clone(), empty, upgraded.clone()], period)+ .await+ .unwrap();+ usage.sort_by(|a, b| a.user.as_ref().cmp(b.user.as_ref()));+ assert_eq!(+ usage,+ vec![+ SeatUsage {+ user: unchanged,+ used_cents: 100,+ chargeable_cost_cents: None,+ },+ SeatUsage {+ user: upgraded,+ used_cents: 2_500,+ chargeable_cost_cents: Some(0),+ },+ ]+ );+}++// PgUsageRepo timestamps writes with the database clock. Explicitly locate this+// fixture's newest row on either side of the upgrade instead of relying on sleeps.+async fn insert_upgrade_usage(pool: &PgPool, usage: &CompletionUsage) {+ PgUsageRepo::new(pool.clone())+ .insert_usage(usage, true)+ .await+ .unwrap();+ sqlx::query!("UPDATE ai_usage SET created_at = $2 WHERE id = (SELECT id FROM ai_usage WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1)", usage.user.as_ref(), usage.cost.created_at).execute(pool).await.unwrap();+}++trait UpgradeFixture {+ async fn reset_usage(+ &self,+ user: &MacroUserIdStr<'_>,+ start: chrono::DateTime<Utc>,+ at: chrono::DateTime<Utc>,+ previous: Option<i64>,+ to: crate::domain::PlanTier,+ ) -> crate::domain::Result<()>;+}+impl UpgradeFixture for crate::outbound::PgBillingRepo {+ async fn reset_usage(+ &self,+ user: &MacroUserIdStr<'_>,+ start: chrono::DateTime<Utc>,+ at: chrono::DateTime<Utc>,+ previous: Option<i64>,+ to: crate::domain::PlanTier,+ ) -> crate::domain::Result<()> {+ use crate::domain::{BillingRepo, PlanTier};+ self.record_plan_change(+ user,+ crate::domain::plan_change::RecordedPlanChange {+ change: crate::domain::plan_change::PlanChange {+ from: if previous.is_some() {+ PlanTier::Premium+ } else {+ PlanTier::Free+ },+ to,+ at,+ period: crate::domain::BillingPeriod {+ start,+ end: start + chrono::Duration::days(30),+ },+ },+ previous_included_cents: previous,+ new_included_cents: Some(if to == PlanTier::Max { 10_000 } else { 2_000 }),+ },+ )+ .await+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delayed_plan_cycle_retains_max_consumption_without_creating_downgrade_debt(pool: PgPool) {+ use crate::domain::plan_change::{PlanChange, RecordedPlanChange};+ use crate::domain::{AiPricing, BillingRepo, PlanTier};+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let period = current_period();+ let at = Utc::now();+ let mut usage = completion(user.clone(), AiFeature::Chat, 80.0);+ usage.cost.created_at = at - Duration::seconds(1);+ insert_upgrade_usage(&pool, &usage).await;+ let billing = crate::outbound::PgBillingRepo::new(pool.clone(), AiPricing::testing());+ // The later event arrives first; readers use occurrence order, not insertion order.+ for (from, to, stamp, old, new) in [+ (+ PlanTier::Premium,+ PlanTier::Max,+ at + Duration::seconds(1),+ 2_000,+ 10_000,+ ),+ (PlanTier::Max, PlanTier::Premium, at, 10_000, 2_000),+ ] {+ let change = RecordedPlanChange {+ change: PlanChange {+ from,+ to,+ at: stamp,+ period,+ },+ previous_included_cents: Some(old),+ new_included_cents: Some(new),+ };+ billing.record_plan_change(&user, change).await.unwrap();+ billing.record_plan_change(&user, change).await.unwrap();+ }+ let reader = PgUsageReader::new(pool.clone());+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 8_000);+ assert_eq!(position[0].chargeable_cost_cents, Some(0));+ usage.cost.created_at = at + Duration::seconds(2);+ usage.cost.price.as_mut().unwrap().total = 25.0;+ insert_upgrade_usage(&pool, &usage).await;+ let position = reader+ .usage_cost_cents_by_user(std::slice::from_ref(&user), period)+ .await+ .unwrap();+ assert_eq!(position[0].used_cents, 10_500);+ assert_eq!(position[0].chargeable_cost_cents, Some(500));+}diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/usage.sql b/crates/ai_billing/src/outbound/pg_usage_reader/usage.sqlnew file mode 100644index 0000000000..4d8c1fca93--- /dev/null+++ b/crates/ai_billing/src/outbound/pg_usage_reader/usage.sql@@ -0,0 +1,45 @@+WITH history AS MATERIALIZED (+ SELECT user_id, changed_at, previous_plan, new_plan,+ previous_included_cost_cents, new_included_cost_cents+ FROM ai_billing_plan_change+ WHERE user_id = ANY($1) AND period_start = $2 AND changed_at < $3+), boundaries AS (+ SELECT requested.user_id, $2::timestamptz AS start+ FROM UNNEST($1::text[]) AS requested(user_id)+ UNION+ SELECT user_id, changed_at FROM history+), intervals AS (+ SELECT user_id, start,+ LEAD(start, 1, $3) OVER (PARTITION BY user_id ORDER BY start) AS end+ FROM boundaries+), usage_segments AS (+ SELECT interval.user_id, interval.start,+ COALESCE(SUM(COALESCE(+ usage.total::float8,+ usage.input_tokens::float8 / 1000000.0 * $4+ + usage.output_tokens::float8 / 1000000.0 * $5+ + usage.cache_read_input_tokens::float8 / 1000000.0 * $6+ + usage.cache_write_input_tokens::float8 / 1000000.0 * $7+ )), 0)::float8 AS usd,+ EXISTS (+ SELECT 1 FROM ai_billing_usage_period AS policy+ WHERE policy.user_id = interval.user_id AND policy.period_start = $2+ AND policy.policy = 'public_allowance_v1'+ ) AS public_funding+ FROM intervals AS interval+ LEFT JOIN ai_usage AS usage+ ON usage.user_id = interval.user_id+ AND usage.created_at >= interval.start AND usage.created_at < interval.end+ AND usage.count_usage = TRUE+ GROUP BY interval.user_id, interval.start+)+SELECT TRUE AS "is_plan_change!", user_id AS "user_id!", changed_at AS "start!",+ previous_plan AS "previous_plan?", new_plan AS "new_plan?",+ previous_included_cost_cents, new_included_cost_cents,+ NULL::float8 AS "usd?", NULL::boolean AS "public_funding?"+FROM history+UNION ALL+SELECT FALSE, user_id, start, NULL::text, NULL::text,+ NULL::bigint, NULL::bigint, usd, public_funding+FROM usage_segments+ORDER BY "user_id!", "start!", "is_plan_change!" DESC, "previous_plan?", "new_plan?"diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rsindex d1d8f3e959..ff7cc452e0 100644--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs@@ -53,6 +53,14 @@ struct FakeBilling {}impl BillingService for FakeBilling {+ async fn change_plan(+ &self,+ _: &MacroUserIdStr<'_>,+ _: crate::domain::plan_change::PlanChange,+ ) -> Result<()> {+ panic!("this use case must not change plans")+ }+async fn snapshot(&self, _user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {self.snapshots.fetch_add(1, Ordering::SeqCst);Ok(self.snapshot.clone())diff --git a/crates/macro_db_client/migrations/20261007172436_ai_billing_plan_upgrade_usage_reset.sql b/crates/macro_db_client/migrations/20261007172436_ai_billing_plan_upgrade_usage_reset.sqlnew file mode 100644index 0000000000..1628038d5c--- /dev/null+++ b/crates/macro_db_client/migrations/20261007172436_ai_billing_plan_upgrade_usage_reset.sql@@ -0,0 +1,16 @@+-- Per-seat plan history survives departure/deletion, like ai_billing_account.+-- Additive: existing binaries can continue recording usage without this table.+CREATE TABLE ai_billing_plan_change (+ user_id TEXT NOT NULL,+ period_start TIMESTAMPTZ NOT NULL,+ changed_at TIMESTAMPTZ NOT NULL,+ previous_plan TEXT NOT NULL CHECK (previous_plan IN ('free', 'premium', 'max')),+ new_plan TEXT NOT NULL CHECK (new_plan IN ('free', 'premium', 'max')),+ previous_included_cost_cents BIGINT CHECK (previous_included_cost_cents >= 0),+ new_included_cost_cents BIGINT CHECK (new_included_cost_cents >= 0),+ PRIMARY KEY (user_id, period_start, changed_at, previous_plan, new_plan),+ CHECK (changed_at >= period_start),+ CHECK (previous_plan <> new_plan),+ CHECK ((previous_plan = 'free') = (previous_included_cost_cents IS NULL)),+ CHECK ((new_plan = 'free') = (new_included_cost_cents IS NULL))+);diff --git a/crates/macro_db_client/migrations/20261007172437_subscription_plan_schedule.sql b/crates/macro_db_client/migrations/20261007172437_subscription_plan_schedule.sqlnew file mode 100644index 0000000000..cdb056046e--- /dev/null+++ b/crates/macro_db_client/migrations/20261007172437_subscription_plan_schedule.sql@@ -0,0 +1,9 @@+-- Immutable provider schedule payloads. Stripe metadata holds only this row's+-- UUID, so large teams do not exceed Stripe's metadata size limits. Retain facts+-- through retries and delayed renewal webhooks.+CREATE TABLE subscription_plan_schedule (+ id UUID PRIMARY KEY,+ subscription_id TEXT NOT NULL,+ effective_at TIMESTAMPTZ NOT NULL,+ member_plans JSONB NOT NULL CHECK (jsonb_typeof(member_plans) = 'object')+);diff --git a/crates/teams/Cargo.toml b/crates/teams/Cargo.tomlindex c46a3ad5fa..ef4e9f565d 100644--- a/crates/teams/Cargo.toml+++ b/crates/teams/Cargo.toml@@ -85,6 +85,7 @@ roles_and_permissions = { path = "../roles_and_permissions", default-features =rootcause = { workspace = true }schemars = { workspace = true, optional = true }serde = { workspace = true }+serde_json = { workspace = true }shared_entity_registry = { path = "../entity_registry/shared_entity_registry" }thiserror = { workspace = true }tracing = { workspace = true }@@ -119,8 +120,8 @@ url = { workspace = true, optional = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+wiremock = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }models_pagination = { path = "../models_pagination" }-serde_json = { workspace = true }tokio = { workspace = true }tower = { workspace = true }diff --git a/crates/teams/src/domain/customer_repo.rs b/crates/teams/src/domain/customer_repo.rsindex b49c22036e..3c8f6b5f9e 100644--- a/crates/teams/src/domain/customer_repo.rs+++ b/crates/teams/src/domain/customer_repo.rs@@ -1,8 +1,10 @@//! Contains the domain logic for teams handling the customers+use std::collections::HashMap;+use macro_user_id::user_id::MacroUserIdStr;-use crate::domain::model::{CustomerError, SeatPlan};+use crate::domain::model::{CustomerError, ScheduledSeatPlan, SeatPlan};/// The CustomerRepository defines a set of actions to perform on customer data///@@ -10,6 +12,39 @@ use crate::domain::model::{CustomerError, SeatPlan};/// with `quantity` = the members on that plan. Implementations add the item/// when the first seat on a plan appears and drop it when the last one goes.pub trait CustomerRepository: Clone + Send + Sync + 'static {+ /// Keeps one team's billing reconciliation and seat changes serialized across replicas.+ /// Dropping the guard releases the lock, including on errors or cancellation.+ type TeamBillingGuard: Send;++ /// Acquire before reading or changing effective membership plans or renewal facts.+ fn lock_team_billing(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Self::TeamBillingGuard, CustomerError>> + Send;++ /// Read only this user's plan from an attached, Macro-owned schedule.+ fn scheduled_seat_plan(+ &self,+ subscription: &stripe::SubscriptionId,+ schedule: &stripe::SubscriptionScheduleId,+ user: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<ScheduledSeatPlan>, CustomerError>> + Send;++ /// Read this member's pending change from the subscription's attached schedule.+ /// Already applied phases do not count as pending changes.+ fn pending_seat_plan(+ &self,+ subscription: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<ScheduledSeatPlan>, CustomerError>> + Send;++ /// Read all pending seat changes from the attached, Macro-owned schedule.+ /// Already applied phases do not count as pending changes.+ fn pending_seat_plans(+ &self,+ subscription: &stripe::SubscriptionId,+ ) -> impl Future<Output = Result<HashMap<String, ScheduledSeatPlan>, CustomerError>> + Send;+/// Mark subscription as a team subscriptionfn convert_subscription_to_team(&self,@@ -53,6 +88,35 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {to: SeatPlan,) -> impl Future<Output = Result<(), CustomerError>> + Send;+ /// Schedule a seat downgrade at renewal, or cancel that seat's pending change.+ /// Current prices and entitlements remain unchanged.+ fn schedule_seat_plan(+ &self,+ subscription: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ plan: Option<SeatPlan>,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;++ /// Cancel any pending downgrade and replace the personal price atomically with+ /// respect to other provider mutations, invoicing proration immediately.+ fn upgrade_personal_plan(+ &self,+ subscription: &stripe::SubscriptionId,+ plan: SeatPlan,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;++ /// Member plans whose scheduled phase has actually started at the provider.+ fn renewed_seat_plans(+ &self,+ subscription: &stripe::SubscriptionId,+ ) -> impl Future<Output = Result<Vec<(String, SeatPlan)>, CustomerError>> + Send;++ /// Acknowledge successfully applied renewal changes; retries remain safe.+ fn acknowledge_renewed_seat_plans(+ &self,+ subscription: &stripe::SubscriptionId,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;+/// Cancels a subscription immediately. A subscription that is already/// cancelled or no longer exists counts as cancelled.fn cancel_subscription(diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex 10e3974acd..ae4b3c9391 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -288,6 +288,10 @@ pub struct TeamWithMembers {pub team: Team,/// The members of the teampub members: Vec<TeamMember<'static>>,+ /// Provider-confirmed pending seat changes, keyed by member user ID.+ /// Only available to paid-team admins and owners; empty means no pending changes.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub scheduled_seat_plans: Option<HashMap<String, ScheduledSeatPlan>>,}/// Current and invited members for a team.@@ -744,6 +748,9 @@ pub enum SetTeamMemberPlanError {/// Underlying customer error#[error("{0}")]CustomerError(#[from] CustomerError),+ /// Usage could not be reset for the upgraded seat.+ #[error("failed to update seat usage after a plan change")]+ UsageReset(#[source] Box<dyn std::error::Error + Send + Sync>),/// Roles could not be updated#[error("Roles error: {0}")]RolesError(#[from] UserRolesAndPermissionsError),@@ -859,12 +866,18 @@ pub enum RevokePermissionsForTeamMembersError {/// Error when restoring permissions for team members#[derive(Debug, thiserror::Error)]pub enum RestorePermissionsForTeamMembersError {+ /// Provider renewal state could not be read or acknowledged.+ #[error(transparent)]+ Customer(#[from] CustomerError),/// Underlying team error#[error("Underlying team error")]TeamError(#[from] TeamError),/// Underlying user roles and permissions error#[error("Underlying user roles and permissions error")]AddRolesToUserError(#[from] UserRolesAndPermissionsError),+ /// Initial seat upgrade usage could not be reset; retry activation.+ #[error("failed to reset usage for an activated team seat")]+ UsageReset(#[source] Box<dyn std::error::Error + Send + Sync>),}/// Error when creating team checkout@@ -889,3 +902,13 @@ pub enum TeamCheckoutError {#[cfg(test)]mod test;+/// A seat's future plan in the subscription's currently attached schedule.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct ScheduledSeatPlan {+ /// Plan that takes effect at renewal.+ pub plan: SeatPlan,+ /// Provider-confirmed time when the future phase starts.+ pub effective_at: chrono::DateTime<chrono::Utc>,+}diff --git a/crates/teams/src/domain/open_seat_release.rs b/crates/teams/src/domain/open_seat_release.rsindex 896e686be3..c4269e4270 100644--- a/crates/teams/src/domain/open_seat_release.rs+++ b/crates/teams/src/domain/open_seat_release.rs@@ -1,16 +1,49 @@-//! Outbound port for releasing a member's open seat when they leave a team.+//! Outbound billing port for seat departure and paid-plan changes.//!//! The teams service uses this port to release that seat without depending on//! a particular storage implementation.+use super::model::SeatPlan;+use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use std::convert::Infallible;-/// Releases a member's open seat for a team.+/// Original provider facts for a newly activated team subscription.+#[derive(Debug, Clone, Copy)]+pub struct SubscriptionStart {+ /// Original event time, retained on retries.+ pub at: DateTime<Utc>,+ /// Provider interval start.+ pub period_start: DateTime<Utc>,+ /// Provider interval end.+ pub period_end: DateTime<Utc>,+}++/// A team seat's transition into a paid plan.+#[derive(Debug, Clone, Copy)]+pub struct SeatPlanChange {+ /// Previous paid plan; None means Free.+ pub from: Option<SeatPlan>,+ /// Destination paid plan.+ pub to: SeatPlan,+ /// When the plan changed.+ pub at: DateTime<Utc>,+ /// Explicit provider interval for initial activation; otherwise billing resolves it.+ pub period: Option<(DateTime<Utc>, DateTime<Utc>)>,+}++/// Synchronizes team seat departures and plan changes with billing.pub trait OpenSeatRelease: Clone + Send + Sync + 'static {/// Error returned when releasing an open seat fails.type Err: std::error::Error + Send + Sync + 'static;+ /// Notify billing of a seat plan change after the provider accepted it.+ fn change_plan(+ &self,+ member: &MacroUserIdStr<'_>,+ change: SeatPlanChange,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Releases the open seat held by `member` on `team_id`.fn release(&self,@@ -26,6 +59,14 @@ pub struct NoOpOpenSeatRelease;impl OpenSeatRelease for NoOpOpenSeatRelease {type Err = Infallible;+ async fn change_plan(+ &self,+ _member: &MacroUserIdStr<'_>,+ _change: SeatPlanChange,+ ) -> Result<(), Self::Err> {+ Ok(())+ }+async fn release(&self,_team_id: uuid::Uuid,diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rsindex ff530b412e..18862f2f6f 100644--- a/crates/teams/src/domain/team_repo.rs+++ b/crates/teams/src/domain/team_repo.rs@@ -438,6 +438,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {fn restore_permissions_for_team_members(&self,team_id: &uuid::Uuid,+ started: Option<super::open_seat_release::SubscriptionStart>,) -> impl Future<Output = Result<(), RestorePermissionsForTeamMembersError>> + Send;/// Moves a member's seat to `plan`: swaps the seat between the teamdiff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex 3cbc8f78ed..42d61f0572 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -3,10 +3,7 @@#[cfg(test)]mod test;-use std::{- collections::{HashMap, HashSet},- sync::{Arc, LazyLock, Mutex, Weak},-};+use std::{collections::HashSet, sync::Arc};use channels::domain::{models::{ChannelType, CreateChannelRequest, Sender},@@ -50,7 +47,7 @@ use crate::domain::{TeamMembers, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,TryJoinTeamByDomainError, is_generic_email_domain, team_slug_from_name,},- open_seat_release::{NoOpOpenSeatRelease, OpenSeatRelease},+ open_seat_release::{NoOpOpenSeatRelease, OpenSeatRelease, SeatPlanChange, SubscriptionStart},owned_entity_cleanup::{OwnedEntityCleanup, UnwiredOwnedEntityCleanup, clear_team},team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},team_crm_settings_repo::TeamCrmSettingsRepository,@@ -71,27 +68,11 @@ fn team_member_roles_to_remove() -> Vec<RoleId> {.collect()}-/// Per-team locks serializing seat moves within this process (see-/// [`TeamService::set_team_member_plan`]). Entries are weak so a team whose-/// move finished costs nothing; a concurrent move on the same team picks up-/// the live lock instead. Replicas of the service do not share this, so two-/// admins on different replicas moving seats in the same instant can still-/// race; the seat picker disables itself while a move is in flight, which-/// covers the realistic case of one admin double-clicking.-fn seat_move_lock(team_id: &uuid::Uuid) -> Arc<tokio::sync::Mutex<()>> {- static LOCKS: LazyLock<Mutex<HashMap<uuid::Uuid, Weak<tokio::sync::Mutex<()>>>>> =- LazyLock::new(Default::default);- let mut locks = LOCKS- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- if let Some(live) = locks.get(team_id).and_then(Weak::upgrade) {- return live;- }- // Drop entries whose lock nobody holds any more while we are here.- locks.retain(|_, weak| weak.strong_count() > 0);- let lock = Arc::new(tokio::sync::Mutex::new(()));- locks.insert(*team_id, Arc::downgrade(&lock));- lock+/// Renewed seat plans may be reconciled without restoring revoked paid access.+#[derive(Clone, Copy)]+enum TeamBillingRoleUpdate {+ RestorePermissions,+ PreservePermissions,}/// Implementation of the TeamService using a TeamRepository@@ -311,6 +292,113 @@ whereOSR: OpenSeatRelease,OEC: OwnedEntityCleanup,{+ /// Reconcile while the caller holds the owning team billing guard.+ async fn reconcile_team_billing_locked(+ &self,+ team_id: &uuid::Uuid,+ started: Option<SubscriptionStart>,+ role_update: TeamBillingRoleUpdate,+ ) -> Result<(), RestorePermissionsForTeamMembersError> {+ let subscription = self+ .team_repository+ .get_team_subscription_id(team_id)+ .await?;+ let renewed = if let Some(id) = subscription.as_ref() {+ self.customer_repository.renewed_seat_plans(id).await?+ } else {+ Vec::new()+ };+ let mut members = self.team_repository.get_team_members(team_id).await?;+ for member in &mut members {+ if let Some((_, plan)) = renewed+ .iter()+ .find(|(user, _)| user == member.user_id.as_ref())+ {+ self.team_repository+ .patch_team_member_plan(team_id, &member.user_id, *plan)+ .await?;+ member.plan = *plan;+ }+ }++ if members.is_empty() {+ return Ok(());+ }++ for member in members {+ if matches!(role_update, TeamBillingRoleUpdate::PreservePermissions) {+ if !renewed+ .iter()+ .any(|(user, _)| user == member.user_id.as_ref())+ {+ continue;+ }+ let roles = self+ .user_roles_and_permissions_service+ .get_user_roles(&member.user_id)+ .await?;+ if !roles.contains(&RoleId::TeamSubscriber) {+ continue;+ }+ }+ if let Some(started) = started {+ let previous_roles = self+ .user_roles_and_permissions_service+ .get_user_roles(&member.user_id)+ .await?;+ let from = previous_roles+ .iter()+ .any(RoleId::is_paid_subscription)+ .then(|| SeatPlan::from_roles(&previous_roles));+ // Reset before stamping roles so a storage failure retains the+ // source tier and the same upgrade can be retried safely.+ self.open_seat_release+ .change_plan(+ &member.user_id,+ SeatPlanChange {+ from,+ to: member.plan,+ at: started.at,+ period: Some((started.period_start, started.period_end)),+ },+ )+ .await+ .map_err(|error| {+ RestorePermissionsForTeamMembersError::UsageReset(Box::new(error))+ })?;+ }+ let roles = match role_update {+ TeamBillingRoleUpdate::RestorePermissions => team_member_roles_to_add(member.plan),+ TeamBillingRoleUpdate::PreservePermissions => vec![member.plan.role()],+ };+ let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();++ self.user_roles_and_permissions_service+ .dangerous_upsert_roles_for_user(&member.user_id, roles)+ .await+ .map_err(RestorePermissionsForTeamMembersError::AddRolesToUserError)?;++ // Exactly one tier role per member: the one their seat's plan says.+ let stale_tier_roles = member.plan.other_tier_roles();+ if let Ok(stale_tier_roles) = non_empty::NonEmpty::new(stale_tier_roles.as_slice()) {+ self.user_roles_and_permissions_service+ .dangerous_remove_roles_from_user(&member.user_id, &stale_tier_roles)+ .await+ .map_err(RestorePermissionsForTeamMembersError::AddRolesToUserError)?;+ }+ }++ if !renewed.is_empty()+ && let Some(id) = subscription.as_ref()+ {+ self.customer_repository+ .acknowledge_renewed_seat_plans(id)+ .await?;+ }++ Ok(())+ }+/// Replaces the contacts enqueuer while preserving every other service dependency.pub fn with_contacts_enqueuer<CNE2>(self,@@ -453,6 +541,28 @@ where.ok();}+ /// Restore a removed seat's pending downgrade after membership and seat rollback.+ async fn restore_pending_seat_change(+ &self,+ subscription_id: Option<&stripe::SubscriptionId>,+ user_id: &MacroUserIdStr<'_>,+ pending_plan: Option<SeatPlan>,+ ) {+ if let (Some(subscription), Some(plan)) = (subscription_id, pending_plan) {+ self.customer_repository+ .schedule_seat_plan(subscription, user_id, Some(plan))+ .await+ .inspect_err(|error| {+ tracing::error!(+ error = ?error,+ user_id = %user_id,+ "unable to restore pending seat downgrade after member removal failed"+ );+ })+ .ok();+ }+ }+/// Deletes `team_id` on behalf of `actor_user_id`. Purges everything the/// team and its bots own, cancels the team subscription, deletes the team/// with its memberships, bots, and grants, publishes `team.deleted`, and@@ -537,6 +647,32 @@ where.get_team_enterprise_status(&team_id).await?;+ let _billing = self.customer_repository.lock_team_billing(&team_id).await?;+ let subscription_id = if enterprise {+ None+ } else {+ self.team_repository+ .get_team_subscription_id(&team_id)+ .await?+ };+ // Stripe may have entered the downgrade phase before its webhook arrives.+ // Remove the effective seat plan, rather than decrementing its old price.+ if let Some(subscription) = subscription_id.as_ref()+ && !self+ .customer_repository+ .renewed_seat_plans(subscription)+ .await?+ .is_empty()+ {+ self.reconcile_team_billing_locked(+ &team_id,+ None,+ TeamBillingRoleUpdate::PreservePermissions,+ )+ .await+ .map_err(anyhow::Error::from)?;+ }+let roles_to_remove = team_member_roles_to_remove();let current_roles = self.user_roles_and_permissions_service@@ -549,6 +685,14 @@ where.cloned().collect();+ let pending_plan = if let Some(subscription) = subscription_id.as_ref() {+ self.customer_repository+ .pending_seat_plan(subscription, user_id)+ .await?+ .map(|change| change.plan)+ } else {+ None+ };let removed_member = match self.team_repository.remove_user_from_team(&team_id, user_id)@@ -564,37 +708,16 @@ whereErr(error) => return Err(error),};- let subscription_id = if enterprise {- None- } else {- // Free teams have no linked subscription - nothing to decrement.- match self- .team_repository- .get_team_subscription_id(&team_id)- .await- {- Ok(subscription_id) => subscription_id,- Err(e) => {- self.team_repository- .rollback_remove_user_from_team(&removed_member)- .await- .inspect_err(|rollback_err| {- tracing::error!(- error=?rollback_err,- "unable to rollback removed team member after getting team subscription failed"- );- })- .ok();- return Err(RemoveUserFromTeamError::TeamError(e));- }- }- };-if let Some(subscription_id) = subscription_id.as_ref()- && let Err(e) = self- .customer_repository- .decrement_seat_count(subscription_id, removed_member.plan, 1)- .await+ && let Err(e) = async {+ self.customer_repository+ .schedule_seat_plan(subscription_id, user_id, None)+ .await?;+ self.customer_repository+ .decrement_seat_count(subscription_id, removed_member.plan, 1)+ .await+ }+ .await{self.team_repository.rollback_remove_user_from_team(&removed_member)@@ -606,6 +729,8 @@ where);}).ok();+ self.restore_pending_seat_change(Some(subscription_id), user_id, pending_plan)+ .await;return Err(RemoveUserFromTeamError::CustomerError(e));}@@ -638,6 +763,8 @@ where);}).ok();+ self.restore_pending_seat_change(subscription_id.as_ref(), user_id, pending_plan)+ .await;return Err(RemoveUserFromTeamError::TeamError(channel_error_to_team_error(error),));@@ -659,6 +786,8 @@ where"removing team member roles",).await;+ self.restore_pending_seat_change(subscription_id.as_ref(), user_id, pending_plan)+ .await;return Err(RemoveUserFromTeamError::RemoveRolesFromUserError(e));}@@ -683,6 +812,8 @@ where"releasing the open seat",).await;+ self.restore_pending_seat_change(subscription_id.as_ref(), user_id, pending_plan)+ .await;return Err(RemoveUserFromTeamError::OpenSeatRelease(Box::new(error)));}@@ -1672,6 +1803,17 @@ where&self,team_id: &uuid::Uuid,) -> Result<(), RevokePermissionsForTeamMembersError> {+ // Revocation must not race a renewed seat's tier-role update.+ let _billing = self+ .customer_repository+ .lock_team_billing(team_id)+ .await+ .map_err(|error| TeamError::StorageLayerError(error.into()))?;+ // Plan changes must see the failed payment before revoked roles can+ // become observable, including while the webhook finishes other work.+ self.team_repository+ .update_team_payment_status(team_id, false)+ .await?;let members = self.team_repository.get_team_members(team_id).await?;if members.is_empty() {@@ -1697,33 +1839,15 @@ whereasync fn restore_permissions_for_team_members(&self,team_id: &uuid::Uuid,+ started: Option<SubscriptionStart>,) -> Result<(), RestorePermissionsForTeamMembersError> {- let members = self.team_repository.get_team_members(team_id).await?;-- if members.is_empty() {- return Ok(());- }-- for member in members {- let roles = team_member_roles_to_add(member.plan);- let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();-- self.user_roles_and_permissions_service- .dangerous_upsert_roles_for_user(&member.user_id, roles)- .await- .map_err(RestorePermissionsForTeamMembersError::AddRolesToUserError)?;-- // Exactly one tier role per member: the one their seat's plan says.- let stale_tier_roles = member.plan.other_tier_roles();- if let Ok(stale_tier_roles) = non_empty::NonEmpty::new(stale_tier_roles.as_slice()) {- self.user_roles_and_permissions_service- .dangerous_remove_roles_from_user(&member.user_id, &stale_tier_roles)- .await- .map_err(RestorePermissionsForTeamMembersError::AddRolesToUserError)?;- }- }-- Ok(())+ let _billing = self.customer_repository.lock_team_billing(team_id).await?;+ self.reconcile_team_billing_locked(+ team_id,+ started,+ TeamBillingRoleUpdate::RestorePermissions,+ )+ .await}#[tracing::instrument(skip(self), err)]@@ -1756,26 +1880,19 @@ where) -> Result<TeamMember<'static>, SetTeamMemberPlanError> {let team_id =macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();- // Moving a seat reads the subscription's per-plan quantities and- // writes them back, so two moves on one team must not interleave:- // both would apply the same pre-image and Stripe would under-count a- // plan. Serialize per team for the whole move.- let lock = seat_move_lock(&team_id);- let _moving = lock.lock().await;+ // Serialize the whole use case with renewal reconciliation across replicas.+ let _billing = self.customer_repository.lock_team_billing(&team_id).await?;let changed_by = entity_access_receipt.get_authenticated_user().map_err(|e| SetTeamMemberPlanError::TeamError(TeamError::AccessError(e)))?.clone().into_owned();- let member = self+ let mut member = self.team_repository.get_team_member(&team_id, user_id).await?.into_owned();- if member.plan == plan {- return Ok(member);- }if !SeatPlan::PURCHASABLE.contains(&plan) {return Err(CustomerError::PlanUnavailable(plan).into());}@@ -1804,6 +1921,50 @@ where}};+ // A request can race renewal's webhook. Reconcile the provider's+ // effective phase before comparing against the stored member plan.+ if let Some(subscription) = subscription_id.as_ref() {+ let renewed = self+ .customer_repository+ .renewed_seat_plans(subscription)+ .await?;+ if !renewed.is_empty() {+ self.reconcile_team_billing_locked(+ &team_id,+ None,+ TeamBillingRoleUpdate::PreservePermissions,+ )+ .await+ .map_err(|error| SetTeamMemberPlanError::UsageReset(Box::new(error)))?;+ member = self+ .team_repository+ .get_team_member(&team_id, user_id)+ .await?+ .into_owned();+ }+ }++ if let Some(subscription) = subscription_id.as_ref() {+ if member.plan == plan {+ self.customer_repository+ .schedule_seat_plan(subscription, user_id, None)+ .await?;+ return Ok(member);+ }+ if member.plan == SeatPlan::Max && plan == SeatPlan::Premium {+ self.customer_repository+ .schedule_seat_plan(subscription, user_id, Some(plan))+ .await?;+ return Ok(member);+ }+ self.customer_repository+ .schedule_seat_plan(subscription, user_id, None)+ .await?;+ } else if member.plan == plan {+ return Ok(member);+ }++ let changed_at = chrono::Utc::now();if let Some(subscription_id) = subscription_id.as_ref() {self.customer_repository.move_seat(subscription_id, member.plan, plan)@@ -1834,7 +1995,7 @@ where// allowance follow the seat.let roles_to_add = team_member_roles_to_add(plan);let stale_tier_roles = plan.other_tier_roles();- let role_result = async {+ let plan_result = async {self.user_roles_and_permissions_service.dangerous_upsert_roles_for_user(user_id,@@ -1846,10 +2007,47 @@ where.dangerous_remove_roles_from_user(user_id, &stale_tier_roles).await?;}- Ok::<(), roles_and_permissions::domain::model::UserRolesAndPermissionsError>(())+ if !enterprise {+ self.open_seat_release+ .change_plan(+ user_id,+ SeatPlanChange {+ from: Some(member.plan),+ to: plan,+ at: changed_at,+ period: None,+ },+ )+ .await+ .map_err(|error| SetTeamMemberPlanError::UsageReset(Box::new(error)))?;+ }+ Ok::<(), SetTeamMemberPlanError>(())}.await;- if let Err(e) = role_result {+ if let Err(e) = plan_result {+ // The plan and billing update are one use case. Restore permissions+ // as well as the recorded/Stripe plan if any step fails.+ let original_roles = team_member_roles_to_add(member.plan);+ self.user_roles_and_permissions_service+ .dangerous_upsert_roles_for_user(+ user_id,+ non_empty::NonEmpty::new(original_roles.as_slice()).unwrap(),+ )+ .await+ .inspect_err(|error| {+ tracing::error!(?error, "unable to restore original seat roles")+ })+ .ok();+ let stale_roles = member.plan.other_tier_roles();+ if let Ok(stale_roles) = non_empty::NonEmpty::new(stale_roles.as_slice()) {+ self.user_roles_and_permissions_service+ .dangerous_remove_roles_from_user(user_id, &stale_roles)+ .await+ .inspect_err(|error| {+ tracing::error!(?error, "unable to remove rolled-back seat roles")+ })+ .ok();+ }self.team_repository.patch_team_member_plan(&team_id, user_id, member.plan).await@@ -1872,7 +2070,7 @@ where}).ok();}- return Err(e.into());+ return Err(e);}tracing::info!(@@ -1920,7 +2118,51 @@ where) -> Result<TeamWithMembers, TeamError> {let team_id =macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();- self.team_repository.get_team_by_id(&team_id).await+ let mut team = self.team_repository.get_team_by_id(&team_id).await?;+ team.scheduled_seat_plans = None;+ if !entity_access_receipt+ .entity_permission()+ .satisfies::<AdminTeamRole>()+ || team.team.enterprise()+ {+ return Ok(team);+ }++ // Billing-provider availability must not prevent viewing team membership.+ let pending: anyhow::Result<_> = async {+ if !self+ .team_repository+ .get_team_payment_status(&team_id)+ .await?+ {+ return Ok(None);+ }+ let Some(subscription) = self+ .team_repository+ .get_team_subscription_id(&team_id)+ .await?+ else {+ return Ok(None);+ };+ let mut changes = self+ .customer_repository+ .pending_seat_plans(&subscription)+ .await?;+ changes.retain(|user, _| {+ team.members+ .iter()+ .any(|member| member.user_id.as_ref() == user)+ });+ Ok(Some(changes))+ }+ .await;+ match pending {+ Ok(changes) => team.scheduled_seat_plans = changes,+ Err(error) => {+ tracing::warn!(?error, %team_id, "unable to read pending team seat changes")+ }+ }+ Ok(team)}#[tracing::instrument(skip(self), err)]diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex 18aba41cad..6de1c109b3 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -1,5 +1,5 @@use std::{- collections::HashSet,+ collections::{HashMap, HashSet},future::Future,sync::{Arc, Mutex,@@ -281,10 +281,18 @@ impl TeamRepository for MockTeamRepository {fn get_team_payment_status(&self,- _: &uuid::Uuid,+ team_id: &uuid::Uuid,) -> impl Future<Output = Result<bool, TeamError>> + Send {*self.team_payment_status_lookup_calls.lock().unwrap() += 1;- let team_payment_status = self.team_payment_status;+ let team_payment_status = self+ .payment_update_calls+ .lock()+ .unwrap()+ .iter()+ .rev()+ .find(|(id, _)| id == team_id)+ .map(|(_, paying)| *paying)+ .unwrap_or(self.team_payment_status);let fail = self.fail_team_payment_status_lookup;async move {if fail {@@ -439,7 +447,18 @@ impl TeamRepository for MockTeamRepository {) -> impl Future<Output = Result<TeamMember<'static>, RemoveUserFromTeamError>> + Send {*self.remove_user_calls.lock().unwrap() += 1;let reject_owner = self.reject_owner;- let removed_member = self.removed_member.clone();+ let mut removed_member = self.removed_member.clone();+ if let Some(member) = removed_member.as_mut()+ && let Some((_, _, plan)) = self+ .patch_team_member_plan_calls+ .lock()+ .unwrap()+ .iter()+ .rev()+ .find(|(_, user, _)| user == member.user_id.as_ref())+ {+ member.plan = *plan;+ }async move {if reject_owner {Err(RemoveUserFromTeamError::CannotRemoveOwner)@@ -598,7 +617,19 @@ impl TeamRepository for MockTeamRepository {&self,_: &uuid::Uuid,) -> impl Future<Output = Result<Vec<TeamMember<'_>>, TeamError>> + Send {- let members = self.team_members.clone();+ let mut members = self.team_members.clone();+ for member in &mut members {+ if let Some((_, _, plan)) = self+ .patch_team_member_plan_calls+ .lock()+ .unwrap()+ .iter()+ .rev()+ .find(|(_, user, _)| user == member.user_id.as_ref())+ {+ member.plan = *plan;+ }+ }async move { Ok(members) }}@@ -619,7 +650,11 @@ impl TeamRepository for MockTeamRepository {let members = self.team_members.clone();async move {let team = team.ok_or(TeamError::TeamDoesNotExist)?;- Ok(TeamWithMembers { team, members })+ Ok(TeamWithMembers {+ team,+ members,+ scheduled_seat_plans: None,+ })}}@@ -689,11 +724,22 @@ impl TeamRepository for MockTeamRepository {team_id: &uuid::Uuid,user_id: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<TeamMember<'_>, TeamError>> + Send {- let member = self+ let mut member = self.team_members.iter().find(|member| member.user_id.as_ref() == user_id.as_ref()).cloned();+ if let Some(member) = member.as_mut()+ && let Some((_, _, plan)) = self+ .patch_team_member_plan_calls+ .lock()+ .unwrap()+ .iter()+ .rev()+ .find(|(_, user, _)| user == member.user_id.as_ref())+ {+ member.plan = *plan;+ }let team_id = *team_id;async move { member.ok_or(TeamError::TeamMemberNotFound(team_id)) }}@@ -844,11 +890,21 @@ impl TeamRepository for MockTeamRepository {#[derive(Clone)]struct MockCustomerRepository {+ billing_lock: Arc<tokio::sync::Mutex<()>>,+ renewal_read_pause: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>)>,+ renewal_reads: Arc<AtomicUsize>,subscription_id: stripe::SubscriptionId,increment_calls: Arc<Mutex<Vec<(String, u64)>>>,decrement_calls: Arc<Mutex<Vec<(String, u64)>>>,seat_plan_calls: Arc<Mutex<Vec<(String, SeatPlan, u64)>>>,move_seat_calls: Arc<Mutex<Vec<(String, SeatPlan, SeatPlan)>>>,+ schedule_calls: Arc<Mutex<Vec<(String, String, Option<SeatPlan>)>>>,+ pending_plan: Option<SeatPlan>,+ pending_plans: HashMap<String, crate::domain::model::ScheduledSeatPlan>,+ pending_plans_calls: Arc<Mutex<Vec<String>>>,+ fail_pending_plans: bool,+ renewed_plans: Vec<(String, SeatPlan)>,+ acknowledged: Arc<Mutex<usize>>,fail_move_seat: bool,convert_calls: Arc<Mutex<Vec<(String, uuid::Uuid, String)>>>,subscription_lookup_calls: Arc<Mutex<usize>>,@@ -861,11 +917,21 @@ struct MockCustomerRepository {impl Default for MockCustomerRepository {fn default() -> Self {Self {+ billing_lock: Arc::new(tokio::sync::Mutex::new(())),+ renewal_read_pause: None,+ renewal_reads: Arc::new(AtomicUsize::new(0)),subscription_id: "sub_test".parse().unwrap(),increment_calls: Arc::new(Mutex::new(Vec::new())),decrement_calls: Arc::new(Mutex::new(Vec::new())),seat_plan_calls: Arc::new(Mutex::new(Vec::new())),move_seat_calls: Arc::new(Mutex::new(Vec::new())),+ schedule_calls: Arc::new(Mutex::new(Vec::new())),+ pending_plan: None,+ pending_plans: HashMap::new(),+ pending_plans_calls: Arc::new(Mutex::new(Vec::new())),+ fail_pending_plans: false,+ renewed_plans: Vec::new(),+ acknowledged: Arc::new(Mutex::new(0)),fail_move_seat: false,convert_calls: Arc::new(Mutex::new(Vec::new())),subscription_lookup_calls: Arc::new(Mutex::new(0)),@@ -878,6 +944,104 @@ impl Default for MockCustomerRepository {}impl CustomerRepository for MockCustomerRepository {+ type TeamBillingGuard = tokio::sync::OwnedMutexGuard<()>;++ async fn lock_team_billing(+ &self,+ _: &uuid::Uuid,+ ) -> Result<Self::TeamBillingGuard, CustomerError> {+ Ok(self.billing_lock.clone().lock_owned().await)+ }++ async fn scheduled_seat_plan(+ &self,+ _: &stripe::SubscriptionId,+ _: &stripe::SubscriptionScheduleId,+ _: &MacroUserIdStr<'_>,+ ) -> Result<Option<crate::domain::model::ScheduledSeatPlan>, CustomerError> {+ Ok(None)+ }++ async fn pending_seat_plan(+ &self,+ _: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ ) -> Result<Option<crate::domain::model::ScheduledSeatPlan>, CustomerError> {+ let pending = self+ .schedule_calls+ .lock()+ .unwrap()+ .iter()+ .rev()+ .find(|(_, member, _)| member == user.as_ref())+ .map(|(_, _, plan)| *plan)+ .unwrap_or(self.pending_plan);+ Ok(pending.map(|plan| crate::domain::model::ScheduledSeatPlan {+ plan,+ effective_at: chrono::Utc::now() + chrono::Duration::days(10),+ }))+ }++ async fn pending_seat_plans(+ &self,+ subscription: &stripe::SubscriptionId,+ ) -> Result<HashMap<String, crate::domain::model::ScheduledSeatPlan>, CustomerError> {+ self.pending_plans_calls+ .lock()+ .unwrap()+ .push(subscription.to_string());+ if self.fail_pending_plans {+ return Err(CustomerError::StorageLayerError(anyhow::anyhow!(+ "pending seat plans failed"+ )));+ }+ Ok(self.pending_plans.clone())+ }++ async fn schedule_seat_plan(+ &self,+ sub: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ plan: Option<SeatPlan>,+ ) -> Result<(), CustomerError> {+ self.schedule_calls+ .lock()+ .unwrap()+ .push((sub.to_string(), user.to_string(), plan));+ Ok(())+ }+ async fn upgrade_personal_plan(+ &self,+ _: &stripe::SubscriptionId,+ _: SeatPlan,+ ) -> Result<(), CustomerError> {+ Ok(())+ }+ async fn renewed_seat_plans(+ &self,+ _: &stripe::SubscriptionId,+ ) -> Result<Vec<(String, SeatPlan)>, CustomerError> {+ let plans = if *self.acknowledged.lock().unwrap() == 0 {+ self.renewed_plans.clone()+ } else {+ Vec::new()+ };+ if self.renewal_reads.fetch_add(1, Ordering::SeqCst) == 0+ && let Some((read, resume)) = &self.renewal_read_pause+ {+ read.notify_one();+ resume.notified().await;+ }+ Ok(plans)+ }+ async fn acknowledge_renewed_seat_plans(+ &self,+ _: &stripe::SubscriptionId,+ ) -> Result<(), CustomerError> {+ *self.acknowledged.lock().unwrap() += 1;+ Ok(())+ }+fn convert_subscription_to_team(&self,subscription_id: &stripe::SubscriptionId,@@ -1174,6 +1338,7 @@ struct MockUserRolesAndPermissionsService {fail_upsert: bool,fail_remove: bool,fail_get_roles: bool,+ role_removal_pause: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>)>,}impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {@@ -1242,7 +1407,12 @@ impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {.unwrap().push((user_id.as_ref().to_string(), role_ids.inner().to_vec()));let fail = self.fail_remove;+ let pause = self.role_removal_pause.clone();async move {+ if let Some((entered, resume)) = pause {+ entered.notify_one();+ resume.notified().await;+ }if fail {Err(UserRolesAndPermissionsError::StorageLayerError(anyhow::anyhow!("remove roles failed"),@@ -1434,6 +1604,7 @@ impl ContactsEnqueuer for RecordingContactsEnqueuer {#[derive(Clone, Default)]struct RecordingOpenSeatRelease {releases: Arc<Mutex<Vec<(uuid::Uuid, MacroUserIdStr<'static>)>>>,+ plan_changes: Arc<Mutex<Vec<(String, Option<SeatPlan>, SeatPlan)>>>,published_before: Arc<Mutex<Vec<usize>>>,published: Arc<Mutex<Vec<PublishedTeamEvent>>>,fail: bool,@@ -1459,6 +1630,21 @@ impl RecordingOpenSeatRelease {impl OpenSeatRelease for RecordingOpenSeatRelease {type Err = std::io::Error;+ async fn change_plan(+ &self,+ member: &MacroUserIdStr<'_>,+ change: crate::domain::open_seat_release::SeatPlanChange,+ ) -> Result<(), Self::Err> {+ if self.fail {+ return Err(std::io::Error::other("usage reset failed"));+ }+ self.plan_changes+ .lock()+ .unwrap()+ .push((member.to_string(), change.from, change.to));+ Ok(())+ }+async fn release(&self,team_id: uuid::Uuid,@@ -2120,7 +2306,7 @@ async fn team_payment_restore_adds_exact_premium_roles_to_members() {);service- .restore_permissions_for_team_members(&team_id)+ .restore_permissions_for_team_members(&team_id, None).await.unwrap();@@ -2140,7 +2326,15 @@ fn build_member_plan_service(team_repo: MockTeamRepository,customer_repo: MockCustomerRepository,roles_service: MockUserRolesAndPermissionsService,-) -> impl TeamService {+) -> TeamServiceImpl<+ MockTeamRepository,+ MockCustomerRepository,+ RecordingChannelService,+ MockUserRolesAndPermissionsService,+ MockNotificationIngress,+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+> {TeamServiceImpl::new(team_repo,customer_repo,@@ -2153,7 +2347,81 @@ fn build_member_plan_service(}#[tokio::test]-async fn set_team_member_plan_downgrades_max_seat_and_swaps_tier_role() {+async fn team_subscription_activation_passes_free_to_paid_upgrades_to_billing() {+ for plan in [SeatPlan::Premium, SeatPlan::Max] {+ let team_id = uuid::Uuid::from_u128(5110);+ let member_id = "macro|[email protected]";+ let member = TeamMember {+ plan,+ ..make_team_member(team_id, member_id, TeamRole::Member)+ };+ let repo = MockTeamRepository::new(Vec::new(), "Test Team", Default::default())+ .with_team_members(vec![member]);+ let roles = MockUserRolesAndPermissionsService::default();+ let upserts = roles.upsert_calls.clone();+ let billing = RecordingOpenSeatRelease::default();+ let service = build_member_plan_service(repo, MockCustomerRepository::default(), roles)+ .with_open_seat_release(billing.clone());+ let at = chrono::Utc::now();+ service+ .restore_permissions_for_team_members(+ &team_id,+ Some(SubscriptionStart {+ at,+ period_start: at - chrono::Duration::seconds(1),+ period_end: at + chrono::Duration::days(30),+ }),+ )+ .await+ .unwrap();+ assert_eq!(+ *billing.plan_changes.lock().unwrap(),+ vec![(member_id.to_string(), None, plan)]+ );+ assert_eq!(upserts.lock().unwrap().len(), 1);+ // Restoring payment on a later renewal does not replenish usage.+ service+ .restore_permissions_for_team_members(&team_id, None)+ .await+ .unwrap();+ assert_eq!(billing.plan_changes.lock().unwrap().len(), 1);+ }+}++#[tokio::test]+async fn failed_initial_usage_reset_keeps_free_roles_for_webhook_retry() {+ let team_id = uuid::Uuid::from_u128(5111);+ let repo = MockTeamRepository::new(Vec::new(), "Test Team", Default::default())+ .with_team_members(vec![make_team_member(+ team_id,+ "macro|[email protected]",+ TeamRole::Member,+ )]);+ let roles = MockUserRolesAndPermissionsService::default();+ let upserts = roles.upsert_calls.clone();+ let service = build_member_plan_service(repo, MockCustomerRepository::default(), roles)+ .with_open_seat_release(RecordingOpenSeatRelease::failing());+ let at = chrono::Utc::now();+ let error = service+ .restore_permissions_for_team_members(+ &team_id,+ Some(SubscriptionStart {+ at,+ period_start: at - chrono::Duration::seconds(1),+ period_end: at + chrono::Duration::days(30),+ }),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ RestorePermissionsForTeamMembersError::UsageReset(_)+ ));+ assert!(upserts.lock().unwrap().is_empty());+}++#[tokio::test]+async fn set_team_member_plan_defers_max_downgrade_and_keep_max_cancels_it() {let team_id = uuid::Uuid::from_u128(5100);let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();let member_id = "macro|[email protected]";@@ -2168,6 +2436,7 @@ async fn set_team_member_plan_downgrades_max_seat_and_swaps_tier_role() {let plan_calls = team_repo.patch_team_member_plan_calls.clone();let customer_repo = MockCustomerRepository::default();let move_calls = customer_repo.move_seat_calls.clone();+ let scheduled = customer_repo.schedule_calls.clone();let roles_service = MockUserRolesAndPermissionsService::default();let upsert_calls = roles_service.upsert_calls.clone();let remove_calls = roles_service.remove_calls.clone();@@ -2182,30 +2451,29 @@ async fn set_team_member_plan_downgrades_max_seat_and_swaps_tier_role() {.await.unwrap();- assert_eq!(member.plan, SeatPlan::Premium);- assert_eq!(member.role, TeamRole::Member);- assert_eq!(- *move_calls.lock().unwrap(),- vec![("sub_team".to_string(), SeatPlan::Max, SeatPlan::Premium)]- );- assert_eq!(- *plan_calls.lock().unwrap(),- vec![(team_id, member_id.to_string(), SeatPlan::Premium)]- );- assert_eq!(- *upsert_calls.lock().unwrap(),- vec![(- member_id.to_string(),- vec![RoleId::TeamSubscriber, RoleId::SubOpus]- )]- );+ assert_eq!(member.plan, SeatPlan::Max);+ assert!(move_calls.lock().unwrap().is_empty());+ assert!(plan_calls.lock().unwrap().is_empty());+ assert!(upsert_calls.lock().unwrap().is_empty());+ assert!(remove_calls.lock().unwrap().is_empty());assert_eq!(- *remove_calls.lock().unwrap(),+ *scheduled.lock().unwrap(),vec![(+ "sub_team".to_string(),member_id.to_string(),- vec![RoleId::SubHaiku, RoleId::SubSonnet, RoleId::SubMax]+ Some(SeatPlan::Premium))]);+ service+ .set_team_member_plan(+ test_team_receipt::<AdminTeamRole>(team_id, &admin_id),+ &MacroUserIdStr::parse_from_str(member_id).unwrap(),+ SeatPlan::Max,+ )+ .await+ .unwrap();+ assert_eq!(scheduled.lock().unwrap().last().unwrap().2, None);+ assert!(move_calls.lock().unwrap().is_empty());}#[tokio::test]@@ -2259,7 +2527,9 @@ async fn set_team_member_plan_upgrades_premium_seat_to_max_and_swaps_tier_role()let roles_service = MockUserRolesAndPermissionsService::default();let upsert_calls = roles_service.upsert_calls.clone();let remove_calls = roles_service.remove_calls.clone();- let service = build_member_plan_service(team_repo, customer_repo, roles_service);+ let billing = RecordingOpenSeatRelease::default();+ let service = build_member_plan_service(team_repo, customer_repo, roles_service)+ .with_open_seat_release(billing.clone());let member = service.set_team_member_plan(@@ -2270,6 +2540,14 @@ async fn set_team_member_plan_upgrades_premium_seat_to_max_and_swaps_tier_role().await.unwrap();+ assert_eq!(+ billing.plan_changes.lock().unwrap().as_slice(),+ &[(+ member_id.to_string(),+ Some(SeatPlan::Premium),+ SeatPlan::Max+ )]+ );assert_eq!(member.plan, SeatPlan::Max);assert_eq!(*move_calls.lock().unwrap(),@@ -2374,7 +2652,7 @@ async fn set_team_member_plan_rolls_back_seat_move_when_recording_plan_fails() {let member_id = "macro|[email protected]";let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));let member = TeamMember {- plan: SeatPlan::Max,+ plan: SeatPlan::Premium,..make_team_member(team_id, member_id, TeamRole::Member)};let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)@@ -2391,7 +2669,7 @@ async fn set_team_member_plan_rolls_back_seat_move_when_recording_plan_fails() {.set_team_member_plan(test_team_receipt::<AdminTeamRole>(team_id, &admin_id),&MacroUserIdStr::parse_from_str(member_id).unwrap(),- SeatPlan::Premium,+ SeatPlan::Max,).await.unwrap_err();@@ -2400,8 +2678,8 @@ async fn set_team_member_plan_rolls_back_seat_move_when_recording_plan_fails() {assert_eq!(*move_calls.lock().unwrap(),vec![- ("sub_team".to_string(), SeatPlan::Max, SeatPlan::Premium),("sub_team".to_string(), SeatPlan::Premium, SeatPlan::Max),+ ("sub_team".to_string(), SeatPlan::Max, SeatPlan::Premium),]);assert!(upsert_calls.lock().unwrap().is_empty());@@ -3417,6 +3695,79 @@ async fn test_get_team_reports_crm_enabled() {assert!(team.team.crm_enabled());}+#[tokio::test]+async fn get_team_exposes_confirmed_pending_plans_only_to_paid_team_billing_managers() {+ use entity_access::domain::models::{Entity, EntityPermission, TeamRole as AccessTeamRole};++ for (role, paying, enterprise, provider_failure, has_pending) in [+ (AccessTeamRole::Admin, true, false, false, true),+ (AccessTeamRole::Owner, true, false, false, true),+ (AccessTeamRole::Member, true, false, false, true),+ (AccessTeamRole::Admin, false, false, false, true),+ (AccessTeamRole::Admin, true, true, false, true),+ (AccessTeamRole::Admin, true, false, true, true),+ (AccessTeamRole::Admin, true, false, false, false),+ ] {+ let team_id = uuid::Uuid::from_u128(5501);+ let owner = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = make_team_member(team_id, "macro|[email protected]", TeamRole::Member);+ let team = Team::new(+ team_id,+ "Billing".into(),+ "BILLING".into(),+ owner.clone().into_owned(),+ false,+ enterprise,+ );+ let mut repo = MockTeamRepository::new(Vec::new(), "Billing", Default::default())+ .with_team(team)+ .with_team_members(vec![member.clone()]);+ repo.team_subscription_id = Some("sub_team".parse().unwrap());+ repo.team_payment_status = paying;+ repo.enterprise = enterprise;+ let pending = crate::domain::model::ScheduledSeatPlan {+ plan: SeatPlan::Premium,+ effective_at: chrono::Utc::now() + chrono::Duration::days(10),+ };+ let customer = MockCustomerRepository {+ pending_plans: if has_pending {+ HashMap::from([+ (member.user_id.to_string(), pending.clone()),+ ("macro|[email protected]".into(), pending.clone()),+ ])+ } else {+ HashMap::new()+ },+ fail_pending_plans: provider_failure,+ ..Default::default()+ };+ let calls = customer.pending_plans_calls.clone();+ let service = build_member_plan_service(repo, customer, Default::default());+ let receipt = EntityAccessReceipt::<MemberTeamRole>::try_new_authenticated_user(+ owner.into_owned(),+ Entity {+ entity_id: team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole { role },+ )+ .unwrap();+ let result = service.get_team(receipt).await.unwrap();+ assert_eq!(*result.team.id(), team_id);+ assert_eq!(result.members.len(), 1);+ let may_query = role != AccessTeamRole::Member && paying && !enterprise;+ assert_eq!(calls.lock().unwrap().len(), usize::from(may_query));+ let expected = (may_query && !provider_failure).then(|| {+ if has_pending {+ HashMap::from([(member.user_id.to_string(), pending)])+ } else {+ HashMap::new()+ }+ });+ assert_eq!(result.scheduled_seat_plans, expected);+ }+}+/// CrmEnqueuer that records which users had a populate or depopulate enqueued.#[derive(Clone, Default)]struct RecordingCrmEnqueuer {@@ -7264,3 +7615,540 @@ async fn domain_join_does_not_create_teammate_dms_inline() {serde_json::json!([owner.as_ref(), teammate.as_ref()]));}++#[tokio::test]+async fn failed_upgrade_usage_reset_rolls_back_the_team_seat_and_roles() {+ let team_id = uuid::Uuid::from_u128(5109);+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let member_id = "macro|[email protected]";+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", Default::default())+ .with_team_members(vec![make_team_member(team_id, member_id, TeamRole::Member)]);+ team_repo.team_subscription_id = Some("sub_team".parse().unwrap());+ let plan_calls = team_repo.patch_team_member_plan_calls.clone();+ let customer_repo = MockCustomerRepository::default();+ let move_calls = customer_repo.move_seat_calls.clone();+ let roles = MockUserRolesAndPermissionsService::default();+ let upsert_calls = roles.upsert_calls.clone();+ let service = build_member_plan_service(team_repo, customer_repo, roles)+ .with_open_seat_release(RecordingOpenSeatRelease::failing());+ let error = service+ .set_team_member_plan(+ test_team_receipt::<AdminTeamRole>(team_id, &admin_id),+ &MacroUserIdStr::parse_from_str(member_id).unwrap(),+ SeatPlan::Max,+ )+ .await+ .unwrap_err();+ assert!(matches!(error, SetTeamMemberPlanError::UsageReset(_)));+ assert_eq!(+ *plan_calls.lock().unwrap(),+ vec![+ (team_id, member_id.to_string(), SeatPlan::Max),+ (team_id, member_id.to_string(), SeatPlan::Premium),+ ]+ );+ assert_eq!(+ *move_calls.lock().unwrap(),+ vec![+ ("sub_team".to_string(), SeatPlan::Premium, SeatPlan::Max),+ ("sub_team".to_string(), SeatPlan::Max, SeatPlan::Premium),+ ]+ );+ assert_eq!(+ upsert_calls.lock().unwrap().last().unwrap().1,+ vec![RoleId::TeamSubscriber, RoleId::SubOpus]+ );+}++#[tokio::test]+async fn renewed_downgrades_update_membership_and_roles_without_resetting_usage() {+ let team_id = uuid::Uuid::from_u128(5400);+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, "macro|[email protected]", TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Renewal", Default::default())+ .with_team_members(vec![member]);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ let writes = team.patch_team_member_plan_calls.clone();+ let customer = MockCustomerRepository {+ renewed_plans: vec![("macro|[email protected]".into(), SeatPlan::Premium)],+ ..Default::default()+ };+ let ack = customer.acknowledged.clone();+ let roles = MockUserRolesAndPermissionsService::default();+ let upserts = roles.upsert_calls.clone();+ let billing = RecordingOpenSeatRelease::default();+ let service =+ build_member_plan_service(team, customer, roles).with_open_seat_release(billing.clone());+ service+ .restore_permissions_for_team_members(&team_id, None)+ .await+ .unwrap();+ assert_eq!(+ *writes.lock().unwrap(),+ vec![(+ team_id,+ "macro|[email protected]".to_string(),+ SeatPlan::Premium+ )]+ );+ assert!(upserts.lock().unwrap()[0].1.contains(&RoleId::SubOpus));+ assert!(!upserts.lock().unwrap()[0].1.contains(&RoleId::SubMax));+ assert!(billing.plan_changes.lock().unwrap().is_empty());+ assert_eq!(*ack.lock().unwrap(), 1);+}++#[tokio::test]+async fn concurrent_renewal_cannot_overwrite_a_completed_max_upgrade() {+ let team_id = uuid::Uuid::from_u128(5401);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Renewal", Default::default())+ .with_team_members(vec![member]);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ let writes = team.patch_team_member_plan_calls.clone();+ let read = Arc::new(tokio::sync::Notify::new());+ let resume = Arc::new(tokio::sync::Notify::new());+ let customer = MockCustomerRepository {+ renewed_plans: vec![(user.to_string(), SeatPlan::Premium)],+ renewal_read_pause: Some((read.clone(), resume.clone())),+ ..Default::default()+ };+ let moves = customer.move_seat_calls.clone();+ let roles = MockUserRolesAndPermissionsService::default();+ let upserts = roles.upsert_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ let webhook_service = service.clone();+ let webhook = tokio::spawn(async move {+ webhook_service+ .restore_permissions_for_team_members(&team_id, None)+ .await+ });+ read.notified().await;+ let upgrade_service = service.clone();+ let mut upgrade = tokio::spawn(async move {+ upgrade_service+ .set_team_member_plan(+ test_team_receipt::<AdminTeamRole>(team_id, &admin),+ &user,+ SeatPlan::Max,+ )+ .await+ });+ // The provider facts already read by the webhook must be applied before+ // another instance can reconcile them and perform a newer seat upgrade.+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(40), &mut upgrade)+ .await+ .is_err()+ );+ assert!(writes.lock().unwrap().is_empty());+ resume.notify_one();+ webhook.await.unwrap().unwrap();+ let upgraded = tokio::time::timeout(std::time::Duration::from_secs(2), upgrade)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(upgraded.plan, SeatPlan::Max);+ assert_eq!(writes.lock().unwrap().last().unwrap().2, SeatPlan::Max);+ assert_eq!(moves.lock().unwrap().last().unwrap().1, SeatPlan::Premium);+ assert_eq!(moves.lock().unwrap().last().unwrap().2, SeatPlan::Max);+ assert!(+ upserts+ .lock()+ .unwrap()+ .last()+ .unwrap()+ .1+ .contains(&RoleId::SubMax)+ );+ service+ .restore_permissions_for_team_members(&team_id, None)+ .await+ .unwrap();+ assert_eq!(writes.lock().unwrap().last().unwrap().2, SeatPlan::Max);+ assert!(+ upserts+ .lock()+ .unwrap()+ .last()+ .unwrap()+ .1+ .contains(&RoleId::SubMax)+ );+}++#[tokio::test]+async fn removal_before_renewal_webhook_decrements_the_effective_pro_seat() {+ let team_id = uuid::Uuid::from_u128(5402);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let retained = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, "macro|[email protected]", TeamRole::Member)+ };+ let unchanged = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, "macro|[email protected]", TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Renewal", Default::default())+ .with_team_members(vec![member.clone(), retained.clone(), unchanged]);+ team.removed_member = Some(member);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ let customer = MockCustomerRepository {+ renewed_plans: vec![+ (user.to_string(), SeatPlan::Premium),+ (retained.user_id.to_string(), SeatPlan::Premium),+ ],+ ..Default::default()+ };+ let seat_changes = customer.seat_plan_calls.clone();+ let acknowledged = customer.acknowledged.clone();+ let roles = MockUserRolesAndPermissionsService {+ roles: Arc::new(Mutex::new(HashSet::from([+ RoleId::TeamSubscriber,+ RoleId::SubMax,+ ]))),+ ..Default::default()+ };+ let upserts = roles.upsert_calls.clone();+ let removals = roles.remove_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ service+ .remove_user_from_team(test_team_receipt::<AdminTeamRole>(team_id, &admin), &user)+ .await+ .unwrap();+ assert_eq!(+ *seat_changes.lock().unwrap(),+ vec![("sub_team".into(), SeatPlan::Premium, 1)]+ );+ assert_eq!(*acknowledged.lock().unwrap(), 1);+ assert_eq!(+ *upserts.lock().unwrap(),+ vec![+ (user.to_string(), vec![RoleId::SubOpus]),+ (retained.user_id.to_string(), vec![RoleId::SubOpus]),+ ]+ );+ assert!(removals.lock().unwrap().iter().any(|(user, roles)| {+ user == retained.user_id.as_ref() && roles.contains(&RoleId::SubMax)+ }));+}++#[tokio::test]+async fn unpaid_member_removal_reconciles_renewed_seats_without_restoring_paid_access() {+ let team_id = uuid::Uuid::from_u128(5404);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let retained = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, "macro|[email protected]", TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Unpaid renewal", Default::default())+ .with_team_members(vec![member.clone(), retained.clone()]);+ team.removed_member = Some(member);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ team.team_payment_status = false;+ let writes = team.patch_team_member_plan_calls.clone();+ let customer = MockCustomerRepository {+ renewed_plans: vec![+ (user.to_string(), SeatPlan::Premium),+ (retained.user_id.to_string(), SeatPlan::Premium),+ ],+ ..Default::default()+ };+ let seat_changes = customer.seat_plan_calls.clone();+ let acknowledged = customer.acknowledged.clone();+ // Failed renewal has already revoked paid roles from every team member.+ let roles = MockUserRolesAndPermissionsService {+ fail_upsert: true,+ ..Default::default()+ };+ let upserts = roles.upsert_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ service+ .remove_user_from_team(test_team_receipt::<AdminTeamRole>(team_id, &admin), &user)+ .await+ .unwrap();+ assert_eq!(+ *writes.lock().unwrap(),+ vec![+ (team_id, user.to_string(), SeatPlan::Premium),+ (team_id, retained.user_id.to_string(), SeatPlan::Premium),+ ]+ );+ assert_eq!(+ *seat_changes.lock().unwrap(),+ vec![("sub_team".into(), SeatPlan::Premium, 1)]+ );+ assert!(upserts.lock().unwrap().is_empty());+ assert_eq!(*acknowledged.lock().unwrap(), 1);+}++#[tokio::test]+async fn failed_renewal_revocation_waits_for_member_removal_reconciliation() {+ let team_id = uuid::Uuid::from_u128(5405);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let retained = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, "macro|[email protected]", TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Renewal", Default::default())+ .with_team_members(vec![member.clone(), retained.clone()]);+ team.removed_member = Some(member);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ let read = Arc::new(tokio::sync::Notify::new());+ let resume = Arc::new(tokio::sync::Notify::new());+ let customer = MockCustomerRepository {+ renewed_plans: vec![(retained.user_id.to_string(), SeatPlan::Premium)],+ renewal_read_pause: Some((read.clone(), resume.clone())),+ ..Default::default()+ };+ let roles = MockUserRolesAndPermissionsService {+ roles: Arc::new(Mutex::new(HashSet::from([+ RoleId::TeamSubscriber,+ RoleId::SubMax,+ ]))),+ ..Default::default()+ };+ let upserts = roles.upsert_calls.clone();+ let removals = roles.remove_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ let removal_service = service.clone();+ let removal = tokio::spawn(async move {+ removal_service+ .remove_user_from_team(test_team_receipt::<AdminTeamRole>(team_id, &admin), &user)+ .await+ });+ read.notified().await;+ let revoke_service = service.clone();+ let mut revoke = tokio::spawn(async move {+ revoke_service+ .revoke_permissions_for_team_members(&team_id)+ .await+ });+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(40), &mut revoke)+ .await+ .is_err()+ );+ assert!(removals.lock().unwrap().is_empty());+ resume.notify_one();+ removal.await.unwrap().unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(2), revoke)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(+ *upserts.lock().unwrap(),+ vec![(retained.user_id.to_string(), vec![RoleId::SubOpus])]+ );+ let removals = removals.lock().unwrap();+ let (user, roles) = removals.last().unwrap();+ assert_eq!(user, retained.user_id.as_ref());+ assert!(roles.contains(&RoleId::TeamSubscriber));+ assert!(roles.contains(&RoleId::SubOpus));+}++#[tokio::test]+async fn member_plan_reconciliation_preserves_revocation_when_payment_status_lags() {+ for requested in [SeatPlan::Max, SeatPlan::Premium] {+ let team_id = uuid::Uuid::from_u128(5406);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Unpaid renewal", Default::default())+ .with_team_members(vec![member]);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ // The failure webhook revoked roles but has not yet stamped paying=false.+ team.team_payment_status = true;+ let customer = MockCustomerRepository {+ renewed_plans: vec![(user.to_string(), SeatPlan::Premium)],+ fail_move_seat: true,+ ..Default::default()+ };+ let roles = MockUserRolesAndPermissionsService {+ fail_upsert: true,+ ..Default::default()+ };+ let upserts = roles.upsert_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ let result = service+ .set_team_member_plan(+ test_team_receipt::<AdminTeamRole>(team_id, &admin),+ &user,+ requested,+ )+ .await;+ if requested == SeatPlan::Max {+ assert!(matches!(+ result,+ Err(SetTeamMemberPlanError::CustomerError(_))+ ));+ } else {+ assert_eq!(result.unwrap().plan, SeatPlan::Premium);+ }+ assert!(upserts.lock().unwrap().is_empty());+ }+}++#[tokio::test]+async fn failed_renewal_marks_nonpaying_before_releasing_plan_change_guard() {+ let team_id = uuid::Uuid::from_u128(5407);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = make_team_member(team_id, user.as_ref(), TeamRole::Member);+ let mut team = MockTeamRepository::new(Vec::new(), "Renewal", Default::default())+ .with_team_members(vec![member]);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ team.team_payment_status = true;+ let payment_updates = team.payment_update_calls.clone();+ // A successful provider mock proves paying=false itself blocks the upgrade.+ let customer = MockCustomerRepository::default();+ let moves = customer.move_seat_calls.clone();+ let entered = Arc::new(tokio::sync::Notify::new());+ let resume = Arc::new(tokio::sync::Notify::new());+ let roles = MockUserRolesAndPermissionsService {+ roles: Arc::new(Mutex::new(HashSet::from([+ RoleId::TeamSubscriber,+ RoleId::SubOpus,+ ]))),+ role_removal_pause: Some((entered.clone(), resume.clone())),+ ..Default::default()+ };+ let upserts = roles.upsert_calls.clone();+ let service = build_member_plan_service(team, customer, roles);+ let revoke_service = service.clone();+ let revoke = tokio::spawn(async move {+ revoke_service+ .revoke_permissions_for_team_members(&team_id)+ .await+ });+ entered.notified().await;+ assert_eq!(*payment_updates.lock().unwrap(), vec![(team_id, false)]);+ let upgrade_service = service.clone();+ let mut upgrade = tokio::spawn(async move {+ upgrade_service+ .set_team_member_plan(+ test_team_receipt::<AdminTeamRole>(team_id, &admin),+ &user,+ SeatPlan::Max,+ )+ .await+ });+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(40), &mut upgrade)+ .await+ .is_err()+ );+ assert!(moves.lock().unwrap().is_empty());+ assert!(upserts.lock().unwrap().is_empty());+ resume.notify_one();+ revoke.await.unwrap().unwrap();+ let result = tokio::time::timeout(std::time::Duration::from_secs(2), upgrade)+ .await+ .unwrap()+ .unwrap();+ assert!(matches!(result, Err(SetTeamMemberPlanError::TeamNotPaying)));+ assert!(moves.lock().unwrap().is_empty());+ assert!(upserts.lock().unwrap().is_empty());+}++#[tokio::test]+async fn failed_member_removal_preserves_the_pending_downgrade() {+ #[derive(Clone, Copy, Debug)]+ enum Failure {+ Decrement,+ Channels,+ Roles,+ Release,+ }+ for failure in [+ Failure::Decrement,+ Failure::Channels,+ Failure::Roles,+ Failure::Release,+ ] {+ let team_id = uuid::Uuid::from_u128(5403);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let admin = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let member = TeamMember {+ plan: SeatPlan::Max,+ ..make_team_member(team_id, user.as_ref(), TeamRole::Member)+ };+ let mut team = MockTeamRepository::new(Vec::new(), "Pending", Default::default());+ team.removed_member = Some(member);+ team.team_subscription_id = Some("sub_team".parse().unwrap());+ let restored = team.rollback_remove_calls.clone();+ let customer = MockCustomerRepository {+ pending_plan: Some(SeatPlan::Premium),+ fail_decrement: matches!(failure, Failure::Decrement),+ ..Default::default()+ };+ let changes = customer.schedule_calls.clone();+ let channels = RecordingChannelService {+ fail_leave: matches!(failure, Failure::Channels),+ ..Default::default()+ };+ let roles = MockUserRolesAndPermissionsService {+ fail_remove: matches!(failure, Failure::Roles),+ ..Default::default()+ };+ let billing = RecordingOpenSeatRelease {+ fail: matches!(failure, Failure::Release),+ ..Default::default()+ };+ let service = TeamServiceImpl::new(+ team,+ customer.clone(),+ channels,+ roles,+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_open_seat_release(billing);+ assert!(+ service+ .remove_user_from_team(test_team_receipt::<AdminTeamRole>(team_id, &admin), &user)+ .await+ .is_err(),+ "{failure:?}"+ );+ assert_eq!(*restored.lock().unwrap(), 1, "{failure:?}");+ assert_eq!(+ changes.lock().unwrap().first().unwrap().2,+ None,+ "{failure:?}"+ );+ let pending = customer+ .pending_seat_plan(&"sub_team".parse().unwrap(), &user)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(pending.plan, SeatPlan::Premium, "{failure:?}");+ }+}diff --git a/crates/teams/src/inbound/axum_router.rs b/crates/teams/src/inbound/axum_router.rsindex 1c8c678b66..12183132e1 100644--- a/crates/teams/src/inbound/axum_router.rs+++ b/crates/teams/src/inbound/axum_router.rs@@ -358,7 +358,9 @@ impl IntoResponse for SetTeamMemberPlanError {).into_response(),SetTeamMemberPlanError::TeamError(e) => e.into_response(),- SetTeamMemberPlanError::CustomerError(_) | SetTeamMemberPlanError::RolesError(_) => (+ SetTeamMemberPlanError::CustomerError(_)+ | SetTeamMemberPlanError::RolesError(_)+ | SetTeamMemberPlanError::UsageReset(_) => (StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {message: "internal server error".into(),diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rsindex ede986c638..e753e621a9 100644--- a/crates/teams/src/inbound/axum_router/test.rs+++ b/crates/teams/src/inbound/axum_router/test.rs@@ -331,6 +331,7 @@ impl TeamService for FakeTeamService {async fn restore_permissions_for_team_members(&self,_team_id: &uuid::Uuid,+ _started: Option<crate::domain::open_seat_release::SubscriptionStart>,) -> Result<(), RestorePermissionsForTeamMembersError> {panic!("unexpected restore_permissions_for_team_members call")}diff --git a/crates/teams/src/outbound/customer_repo.rs b/crates/teams/src/outbound/customer_repo.rsindex f5de63fb1a..67fb79fa87 100644--- a/crates/teams/src/outbound/customer_repo.rs+++ b/crates/teams/src/outbound/customer_repo.rs@@ -2,12 +2,16 @@use std::{collections::HashMap, sync::Arc};+#[cfg(test)]+mod test;+use anyhow::Context;+use macro_user_id::user_id::MacroUserIdStr;use stripe::{UpdateSubscription, UpdateSubscriptionItems};use crate::domain::{customer_repo::CustomerRepository,- model::{CustomerError, SeatPlan, SeatPrices},+ model::{CustomerError, ScheduledSeatPlan, SeatPlan, SeatPrices},};/// The CustomerRepositoryImpl struct is a wrapper around a stripe::Client connected to stripe.@@ -18,6 +22,9 @@ pub struct CustomerRepositoryImpl {/// The Stripe price behind each plan's seat item. A team subscription/// holds one item per plan its members are on.seat_prices: SeatPrices,+ pool: sqlx::PgPool,+ team_locks: sqlx::PgPool,+ subscription_locks: sqlx::PgPool,}/// One plan's seat item on a subscription.@@ -28,11 +35,210 @@ struct SeatItem {}impl CustomerRepositoryImpl {+ async fn billing_guard(+ locks: &sqlx::PgPool,+ key: &str,+ ) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, CustomerError> {+ let mut guard = locks+ .begin()+ .await+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key)+ .execute(&mut *guard)+ .await+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ Ok(guard)+ }++ async fn subscription_guard(+ &self,+ id: &stripe::SubscriptionId,+ ) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, CustomerError> {+ Self::billing_guard(+ &self.subscription_locks,+ &format!("subscription-billing:{id}"),+ )+ .await+ }++ async fn read_pending(+ &self,+ subscription: &str,+ record: &str,+ ) -> Result<PendingChanges, CustomerError> {+ let id: uuid::Uuid = record+ .parse()+ .map_err(|e| CustomerError::StorageLayerError(anyhow::Error::from(e)))?;+ let row = sqlx::query!("SELECT effective_at, member_plans FROM subscription_plan_schedule WHERE id = $1 AND subscription_id = $2", id, subscription).fetch_one(&self.pool).await.map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ Ok(PendingChanges {+ at: row.effective_at.timestamp(),+ members: serde_json::from_value(row.member_plans)+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?,+ })+ }+ async fn pending_changes(+ &self,+ schedule: &stripe::SubscriptionSchedule,+ subscription: &stripe::Subscription,+ ) -> Result<PendingChanges, CustomerError> {+ match schedule.metadata.as_ref().and_then(|m| m.get(PENDING_KEY)) {+ Some(record) => self.read_pending(subscription.id.as_str(), record).await,+ None => Ok(PendingChanges {+ at: subscription.current_period_end,+ members: HashMap::new(),+ }),+ }+ }++ async fn read_scheduled_seat_plans(+ &self,+ subscription: &stripe::SubscriptionId,+ schedule: &stripe::SubscriptionScheduleId,+ ) -> Result<HashMap<String, ScheduledSeatPlan>, CustomerError> {+ let schedule = stripe::SubscriptionSchedule::retrieve(&self.client, schedule, &[])+ .await+ .map_err(storage)?;+ if schedule+ .metadata+ .as_ref()+ .and_then(|m| m.get(OWNED_KEY))+ .map(String::as_str)+ != Some("1")+ || !matches!(+ schedule.status,+ stripe::SubscriptionScheduleStatus::Active+ | stripe::SubscriptionScheduleStatus::NotStarted+ )+ {+ return Ok(HashMap::new());+ }+ let Some(record) = schedule.metadata.as_ref().and_then(|m| m.get(PENDING_KEY)) else {+ return Ok(HashMap::new());+ };+ let changes = self.read_pending(subscription.as_str(), record).await?;+ let effective_at =+ chrono::DateTime::from_timestamp(changes.at, 0).context("invalid scheduled renewal")?;+ Ok(changes+ .members+ .into_iter()+ .map(|(user, plan)| (user, ScheduledSeatPlan { plan, effective_at }))+ .collect())+ }++ async fn release_schedule(+ &self,+ id: &stripe::SubscriptionScheduleId,+ ) -> Result<(), CustomerError> {+ self.client+ .post::<stripe::SubscriptionSchedule>(&format!("/subscription_schedules/{id}/release"))+ .await+ .map_err(storage)?;+ Ok(())+ }++ async fn write_schedule(+ &self,+ schedule: &stripe::SubscriptionSchedule,+ subscription: &stripe::Subscription,+ mut current: serde_json::Value,+ pending: PendingChanges,+ proration: &str,+ ) -> Result<(), CustomerError> {+ current["end_date"] = pending.at.into();+ let mut next = current.clone();+ next["start_date"] = pending.at.into();+ next.as_object_mut().unwrap().remove("end_date");+ next.as_object_mut().unwrap().remove("trial_end");+ next.as_object_mut().unwrap().remove("add_invoice_items");+ next["iterations"] = 1.into();+ next["proration_behavior"] = "none".into();+ let mut quantities = phase_quantities(¤t)?;+ let max = self.seat_prices.price_id(SeatPlan::Max)?.to_string();+ let pro = self.seat_prices.price_id(SeatPlan::Premium)?.to_string();+ let count = pending.members.len() as u64;+ let source = quantities.get(&max).copied().unwrap_or(0);+ if source < count {+ return Err(CustomerError::StorageLayerError(anyhow::anyhow!(+ "scheduled downgrades exceed active Max seats"+ )));+ }+ // A new lower-price item retains the seat's item-level tax and billing+ // settings as well as the phase-wide settings copied above.+ let source_item = next["items"]+ .as_array()+ .and_then(|items| {+ items+ .iter()+ .find(|item| item["price"].as_str() == Some(max.as_str()))+ })+ .cloned();+ if let Some(mut item) = source_item+ && !next["items"]+ .as_array()+ .unwrap()+ .iter()+ .any(|item| item["price"].as_str() == Some(pro.as_str()))+ {+ item["price"] = pro.clone().into();+ next["items"].as_array_mut().unwrap().push(item);+ }+ quantities.insert(max, source - count);+ *quantities.entry(pro).or_default() += count;+ replace_quantities(&mut next, &quantities);+ if next.get("metadata").is_none() {+ next["metadata"] = serde_json::json!({});+ }+ let record_id = macro_uuid::generate_uuid_v7();+ let effective_at =+ chrono::DateTime::from_timestamp(pending.at, 0).context("invalid scheduled renewal")?;+ let members = serde_json::to_value(&pending.members)+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ sqlx::query!("INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, $2, $3, $4)", record_id, subscription.id.as_str(), effective_at, members).execute(&self.pool).await.map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ let encoded = record_id.to_string();+ next["metadata"][APPLIED_KEY] = encoded.clone().into();+ let request = ScheduleUpdate {+ phases: vec![current, next],+ proration_behavior: proration,+ end_behavior: "release",+ metadata: HashMap::from([+ (OWNED_KEY.to_string(), "1".to_string()),+ (PENDING_KEY.to_string(), encoded),+ ]),+ };+ self.client+ .post_form::<stripe::SubscriptionSchedule, _>(+ &format!("/subscription_schedules/{}", schedule.id),+ &request,+ )+ .await+ .map_err(storage)?;+ Ok(())+ }+/// Creates a new instance of CustomerRepositoryImpl- pub fn new(stripe_client: stripe::Client, seat_prices: SeatPrices) -> Self {+ pub fn new(stripe_client: stripe::Client, seat_prices: SeatPrices, pool: sqlx::PgPool) -> Self {+ // Guards hold connections across provider and repository calls. Separate+ // pools keep waiters from exhausting the pool those calls need, and keep+ // the team -> subscription lock order from exhausting its own capacity.+ let lock_pool = || {+ sqlx::postgres::PgPoolOptions::new()+ .max_connections(pool.options().get_max_connections().min(4))+ .idle_timeout(std::time::Duration::from_secs(60))+ .connect_lazy_with(+ pool.connect_options()+ .as_ref()+ .clone()+ .options([("lock_timeout", "30000")]),+ )+ };+ let team_locks = lock_pool();+ let subscription_locks = lock_pool();Self {client: Arc::new(stripe_client),seat_prices,+ pool,+ team_locks,+ subscription_locks,}}@@ -107,6 +313,57 @@ impl CustomerRepositoryImpl {subscription_id: &stripe::SubscriptionId,items: Vec<UpdateSubscriptionItems>,) -> Result<(), CustomerError> {+ let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])+ .await+ .map_err(storage)?;+ if let Some(schedule_id) = subscription.schedule.as_ref().map(|s| s.id()) {+ let schedule = stripe::SubscriptionSchedule::retrieve(&self.client, &schedule_id, &[])+ .await+ .map_err(storage)?;+ require_owned_schedule(&schedule)?;+ let pending = self.pending_changes(&schedule, &subscription).await?;+ if pending.at > subscription.current_period_start {+ let current = current_phase(&schedule, &subscription)?;+ let mut phase = phase_parameters(current)?;+ let mut quantities = subscription+ .items+ .data+ .iter()+ .filter_map(|i| {+ i.price+ .as_ref()+ .map(|p| (p.id.to_string(), i.quantity.unwrap_or(1)))+ })+ .collect::<HashMap<_, _>>();+ for update in &items {+ let price = update+ .price+ .clone()+ .or_else(|| {+ subscription+ .items+ .data+ .iter()+ .find(|i| Some(i.id.as_str()) == update.id.as_deref())+ .and_then(|i| i.price.as_ref())+ .map(|p| p.id.to_string())+ })+ .context("missing item price")?;+ if update.deleted == Some(true) {+ quantities.remove(&price);+ } else {+ quantities.insert(price, update.quantity.unwrap_or(1));+ }+ }+ replace_quantities(&mut phase, &quantities);+ return self+ .write_schedule(&schedule, &subscription, phase, pending, "always_invoice")+ .await;+ }+ // The scheduled phase already became effective. Release it before+ // an immediate upgrade; acknowledging old metadata cannot undo it.+ self.release_schedule(&schedule.id).await?;+ }let update_params = UpdateSubscription {items: Some(items),proration_behavior: Some(@@ -124,6 +381,52 @@ impl CustomerRepositoryImpl {}impl CustomerRepository for CustomerRepositoryImpl {+ type TeamBillingGuard = sqlx::Transaction<'static, sqlx::Postgres>;++ async fn lock_team_billing(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<Self::TeamBillingGuard, CustomerError> {+ Self::billing_guard(&self.team_locks, &format!("team-billing:{team_id}")).await+ }++ async fn scheduled_seat_plan(+ &self,+ subscription: &stripe::SubscriptionId,+ schedule: &stripe::SubscriptionScheduleId,+ user: &MacroUserIdStr<'_>,+ ) -> Result<Option<ScheduledSeatPlan>, CustomerError> {+ Ok(self+ .read_scheduled_seat_plans(subscription, schedule)+ .await?+ .remove(user.as_ref()))+ }++ async fn pending_seat_plan(+ &self,+ id: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ ) -> Result<Option<ScheduledSeatPlan>, CustomerError> {+ Ok(self.pending_seat_plans(id).await?.remove(user.as_ref()))+ }++ async fn pending_seat_plans(+ &self,+ id: &stripe::SubscriptionId,+ ) -> Result<HashMap<String, ScheduledSeatPlan>, CustomerError> {+ let subscription = stripe::Subscription::retrieve(&self.client, id, &[])+ .await+ .map_err(storage)?;+ let Some(schedule) = subscription.schedule.as_ref() else {+ return Ok(HashMap::new());+ };+ let mut changes = self.read_scheduled_seat_plans(id, &schedule.id()).await?;+ changes.retain(|_, change| {+ change.effective_at.timestamp() > subscription.current_period_start+ });+ Ok(changes)+ }+#[tracing::instrument(skip(self), err)]async fn increment_seat_count(&self,@@ -131,6 +434,7 @@ impl CustomerRepository for CustomerRepositoryImpl {plan: SeatPlan,amount: u64,) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(subscription_id).await?;let items = self.get_seat_items(subscription_id).await?;let existing = items.get(&plan);let quantity = existing@@ -149,6 +453,7 @@ impl CustomerRepository for CustomerRepositoryImpl {plan: SeatPlan,amount: u64,) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(subscription_id).await?;let items = self.get_seat_items(subscription_id).await?;let Some(existing) = items.get(&plan) else {return Err(CustomerError::NoMatchingLineItem);@@ -175,6 +480,7 @@ impl CustomerRepository for CustomerRepositoryImpl {if from == to {return Ok(());}+ let _billing = self.subscription_guard(subscription_id).await?;// Make sure the target plan is sold before touching anything.self.seat_prices.price_id(to)?;@@ -192,11 +498,156 @@ impl CustomerRepository for CustomerRepositoryImpl {self.update_items(subscription_id, updates).await}+ async fn schedule_seat_plan(+ &self,+ id: &stripe::SubscriptionId,+ user: &MacroUserIdStr<'_>,+ plan: Option<SeatPlan>,+ ) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(id).await?;+ let subscription = stripe::Subscription::retrieve(&self.client, id, &[])+ .await+ .map_err(storage)?;+ let existing = if let Some(id) = subscription.schedule.as_ref().map(|s| s.id()) {+ let schedule = stripe::SubscriptionSchedule::retrieve(&self.client, &id, &[])+ .await+ .map_err(storage)?;+ require_owned_schedule(&schedule)?;+ Some(schedule)+ } else {+ None+ };+ if plan.is_none() && existing.is_none() {+ return Ok(());+ }+ let mut pending = if let Some(schedule) = existing.as_ref() {+ self.pending_changes(schedule, &subscription).await?+ } else {+ PendingChanges {+ at: subscription.current_period_end,+ members: HashMap::new(),+ }+ };+ if pending.at <= subscription.current_period_start {+ pending = PendingChanges {+ at: subscription.current_period_end,+ members: HashMap::new(),+ };+ }+ match plan {+ Some(SeatPlan::Premium) => {+ pending.members.insert(user.to_string(), SeatPlan::Premium);+ }+ Some(_) => return Err(CustomerError::PlanUnavailable(plan.unwrap())),+ None => {+ pending.members.remove(user.as_ref());+ }+ }+ if pending.members.is_empty() {+ if let Some(schedule) = existing {+ self.release_schedule(&schedule.id).await?;+ }+ return Ok(());+ }+ let schedule = match existing {+ Some(s) => s,+ None => {+ let mut create = stripe::CreateSubscriptionSchedule::new();+ create.from_subscription = Some(id.as_str());+ create.metadata = Some(HashMap::from([(OWNED_KEY.to_string(), "1".to_string())]));+ stripe::SubscriptionSchedule::create(&self.client, create)+ .await+ .map_err(storage)?+ }+ };+ let current = phase_parameters(current_phase(&schedule, &subscription)?)?;+ self.write_schedule(&schedule, &subscription, current, pending, "none")+ .await+ }++ async fn upgrade_personal_plan(+ &self,+ id: &stripe::SubscriptionId,+ plan: SeatPlan,+ ) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(id).await?;+ let subscription = stripe::Subscription::retrieve(&self.client, id, &[])+ .await+ .map_err(storage)?;+ // Both cancellation and the price replacement use this same guard.+ // Calling the public schedule method here would acquire it recursively.+ if let Some(schedule) = subscription.schedule.as_ref() {+ let schedule =+ stripe::SubscriptionSchedule::retrieve(&self.client, &schedule.id(), &[])+ .await+ .map_err(storage)?;+ require_owned_schedule(&schedule)?;+ self.release_schedule(&schedule.id).await?;+ }+ let item = subscription+ .items+ .data+ .iter()+ .find(|i| {+ i.price+ .as_ref()+ .is_some_and(|p| self.seat_prices.plan_for_price(p.id.as_str()).is_some())+ })+ .ok_or(CustomerError::NoMatchingLineItem)?;+ let params = UpdateSubscription {+ items: Some(vec![UpdateSubscriptionItems { id: Some(item.id.to_string()), price: Some(self.seat_prices.price_id(plan)?.to_string()), ..Default::default() }]),+ metadata: Some(HashMap::from([("macro_plan_change_at".to_string(), chrono::Utc::now().to_rfc3339()), (APPLIED_KEY.to_string(), String::new())])),+ proration_behavior: Some(stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice), ..Default::default()+ };+ stripe::Subscription::update(&self.client, id, params)+ .await+ .map_err(storage)?;+ Ok(())+ }++ async fn renewed_seat_plans(+ &self,+ id: &stripe::SubscriptionId,+ ) -> Result<Vec<(String, SeatPlan)>, CustomerError> {+ let subscription = stripe::Subscription::retrieve(&self.client, id, &[])+ .await+ .map_err(storage)?;+ let Some(encoded) = subscription+ .metadata+ .get(APPLIED_KEY)+ .filter(|s| !s.is_empty())+ else {+ return Ok(Vec::new());+ };+ let changes = self.read_pending(id.as_str(), encoded).await?;+ Ok(if subscription.current_period_start >= changes.at {+ changes.members.into_iter().collect()+ } else {+ Vec::new()+ })+ }++ async fn acknowledge_renewed_seat_plans(+ &self,+ id: &stripe::SubscriptionId,+ ) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(id).await?;+ let params = stripe::UpdateSubscription {+ metadata: Some(HashMap::from([(APPLIED_KEY.to_string(), String::new())])),+ ..Default::default()+ };+ stripe::Subscription::update(&self.client, id, params)+ .await+ .map_err(storage)?;+ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn cancel_subscription(&self,subscription_id: &stripe::SubscriptionId,) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(subscription_id).await?;// Cancelling is idempotent: a subscription that is already cancelled,// or that went away with its customer, needs nothing further.match stripe::Subscription::retrieve(&self.client, subscription_id, &[]).await {@@ -228,6 +679,7 @@ impl CustomerRepository for CustomerRepositoryImpl {team_id: &uuid::Uuid,team_owner_id: ¯o_user_id::user_id::MacroUserIdStr<'_>,) -> Result<(), CustomerError> {+ let _billing = self.subscription_guard(subscription_id).await?;let mut metadata = HashMap::new();metadata.insert("team_id".to_string(), team_id.to_string());metadata.insert("owner_id".to_string(), team_owner_id.to_string());@@ -264,3 +716,119 @@ impl CustomerRepository for CustomerRepositoryImpl {.ok_or(CustomerError::SubscriptionNotActive)}}++const OWNED_KEY: &str = "macro_plan_schedule";+const PENDING_KEY: &str = "macro_pending_seats";+const APPLIED_KEY: &str = "macro_renewed_seats";++#[derive(serde::Serialize, serde::Deserialize)]+struct PendingChanges {+ at: i64,+ members: HashMap<String, SeatPlan>,+}+#[derive(serde::Serialize)]+struct ScheduleUpdate<'a> {+ phases: Vec<serde_json::Value>,+ proration_behavior: &'a str,+ end_behavior: &'a str,+ metadata: HashMap<String, String>,+}+fn storage(error: stripe::StripeError) -> CustomerError {+ CustomerError::StorageLayerError(error.into())+}+fn require_owned_schedule(schedule: &stripe::SubscriptionSchedule) -> Result<(), CustomerError> {+ if schedule+ .metadata+ .as_ref()+ .and_then(|m| m.get(OWNED_KEY))+ .map(String::as_str)+ != Some("1")+ {+ return Err(CustomerError::StorageLayerError(anyhow::anyhow!(+ "subscription has an externally managed schedule"+ )));+ }+ Ok(())+}+fn current_phase<'a>(+ schedule: &'a stripe::SubscriptionSchedule,+ subscription: &stripe::Subscription,+) -> Result<&'a stripe::SubscriptionSchedulePhaseConfiguration, CustomerError> {+ schedule+ .phases+ .iter()+ .find(|p| {+ p.start_date <= subscription.current_period_start+ && p.end_date > subscription.current_period_start+ })+ .ok_or_else(|| {+ CustomerError::StorageLayerError(anyhow::anyhow!("missing current subscription phase"))+ })+}+// Stripe returns expanded objects where updates require IDs. Keep all phase+// settings (discounts, taxes, collection and payment settings), normalizing only+// expandable references and response-only item aliases.+fn phase_parameters(+ phase: &stripe::SubscriptionSchedulePhaseConfiguration,+) -> Result<serde_json::Value, CustomerError> {+ let mut value =+ serde_json::to_value(phase).map_err(|e| CustomerError::StorageLayerError(e.into()))?;+ normalize_references(&mut value);+ value["proration_behavior"] = "none".into();+ if value.get("metadata").is_none_or(serde_json::Value::is_null) {+ value["metadata"] = serde_json::json!({});+ }+ Ok(value)+}+fn normalize_references(value: &mut serde_json::Value) {+ match value {+ serde_json::Value::Object(map) if map.contains_key("id") => {+ *value = map["id"].clone();+ }+ serde_json::Value::Object(map) => {+ map.retain(|key, val| !val.is_null() && key != "plan");+ for value in map.values_mut() {+ normalize_references(value);+ }+ }+ serde_json::Value::Array(values) => {+ for value in values {+ normalize_references(value);+ }+ }+ _ => {}+ }+}+fn phase_quantities(phase: &serde_json::Value) -> Result<HashMap<String, u64>, CustomerError> {+ let items = phase["items"].as_array().context("missing phase items")?;+ items+ .iter()+ .map(|i| {+ Ok((+ i["price"]+ .as_str()+ .context("missing phase price")?+ .to_string(),+ i["quantity"].as_u64().unwrap_or(1),+ ))+ })+ .collect()+}+fn replace_quantities(phase: &mut serde_json::Value, quantities: &HashMap<String, u64>) {+ let old = phase["items"].as_array().cloned().unwrap_or_default();+ let mut items = quantities+ .iter()+ .filter(|(_, n)| **n > 0)+ .map(|(price, quantity)| {+ let mut item = old+ .iter()+ .find(|i| i["price"].as_str() == Some(price.as_str()))+ .cloned()+ .unwrap_or_else(|| serde_json::json!({"price": price}));+ item["quantity"] = (*quantity).into();+ item+ })+ .collect::<Vec<_>>();+ items.sort_by(|a, b| a["price"].as_str().cmp(&b["price"].as_str()));+ phase["items"] = items.into();+}diff --git a/crates/teams/src/outbound/customer_repo/test.rs b/crates/teams/src/outbound/customer_repo/test.rsnew file mode 100644index 0000000000..44592dde0a--- /dev/null+++ b/crates/teams/src/outbound/customer_repo/test.rs@@ -0,0 +1,707 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use serde::{Serialize, de::DeserializeOwned};+use serde_json::{Value, json};+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path},+};++fn subscription() -> stripe::Subscription {+ stripe::Subscription {+ id: "sub_team".parse().unwrap(),+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),+ status: stripe::SubscriptionStatus::Active,+ current_period_start: 1_800_000_000,+ current_period_end: 1_802_678_400,+ currency: stripe::Currency::USD,+ items: stripe::List {+ data: vec![+ item("si_max", "price_max", 2),+ item("si_pro", "price_pro", 2),+ ],+ has_more: false,+ total_count: Some(2),+ url: "/v1/subscription_items".into(),+ },+ ..Default::default()+ }+}+fn item(id: &str, price: &str, quantity: u64) -> stripe::SubscriptionItem {+ stripe::SubscriptionItem {+ id: id.parse().unwrap(),+ price: Some(stripe::Price {+ id: price.parse().unwrap(),+ product: Some(stripe::Expandable::Id("prod_test".parse().unwrap())),+ ..Default::default()+ }),+ quantity: Some(quantity),+ ..Default::default()+ }+}+fn schedule() -> stripe::SubscriptionSchedule {+ stripe::SubscriptionSchedule {+ id: "sub_sched_test".parse().unwrap(),+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),+ metadata: Some(HashMap::from([(OWNED_KEY.into(), "1".into())])),+ phases: vec![stripe::SubscriptionSchedulePhaseConfiguration {+ start_date: 1_800_000_000,+ end_date: 1_802_678_400,+ currency: stripe::Currency::USD,+ coupon: Some(stripe::Expandable::Id("coupon_existing".parse().unwrap())),+ default_payment_method: Some(stripe::Expandable::Id("pm_existing".parse().unwrap())),+ default_tax_rates: Some(vec![stripe::TaxRate {+ id: "txr_existing".parse().unwrap(),+ ..Default::default()+ }]),+ items: vec![+ stripe::SubscriptionScheduleConfigurationItem {+ price: stripe::Expandable::Id("price_max".parse().unwrap()),+ quantity: Some(2),+ ..Default::default()+ },+ stripe::SubscriptionScheduleConfigurationItem {+ price: stripe::Expandable::Id("price_pro".parse().unwrap()),+ quantity: Some(2),+ ..Default::default()+ },+ ],+ ..Default::default()+ }],+ ..Default::default()+ }+}+fn repo(server: &MockServer, pool: sqlx::PgPool) -> CustomerRepositoryImpl {+ CustomerRepositoryImpl::new(+ stripe::Client::from_url(server.uri().as_str(), "sk_test"),+ SeatPrices {+ premium: "price_pro".into(),+ max: Some("price_max".into()),+ },+ pool,+ )+}+async fn mount<T: Serialize + DeserializeOwned>(+ server: &MockServer,+ verb: &str,+ route: &str,+ value: &T,+ priority: u8,+) {+ Mock::given(method(verb))+ .and(path(route))+ .respond_with(ResponseTemplate::new(200).set_body_json(response(value)))+ .with_priority(priority)+ .mount(server)+ .await;+}+fn response<T: Serialize + DeserializeOwned>(value: &T) -> Value {+ let mut value = serde_json::to_value(value).unwrap();+ for _ in 0..256 {+ match serde_json::from_value::<T>(value.clone()) {+ Ok(_) => return value,+ Err(error) => {+ let message = error.to_string();+ let field = message+ .strip_prefix("missing field `")+ .and_then(|s| s.split_once('`'))+ .map(|(s, _)| s)+ .unwrap_or_else(|| panic!("invalid fixture: {message}"));+ fill_missing(&mut value, field);+ }+ }+ }+ panic!("invalid stripe fixture")+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pending_status_reads_only_the_callers_seat_from_an_active_owned_schedule(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let sub = subscription();+ let mut sched = schedule();+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 5).await;+ mount(&server, "POST", "/v1/subscription_schedules", &sched, 5).await;+ mount(+ &server,+ "POST",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 5,+ )+ .await;+ let repo = repo(&server, pool);+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ repo.schedule_seat_plan(&sub.id, &user, Some(SeatPlan::Premium))+ .await+ .unwrap();+ let requests = server.received_requests().await.unwrap();+ let update = form(+ requests+ .iter()+ .find(|r| {+ r.method.as_str() == "POST"+ && r.url.path() == "/v1/subscription_schedules/sub_sched_test"+ })+ .unwrap(),+ );+ sched.status = stripe::SubscriptionScheduleStatus::Active;+ sched.metadata.as_mut().unwrap().insert(+ PENDING_KEY.into(),+ update["metadata[macro_pending_seats]"].clone(),+ );+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 5,+ )+ .await;+ let pending = repo+ .scheduled_seat_plan(&sub.id, &sched.id, &user)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(pending.plan, SeatPlan::Premium);+ assert_eq!(pending.effective_at.timestamp(), sub.current_period_end);+ let mut attached = sub.clone();+ attached.schedule = Some(stripe::Expandable::Id(sched.id.clone()));+ mount(&server, "GET", "/v1/subscriptions/sub_team", &attached, 2).await;+ assert_eq!(+ repo.pending_seat_plan(&sub.id, &user).await.unwrap(),+ Some(pending)+ );+ attached.current_period_start = sub.current_period_end;+ mount(&server, "GET", "/v1/subscriptions/sub_team", &attached, 1).await;+ assert!(+ repo.pending_seat_plan(&sub.id, &user)+ .await+ .unwrap()+ .is_none()+ );+ let other = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ assert!(+ repo.scheduled_seat_plan(&sub.id, &sched.id, &other)+ .await+ .unwrap()+ .is_none()+ );++ sched.status = stripe::SubscriptionScheduleStatus::Released;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 2,+ )+ .await;+ assert!(+ repo.scheduled_seat_plan(&sub.id, &sched.id, &user)+ .await+ .unwrap()+ .is_none()+ );+ sched.status = stripe::SubscriptionScheduleStatus::Active;+ sched.metadata.as_mut().unwrap().remove(OWNED_KEY);+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ assert!(+ repo.scheduled_seat_plan(&sub.id, &sched.id, &user)+ .await+ .unwrap()+ .is_none()+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pending_seat_plans_reads_all_members_once_and_excludes_applied_or_untrusted_changes(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let mut sub = subscription();+ let mut sched = schedule();+ let id = macro_uuid::generate_uuid_v7();+ let at = chrono::DateTime::from_timestamp(sub.current_period_end, 0).unwrap();+ let members = json!({"macro|[email protected]": "premium", "macro|[email protected]": "premium"});+ sqlx::query!("INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, 'sub_team', $2, $3)", id, at, members).execute(&pool).await.unwrap();+ sched.status = stripe::SubscriptionScheduleStatus::Active;+ sched+ .metadata+ .as_mut()+ .unwrap()+ .insert(PENDING_KEY.into(), id.to_string());+ sub.schedule = Some(stripe::Expandable::Id(sched.id.clone()));+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions/sub_team"))+ .respond_with(ResponseTemplate::new(200).set_body_json(response(&sub)))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/subscription_schedules/sub_sched_test"))+ .respond_with(ResponseTemplate::new(200).set_body_json(response(&sched)))+ .expect(1)+ .mount(&server)+ .await;+ let repo = repo(&server, pool);+ let pending = repo.pending_seat_plans(&sub.id).await.unwrap();+ assert_eq!(pending.len(), 2);+ for user in ["macro|[email protected]", "macro|[email protected]"] {+ assert_eq!(+ pending[user],+ ScheduledSeatPlan {+ plan: SeatPlan::Premium,+ effective_at: at+ }+ );+ }+ server.verify().await;++ // An applied phase is not a cancellation control, even before its webhook arrives.+ server.reset().await;+ sub.current_period_start = sub.current_period_end;+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ assert!(repo.pending_seat_plans(&sub.id).await.unwrap().is_empty());++ server.reset().await;+ sub.current_period_start = subscription().current_period_start;+ sched.metadata.as_mut().unwrap().remove(OWNED_KEY);+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ assert!(repo.pending_seat_plans(&sub.id).await.unwrap().is_empty());++ // A schedule's record must also belong to the retrieved subscription.+ server.reset().await;+ sub.id = "sub_other".parse().unwrap();+ sched+ .metadata+ .as_mut()+ .unwrap()+ .insert(OWNED_KEY.into(), "1".into());+ mount(&server, "GET", "/v1/subscriptions/sub_other", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ assert!(repo.pending_seat_plans(&sub.id).await.is_err());++ server.reset().await;+ sub.schedule = None;+ mount(&server, "GET", "/v1/subscriptions/sub_other", &sub, 1).await;+ assert!(repo.pending_seat_plans(&sub.id).await.unwrap().is_empty());+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}++fn fill_missing(value: &mut Value, field: &str) {+ match value {+ Value::Object(map) => {+ map.entry(field).or_insert(Value::Null);+ for child in map.values_mut() {+ fill_missing(child, field);+ }+ }+ Value::Array(values) => {+ for child in values {+ fill_missing(child, field);+ }+ }+ _ => {}+ }+}+fn form(request: &wiremock::Request) -> HashMap<String, String> {+ url::form_urlencoded::parse(&request.body)+ .into_owned()+ .collect()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn downgrade_preserves_current_prices_and_terms_then_keep_max_releases_schedule(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let sub = subscription();+ let mut sched = schedule();+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 5).await;+ mount(&server, "POST", "/v1/subscription_schedules", &sched, 5).await;+ mount(+ &server,+ "POST",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 5,+ )+ .await;+ let repo = repo(&server, pool.clone());+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ repo.schedule_seat_plan(&sub.id, &user, Some(SeatPlan::Premium))+ .await+ .unwrap();+ let requests = server.received_requests().await.unwrap();+ let update = form(+ requests+ .iter()+ .find(|r| {+ r.method.as_str() == "POST"+ && r.url.path() == "/v1/subscription_schedules/sub_sched_test"+ })+ .unwrap(),+ );+ assert_eq!(update["proration_behavior"], "none");+ assert_eq!(+ update["phases[0][end_date]"],+ sub.current_period_end.to_string()+ );+ assert_eq!(update["phases[0][items][0][quantity]"], "2");+ assert_eq!(update["phases[1][items][0][quantity]"], "1");+ assert_eq!(update["phases[1][items][1][quantity]"], "3");+ assert_eq!(+ update["phases[1][start_date]"],+ sub.current_period_end.to_string()+ );+ assert_eq!(update["phases[1][coupon]"], "coupon_existing");+ assert_eq!(update["phases[1][default_payment_method]"], "pm_existing");+ assert_eq!(update["phases[1][default_tax_rates][0]"], "txr_existing");+ assert_eq!(update["end_behavior"], "release");+ assert!(+ !requests+ .iter()+ .any(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")+ );+ sched.metadata.as_mut().unwrap().insert(+ PENDING_KEY.into(),+ update[&format!("metadata[{PENDING_KEY}]")].clone(),+ );+ let mut sub = sub;+ sub.schedule = Some(stripe::Expandable::Id(sched.id.clone()));+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ mount(+ &server,+ "POST",+ "/v1/subscription_schedules/sub_sched_test/release",+ &sched,+ 1,+ )+ .await;+ repo.schedule_seat_plan(&sub.id, &user, None).await.unwrap();+ assert!(+ server+ .received_requests()+ .await+ .unwrap()+ .iter()+ .any(|r| r.url.path().ends_with("/release"))+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn unrelated_upgrade_keeps_other_seats_pending_and_prorates_only_current_phase(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let mut sub = subscription();+ let mut sched = schedule();+ let id = macro_uuid::generate_uuid_v7();+ let at = chrono::DateTime::from_timestamp(sub.current_period_end, 0).unwrap();+ let members = json!({"macro|[email protected]": "premium", "macro|[email protected]": "premium"});+ sqlx::query!("INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, 'sub_team', $2, $3)", id, at, members).execute(&pool).await.unwrap();+ sched+ .metadata+ .as_mut()+ .unwrap()+ .insert(PENDING_KEY.into(), id.to_string());+ sub.schedule = Some(stripe::Expandable::Id(sched.id.clone()));+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ mount(+ &server,+ "POST",+ "/v1/subscription_schedules/sub_sched_test",+ &sched,+ 1,+ )+ .await;+ repo(&server, pool)+ .move_seat(&sub.id, SeatPlan::Premium, SeatPlan::Max)+ .await+ .unwrap();+ let requests = server.received_requests().await.unwrap();+ let update = form(+ requests+ .iter()+ .find(|r| {+ r.method.as_str() == "POST"+ && r.url.path() == "/v1/subscription_schedules/sub_sched_test"+ })+ .unwrap(),+ );+ assert_eq!(update["proration_behavior"], "always_invoice");+ assert_eq!(update["phases[0][items][0][quantity]"], "3");+ assert_eq!(update["phases[0][items][1][quantity]"], "1");+ assert_eq!(update["phases[1][items][0][quantity]"], "1");+ assert_eq!(update["phases[1][items][1][quantity]"], "3");+ assert_eq!(update["phases[1][proration_behavior]"], "none");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn scheduled_members_are_returned_only_after_the_provider_renews(pool: sqlx::PgPool) {+ let server = MockServer::start().await;+ let mut sub = subscription();+ let id = macro_uuid::generate_uuid_v7();+ let at = chrono::DateTime::from_timestamp(sub.current_period_end, 0).unwrap();+ let members = json!({"macro|[email protected]": "premium"});+ sqlx::query!("INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, 'sub_team', $2, $3)", id, at, members).execute(&pool).await.unwrap();+ sub.metadata.insert(APPLIED_KEY.into(), id.to_string());+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 5).await;+ let repo = repo(&server, pool);+ assert!(repo.renewed_seat_plans(&sub.id).await.unwrap().is_empty());+ sub.current_period_start = sub.current_period_end;+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ assert_eq!(+ repo.renewed_seat_plans(&sub.id).await.unwrap(),+ vec![("macro|[email protected]".into(), SeatPlan::Premium)]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn personal_upgrade_replaces_the_existing_item_and_invoices_proration(pool: sqlx::PgPool) {+ let server = MockServer::start().await;+ let mut sub = subscription();+ sub.items.data = vec![item("si_personal", "price_pro", 1)];+ let schedule = schedule();+ sub.schedule = Some(stripe::Expandable::Id(schedule.id.clone()));+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;+ mount(+ &server,+ "GET",+ "/v1/subscription_schedules/sub_sched_test",+ &schedule,+ 1,+ )+ .await;+ mount(+ &server,+ "POST",+ "/v1/subscription_schedules/sub_sched_test/release",+ &schedule,+ 1,+ )+ .await;+ mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;+ repo(&server, pool)+ .upgrade_personal_plan(&sub.id, SeatPlan::Max)+ .await+ .unwrap();+ let requests = server.received_requests().await.unwrap();+ let update = form(+ requests+ .iter()+ .find(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")+ .unwrap(),+ );+ assert_eq!(update["items[0][id]"], "si_personal");+ assert_eq!(update["items[0][price]"], "price_max");+ assert_eq!(update["proration_behavior"], "always_invoice");+ let release = requests+ .iter()+ .position(|request| request.url.path().ends_with("/release"))+ .unwrap();+ let upgrade = requests+ .iter()+ .position(|request| {+ request.method.as_str() == "POST" && request.url.path() == "/v1/subscriptions/sub_team"+ })+ .unwrap();+ assert!(release < upgrade);+ assert!(+ chrono::DateTime::parse_from_rfc3339(&update["metadata[macro_plan_change_at]"]).is_ok()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn concurrent_instances_preserve_all_scheduled_members_and_seat_additions(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let mut sub = subscription();+ let sched = schedule();+ sub.schedule = Some(stripe::Expandable::Id(sched.id.clone()));+ let provider = Arc::new(std::sync::Mutex::new((sub, sched)));+ let read_sub = provider.clone();+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions/sub_team"))+ .respond_with(move |_: &wiremock::Request| {+ ResponseTemplate::new(200)+ .set_body_json(response(&read_sub.lock().unwrap().0))+ .set_delay(std::time::Duration::from_millis(30))+ })+ .mount(&server)+ .await;+ let read_schedule = provider.clone();+ Mock::given(method("GET"))+ .and(path("/v1/subscription_schedules/sub_sched_test"))+ .respond_with(move |_: &wiremock::Request| {+ ResponseTemplate::new(200).set_body_json(response(&read_schedule.lock().unwrap().1))+ })+ .mount(&server)+ .await;+ let write = provider.clone();+ Mock::given(method("POST"))+ .and(path("/v1/subscription_schedules/sub_sched_test"))+ .respond_with(move |request: &wiremock::Request| {+ let fields = form(request);+ let mut state = write.lock().unwrap();+ state.1.metadata.as_mut().unwrap().insert(+ PENDING_KEY.into(),+ fields["metadata[macro_pending_seats]"].clone(),+ );+ let original = state.1.phases[0].clone();+ state.1.phases = (0..2)+ .map(|phase_index| {+ let mut phase = original.clone();+ phase.items = (0..3)+ .filter_map(|index| {+ let price = fields+ .get(&format!("phases[{phase_index}][items][{index}][price]"))?;+ let quantity = fields+ [&format!("phases[{phase_index}][items][{index}][quantity]")]+ .parse()+ .unwrap();+ Some(stripe::SubscriptionScheduleConfigurationItem {+ price: stripe::Expandable::Id(price.parse().unwrap()),+ quantity: Some(quantity),+ ..Default::default()+ })+ })+ .collect();+ phase+ })+ .collect();+ state.0.items.data = state.1.phases[0]+ .items+ .iter()+ .map(|seat| {+ let price = seat.price.id();+ item(+ if price.as_str() == "price_max" {+ "si_max"+ } else {+ "si_pro"+ },+ price.as_str(),+ seat.quantity.unwrap(),+ )+ })+ .collect();+ ResponseTemplate::new(200).set_body_json(response(&state.1))+ })+ .mount(&server)+ .await;+ // Separate adapters (and lock pools) simulate independent service replicas.+ let one = repo(&server, pool.clone());+ let two = repo(&server, pool.clone());+ let seats = repo(&server, pool);+ let subscription = "sub_team".parse().unwrap();+ let first = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let second = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ let (a, b, c) = tokio::join!(+ one.schedule_seat_plan(&subscription, &first, Some(SeatPlan::Premium)),+ two.schedule_seat_plan(&subscription, &second, Some(SeatPlan::Premium)),+ seats.increment_seat_count(&subscription, SeatPlan::Premium, 1),+ );+ a.unwrap();+ b.unwrap();+ c.unwrap();+ let schedule = provider.lock().unwrap().1.clone();+ let sub = provider.lock().unwrap().0.clone();+ let pending = one.pending_changes(&schedule, &sub).await.unwrap();+ assert_eq!(pending.members.len(), 2);+ assert_eq!(+ pending.members.get(first.as_ref()),+ Some(&SeatPlan::Premium)+ );+ assert_eq!(+ pending.members.get(second.as_ref()),+ Some(&SeatPlan::Premium)+ );+ assert_eq!(+ phase_quantities(&phase_parameters(&schedule.phases[0]).unwrap()).unwrap(),+ HashMap::from([("price_max".into(), 2), ("price_pro".into(), 3)])+ );+ assert_eq!(+ phase_quantities(&phase_parameters(&schedule.phases[1]).unwrap()).unwrap(),+ HashMap::from([("price_pro".into(), 5)])+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn cancelling_a_guard_holder_releases_the_subscription_for_another_instance(+ pool: sqlx::PgPool,+) {+ let server = MockServer::start().await;+ let holder = repo(&server, pool.clone());+ let waiter = repo(&server, pool);+ let locked = Arc::new(tokio::sync::Notify::new());+ let acquired = locked.clone();+ let task = tokio::spawn(async move {+ let id = "sub_team".parse().unwrap();+ let _guard = holder.subscription_guard(&id).await.unwrap();+ acquired.notify_one();+ std::future::pending::<()>().await;+ });+ locked.notified().await;+ let id = "sub_team".parse().unwrap();+ let mut waiting = Box::pin(waiter.subscription_guard(&id));+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(40), &mut waiting)+ .await+ .is_err()+ );+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ let _guard = tokio::time::timeout(std::time::Duration::from_secs(2), waiting)+ .await+ .unwrap()+ .unwrap();+}diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rsindex 11aac40715..4be6c05d65 100644--- a/crates/teams/src/outbound/team_repo.rs+++ b/crates/teams/src/outbound/team_repo.rs@@ -1125,7 +1125,11 @@ impl TeamRepository for TeamRepositoryImpl {}).collect();- Ok(TeamWithMembers { team, members })+ Ok(TeamWithMembers {+ team,+ members,+ scheduled_seat_plans: None,+ })}#[tracing::instrument(skip(self), err)]diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex d9c38069c6..c9e2947b61 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2416,7 +2416,18 @@ editing. **Usage Credits** shows the dollar balance and `Add more`, which opens**Need more usage?** with `$25` / `$50` / `$100` / `Other`. Supported amountsredirect to Stripe Checkout; unsupported custom amounts are disabled. Freeaccounts see `View plans` instead of purchase or reload controls; paid team-members who are not the payer cannot manage billing.+members who are not the payer see only “Usage credits are managed by your team.”+Their credit balance and automatic reload row are hidden, with no+credit-purchase action.+Team owners who pay for their team's seats manage the shared credit balance and+automatic reload here in Usage, including purchases, balance thresholds, the+monthly reload cap, and payment methods. Team payers see **Team Usage+Credits**, “Credits are shared by your entire team.” and **Shared team balance**.+The purchase and auto-reload dialogs also identify the team-wide credit balance.+Team settings manages seats. Included+usage remains per seat: the owner's Monthly limit meter describes their own+usage, not the sum of the team's allowances. Team payers with a finite+allowance see “This is your personal monthly usage limit.” beneath the meter.Unlimited enterprise plans show `Unlimited` and do not offer credit purchasesor automatic reload. The development paid-plan preview can still displaythose controls, with purchases disabled.@@ -2428,9 +2439,11 @@ and the automatic-charge warning. The dialog saves for paid payers:`Turn on auto-reload` enables automatic credit purchases with those thresholds,`Save` updates them while on, and `Turn off` disables automatic reload. The monthlylimit caps reload purchases per UTC calendar month. The **Automatic reload**-switch reflects the saved state. Paid team members who are not the payer see+switch reflects the saved state and is the billing opt-in indicator. Paid team+members who are not the payer see`Only the account that pays for this plan can change automatic reload.` and-cannot save. After a failed automatic reload the dialog shows `Your last+cannot save. After a failed automatic reload the Usage row shows+`Paused — payment failed` while preserving the enabled setting. The dialog shows `Your lastautomatic reload could not be charged. Update your payment method, then save totry again.`; saving retries. Extra usage is funded entirely by prepaid credits.If the reload budget runs out or payment fails, uncovered usage cannot trigger a@@ -2450,6 +2463,34 @@ Usage controls, including usage-limit dialogs. Dev tools remain interactive:Free and paid previews can be combined with this state, and `Reset preview`restores the normal dev view.+Local **Developer tools → Open Billing Lab** opens `/billing-lab.html`, a+standalone simulator with no login or billing API calls. Its 20 presets include+Max with a pending Pro downgrade, exhausted allowances, credits, payment+failures, team roles, loading, and errors. Select **Max → Pro at renewal**+to start with a scheduled downgrade, and choose **Advance to+renewal**: Max stays active until renewal, then Pro becomes active and included+usage resets. Billing displays the scheduled downgrade and effective date;+**Keep Max plan** cancels it and preserves the active plan and usage. The+timeline also offers **Cancel scheduled change**. Purchases open a simulated checkout with explicit completion;+**Fail the next billing request** enables error and retry checks. Scenario links+restore the preset, not edits. **Monthly reload limit reached** opens Usage with+a notice banner: **Monthly auto-reload $50 limit reached**, with **resets Nov 1**+on the right. **Adjust limit** opens Auto-Reload; **Add credits** opens credit purchase.+Manual credits do not count toward the monthly reload cap, which resets at the+UTC month boundary. Live Usage shows this same banner from the API's monthly+reload commitments and reset date, including when remaining cap room is below+the minimum reload charge. Paid/pending reloads and failed invoices that can+still collect count toward the cap. Older backends without these facts show no notice.+The **Teams** scenario group opens Usage directly. **Mixed-plan team owner**+previews shared credits and enabled reload for one Max and three Pro seats;+**Team credits exhausted**, **Team reload paused**, and **Team monthly reload+limit** exercise the owner's purchase, payment-recovery, and cap controls through+the same Usage dialogs. Credit purchases add to the shared balance, while the+included-usage meter remains scoped to the viewer's own seat. **Team-paid Max+member** previews the notice-only member view. The simulator does not meter+other members' activity or perform automatic charges.+See [Billing Lab setup and boundaries](../../apps/web/src/features/billing-lab/README.md).+`Billing` shows the current plan and `Manage`. Free users see separate Pro(`Get Pro`) and Max (`Get Max`) cards, side by side when the panel is wide enoughand stacked on narrow panels. The Pro card shows `Free for one month!` for Free@@ -2460,7 +2501,7 @@ Ineligible accounts see the rejection reason and are not silently charged.`per seat / month` for team accounts. Each card puts its button beside the price when wide enough and belowthe price when narrow. Free lists 2 connected email accounts; Pro and Max listunlimited connected email accounts. Pro users see a Max card (`Upgrade to Max`); Max-users see a Pro card (`Switch to Pro`). Cards appear only for users who can+users keep their current plan. Cards appear only for users who canmanage their subscription. Team-paid members see no plan options, includingon Free seats. Member options stay hidden until the billing summary confirmsthey pay for their own seat. On a team, a plan change moves only the viewer's@@ -2488,9 +2529,16 @@ with the selection preserved. `Manage plan` returns to the selected Billing prevthe signed-in account. State is not persisted and resets on leaving Billing.These controls are excluded from deployed builds, including dev.macro.com.+Billing shows the current billing period end and any scheduled downgrade date.+Max stays active until renewal; **Keep Max plan** cancels a pending downgrade+without resetting usage. Failed renewal-detail reads offer **Try again**.+Team members who cannot manage billing see the notice without its action.+`Team` (members list; on a paid team each row shows the seat's plan,-and admins/owners can move a seat between Premium and Max with the `Seat plan`-menu; moves are prorated at once). CRM (enable/disable; once enabled, a `Deal stages` section+and admins/owners can move a seat between Pro and Max with the `Seat plan`+menu; Max upgrades are immediate and prorated, Pro downgrades start at renewal.+**Keep Max** appears only for a confirmed pending downgrade and cancels it;+failed scheduled-plan reads offer **Try again**). CRM (enable/disable; once enabled, a `Deal stages` sectionwith `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/downbuttons on touch), delete, `Add stage`, `Reset to defaults`, and `Closed stages`checkboxes, editable by the role set as `edit_stages_role`)diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex 6942877332..8199dc987b 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex a293127c15..cc654e985e 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -934,15 +934,16 @@ export class Sdk extends HeyApiClient {}/**- * Moves the caller's own seat between paid plans.- *- * On a team billed per seat this moves only the caller's seat (team admins- * and the owner may do so; teammates' seats are managed from team- * settings). Members of a free team, and solo subscribers, get the price on- * their own subscription's seat item swapped. The proration is invoiced- * immediately either way; roles and the AI allowance follow at once on a- * team and from the `customer.subscription.updated` webhook for a personal- * subscription.+ * Read subscription state for the authenticated user's seat.+ */+ public getSubscriptionStatus<ThrowOnError extends boolean = false>(options?: Options<GetSubscriptionStatusData, ThrowOnError>): RequestResult<GetSubscriptionStatusResponses, GetSubscriptionStatusErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<GetSubscriptionStatusResponses, GetSubscriptionStatusErrors, ThrowOnError>({ url: '/user/stripe/plan', ...options });+ }++ /**+ * Changes the caller's paid plan. Upgrades are prorated immediately;+ * downgrades retain the active plan until renewal. Selecting the active plan+ * cancels a pending downgrade without charging or resetting usage.*/public changePlan<ThrowOnError extends boolean = false>(options: Options<ChangePlanData, ThrowOnError>): RequestResult<ChangePlanResponses, ChangePlanErrors, ThrowOnError> {return (options.client ?? this.client).post<ChangePlanResponses, ChangePlanErrors, ThrowOnError>({diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex f885205646..5eba0e4d66 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -35,6 +35,25 @@ export type AutoReloadDefaults = {target_balance_cents: number;};+/**+ * Calendar-month commitments that consume the payer's automatic reload cap.+ */+export type AutoReloadMonthlyBudget = {+ /**+ * Reloads paid, pending, or failed with an invoice that can still collect.+ * Customer cents; manual credit purchases do not count.+ */+ committed_cents: number;+ /**+ * Remaining cap cannot fund the minimum automatic reload charge.+ */+ limit_reached: boolean;+ /**+ * Start of the next UTC calendar month, independently of subscription renewal.+ */+ resets_at: string;+};+/*** The payer's automatic reload settings, as shown in Billing settings.*/@@ -47,6 +66,7 @@ export type AutoReloadSnapshot = {* Reload once the effective balance drops below this, in customer cents.*/minimum_balance_cents: number;+ monthly_budget?: null | AutoReloadMonthlyBudget;/*** Most reloaded per UTC calendar month, in customer cents. `null` when* there is no limit.@@ -1349,6 +1369,20 @@ export type ResendFusionauthVerifyUserEmailRequest = {email: string;};+/**+ * A seat's future plan in the subscription's currently attached schedule.+ */+export type ScheduledSeatPlan = {+ /**+ * Provider-confirmed time when the future phase starts.+ */+ effectiveAt: string;+ /**+ * Plan that takes effect at renewal.+ */+ plan: SeatPlan;+};+/*** The paid plan a seat is billed at. Every member of a paying team has one;* a team may mix them, and its Stripe subscription carries one seat item per@@ -1397,6 +1431,17 @@ export type StripeSessionResponse = {url: string;};+/**+ * Current renewal and scheduled change; empty for accounts without a subscription.+ */+export type SubscriptionStatus = {+ /**+ * Provider-confirmed subscription renewal date.+ */+ renewalDate?: string | null;+ scheduledChange?: null | ScheduledSeatPlan;+};+/*** The Team struct*/@@ -1514,6 +1559,13 @@ export type TeamWithMembers = {* The members of the team*/members: Array<TeamMember>;+ /**+ * Provider-confirmed pending seat changes, keyed by member user ID.+ * Only available to paid-team admins and owners; empty means no pending changes.+ */+ scheduled_seat_plans?: {+ [key: string]: ScheduledSeatPlan;+ } | null;/*** The team*/@@ -1603,6 +1655,10 @@ export type UsageSnapshot = {* Shared payer credits already applied to this period, in customer cents.*/credits_consumed_cents: number;+ /**+ * Whether prepaid credits belong to the team, including a team with one seat.+ */+ credits_shared_with_team: boolean;/*** Included AI for this user's seat this period, in cents at provider cost.*/@@ -3710,6 +3766,30 @@ export type CreateCheckoutSessionV2Responses = {export type CreateCheckoutSessionV2Response = CreateCheckoutSessionV2Responses[keyof CreateCheckoutSessionV2Responses];+export type GetSubscriptionStatusData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/user/stripe/plan';+};++export type GetSubscriptionStatusErrors = {+ 401: ErrorResponse;+ /**+ * More than one active subscription+ */+ 409: ErrorResponse;+ 500: ErrorResponse;+};++export type GetSubscriptionStatusError = GetSubscriptionStatusErrors[keyof GetSubscriptionStatusErrors];++export type GetSubscriptionStatusResponses = {+ 200: SubscriptionStatus;+};++export type GetSubscriptionStatusResponse = GetSubscriptionStatusResponses[keyof GetSubscriptionStatusResponses];+export type ChangePlanData = {body: ChangePlanRequest;path?: never;@@ -3735,7 +3815,7 @@ export type ChangePlanErrors = {*/404: ErrorResponse;/**- * Already on this plan, or more than one active subscription+ * More than one active subscription*/409: ErrorResponse;500: ErrorResponse;diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 23c9831b11..2ea9d10496 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -4630,10 +4630,56 @@}},"/user/stripe/plan": {+ "get": {+ "tags": ["user::stripe::subscription_status"],+ "summary": "Read subscription state for the authenticated user's seat.",+ "operationId": "get_subscription_status",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubscriptionStatus"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "More than one active subscription",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },"post": {"tags": ["user::stripe::change_plan"],- "summary": "Moves the caller's own seat between paid plans.",- "description": "On a team billed per seat this moves only the caller's seat (team admins\nand the owner may do so; teammates' seats are managed from team\nsettings). Members of a free team, and solo subscribers, get the price on\ntheir own subscription's seat item swapped. The proration is invoiced\nimmediately either way; roles and the AI allowance follow at once on a\nteam and from the `customer.subscription.updated` webhook for a personal\nsubscription.",+ "summary": "Changes the caller's paid plan. Upgrades are prorated immediately;\ndowngrades retain the active plan until renewal. Selecting the active plan\ncancels a pending downgrade without charging or resetting usage.","operationId": "change_plan","requestBody": {"content": {@@ -4697,7 +4743,7 @@}},"409": {- "description": "Already on this plan, or more than one active subscription",+ "description": "More than one active subscription","content": {"application/json": {"schema": {@@ -4874,6 +4920,27 @@}}},+ "AutoReloadMonthlyBudget": {+ "type": "object",+ "description": "Calendar-month commitments that consume the payer's automatic reload cap.",+ "required": ["committed_cents", "resets_at", "limit_reached"],+ "properties": {+ "committed_cents": {+ "type": "integer",+ "format": "int64",+ "description": "Reloads paid, pending, or failed with an invoice that can still collect.\nCustomer cents; manual credit purchases do not count."+ },+ "limit_reached": {+ "type": "boolean",+ "description": "Remaining cap cannot fund the minimum automatic reload charge."+ },+ "resets_at": {+ "type": "string",+ "format": "date-time",+ "description": "Start of the next UTC calendar month, independently of subscription renewal."+ }+ }+ },"AutoReloadSnapshot": {"type": "object","description": "The payer's automatic reload settings, as shown in Billing settings.",@@ -4893,6 +4960,17 @@"format": "int64","description": "Reload once the effective balance drops below this, in customer cents."},+ "monthly_budget": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AutoReloadMonthlyBudget",+ "description": "Present for paid finite accounts with a configured monthly cap."+ }+ ]+ },"monthly_spend_limit_cents": {"type": ["integer", "null"],"format": "int64",@@ -6561,6 +6639,22 @@}}},+ "ScheduledSeatPlan": {+ "type": "object",+ "description": "A seat's future plan in the subscription's currently attached schedule.",+ "required": ["plan", "effectiveAt"],+ "properties": {+ "effectiveAt": {+ "type": "string",+ "format": "date-time",+ "description": "Provider-confirmed time when the future phase starts."+ },+ "plan": {+ "$ref": "#/components/schemas/SeatPlan",+ "description": "Plan that takes effect at renewal."+ }+ }+ },"SeatPlan": {"type": "string","description": "The paid plan a seat is billed at. Every member of a paying team has one;\na team may mix them, and its Stripe subscription carries one seat item per\nplan in use.",@@ -6618,6 +6712,28 @@}}},+ "SubscriptionStatus": {+ "type": "object",+ "description": "Current renewal and scheduled change; empty for accounts without a subscription.",+ "properties": {+ "renewalDate": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Provider-confirmed subscription renewal date."+ },+ "scheduledChange": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ScheduledSeatPlan",+ "description": "Future downgrade for the caller's seat, if still pending."+ }+ ]+ }+ }+ },"Team": {"type": "object","description": "The Team struct",@@ -6780,6 +6896,16 @@},"description": "The members of the team"},+ "scheduled_seat_plans": {+ "type": ["object", "null"],+ "description": "Provider-confirmed pending seat changes, keyed by member user ID.\nOnly available to paid-team admins and owners; empty means no pending changes.",+ "additionalProperties": {+ "$ref": "#/components/schemas/ScheduledSeatPlan"+ },+ "propertyNames": {+ "type": "string"+ }+ },"team": {"$ref": "#/components/schemas/Team","description": "The team"@@ -6864,6 +6990,7 @@"used_cents","credits_consumed_cents","credit_balance_cents",+ "credits_shared_with_team","overage_enabled","overage_limit_cents","overage_charged_cents",@@ -6902,6 +7029,10 @@"format": "int64","description": "Shared payer credits already applied to this period, in customer cents."},+ "credits_shared_with_team": {+ "type": "boolean",+ "description": "Whether prepaid credits belong to the team, including a team with one seat."+ },"included_cents": {"type": "integer","format": "int64",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 93c076d472..2c717c73df 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -75,6 +75,8 @@ export const authExcluded = ['getLegacyUserPermissions','getPermissions','getReferralCode',+ // Renewal and scheduled-plan details are part of the app's billing settings.+ 'getSubscriptionStatus','getTeamInvites','getUserInvites','getUserLinkExists',diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex b7edd1060b..952816e962 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -13,6 +13,8 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/billing-lab/components/**+ - apps/web/src/features/paywall/components/ai-usage-limit-dialog*- apps/web/src/features/calendar-team/components/**- apps/web/src/features/tasks-view/components/task-board*- apps/web/src/features/routines/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex bce50334bd..3789eb0ceb 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/billing-lab/core/**- apps/web/src/features/calendar-team/core/**- apps/web/src/features/tasks-view/core/task-board*- apps/web/src/features/routines/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 3c6abf064f..32b8e42ea2 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/billing-lab/queries/**+ - apps/web/src/features/billing-lab/primitives/**- apps/web/src/features/calendar-team/queries/**- apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/tasks-view/queries/task-board*diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex c1369a691b..0a784cedd1 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -15,6 +15,13 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/billing-lab/context/**+ - apps/web/src/features/billing-lab/queries/**+ - apps/web/src/features/billing-lab/primitives/**+ - apps/web/src/features/billing-lab/components/**+ - apps/web/src/features/billing-lab/views/**+ - apps/web/src/features/settings/context/billing-context.ts+ - apps/web/src/features/settings/views/billing-settings*- apps/web/src/features/calendar-team/queries/**- apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/calendar-team/components/**diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex 34692c9613..2ed34fed53 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -13,6 +13,8 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/billing-lab/components/**+ - apps/web/src/features/paywall/components/ai-usage-limit-dialog*- apps/web/src/features/calendar-team/components/**- apps/web/src/features/tasks-view/components/task-board*- apps/web/src/features/routines/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 095c9a521a..124415ab0b 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/billing-lab/core/**- apps/web/src/features/calendar-team/core/**- apps/web/src/features/tasks-view/core/task-board*- apps/web/src/features/routines/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex 4c1af3e60c..0f9ef0bba0 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/billing-lab/queries/**+ - apps/web/src/features/billing-lab/primitives/**- apps/web/src/features/calendar-team/queries/**- apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/tasks-view/queries/task-board*diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex d584e29829..eb48b11366 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -15,6 +15,13 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/billing-lab/context/**+ - apps/web/src/features/billing-lab/queries/**+ - apps/web/src/features/billing-lab/primitives/**+ - apps/web/src/features/billing-lab/components/**+ - apps/web/src/features/billing-lab/views/**+ - apps/web/src/features/settings/context/billing-context.ts+ - apps/web/src/features/settings/views/billing-settings*- apps/web/src/features/calendar-team/queries/**- apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/calendar-team/components/**diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex f6bf060d41..0ab56b82e2 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -92,6 +92,17 @@ pub(crate) type AiBillingServiceType = ai_billing::domain::BillingServiceImpl<ai_billing::outbound::StripePaymentGateway,>;+pub(crate) type SubscriptionStatusServiceType =+ crate::service::subscription_status::SubscriptionStatusService<+ ai_billing::outbound::RolesTeamsEntitlementSource<+ UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,+ teams::outbound::team_repo::TeamRepositoryImpl,+ >,+ crate::outbound::subscription_plan::StripePlanGateway<+ teams::outbound::customer_repo::CustomerRepositoryImpl,+ >,+ >;+pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<teams::outbound::team_repo::TeamRepositoryImpl,teams::outbound::customer_repo::CustomerRepositoryImpl,@@ -152,6 +163,14 @@ pub(crate) struct ApiContext {pub codex_connection: Option<Arc<dyn codex_connection::domain::ConnectionService>>,pub macro_cache_client: Arc<MacroCache>,pub stripe_client: Arc<stripe::Client>,+ pub subscription_status: Arc<SubscriptionStatusServiceType>,+ pub subscription_plan: Arc<+ crate::service::subscription_plan::PlanService<+ crate::outbound::subscription_plan::StripePlanGateway<+ teams::outbound::customer_repo::CustomerRepositoryImpl,+ >,+ >,+ >,pub subscription_checkout: Arc<crate::service::subscription_checkout::CheckoutService<crate::outbound::subscription_checkout::StripeCheckoutGateway<GtmInviteServiceType>,diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex 7fdd1b2e8f..8706f14603 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -141,6 +141,7 @@ use model::user::{user::stripe::create_checkout_session_v2::create_checkout_session,user::stripe::create_portal_session::create_portal_session,user::stripe::change_plan::change_plan,+ user::stripe::subscription_status::subscription_status,/// /ai-billingai_billing::inbound::axum_router::get_summary_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,diff --git a/services/authentication_service/src/api/user.rs b/services/authentication_service/src/api/user.rsindex 6d272320ab..c6a455672e 100644--- a/services/authentication_service/src/api/user.rs+++ b/services/authentication_service/src/api/user.rs@@ -58,7 +58,11 @@ fn router_with_auth() -> Router<ApiContext> {"/stripe/portal",post(stripe::create_portal_session::create_portal_session),)- .route("/stripe/plan", post(stripe::change_plan::change_plan))+ .route(+ "/stripe/plan",+ post(stripe::change_plan::change_plan)+ .get(stripe::subscription_status::subscription_status),+ ).route("/legacy_user_permissions",get(get_legacy_user_permissions::handler),diff --git a/services/authentication_service/src/api/user/stripe/change_plan.rs b/services/authentication_service/src/api/user/stripe/change_plan.rsindex f9e09cc4de..e6b1adf9f3 100644--- a/services/authentication_service/src/api/user/stripe/change_plan.rs+++ b/services/authentication_service/src/api/user/stripe/change_plan.rs@@ -29,15 +29,9 @@ pub struct ChangePlanResponse {pub plan: PaidPlan,}-/// Moves the caller's own seat between paid plans.-///-/// On a team billed per seat this moves only the caller's seat (team admins-/// and the owner may do so; teammates' seats are managed from team-/// settings). Members of a free team, and solo subscribers, get the price on-/// their own subscription's seat item swapped. The proration is invoiced-/// immediately either way; roles and the AI allowance follow at once on a-/// team and from the `customer.subscription.updated` webhook for a personal-/// subscription.+/// Changes the caller's paid plan. Upgrades are prorated immediately;+/// downgrades retain the active plan until renewal. Selecting the active plan+/// cancels a pending downgrade without charging or resetting usage.#[utoipa::path(post,path = "/user/stripe/plan",@@ -49,7 +43,7 @@ pub struct ChangePlanResponse {(status = 402, description = "The team has no active subscription", body = ErrorResponse),(status = 403, description = "Only team admins change plans on a team", body = ErrorResponse),(status = 404, description = "No active subscription", body = ErrorResponse),- (status = 409, description = "Already on this plan, or more than one active subscription", body = ErrorResponse),+ (status = 409, description = "More than one active subscription", body = ErrorResponse),(status = 500, body = ErrorResponse),))]@@ -92,73 +86,6 @@ pub async fn change_plan(}}- let stripe_customer_id = macro_db_client::user::get::get_stripe_customer_id_by_user_id(- &ctx.db,- &user.authorization.user.macro_user_id,- )- .await?- .ok_or(StripeOperationError::MissingStripeId)?;- let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;-- let mut list_subscriptions = stripe::ListSubscriptions::new();- list_subscriptions.customer = Some(customer_id);- list_subscriptions.limit = Some(10);- let subscriptions = stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;-- // Only this customer's own seat: a team subscription on the same customer- // (the caller owns a team) carries `team_id` and is repriced per seat- // from team settings, never here. Two live personal subscriptions (a- // checkout raced the webhook that cancels duplicates) is ambiguous, and- // repricing whichever Stripe listed first could hit the one about to be- // cancelled; refuse rather than guess.- let mut personal = subscriptions.data.into_iter().filter(|sub| {- !sub.metadata.contains_key("team_id")- && matches!(- sub.status,- stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing- )- });- let subscription = personal- .next()- .ok_or(StripeOperationError::NoSubscription)?;- if personal.next().is_some() {- return Err(StripeOperationError::AmbiguousSubscription);- }-- let seat_prices = ctx.stripe_prices.seat_price_ids();- let seat_item = subscription- .items- .data- .iter()- .find(|item| {- item.price- .as_ref()- .is_some_and(|price| seat_prices.iter().any(|id| *id == price.id.as_str()))- })- .ok_or(StripeOperationError::NoSubscription)?;-- let current_plan = seat_item- .price- .as_ref()- .and_then(|price| ctx.stripe_prices.plan_for_price(price.id.as_str()))- .ok_or(StripeOperationError::NoSubscription)?;- if current_plan == req.plan {- return Err(StripeOperationError::AlreadyOnPlan);- }-- let target_price = ctx.stripe_prices.price_id(req.plan)?.to_string();- let params = stripe::UpdateSubscription {- items: Some(vec![stripe::UpdateSubscriptionItems {- id: Some(seat_item.id.to_string()),- price: Some(target_price),- ..Default::default()- }]),- proration_behavior: Some(- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,- ),- ..Default::default()- };- stripe::Subscription::update(&ctx.stripe_client, &subscription.id, params).await?;-- Ok(Json(ChangePlanResponse { plan: req.plan }))+ let plan = ctx.subscription_plan.change(user_id, req.plan).await?;+ Ok(Json(ChangePlanResponse { plan }))}diff --git a/services/authentication_service/src/api/user/stripe/mod.rs b/services/authentication_service/src/api/user/stripe/mod.rsindex 1dd35eec4d..9f081b8c6b 100644--- a/services/authentication_service/src/api/user/stripe/mod.rs+++ b/services/authentication_service/src/api/user/stripe/mod.rs@@ -2,5 +2,6 @@ pub mod change_plan;pub mod create_checkout_session_v2;pub mod create_portal_session;mod shared;+pub mod subscription_status;pub use shared::{PaidPlan, StripeOperationError, StripePrices, StripeSessionResponse};diff --git a/services/authentication_service/src/api/user/stripe/shared.rs b/services/authentication_service/src/api/user/stripe/shared.rsindex 3b79750356..9f6aa2b90b 100644--- a/services/authentication_service/src/api/user/stripe/shared.rs+++ b/services/authentication_service/src/api/user/stripe/shared.rs@@ -29,20 +29,6 @@ pub struct StripePrices {}impl StripePrices {- /// The price to sell `plan` at.- pub fn price_id(&self, plan: PaidPlan) -> Result<&str, StripeOperationError> {- if !PaidPlan::PURCHASABLE.contains(&plan) {- return Err(StripeOperationError::PlanUnavailable);- }- match plan {- PaidPlan::Premium => Ok(&self.premium),- PaidPlan::Max => self- .max- .as_deref()- .ok_or(StripeOperationError::PlanUnavailable),- }- }-/// Which plan a subscription item's price belongs to, if any.pub fn plan_for_price(&self, price_id: &str) -> Option<PaidPlan> {if price_id == self.premium {@@ -54,11 +40,6 @@ impl StripePrices {}}- /// Every price that carries a seat item.- pub fn seat_price_ids(&self) -> Vec<String> {- self.seat_prices().all()- }-/// The same prices, for the teams crate's per-plan seat items.pub fn seat_prices(&self) -> SeatPrices {SeatPrices {@@ -101,8 +82,8 @@ pub enum StripeOperationError {NoSubscription,#[error("More than one active subscription; contact support to change plans")]AmbiguousSubscription,- #[error("Already on this plan")]- AlreadyOnPlan,+ #[error("Plan change gateway failed")]+ PlanChangeGateway(anyhow::Error),#[error("Only team admins can change plans on a team")]NotTeamAdmin,#[error("Team plan change failed")]@@ -116,6 +97,7 @@ impl IntoResponse for StripeOperationError {// user id, DB-stored Stripe customer id) — a parse failure is a server/auth// misconfiguration, not bad client input. Map to 500 so metrics don't blame callers.StripeOperationError::ParseId(_) => StatusCode::INTERNAL_SERVER_ERROR,+ StripeOperationError::PlanChangeGateway(_) => StatusCode::INTERNAL_SERVER_ERROR,StripeOperationError::DbErr(_) => StatusCode::INTERNAL_SERVER_ERROR,StripeOperationError::MissingStripeId => StatusCode::BAD_REQUEST,StripeOperationError::StripeIdParse(_) => StatusCode::INTERNAL_SERVER_ERROR,@@ -130,7 +112,6 @@ impl IntoResponse for StripeOperationError {StripeOperationError::PlanUnavailable => StatusCode::BAD_REQUEST,StripeOperationError::NoSubscription => StatusCode::NOT_FOUND,StripeOperationError::AmbiguousSubscription => StatusCode::CONFLICT,- StripeOperationError::AlreadyOnPlan => StatusCode::CONFLICT,StripeOperationError::NotTeamAdmin => StatusCode::FORBIDDEN,StripeOperationError::TeamPlanErr(e) => match e {SetTeamMemberPlanError::TeamNotPaying => StatusCode::PAYMENT_REQUIRED,@@ -139,7 +120,8 @@ impl IntoResponse for StripeOperationError {}SetTeamMemberPlanError::TeamError(_)| SetTeamMemberPlanError::CustomerError(_)- | SetTeamMemberPlanError::RolesError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ | SetTeamMemberPlanError::RolesError(_)+ | SetTeamMemberPlanError::UsageReset(_) => StatusCode::INTERNAL_SERVER_ERROR,},};(@@ -175,3 +157,16 @@ impl From<CheckoutError<StripeCheckoutError>> for StripeOperationError {}}}++impl From<crate::service::subscription_plan::PlanChangeError> for StripeOperationError {+ fn from(error: crate::service::subscription_plan::PlanChangeError) -> Self {+ use crate::service::subscription_plan::PlanChangeError as E;+ match error {+ E::MissingCustomer => Self::MissingStripeId,+ E::NoSubscription => Self::NoSubscription,+ E::AmbiguousSubscription => Self::AmbiguousSubscription,+ E::PlanUnavailable => Self::PlanUnavailable,+ E::Gateway(error) => Self::PlanChangeGateway(error),+ }+ }+}diff --git a/services/authentication_service/src/api/user/stripe/shared/test.rs b/services/authentication_service/src/api/user/stripe/shared/test.rsindex 69d4e3086f..565835e016 100644--- a/services/authentication_service/src/api/user/stripe/shared/test.rs+++ b/services/authentication_service/src/api/user/stripe/shared/test.rs@@ -1,4 +1,5 @@-use super::{PaidPlan, StripeOperationError, StripePrices};+use super::{PaidPlan, StripePrices};+use teams::domain::model::CustomerError;fn prices() -> StripePrices {StripePrices {@@ -10,10 +11,13 @@ fn prices() -> StripePrices {#[test]fn every_purchasable_plan_resolves_to_its_configured_price() {assert_eq!(- prices().price_id(PaidPlan::Premium).unwrap(),+ prices().seat_prices().price_id(PaidPlan::Premium).unwrap(),"price_premium");- assert_eq!(prices().price_id(PaidPlan::Max).unwrap(), "price_max");+ assert_eq!(+ prices().seat_prices().price_id(PaidPlan::Max).unwrap(),+ "price_max"+ );}#[test]@@ -23,10 +27,13 @@ fn max_is_unavailable_until_its_price_is_configured() {max: None,};assert!(matches!(- prices.price_id(PaidPlan::Max),- Err(StripeOperationError::PlanUnavailable)+ prices.seat_prices().price_id(PaidPlan::Max),+ Err(CustomerError::PlanUnavailable(PaidPlan::Max))));- assert_eq!(prices.price_id(PaidPlan::Premium).unwrap(), "price_premium");+ assert_eq!(+ prices.seat_prices().price_id(PaidPlan::Premium).unwrap(),+ "price_premium"+ );}#[test]diff --git a/services/authentication_service/src/api/user/stripe/subscription_status.rs b/services/authentication_service/src/api/user/stripe/subscription_status.rsnew file mode 100644index 0000000000..a7214058fb--- /dev/null+++ b/services/authentication_service/src/api/user/stripe/subscription_status.rs@@ -0,0 +1,33 @@+//! Authenticated adapter for the caller's renewal and pending seat change.++use axum::{Json, extract::State};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};++use super::StripeOperationError;+use crate::api::context::{ApiContext, AuthorizationService};+use crate::service::subscription_status::SubscriptionStatus;+use model::response::ErrorResponse;++/// Read subscription state for the authenticated user's seat.+#[utoipa::path(+ get,+ path = "/user/stripe/plan",+ operation_id = "get_subscription_status",+ responses(+ (status = 200, body = SubscriptionStatus),+ (status = 401, body = ErrorResponse),+ (status = 409, description = "More than one active subscription", body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user), err)]+pub async fn subscription_status(+ State(ctx): State<ApiContext>,+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+) -> Result<Json<SubscriptionStatus>, StripeOperationError> {+ Ok(Json(+ ctx.subscription_status+ .status(&user.authorization.user.macro_user_id)+ .await?,+ ))+}diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rsindex 9dc807edaf..285d4cb24b 100644--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs@@ -705,6 +705,15 @@ async fn handle_customer_subscription_event().await?;sync_personal_billing_period(ctx, &email, period, verified).await?;+ if let Some(change) =+ billing::personal_plan_change(billing_event, &ctx.stripe_prices, is_new_subscription)+ {+ let user = MacroUserIdStr::try_from_email(email.as_ref())?;+ ctx.ai_billing_service+ .change_plan(&user, change)+ .await+ .context("failed to reset upgraded personal seat usage")?;+ }// Track conversion events to GA and Meta (fire-and-forget)let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();@@ -818,7 +827,21 @@ async fn handle_team_subscription_event<'a>(// Restore stamps every member (owner included) with the team// subscriber role and the tier role of their own seat's plan.ctx.teams_service- .restore_permissions_for_team_members(team_id)+ .restore_permissions_for_team_members(+ team_id,+ tracking_data+ .is_new+ .then(|| {+ plan_sync.verified.first().map(|facts| {+ teams::domain::open_seat_release::SubscriptionStart {+ at: facts.event_at,+ period_start: facts.period.start,+ period_end: facts.period.end,+ }+ })+ })+ .flatten(),+ ).await?;sync_team_billing_period(ctx, &plan_sync).await?;diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rsindex 1c87acd274..adac312537 100644--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs@@ -24,6 +24,7 @@ pub(super) struct BillingEvent {pub id: String,pub at: DateTime<Utc>,pub object: Value,+ pub previous: Value,}impl BillingEvent {@@ -36,10 +37,66 @@ impl BillingEvent {.to_owned(),at: timestamp(&event["created"]).context("invalid verified event time")?,object: event["data"]["object"].clone(),+ previous: event["data"]["previous_attributes"].clone(),})}}+/// Translate a personal item's previous/current provider prices into domain facts.+/// Matching item ids avoids treating unrelated item edits as a seat upgrade.+pub(super) fn personal_plan_change(+ event: &BillingEvent,+ prices: &crate::api::user::stripe::StripePrices,+ initial: bool,+) -> Option<ai_billing::domain::plan_change::PlanChange> {+ let subscription = &event.object;+ if subscription["metadata"].get("team_id").is_some()+ || !matches!(subscription["status"].as_str(), Some("active" | "trialing"))+ {+ return None;+ }+ let previous = event.previous["items"]["data"].as_array();+ let items = subscription["items"]["data"].as_array()?;+ items.iter().find_map(|item| {+ let item_id = object_id(&item["id"])?;+ let from = if initial {+ ai_billing::PlanTier::Free+ } else {+ let old = previous?+ .iter()+ .find(|old| object_id(&old["id"]) == Some(item_id))?;+ prices.plan_for_price(object_id(&old["price"])?)?.into()+ };+ let to = prices.plan_for_price(object_id(&item["price"])?)?.into();+ let period = period(subscription, item)?;+ let previous_period = previous+ .and_then(|items| {+ items+ .iter()+ .find(|old| object_id(&old["id"]) == Some(item_id))+ })+ .and_then(|old| timestamp(&old["current_period_start"]))+ .or_else(|| timestamp(&event.previous["current_period_start"]));+ let renewed = previous_period.is_some_and(|start| start < period.start);+ let at = if renewed && !ai_billing::domain::plan_change::PlanChange::is_upgrade(from, to) {+ period.start+ } else {+ event.previous["metadata"]+ .get("macro_plan_change_at")+ .and_then(|_| subscription["metadata"]["macro_plan_change_at"].as_str())+ .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok())+ .map(|stamp| stamp.with_timezone(&Utc))+ .unwrap_or(event.at)+ };+ Some(ai_billing::domain::plan_change::PlanChange {+ from,+ to,+ at,+ period,+ })+ })+}+fn timestamp(value: &Value) -> Option<DateTime<Utc>> {DateTime::from_timestamp(value.as_i64()?, 0)}diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rsindex 9f158c9e57..d01a36c2e6 100644--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs@@ -1,4 +1,5 @@use super::*;+use ai_billing::PlanTier;use serde_json::json;#[tokio::test]@@ -79,6 +80,7 @@ fn event(object: Value) -> BillingEvent {id: "evt_paid".into(),at: DateTime::from_timestamp(1_800_000_010, 0).unwrap(),object,+ previous: Value::Null,}}@@ -159,3 +161,94 @@ fn newer_invoice_parent_fields_are_matched_by_item_and_price() {PeriodEvidence::Renewal);}++#[test]+fn personal_plan_change_retains_original_time_period_and_matching_item() {+ let prices = crate::api::user::stripe::StripePrices {+ premium: "price_40".into(),+ max: Some("price_max".into()),+ };+ let mut event = event(subscription());+ event.previous =+ json!({"items": {"data": [{"id": "si_verified", "price": {"id": "price_40"}}]}});+ event.object["items"]["data"][0]["price"]["id"] = json!("price_max");+ let change = personal_plan_change(&event, &prices, false).unwrap();+ assert!(change.resets_usage());+ assert_eq!(change.at, event.at);+ assert_eq!(change.period.start.timestamp(), 1_800_000_000);+ assert_eq!(change.period.end.timestamp(), 1_802_678_400);+ event.previous["items"]["data"][0]["id"] = json!("si_unrelated");+ assert!(personal_plan_change(&event, &prices, false).is_none());+ event.previous["items"]["data"][0]["id"] = json!("si_verified");+ event.object["metadata"]["team_id"] = json!("team");+ assert!(personal_plan_change(&event, &prices, false).is_none());+ event.object["metadata"] = json!({});+ event.object["status"] = json!("canceled");+ assert!(personal_plan_change(&event, &prices, false).is_none());+}++#[test]+fn personal_updates_without_previous_seat_price_do_not_reset_usage() {+ let prices = crate::api::user::stripe::StripePrices {+ premium: "price_40".into(),+ max: Some("price_max".into()),+ };+ assert!(personal_plan_change(&event(subscription()), &prices, false).is_none());+}++#[test]+fn personal_subscription_activation_resets_free_usage_for_both_paid_plans() {+ let prices = crate::api::user::stripe::StripePrices {+ premium: "price_40".into(),+ max: Some("price_max".into()),+ };+ for (price, tier) in [+ ("price_40", PlanTier::Premium),+ ("price_max", PlanTier::Max),+ ] {+ let mut event = event(subscription());+ event.object["items"]["data"][0]["price"]["id"] = json!(price);+ let change = personal_plan_change(&event, &prices, true).unwrap();+ assert_eq!(change.from, PlanTier::Free);+ assert_eq!(change.to, tier);+ assert!(change.resets_usage());+ assert_eq!(change.at, event.at);+ // Renewal snapshots don't prove a Free-to-paid activation.+ assert!(personal_plan_change(&event, &prices, false).is_none());+ }+}++#[test]+fn renewal_downgrade_belongs_to_the_new_period_start() {+ let prices = crate::api::user::stripe::StripePrices {+ premium: "price_40".into(),+ max: Some("price_max".into()),+ };+ let mut event = event(subscription());+ event.previous = json!({"current_period_start": 1_797_321_600, "items": {"data": [{"id": "si_verified", "price": {"id": "price_max"}}]}});+ let change = personal_plan_change(&event, &prices, false).unwrap();+ assert_eq!(change.from, PlanTier::Max);+ assert_eq!(change.to, PlanTier::Premium);+ assert_eq!(change.at, change.period.start);+}+#[test]+fn application_timestamp_distinguishes_immediate_changes_and_is_not_reused_by_portal_edits() {+ let prices = crate::api::user::stripe::StripePrices {+ premium: "price_40".into(),+ max: Some("price_max".into()),+ };+ let mut event = event(subscription());+ event.object["items"]["data"][0]["price"]["id"] = "price_max".into();+ let precise = event.at + chrono::Duration::microseconds(123_456);+ event.object["metadata"]["macro_plan_change_at"] = precise.to_rfc3339().into();+ event.previous = json!({"items": {"data": [{"id": "si_verified", "price": {"id": "price_40"}}]}, "metadata": {"macro_plan_change_at": null}});+ assert_eq!(+ personal_plan_change(&event, &prices, false).unwrap().at,+ precise+ );+ event.previous.as_object_mut().unwrap().remove("metadata");+ assert_eq!(+ personal_plan_change(&event, &prices, false).unwrap().at,+ event.at+ );+}diff --git a/services/authentication_service/src/outbound.rs b/services/authentication_service/src/outbound.rsindex aacc43bd2f..62ab73092c 100644--- a/services/authentication_service/src/outbound.rs+++ b/services/authentication_service/src/outbound.rs@@ -3,3 +3,5 @@pub mod subscription_checkout;pub mod team_owned_entity_cleanup;pub mod user_deletion;++pub mod subscription_plan;diff --git a/services/authentication_service/src/outbound/subscription_plan.rs b/services/authentication_service/src/outbound/subscription_plan.rsnew file mode 100644index 0000000000..7c64f8af91--- /dev/null+++ b/services/authentication_service/src/outbound/subscription_plan.rs@@ -0,0 +1,160 @@+//! Authenticated customer lookup and Stripe subscription translation.+use crate::service::subscription_plan::{+ PersonalSubscription, PlanAction, PlanChangeError, PlanGateway,+};+use crate::service::subscription_status::{SubscriptionPlanFacts, SubscriptionStatusGateway};+use ai_billing::domain::SubscriptionScope;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use std::sync::Arc;+use teams::domain::{+ customer_repo::CustomerRepository,+ model::{SeatPlan, SeatPrices},+};+/// Composed with the owning billing adapter through its domain port.+#[derive(Clone)]+pub struct StripePlanGateway<C> {+ db: PgPool,+ stripe: Arc<stripe::Client>,+ prices: SeatPrices,+ customer: C,+}+impl<C> StripePlanGateway<C> {+ /// Inject customer storage, provider client and billing domain capabilities.+ pub fn new(db: PgPool, stripe: Arc<stripe::Client>, prices: SeatPrices, customer: C) -> Self {+ Self {+ db,+ stripe,+ prices,+ customer,+ }+ }++ async fn subscription(+ &self,+ customer: &str,+ scope: SubscriptionScope,+ ) -> Result<Option<stripe::Subscription>, PlanChangeError> {+ let mut params = stripe::ListSubscriptions::new();+ params.customer = Some(customer.parse().map_err(anyhow::Error::from)?);+ params.limit = Some(100);+ let mut found = None;+ loop {+ let page = stripe::Subscription::list(&self.stripe, ¶ms)+ .await+ .map_err(anyhow::Error::from)?;+ let last = page.data.last().map(|s| s.id.clone());+ for subscription in page.data {+ let matches_scope = match scope {+ SubscriptionScope::Personal => !subscription.metadata.contains_key("team_id"),+ SubscriptionScope::Team { team_id } => {+ subscription.metadata.get("team_id") == Some(&team_id.to_string())+ }+ };+ if matches_scope+ && matches!(+ subscription.status,+ stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing+ )+ {+ if found.is_some() {+ return Err(PlanChangeError::AmbiguousSubscription);+ }+ found = Some(subscription);+ }+ }+ if !page.has_more {+ break;+ }+ params.starting_after =+ Some(last.ok_or_else(|| anyhow::anyhow!("missing pagination cursor"))?);+ }+ Ok(found)+ }+}+impl<C: CustomerRepository> PlanGateway for StripePlanGateway<C> {+ async fn personal_subscription(+ &self,+ user: &MacroUserIdStr<'_>,+ ) -> Result<PersonalSubscription, PlanChangeError> {+ let id = macro_db_client::user::get::get_stripe_customer_id_by_user_id(&self.db, user)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PlanChangeError::MissingCustomer)?;+ let subscription = self+ .subscription(&id, SubscriptionScope::Personal)+ .await?+ .ok_or(PlanChangeError::NoSubscription)?;+ let seats = subscription+ .items+ .data+ .iter()+ .filter_map(|item| {+ let plan = item+ .price+ .as_ref()+ .and_then(|p| self.prices.plan_for_price(p.id.as_str()))?;+ Some((plan, item.quantity.unwrap_or(1)))+ })+ .collect::<Vec<_>>();+ let plan = match seats.as_slice() {+ [(plan, 1)] => *plan,+ [] => return Err(PlanChangeError::NoSubscription),+ _ => return Err(PlanChangeError::AmbiguousSubscription),+ };+ Ok(PersonalSubscription {+ id: subscription.id.to_string(),+ plan,+ })+ }+ async fn apply(+ &self,+ user: &MacroUserIdStr<'_>,+ subscription: PersonalSubscription,+ target: SeatPlan,+ action: PlanAction,+ ) -> Result<(), PlanChangeError> {+ self.prices+ .price_id(target)+ .map_err(|_| PlanChangeError::PlanUnavailable)?;+ let id = subscription.id.parse().map_err(anyhow::Error::from)?;+ match action {+ PlanAction::ScheduleDowngrade => {+ self.customer+ .schedule_seat_plan(&id, user, Some(target))+ .await+ }+ PlanAction::KeepCurrent => self.customer.schedule_seat_plan(&id, user, None).await,+ PlanAction::Upgrade => self.customer.upgrade_personal_plan(&id, target).await,+ }+ .map_err(anyhow::Error::from)?;+ Ok(())+ }+}++impl<C: CustomerRepository> SubscriptionStatusGateway for StripePlanGateway<C> {+ async fn status(+ &self,+ customer: &str,+ scope: SubscriptionScope,+ user: &MacroUserIdStr<'_>,+ ) -> Result<Option<SubscriptionPlanFacts>, PlanChangeError> {+ let Some(subscription) = self.subscription(customer, scope).await? else {+ return Ok(None);+ };+ let period_end = chrono::DateTime::from_timestamp(subscription.current_period_end, 0)+ .ok_or_else(|| anyhow::anyhow!("invalid subscription renewal date"))?;+ let scheduled_change = match subscription.schedule.as_ref() {+ Some(schedule) => self+ .customer+ .scheduled_seat_plan(&subscription.id, &schedule.id(), user)+ .await+ .map_err(anyhow::Error::from)?,+ None => None,+ };+ Ok(Some(SubscriptionPlanFacts {+ period_end,+ scheduled_change,+ }))+ }+}diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rsindex 29aa22d5e9..bdf8f4abe0 100644--- a/services/authentication_service/src/server.rs+++ b/services/authentication_service/src/server.rs@@ -365,8 +365,11 @@ pub async fn run() -> anyhow::Result<()> {}let teams_repo_impl = TeamRepositoryImpl::new(db.clone());- let customer_repo_impl =- CustomerRepositoryImpl::new(stripe_client.clone(), stripe_prices.seat_prices());+ let customer_repo_impl = CustomerRepositoryImpl::new(+ stripe_client.clone(),+ stripe_prices.seat_prices(),+ db.clone(),+ );let favorites_service = favorites::domain::service::FavoritesServiceImpl::new(favorites::outbound::pg_favorites_repo::PgFavoritesRepo::new(db.clone()),);@@ -512,7 +515,30 @@ pub async fn run() -> anyhow::Result<()> {None};+ let plan_customer = CustomerRepositoryImpl::new(+ stripe_client.clone(),+ stripe_prices.seat_prices(),+ db.clone(),+ );let stripe_client = Arc::new(stripe_client);+ let plan_gateway = crate::outbound::subscription_plan::StripePlanGateway::new(+ db.clone(),+ stripe_client.clone(),+ stripe_prices.seat_prices(),+ plan_customer,+ );+ let subscription_plan = Arc::new(crate::service::subscription_plan::PlanService::new(+ plan_gateway.clone(),+ ));+ let subscription_status = Arc::new(+ crate::service::subscription_status::SubscriptionStatusService::new(+ ai_billing::outbound::RolesTeamsEntitlementSource::new(+ user_roles_and_permissions_service.clone(),+ teams_repo_impl.clone(),+ ),+ plan_gateway,+ ),+ );let gtm_invite_service = Arc::new(gtm_invite_service);let subscription_checkout =Arc::new(crate::service::subscription_checkout::CheckoutService::new(@@ -617,6 +643,8 @@ pub async fn run() -> anyhow::Result<()> {macro_cache_client: Arc::new(macro_cache_client),stripe_client,subscription_checkout,+ subscription_plan,+ subscription_status,document_storage_service_client,user_deletion,email_service_client: Arc::new(email_service_client),diff --git a/services/authentication_service/src/service/mod.rs b/services/authentication_service/src/service/mod.rsindex 513dd9b2e5..cee5221a53 100644--- a/services/authentication_service/src/service/mod.rs+++ b/services/authentication_service/src/service/mod.rs@@ -1,3 +1,6 @@pub mod signup_policy;pub mod subscription_checkout;pub mod user;++pub mod subscription_plan;+pub mod subscription_status;diff --git a/services/authentication_service/src/service/subscription_plan.rs b/services/authentication_service/src/service/subscription_plan.rsnew file mode 100644index 0000000000..493e7b4b08--- /dev/null+++ b/services/authentication_service/src/service/subscription_plan.rs@@ -0,0 +1,146 @@+//! Personal plan-change policy. Downgrades preserve already paid access until renewal.+use macro_user_id::user_id::MacroUserIdStr;+use teams::domain::model::SeatPlan;++/// Active personal subscription facts, with provider identity kept opaque.+pub struct PersonalSubscription {+ /// Provider subscription identifier supplied by the authenticated customer lookup.+ pub id: String,+ /// Currently effective tier, excluding future phases.+ pub plan: SeatPlan,+}+/// Operation selected by the service, never by an untrusted client.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PlanAction {+ /// Apply and prorate the higher plan immediately.+ Upgrade,+ /// Apply the lower plan at the next renewal.+ ScheduleDowngrade,+ /// Cancel a pending downgrade without changing the current price.+ KeepCurrent,+}+/// Errors independent of HTTP or the payment provider.+#[derive(Debug, thiserror::Error)]+pub enum PlanChangeError {+ #[error("User has no billing customer")]+ MissingCustomer,+ #[error("No active personal subscription")]+ NoSubscription,+ #[error("Multiple active personal subscriptions")]+ AmbiguousSubscription,+ #[error("Plan unavailable")]+ PlanUnavailable,+ #[error(transparent)]+ Gateway(#[from] anyhow::Error),+}+/// Capabilities for authenticated, customer-scoped personal subscriptions.+pub trait PlanGateway: Send + Sync {+ /// Load all live personal subscriptions belonging to this user.+ fn personal_subscription(+ &self,+ user: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<PersonalSubscription, PlanChangeError>> + Send;+ /// Execute exactly the timing selected by the service.+ fn apply(+ &self,+ user: &MacroUserIdStr<'_>,+ subscription: PersonalSubscription,+ target: SeatPlan,+ action: PlanAction,+ ) -> impl Future<Output = Result<(), PlanChangeError>> + Send;+}+/// Owns upgrade/downgrade timing; the gateway handles provider details.+pub struct PlanService<G> {+ gateway: G,+}+impl<G: PlanGateway> PlanService<G> {+ /// Compose policy with its provider port.+ pub fn new(gateway: G) -> Self {+ Self { gateway }+ }+ /// Select immediate upgrade, renewal downgrade or cancellation of a pending change.+ pub async fn change(+ &self,+ user: &MacroUserIdStr<'_>,+ target: SeatPlan,+ ) -> Result<SeatPlan, PlanChangeError> {+ if !SeatPlan::PURCHASABLE.contains(&target) {+ return Err(PlanChangeError::PlanUnavailable);+ }+ let subscription = self.gateway.personal_subscription(user).await?;+ let action = action(subscription.plan, target);+ let active = if action == PlanAction::Upgrade {+ target+ } else {+ subscription.plan+ };+ self.gateway+ .apply(user, subscription, target, action)+ .await?;+ Ok(active)+ }+}+fn action(current: SeatPlan, target: SeatPlan) -> PlanAction {+ if current == target {+ PlanAction::KeepCurrent+ } else if target == SeatPlan::Max {+ PlanAction::Upgrade+ } else {+ PlanAction::ScheduleDowngrade+ }+}+#[cfg(test)]+mod test {+ use super::*;+ use std::sync::Mutex;+ struct Fake {+ calls: Mutex<Vec<PlanAction>>,+ }+ impl PlanGateway for Fake {+ async fn personal_subscription(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> Result<PersonalSubscription, PlanChangeError> {+ Ok(PersonalSubscription {+ id: "sub_test".into(),+ plan: SeatPlan::Max,+ })+ }+ async fn apply(+ &self,+ _: &MacroUserIdStr<'_>,+ _: PersonalSubscription,+ _: SeatPlan,+ action: PlanAction,+ ) -> Result<(), PlanChangeError> {+ self.calls.lock().unwrap().push(action);+ Ok(())+ }+ }+ #[tokio::test]+ async fn max_pro_max_schedules_then_cancels_without_an_upgrade() {+ let service = PlanService::new(Fake {+ calls: Mutex::new(Vec::new()),+ });+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();+ assert_eq!(+ service.change(&user, SeatPlan::Premium).await.unwrap(),+ SeatPlan::Max+ );+ assert_eq!(+ service.change(&user, SeatPlan::Max).await.unwrap(),+ SeatPlan::Max+ );+ assert_eq!(+ *service.gateway.calls.lock().unwrap(),+ vec![PlanAction::ScheduleDowngrade, PlanAction::KeepCurrent]+ );+ }+ #[test]+ fn pro_max_is_an_immediate_upgrade() {+ assert_eq!(+ action(SeatPlan::Premium, SeatPlan::Max),+ PlanAction::Upgrade+ );+ }+}diff --git a/services/authentication_service/src/service/subscription_status.rs b/services/authentication_service/src/service/subscription_status.rsnew file mode 100644index 0000000000..9cfbe7cbc9--- /dev/null+++ b/services/authentication_service/src/service/subscription_status.rs@@ -0,0 +1,98 @@+//! Read the caller's scheduled seat change without running usage settlement.++use ai_billing::domain::{EntitlementSource, PlanTier, SubscriptionScope};+use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use teams::domain::model::ScheduledSeatPlan;++use super::subscription_plan::PlanChangeError;++#[cfg(test)]+mod test;++/// Provider facts for one authenticated subscription scope.+#[derive(Clone)]+pub struct SubscriptionPlanFacts {+ /// End of the subscription's currently effective billing period.+ pub period_end: DateTime<Utc>,+ /// Only the caller's seat, from the currently attached provider schedule.+ pub scheduled_change: Option<ScheduledSeatPlan>,+}++/// Capability for reading customer-scoped subscription and schedule facts.+pub trait SubscriptionStatusGateway: Send + Sync {+ /// Find the live subscription in the trusted scope and its caller-specific change.+ fn status(+ &self,+ customer: &str,+ scope: SubscriptionScope,+ user: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<SubscriptionPlanFacts>, PlanChangeError>> + Send;+}++/// Current renewal and scheduled change; empty for accounts without a subscription.+#[derive(Default, Debug, serde::Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct SubscriptionStatus {+ /// Provider-confirmed subscription renewal date.+ pub renewal_date: Option<DateTime<Utc>>,+ /// Future downgrade for the caller's seat, if still pending.+ pub scheduled_change: Option<ScheduledSeatPlan>,+}++/// Resolves the caller's payer and scope before reading subscription facts.+pub struct SubscriptionStatusService<E, G> {+ entitlements: E,+ gateway: G,+}++impl<E: EntitlementSource, G: SubscriptionStatusGateway> SubscriptionStatusService<E, G> {+ /// Compose the owning entitlement port with the provider read capability.+ pub fn new(entitlements: E, gateway: G) -> Self {+ Self {+ entitlements,+ gateway,+ }+ }++ /// Return only the authenticated caller's current subscription and future downgrade.+ pub async fn status(+ &self,+ user: &MacroUserIdStr<'_>,+ ) -> Result<SubscriptionStatus, PlanChangeError> {+ let entitlement = self+ .entitlements+ .entitlement(user)+ .await+ .map_err(anyhow::Error::from)?;+ if !entitlement.tier.is_paid() || entitlement.unlimited {+ return Ok(SubscriptionStatus::default());+ }+ let Some(customer) = self+ .entitlements+ .stripe_customer_id(&entitlement.payer)+ .await+ .map_err(anyhow::Error::from)?+ else {+ return Ok(SubscriptionStatus::default());+ };+ let Some(facts) = self+ .gateway+ .status(&customer, SubscriptionScope::from(&entitlement.scope), user)+ .await?+ else {+ return Ok(SubscriptionStatus::default());+ };+ // An applied phase or already-Pro seat is not a future downgrade, even+ // while entitlement webhooks or schedule acknowledgements are catching up.+ let scheduled_change = facts.scheduled_change.filter(|change| {+ entitlement.tier == PlanTier::Max+ && change.plan == teams::domain::model::SeatPlan::Premium+ && change.effective_at >= facts.period_end+ });+ Ok(SubscriptionStatus {+ renewal_date: Some(facts.period_end),+ scheduled_change,+ })+ }+}diff --git a/services/authentication_service/src/service/subscription_status/test.rs b/services/authentication_service/src/service/subscription_status/test.rsnew file mode 100644index 0000000000..ab9b918b7c--- /dev/null+++ b/services/authentication_service/src/service/subscription_status/test.rs@@ -0,0 +1,167 @@+use super::*;+use ai_billing::domain::{Entitlement, PayerScope};+use macro_user_id::cowlike::CowLike;+use std::sync::Mutex;+use teams::domain::model::SeatPlan;++struct Entitlements {+ value: Entitlement,+ customer_for: Mutex<Vec<String>>,+}+impl EntitlementSource for Entitlements {+ async fn entitlement(&self, _: &MacroUserIdStr<'_>) -> ai_billing::domain::Result<Entitlement> {+ Ok(self.value.clone())+ }+ async fn stripe_customer_id(+ &self,+ user: &MacroUserIdStr<'_>,+ ) -> ai_billing::domain::Result<Option<String>> {+ self.customer_for.lock().unwrap().push(user.to_string());+ Ok(Some("cus_payer".into()))+ }+ async fn team_payer(+ &self,+ _: macro_uuid::Uuid,+ ) -> ai_billing::domain::Result<Option<MacroUserIdStr<'static>>> {+ unreachable!()+ }+}+struct Gateway {+ facts: Option<SubscriptionPlanFacts>,+ calls: Mutex<Vec<(String, SubscriptionScope, String)>>,+}+impl SubscriptionStatusGateway for Gateway {+ async fn status(+ &self,+ customer: &str,+ scope: SubscriptionScope,+ user: &MacroUserIdStr<'_>,+ ) -> Result<Option<SubscriptionPlanFacts>, PlanChangeError> {+ self.calls+ .lock()+ .unwrap()+ .push((customer.into(), scope, user.to_string()));+ Ok(self.facts.clone())+ }+}+fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]")+ .unwrap()+ .into_owned()+}+fn date(value: &str) -> DateTime<Utc> {+ value.parse().unwrap()+}+fn service(+ value: Entitlement,+ change: Option<ScheduledSeatPlan>,+) -> SubscriptionStatusService<Entitlements, Gateway> {+ SubscriptionStatusService::new(+ Entitlements {+ value,+ customer_for: Mutex::new(Vec::new()),+ },+ Gateway {+ facts: Some(SubscriptionPlanFacts {+ period_end: date("2026-11-01T12:00:00Z"),+ scheduled_change: change,+ }),+ calls: Mutex::new(Vec::new()),+ },+ )+}+fn downgrade(at: &str) -> Option<ScheduledSeatPlan> {+ Some(ScheduledSeatPlan {+ plan: SeatPlan::Premium,+ effective_at: date(at),+ })+}++#[tokio::test]+async fn returns_pending_downgrade_from_the_authenticated_personal_scope() {+ let service = service(+ Entitlement::personal(user(), PlanTier::Max),+ downgrade("2026-11-01T12:00:00Z"),+ );+ let status = service.status(&user()).await.unwrap();+ assert_eq!(status.scheduled_change.unwrap().plan, SeatPlan::Premium);+ assert_eq!(status.renewal_date, Some(date("2026-11-01T12:00:00Z")));+ assert_eq!(+ *service.gateway.calls.lock().unwrap(),+ vec![(+ "cus_payer".into(),+ SubscriptionScope::Personal,+ user().to_string()+ )]+ );+}++#[tokio::test]+async fn team_member_reads_the_owners_customer_but_only_their_own_seat() {+ let owner = MacroUserIdStr::try_from("macro|[email protected]")+ .unwrap()+ .into_owned();+ let team_id = macro_uuid::generate_uuid_v7();+ let mut entitlement = Entitlement::personal(user(), PlanTier::Max);+ entitlement.payer = owner.clone();+ entitlement.scope = PayerScope::TeamMember { team_id };+ let service = service(entitlement, downgrade("2026-11-01T12:00:00Z"));+ service.status(&user()).await.unwrap();+ assert_eq!(+ *service.entitlements.customer_for.lock().unwrap(),+ vec![owner.to_string()]+ );+ assert_eq!(+ *service.gateway.calls.lock().unwrap(),+ vec![(+ "cus_payer".into(),+ SubscriptionScope::Team { team_id },+ user().to_string()+ )]+ );+}++#[tokio::test]+async fn applied_or_already_effective_changes_are_hidden() {+ for (tier, at) in [+ (PlanTier::Max, "2026-10-01T12:00:00Z"),+ (PlanTier::Premium, "2026-11-01T12:00:00Z"),+ ] {+ let service = service(Entitlement::personal(user(), tier), downgrade(at));+ assert!(+ service+ .status(&user())+ .await+ .unwrap()+ .scheduled_change+ .is_none()+ );+ }+}++#[tokio::test]+async fn canceled_schedule_has_no_banner_but_keeps_the_renewal_date() {+ let service = service(Entitlement::personal(user(), PlanTier::Max), None);+ let status = service.status(&user()).await.unwrap();+ assert!(status.scheduled_change.is_none());+ assert!(status.renewal_date.is_some());+}++#[tokio::test]+async fn free_and_unlimited_accounts_do_not_read_stripe() {+ for (tier, unlimited) in [(PlanTier::Free, false), (PlanTier::Max, true)] {+ let mut entitlement = Entitlement::personal(user(), tier);+ entitlement.unlimited = unlimited;+ let service = service(entitlement, None);+ assert!(+ service+ .status(&user())+ .await+ .unwrap()+ .renewal_date+ .is_none()+ );+ assert!(service.gateway.calls.lock().unwrap().is_empty());+ assert!(service.entitlements.customer_for.lock().unwrap().is_empty());+ }+}