Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

AI usage allowances, prepaid credits, overage billing, and the Max plan (#6336)

Jacob Beckerman9b4a0a5a2fcc
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index f071af99d8..65860b69f5 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -879,6 +879,94 @@
"crates/workspace-hack",
"services/agent_trigger_service"
],
+ "ai_billing": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
+ "crates/workspace-hack"
+ ],
"ai_projections": [
"crates/activity",
"crates/agent",
@@ -1291,6 +1379,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
"crates/analytics_client",
@@ -3273,6 +3362,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_projections",
"crates/ai_tools",
"crates/ai_toolset",
diff --git a/.sqlx/query-0638b88c64a545b8ff3679c47169133e60f79b86620b89c438d9d91d529e85a1.json b/.sqlx/query-0638b88c64a545b8ff3679c47169133e60f79b86620b89c438d9d91d529e85a1.json
new file mode 100644
index 0000000000..bb4d3da34e
--- /dev/null
+++ b/.sqlx/query-0638b88c64a545b8ff3679c47169133e60f79b86620b89c438d9d91d529e85a1.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (team_id, user_id, team_role, plan)\n VALUES ($1, $2, 'owner', $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "seat_plan",
+ "kind": {
+ "Enum": [
+ "premium",
+ "max"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0638b88c64a545b8ff3679c47169133e60f79b86620b89c438d9d91d529e85a1"
+}
diff --git a/.sqlx/query-1d787282a8b72ed682cc1d3b9a050fdafa95343c0d778f7b198d84a8d428562b.json b/.sqlx/query-1d787282a8b72ed682cc1d3b9a050fdafa95343c0d778f7b198d84a8d428562b.json
new file mode 100644
index 0000000000..51b763ac38
--- /dev/null
+++ b/.sqlx/query-1d787282a8b72ed682cc1d3b9a050fdafa95343c0d778f7b198d84a8d428562b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(-SUM(delta_cents), 0)::bigint AS \"consumed!\"\n FROM ai_credit_ledger\n WHERE user_id = $1 AND kind = 'consumption' AND period_start = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "consumed!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "1d787282a8b72ed682cc1d3b9a050fdafa95343c0d778f7b198d84a8d428562b"
+}
diff --git a/.sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json b/.sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json
new file mode 100644
index 0000000000..5d3591e8b7
--- /dev/null
+++ b/.sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_billing_account (user_id, period_start, period_end)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id) DO UPDATE\n SET period_start = EXCLUDED.period_start,\n period_end = EXCLUDED.period_end,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9"
+}
diff --git a/.sqlx/query-265f2d683fc4afcd0723e7285f26ceb38843c39dae4a577853837803df0f84ee.json b/.sqlx/query-265f2d683fc4afcd0723e7285f26ceb38843c39dae4a577853837803df0f84ee.json
new file mode 100644
index 0000000000..ea804e2b9b
--- /dev/null
+++ b/.sqlx/query-265f2d683fc4afcd0723e7285f26ceb38843c39dae4a577853837803df0f84ee.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_overage_charge SET updated_at = NOW() - INTERVAL '1 hour' WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "265f2d683fc4afcd0723e7285f26ceb38843c39dae4a577853837803df0f84ee"
+}
diff --git a/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.json b/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.json
new file mode 100644
index 0000000000..d45007a2ec
--- /dev/null
+++ b/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user\n )\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (user_id, period_start) DO UPDATE\n SET billed_users = EXCLUDED.billed_users,\n included_cents_by_user = EXCLUDED.included_cents_by_user,\n updated_at = NOW()\n WHERE ai_billing_period_allowance.billed_users\n IS DISTINCT FROM EXCLUDED.billed_users\n OR ai_billing_period_allowance.included_cents_by_user\n IS DISTINCT FROM EXCLUDED.included_cents_by_user\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "TextArray",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8"
+}
diff --git a/.sqlx/query-3eb27474ff84463a8866c5f3d65a095e7e46cc9db3496dd2754927210aa29a5f.json b/.sqlx/query-3eb27474ff84463a8866c5f3d65a095e7e46cc9db3496dd2754927210aa29a5f.json
new file mode 100644
index 0000000000..fa4999bba7
--- /dev/null
+++ b/.sqlx/query-3eb27474ff84463a8866c5f3d65a095e7e46cc9db3496dd2754927210aa29a5f.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT overage_enabled, overage_limit_cents, overage_suspended_at\n FROM ai_billing_account\n WHERE user_id = $1\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "overage_enabled",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "overage_limit_cents",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "overage_suspended_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "3eb27474ff84463a8866c5f3d65a095e7e46cc9db3496dd2754927210aa29a5f"
+}
diff --git a/.sqlx/query-3f55e29e4b01ea495af980ccec349f7e251bd2034994a95de309c89a4394d723.json b/.sqlx/query-3f55e29e4b01ea495af980ccec349f7e251bd2034994a95de309c89a4394d723.json
new file mode 100644
index 0000000000..cb96e988ef
--- /dev/null
+++ b/.sqlx/query-3f55e29e4b01ea495af980ccec349f7e251bd2034994a95de309c89a4394d723.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(SUM(amount_cents), 0)::bigint AS \"charged!\"\n FROM ai_overage_charge\n WHERE user_id = $1\n AND period_start = $2\n AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "charged!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3f55e29e4b01ea495af980ccec349f7e251bd2034994a95de309c89a4394d723"
+}
diff --git a/.sqlx/query-4dab09dc05e20ee33cf78fe906292dc6f2f89653afda45138f00315648a77342.json b/.sqlx/query-4dab09dc05e20ee33cf78fe906292dc6f2f89653afda45138f00315648a77342.json
new file mode 100644
index 0000000000..c3e03ee498
--- /dev/null
+++ b/.sqlx/query-4dab09dc05e20ee33cf78fe906292dc6f2f89653afda45138f00315648a77342.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT status::text AS \"status!\"\n FROM ai_overage_charge\n WHERE user_id = $1\n ORDER BY created_at DESC, id DESC\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4dab09dc05e20ee33cf78fe906292dc6f2f89653afda45138f00315648a77342"
+}
diff --git a/.sqlx/query-5515559e4a496f9a814d89aa832e20e4804beb7e5ce4b1aff5bb621838f62010.json b/.sqlx/query-5515559e4a496f9a814d89aa832e20e4804beb7e5ce4b1aff5bb621838f62010.json
new file mode 100644
index 0000000000..0812cd8d1a
--- /dev/null
+++ b/.sqlx/query-5515559e4a496f9a814d89aa832e20e4804beb7e5ce4b1aff5bb621838f62010.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(SUM(amount_cents), 0)::bigint AS \"charged!\"\n FROM ai_overage_charge\n WHERE user_id = $1 AND period_start = $2 AND status <> 'failed'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "charged!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "5515559e4a496f9a814d89aa832e20e4804beb7e5ce4b1aff5bb621838f62010"
+}
diff --git a/.sqlx/query-64361492f9ed5fe845d3b41c1fdd9bf9acf99cefb9061bfb19648f8651f9de02.json b/.sqlx/query-64361492f9ed5fe845d3b41c1fdd9bf9acf99cefb9061bfb19648f8651f9de02.json
new file mode 100644
index 0000000000..2a7cb15b89
--- /dev/null
+++ b/.sqlx/query-64361492f9ed5fe845d3b41c1fdd9bf9acf99cefb9061bfb19648f8651f9de02.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE ai_billing_account\n SET overage_suspended_at = NULL, updated_at = NOW()\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "64361492f9ed5fe845d3b41c1fdd9bf9acf99cefb9061bfb19648f8651f9de02"
+}
diff --git a/.sqlx/query-653d621afe6040793075958b707ed8477dee6340727d50f972443cbd7387d6d5.json b/.sqlx/query-653d621afe6040793075958b707ed8477dee6340727d50f972443cbd7387d6d5.json
new file mode 100644
index 0000000000..273dcc04d9
--- /dev/null
+++ b/.sqlx/query-653d621afe6040793075958b707ed8477dee6340727d50f972443cbd7387d6d5.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, period_start, note)\n VALUES ($1, $2, 'consumption', $3, $4, 'AI usage beyond plan allowance')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "653d621afe6040793075958b707ed8477dee6340727d50f972443cbd7387d6d5"
+}
diff --git a/.sqlx/query-738436737088d0f56a421383c30abe459fd6bdd04a1d1b511ca4e6b813916aa7.json b/.sqlx/query-738436737088d0f56a421383c30abe459fd6bdd04a1d1b511ca4e6b813916aa7.json
new file mode 100644
index 0000000000..ed79bc97a9
--- /dev/null
+++ b/.sqlx/query-738436737088d0f56a421383c30abe459fd6bdd04a1d1b511ca4e6b813916aa7.json
@@ -0,0 +1,56 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\",\n plan as \"plan!: SeatPlan\"\n FROM team_user\n WHERE team_id = $1\n AND user_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 2,
+ "name": "plan!: SeatPlan",
+ "type_info": {
+ "Custom": {
+ "name": "seat_plan",
+ "kind": {
+ "Enum": [
+ "premium",
+ "max"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "738436737088d0f56a421383c30abe459fd6bdd04a1d1b511ca4e6b813916aa7"
+}
diff --git a/.sqlx/query-8140bf3cd5979d53c7261e414bfa7a4f7194142d323d8a0aa1160e5ccf73c534.json b/.sqlx/query-8140bf3cd5979d53c7261e414bfa7a4f7194142d323d8a0aa1160e5ccf73c534.json
new file mode 100644
index 0000000000..a4c7bc3ea7
--- /dev/null
+++ b/.sqlx/query-8140bf3cd5979d53c7261e414bfa7a4f7194142d323d8a0aa1160e5ccf73c534.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE ai_overage_charge\n SET status = 'pending', updated_at = NOW()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8140bf3cd5979d53c7261e414bfa7a4f7194142d323d8a0aa1160e5ccf73c534"
+}
diff --git a/.sqlx/query-904248cdade2f9b74f4612195cfee182ca877615bc144fd491c251b70003eb37.json b/.sqlx/query-904248cdade2f9b74f4612195cfee182ca877615bc144fd491c251b70003eb37.json
new file mode 100644
index 0000000000..d4754b4f4c
--- /dev/null
+++ b/.sqlx/query-904248cdade2f9b74f4612195cfee182ca877615bc144fd491c251b70003eb37.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT overage_enabled, overage_limit_cents, overage_suspended_at,\n period_start, period_end\n FROM ai_billing_account\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "overage_enabled",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "overage_limit_cents",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "overage_suspended_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "period_start",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "period_end",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "904248cdade2f9b74f4612195cfee182ca877615bc144fd491c251b70003eb37"
+}
diff --git a/.sqlx/query-97cb7478b93746370096159cf3ea1d204737836a35ff6ec31cdb7f3c047ce34a.json b/.sqlx/query-97cb7478b93746370096159cf3ea1d204737836a35ff6ec31cdb7f3c047ce34a.json
new file mode 100644
index 0000000000..09747fc1e7
--- /dev/null
+++ b/.sqlx/query-97cb7478b93746370096159cf3ea1d204737836a35ff6ec31cdb7f3c047ce34a.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\",\n plan as \"plan!: SeatPlan\"\n FROM team_user\n WHERE team_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 2,
+ "name": "plan!: SeatPlan",
+ "type_info": {
+ "Custom": {
+ "name": "seat_plan",
+ "kind": {
+ "Enum": [
+ "premium",
+ "max"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "97cb7478b93746370096159cf3ea1d204737836a35ff6ec31cdb7f3c047ce34a"
+}
diff --git a/.sqlx/query-9817d0f3c0c5addd52244e9ff830efa69845b5df2f117bb027264c72b0e1f3ea.json b/.sqlx/query-9817d0f3c0c5addd52244e9ff830efa69845b5df2f117bb027264c72b0e1f3ea.json
new file mode 100644
index 0000000000..09175f2e80
--- /dev/null
+++ b/.sqlx/query-9817d0f3c0c5addd52244e9ff830efa69845b5df2f117bb027264c72b0e1f3ea.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_billing_account (user_id, overage_suspended_at)\n VALUES ($1, NOW())\n ON CONFLICT (user_id) DO UPDATE\n SET overage_suspended_at = COALESCE(ai_billing_account.overage_suspended_at, NOW()),\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9817d0f3c0c5addd52244e9ff830efa69845b5df2f117bb027264c72b0e1f3ea"
+}
diff --git a/.sqlx/query-a3d091f2a54954ba8bb1aa6fcd500d7118220a8f0e0d971646892f627ef6c554.json b/.sqlx/query-a3d091f2a54954ba8bb1aa6fcd500d7118220a8f0e0d971646892f627ef6c554.json
new file mode 100644
index 0000000000..73c3298737
--- /dev/null
+++ b/.sqlx/query-a3d091f2a54954ba8bb1aa6fcd500d7118220a8f0e0d971646892f627ef6c554.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)\n VALUES ($1, $2, 'purchase', $3, $4, 'Credit pack purchase')\n ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a3d091f2a54954ba8bb1aa6fcd500d7118220a8f0e0d971646892f627ef6c554"
+}
diff --git a/.sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json b/.sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json
new file mode 100644
index 0000000000..69347bfecb
--- /dev/null
+++ b/.sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json
@@ -0,0 +1,32 @@
+{
+ "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 )\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 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"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5"
+}
diff --git a/.sqlx/query-a6c5e0b67bfc2fcab27342d238de9f6eca65da5be07e916915e7afb8b27fe713.json b/.sqlx/query-a6c5e0b67bfc2fcab27342d238de9f6eca65da5be07e916915e7afb8b27fe713.json
new file mode 100644
index 0000000000..fbd45070c6
--- /dev/null
+++ b/.sqlx/query-a6c5e0b67bfc2fcab27342d238de9f6eca65da5be07e916915e7afb8b27fe713.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, amount_cents, stripe_invoice_id, status::text AS \"status!\"\n FROM ai_overage_charge\n WHERE user_id = $1\n AND period_start = $2\n AND (\n status = 'failed'\n OR (\n status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes'\n )\n )\n ORDER BY created_at\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "amount_cents",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "stripe_invoice_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "status!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "a6c5e0b67bfc2fcab27342d238de9f6eca65da5be07e916915e7afb8b27fe713"
+}
diff --git a/.sqlx/query-a7f782a9d4d647fc38cdef92ede9b3bf09a20f03c89eafcfc24d1d439b630a41.json b/.sqlx/query-a7f782a9d4d647fc38cdef92ede9b3bf09a20f03c89eafcfc24d1d439b630a41.json
new file mode 100644
index 0000000000..5ee8cf566f
--- /dev/null
+++ b/.sqlx/query-a7f782a9d4d647fc38cdef92ede9b3bf09a20f03c89eafcfc24d1d439b630a41.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id,\n team_role as \"team_role!: TeamRole\",\n plan as \"plan!: SeatPlan\"\n FROM team_user\n WHERE team_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 2,
+ "name": "plan!: SeatPlan",
+ "type_info": {
+ "Custom": {
+ "name": "seat_plan",
+ "kind": {
+ "Enum": [
+ "premium",
+ "max"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "a7f782a9d4d647fc38cdef92ede9b3bf09a20f03c89eafcfc24d1d439b630a41"
+}
diff --git a/.sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.json b/.sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.json
new file mode 100644
index 0000000000..e2a7eace02
--- /dev/null
+++ b/.sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT billed_users as \"billed_users!\",\n included_cents_by_user as \"included_cents_by_user!\"\n FROM ai_billing_period_allowance\n WHERE user_id = $1 AND period_start = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "billed_users!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 1,
+ "name": "included_cents_by_user!",
+ "type_info": "Int8Array"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e"
+}
diff --git a/.sqlx/query-b0bce53a8fb9a13f6fcbbfb2b1fdd7f36b3812341a155800766239592445d03f.json b/.sqlx/query-b0bce53a8fb9a13f6fcbbfb2b1fdd7f36b3812341a155800766239592445d03f.json
new file mode 100644
index 0000000000..2028971041
--- /dev/null
+++ b/.sqlx/query-b0bce53a8fb9a13f6fcbbfb2b1fdd7f36b3812341a155800766239592445d03f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(SUM(delta_cents), 0)::bigint AS \"balance!\"\n FROM ai_credit_ledger\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "balance!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "b0bce53a8fb9a13f6fcbbfb2b1fdd7f36b3812341a155800766239592445d03f"
+}
diff --git a/.sqlx/query-cc6de9625eb30222496b063c1a1c4cdf254e1440fae044519a69d8fe4e03a44f.json b/.sqlx/query-cc6de9625eb30222496b063c1a1c4cdf254e1440fae044519a69d8fe4e03a44f.json
new file mode 100644
index 0000000000..ab705ab75f
--- /dev/null
+++ b/.sqlx/query-cc6de9625eb30222496b063c1a1c4cdf254e1440fae044519a69d8fe4e03a44f.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_billing_account (user_id, overage_enabled, overage_limit_cents)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id) DO UPDATE\n SET overage_enabled = EXCLUDED.overage_enabled,\n overage_limit_cents = EXCLUDED.overage_limit_cents,\n overage_suspended_at = NULL,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Bool",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cc6de9625eb30222496b063c1a1c4cdf254e1440fae044519a69d8fe4e03a44f"
+}
diff --git a/.sqlx/query-cde3129e76f0a471008db6e006b9d099e2acc19622f668f486c69aa26c93c5a9.json b/.sqlx/query-cde3129e76f0a471008db6e006b9d099e2acc19622f668f486c69aa26c93c5a9.json
new file mode 100644
index 0000000000..6addf8ffa8
--- /dev/null
+++ b/.sqlx/query-cde3129e76f0a471008db6e006b9d099e2acc19622f668f486c69aa26c93c5a9.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status)\n VALUES ($1, $2, $3, $4, 'pending')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cde3129e76f0a471008db6e006b9d099e2acc19622f668f486c69aa26c93c5a9"
+}
diff --git a/.sqlx/query-d291bb82b6215c74ade9d21a92df7b58d21cc627a076a9bfa3148873c57b58e2.json b/.sqlx/query-d291bb82b6215c74ade9d21a92df7b58d21cc627a076a9bfa3148873c57b58e2.json
new file mode 100644
index 0000000000..e36d7e55a0
--- /dev/null
+++ b/.sqlx/query-d291bb82b6215c74ade9d21a92df7b58d21cc627a076a9bfa3148873c57b58e2.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE team_user\n SET plan = $3\n WHERE team_id = $1\n AND user_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "seat_plan",
+ "kind": {
+ "Enum": [
+ "premium",
+ "max"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d291bb82b6215c74ade9d21a92df7b58d21cc627a076a9bfa3148873c57b58e2"
+}
diff --git a/.sqlx/query-d3e2b4f0a9136b8cc8c8ffc7cd63db82ba5eb2ba4d9d3a6e05f0618edf0292e7.json b/.sqlx/query-d3e2b4f0a9136b8cc8c8ffc7cd63db82ba5eb2ba4d9d3a6e05f0618edf0292e7.json
new file mode 100644
index 0000000000..9ace4c7c41
--- /dev/null
+++ b/.sqlx/query-d3e2b4f0a9136b8cc8c8ffc7cd63db82ba5eb2ba4d9d3a6e05f0618edf0292e7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*)::bigint AS \"count!\" FROM ai_overage_charge WHERE user_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d3e2b4f0a9136b8cc8c8ffc7cd63db82ba5eb2ba4d9d3a6e05f0618edf0292e7"
+}
diff --git a/.sqlx/query-d4225efdfb41c2d12627c80f40ca41b860ccd92ea32967fe878e3e905c107db8.json b/.sqlx/query-d4225efdfb41c2d12627c80f40ca41b860ccd92ea32967fe878e3e905c107db8.json
new file mode 100644
index 0000000000..80e2b633f7
--- /dev/null
+++ b/.sqlx/query-d4225efdfb41c2d12627c80f40ca41b860ccd92ea32967fe878e3e905c107db8.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE ai_overage_charge\n SET status = ($2::text)::ai_overage_charge_status, updated_at = NOW()\n WHERE stripe_invoice_id = $1\n AND status <> 'paid'\n AND status <> ($2::text)::ai_overage_charge_status\n RETURNING user_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "d4225efdfb41c2d12627c80f40ca41b860ccd92ea32967fe878e3e905c107db8"
+}
diff --git a/.sqlx/query-f37337f9ab4399c14d083aec9bce8e7a7d1120edc476a7281ef2057f80c901e0.json b/.sqlx/query-f37337f9ab4399c14d083aec9bce8e7a7d1120edc476a7281ef2057f80c901e0.json
new file mode 100644
index 0000000000..14cf43d87d
--- /dev/null
+++ b/.sqlx/query-f37337f9ab4399c14d083aec9bce8e7a7d1120edc476a7281ef2057f80c901e0.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_billing_account (user_id) VALUES ($1)\n ON CONFLICT (user_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f37337f9ab4399c14d083aec9bce8e7a7d1120edc476a7281ef2057f80c901e0"
+}
diff --git a/.sqlx/query-f39340afa533e4eaec5fa2a124832f770ddc6d85a811c49f5eedb6a70c8c88a1.json b/.sqlx/query-f39340afa533e4eaec5fa2a124832f770ddc6d85a811c49f5eedb6a70c8c88a1.json
new file mode 100644
index 0000000000..34214a9983
--- /dev/null
+++ b/.sqlx/query-f39340afa533e4eaec5fa2a124832f770ddc6d85a811c49f5eedb6a70c8c88a1.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE ai_overage_charge\n SET stripe_invoice_id = COALESCE($2, stripe_invoice_id),\n status = ($3::text)::ai_overage_charge_status,\n updated_at = NOW()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f39340afa533e4eaec5fa2a124832f770ddc6d85a811c49f5eedb6a70c8c88a1"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 41a3bdad6e..0efd2e11ed 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -639,6 +639,34 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "ai_billing"
+version = "0.1.0"
+dependencies = [
+ "ai_usage",
+ "anyhow",
+ "async-stripe",
+ "authentication_service_client",
+ "axum",
+ "chrono",
+ "macro_authorization",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "roles_and_permissions",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "strum 0.27.2",
+ "teams",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "workspace-hack",
+]
+
[[package]]
name = "ai_projections"
version = "0.1.0"
@@ -1655,6 +1683,7 @@ name = "authentication_service"
version = "0.1.0"
dependencies = [
"aes-gcm",
+ "ai_billing",
"analytics_client",
"anyhow",
"async-stripe",
@@ -5441,6 +5470,7 @@ version = "0.1.0"
dependencies = [
"agent",
"aho-corasick",
+ "ai_billing",
"ai_projections",
"ai_tools",
"ai_toolset",
@@ -5450,6 +5480,7 @@ dependencies = [
"async-stream",
"async-trait",
"attachment",
+ "authentication_service_client",
"aws-sdk-dynamodb",
"aws-sdk-s3",
"aws-sdk-secretsmanager",
@@ -5533,6 +5564,7 @@ dependencies = [
"stream",
"strum 0.27.2",
"sync_service_client",
+ "teams",
"thiserror 2.0.18",
"time",
"tokio",
diff --git a/Cargo.toml b/Cargo.toml
index 235952b164..81d2051d2d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,6 +8,7 @@ members = [
"crates/agent_inmem",
"crates/agent_runtime_protocol", "crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_projections",
"crates/ai_usage",
"crates/bot_id",
diff --git a/apps/docs/account/billing.mdx b/apps/docs/account/billing.mdx
index 5007e50296..183ed67936 100644
--- a/apps/docs/account/billing.mdx
+++ b/apps/docs/account/billing.mdx
@@ -1,24 +1,39 @@
---
title: "Billing & Plans"
icon: "credit-card"
-description: "Macro's free and premium plans, and how to manage your subscription."
+description: "Macro's free, Premium, and Max plans, how AI usage is included, and how to manage your subscription."
---
-Macro has one paid plan, priced per person. The price is the same whether you're solo or on a team.
+Macro has two paid plans, priced per person. The price is the same whether you're solo or on a team.
-| | Free | Premium |
-| --- | --- | --- |
-| Price | \$0 | \$40 / month |
-| AI agent | Fast model only | All models |
-| AI tool calls | Limited | Unlimited |
-| Storage | 5 GB | 1 TB |
+| | Free | Premium | Max |
+| --- | --- | --- | --- |
+| Price | \$0 | \$40 / month | \$200 / month |
+| AI agent | Fast model only | All models | All models |
+| AI usage included each month | Limited | \$40 | \$200 |
+| Beyond included AI | — | Credits or usage billing | Credits or usage billing |
+| Storage | 5 GB | 1 TB | 1 TB |
-Teams require a paid seat for every member; there's no free plan for teams. Your current plan is shown in **Settings → Account**, with an **Upgrade** button if you're on the free plan.
+Teams require a paid seat for every member; there's no free plan for teams. Each seat has its own plan: a team can mix Premium and Max seats, and team admins choose the plan for every member from the **Plan** menu next to their name in **Settings → Team**. Moving a seat is prorated for the rest of the billing period. Your current plan is shown in **Settings → Billing**, with **Upgrade** buttons if you're on the free plan and an **Upgrade to Max** button on Premium (on a team, that moves only your own seat).
+
+## AI usage
+
+Every paid plan includes a monthly amount of AI usage worth the plan's price, measured at Macro's usage rates: Premium includes \$40 of AI each month and Max includes \$200. Each AI request draws on that amount based on the model and the tokens it used, so the heavy models go further into it: Opus 5 uses about 2.5×, and Fable 5.1 and GPT-6 Astra about 5×, what Sonnet 5 does for the same conversation (the model picker shows the multiplier). On a team, every seat keeps its own allowance: unused usage on one seat doesn't move to another. Prepaid credits and usage billing are shared across the team and managed by the team owner.
+
+**Settings → Billing** shows how much of this period's included AI you've used, when it resets, your credit balance, and your usage billing settings. Included usage resets at the start of each billing period; it doesn't roll over.
+
+When the included amount is used up, AI requests pause until one of these applies:
+
+- **Credits** — prepaid AI usage you buy in \$10, \$25, \$50, or \$100 packs. Credits are applied after your included amount, never expire, and carry over between periods.
+- **Usage billing** — turn it on to bill AI beyond your included amount and credits to your card in \$10 increments, up to a monthly limit you choose. If a charge fails, usage billing pauses until you update your payment method and turn it back on.
+- **Upgrading to Max** — five times the included usage for that seat. Upgrades take effect immediately and are prorated for the rest of the period. On a team, move the heavy users' seats to Max from **Settings → Team** and leave the rest on Premium.
+
+On a team, the team owner buys credits and controls usage billing for everyone; members see the team's position but not the controls.
## Managing your subscription
-Subscriptions are handled through Stripe. From **Settings → Account**, choose **Manage Subscription** to open the billing portal, where you can update your payment method, download invoices, or cancel. If you cancel, your plan stays active until the end of the billing period.
+Subscriptions are handled through Stripe. From **Settings → Billing**, choose **Manage** to open the billing portal, where you can update your payment method, download invoices, or cancel. If you cancel, your plan stays active until the end of the billing period.
## Self-hosting
-Macro is open source under the AGPLv3, and self-hosting is free, though some bundled services require your own licenses and it isn't our primary focus yet. See the [FAQ](/faq) for the current state of self-hosting, and contact [[email protected]](mailto:[email protected]) if you want to build on Macro under a different license.
\ No newline at end of file
+Macro is open source under the AGPLv3, and self-hosting is free, though some bundled services require your own licenses and it isn't our primary focus yet. See the [FAQ](/faq) for the current state of self-hosting, and contact [[email protected]](mailto:[email protected]) if you want to build on Macro under a different license.
diff --git a/apps/docs/product/agents.mdx b/apps/docs/product/agents.mdx
index 8c26536fbb..87d246229e 100644
--- a/apps/docs/product/agents.mdx
+++ b/apps/docs/product/agents.mdx
@@ -77,7 +77,7 @@ Agents can run on a schedule. An automation is a saved prompt that runs on its o
A model picker sits in the chat input. You can choose a model per chat depending on how difficult you deem the question. Your choice is remembered for that chat and carried forward when you start a new one from the composer.
-Without a Macro Pro account you can only use Haiku, the fast model. More capable models are available once you upgrade.
+On the free plan you can only use Haiku, the fast model. Every paid plan (Premium and Max) unlocks the rest, including Opus 5, Fable 5.1 (Anthropic's most capable model), and GPT-6 Astra (OpenAI's). Heavier models draw down your included AI faster, and the picker shows by how much: Opus uses about 2.5×, and Fable and Astra about 5×, what Sonnet does for the same conversation.
<Frame>
![The model picker, showing the available models](/images/model_options.png)
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index 73451c91ca..8a1ab709c9 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -23,6 +23,7 @@ import {
isAddInboxDialogOpen,
} from '@app/features/inbox/AddInboxDialog';
import { MacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';
+import { AiUsageLimitDialog } from '@app/features/paywall/AiUsageLimitDialog';
import { Paywall } from '@app/features/paywall/Paywall';
import { PropertyEditorModal } from '@app/features/property/editor/PropertyEditorModal';
import { ReminderComposerModal } from '@app/features/reminders/ReminderComposerModal';
@@ -52,6 +53,7 @@ import {
} from '@components/app/sidebarVisibility';
import { useIsAuthenticated } from '@core/auth';
import { UserCardDrawer } from '@core/component/UserCardDrawer';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
import { enableReminders } from '@core/constant/featureFlags';
import { usePaywallState } from '@core/constant/PaywallState';
import { isSoloSettings } from '@core/constant/SettingsState';
@@ -352,6 +354,7 @@ function NewOnboardingRedirect() {
function LayoutInner(props: RouteSectionProps) {
const isAuthenticated = useIsAuthenticated();
const { paywallOpen, showPaywall } = usePaywallState();
+ const { usageLimitOpen } = useAiUsageLimitState();
const location = useLocation();
const [sidebarOverlayOpen, setSidebarOverlayOpen] = createSignal(false);
const [sidebarOverlayTriggerHovered, setSidebarOverlayTriggerHovered] =
@@ -498,6 +501,9 @@ function LayoutInner(props: RouteSectionProps) {
<Paywall />
</Suspense>
</Show>
+ <Show when={usageLimitOpen()}>
+ <AiUsageLimitDialog />
+ </Show>
<div class="max-h-full grow flex">
{/* The provider spans the sidebar too so its favorites can register
sortables with the same drag-drop context as the entity drags. */}
diff --git a/apps/web/src/features/block-chat/component/Chat.tsx b/apps/web/src/features/block-chat/component/Chat.tsx
index 8ec3573454..973f386087 100644
--- a/apps/web/src/features/block-chat/component/Chat.tsx
+++ b/apps/web/src/features/block-chat/component/Chat.tsx
@@ -41,6 +41,7 @@ import {
storeChatState,
} from '@core/component/AI/util/storage';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
import { usePaywallState } from '@core/constant/PaywallState';
import { TOKENS } from '@core/hotkey/tokens';
import { registerScopeSignalHotkey } from '@core/hotkey/utils';
@@ -97,6 +98,7 @@ function ChatWithController(props: {
loadedInputText: string | undefined;
}) {
const { showPaywall } = usePaywallState();
+ const { showUsageLimit } = useAiUsageLimitState();
const input = useChatInputContext();
const hasPaidAccess = useHasPaidAccess();
@@ -127,6 +129,7 @@ function ChatWithController(props: {
messages={props.data.chat.messages}
controllerOptions={{
onShowPaywall: showPaywall,
+ onShowUsageLimit: showUsageLimit,
onSwitchModel,
hasAlternateModel: () => nextModel() !== undefined,
}}
@@ -227,6 +230,7 @@ function ChatInner(props: {
chat.dispatch({
type: 'send_failed',
paymentError: result.paymentError,
+ usageLimit: result.usageLimit,
});
return;
}
diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts
index a7fe3cd6bb..a00a74bcab 100644
--- a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts
+++ b/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts
@@ -2,43 +2,27 @@
* @vitest-environment jsdom
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
-const mocks = vi.hoisted(() => ({
- createCheckoutSessionV2: vi.fn(),
-}));
+import { onboardingCheckoutArgs } from './use-onboarding-checkout';
-vi.mock('@service-stripe/client', () => ({
- stripeServiceClient: {
- createCheckoutSessionV2: mocks.createCheckoutSessionV2,
- },
-}));
-
-import { createOnboardingCheckoutSession } from './use-onboarding-checkout';
-
-beforeEach(() => {
- mocks.createCheckoutSessionV2.mockReset();
-});
-
-describe('createOnboardingCheckoutSession', () => {
- it('uses the supported v2 checkout endpoint and returns both legs to the flow', async () => {
- mocks.createCheckoutSessionV2.mockResolvedValue('https://checkout.test/1');
-
- await expect(createOnboardingCheckoutSession('premium')).resolves.toEqual({
- checkoutUrl: 'https://checkout.test/1',
- });
- expect(mocks.createCheckoutSessionV2).toHaveBeenCalledOnce();
- expect(mocks.createCheckoutSessionV2).toHaveBeenCalledWith({
+describe('onboardingCheckoutArgs', () => {
+ it('returns both checkout legs to the onboarding flow with the plan', () => {
+ expect(onboardingCheckoutArgs('premium')).toEqual({
successUrl: `${window.location.origin}/app/onboarding?subscriptionSuccess=true&type=premium`,
cancelUrl: `${window.location.origin}/app/onboarding?subscriptionCancel=true`,
+ plan: 'premium',
});
});
- it('rejects an empty checkout URL', async () => {
- mocks.createCheckoutSessionV2.mockResolvedValue('');
-
- await expect(createOnboardingCheckoutSession('premium')).rejects.toThrow(
- 'No checkout URL returned'
+ it('carries the purchased tier back on the success leg', () => {
+ const args = onboardingCheckoutArgs('max');
+ expect(args.plan).toBe('max');
+ expect(args.successUrl).toBe(
+ `${window.location.origin}/app/onboarding?subscriptionSuccess=true&type=max`
+ );
+ expect(args.cancelUrl).toBe(
+ `${window.location.origin}/app/onboarding?subscriptionCancel=true`
);
});
});
diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.ts
index 7849fb752f..b15c58f941 100644
--- a/apps/web/src/features/onboarding/use-onboarding-checkout.ts
+++ b/apps/web/src/features/onboarding/use-onboarding-checkout.ts
@@ -1,6 +1,9 @@
import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
import type { PaidPlanTier } from '@app/features/paywall/plans';
-import { stripeServiceClient } from '@service-stripe/client';
+import {
+ type CreateCheckoutSessionArgs,
+ useCreateCheckoutSessionMutation,
+} from '@queries/auth';
import { useMutation } from '@tanstack/solid-query';
const PENDING_TEAM_KEY = 'onboarding_pending_team';
@@ -19,25 +22,21 @@ interface OnboardingCheckoutResult {
}
/**
- * Creates a Stripe checkout session whose round-trip returns to the
- * onboarding flow: the flow is still incomplete during checkout, so both
- * legs land back on the plan step (restored from sessionStorage), which
- * reads the query params to show the paid or cancelled state.
+ * The checkout request for a plan bought during onboarding. Both legs of the
+ * Stripe round-trip return to the onboarding flow: the flow is still
+ * incomplete during checkout, so success and cancel land back on the plan
+ * step (restored from sessionStorage), which reads the query params to show
+ * the paid or cancelled state.
*/
-export async function createOnboardingCheckoutSession(
+export function onboardingCheckoutArgs(
tier: PaidPlanTier
-): Promise<OnboardingCheckoutResult> {
+): CreateCheckoutSessionArgs {
const onboardingUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}onboarding`;
- const checkoutUrl = await stripeServiceClient.createCheckoutSessionV2({
+ return {
successUrl: `${onboardingUrl}?subscriptionSuccess=true&type=${tier}`,
cancelUrl: `${onboardingUrl}?subscriptionCancel=true`,
- });
-
- if (!checkoutUrl) {
- throw new Error('No checkout URL returned');
- }
-
- return { checkoutUrl };
+ plan: tier,
+ };
}
// Pending team info is saved to localStorage before checkout redirect,
@@ -64,11 +63,15 @@ export function useOnboardingCheckoutMutation(callbacks?: {
onSuccess?: (result: OnboardingCheckoutResult) => void;
onError?: (error: Error) => void;
}) {
+ const checkout = useCreateCheckoutSessionMutation();
return useMutation(() => ({
mutationFn: async (
args: OnboardingCheckoutArgs
- ): Promise<OnboardingCheckoutResult> =>
- await createOnboardingCheckoutSession(args.tier),
+ ): Promise<OnboardingCheckoutResult> => ({
+ checkoutUrl: await checkout.mutateAsync(
+ onboardingCheckoutArgs(args.tier)
+ ),
+ }),
onSuccess: callbacks?.onSuccess,
onError: callbacks?.onError,
}));
diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
new file mode 100644
index 0000000000..04882f2cfa
--- /dev/null
+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
@@ -0,0 +1,125 @@
+import { AiUsageControls, AiUsageMeter } from '@app/features/settings/AiUsage';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { toast } from '@core/component/Toast/Toast';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import { useAiBillingSummaryQuery, useChangePlanMutation } from '@queries/auth';
+import type { AiDenyCode } from '@service-auth/ai-billing-types';
+import { useNavigate } from '@solidjs/router';
+import { Button, Dialog, Surface } from '@ui';
+import { Show, Suspense } from 'solid-js';
+
+const TITLES: Record<AiDenyCode, string> = {
+ ai_allowance_exhausted: "You've used this month's included AI",
+ ai_overage_limit_reached: "You've hit your AI spending limit",
+ ai_overage_payment_failed: 'Your last AI usage charge failed',
+};
+
+/**
+ * Shown when the backend refuses an AI request with a billing code. Offers the
+ * payer the same controls as Billing settings, right where they were blocked.
+ */
+export function AiUsageLimitDialog() {
+ const { usageLimitOpen, usageLimitCode, hideUsageLimit } =
+ useAiUsageLimitState();
+ const analytics = useAnalytics();
+ const navigate = useNavigate();
+ const summary = useAiBillingSummaryQuery({ enabled: usageLimitOpen });
+ const changePlan = useChangePlanMutation();
+
+ const title = () => TITLES[usageLimitCode() ?? 'ai_allowance_exhausted'];
+ const returnUrl = () => `${window.location.origin}/app/settings/billing`;
+
+ const upgradeToMax = async () => {
+ try {
+ await changePlan.mutateAsync({ plan: 'max' });
+ analytics.track('plan_changed', { plan: 'max', from: 'usage_limit' });
+ toast.success('Upgraded to Max. Send your message again.');
+ hideUsageLimit();
+ } catch (error) {
+ console.error(error);
+ toast.failure("Couldn't upgrade. Please try again from Billing.");
+ }
+ };
+
+ return (
+ <Dialog
+ open={usageLimitOpen()}
+ 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">
+ <h2 class="text-xl font-semibold text-ink">{title()}</h2>
+ <p class="text-sm text-ink-extra-muted">
+ Your plan includes AI each month at Macro's usage rates. Add
+ credits or turn on usage billing to keep going now, or move to Max
+ for five times the included usage.
+ </p>
+ </div>
+
+ {/* The summary is a suspending query resource; keep its
+ suspension inside the dialog rather than the route boundary. */}
+ <Suspense fallback={null}>
+ <Show when={summary.isSuccess && summary.data}>
+ {(snapshot) => (
+ <div class="flex flex-col gap-4 rounded-lg bg-active p-4">
+ <AiUsageMeter snapshot={snapshot()} />
+ <div class="border-t border-t-edge-muted pt-4">
+ <AiUsageControls
+ snapshot={snapshot()}
+ returnUrl={returnUrl()}
+ />
+ </div>
+ </div>
+ )}
+ </Show>
+ </Suspense>
+
+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <Button
+ variant="ghost"
+ depth={3}
+ class="rounded-full px-3 py-1.5"
+ onClick={() => {
+ hideUsageLimit();
+ navigate('/app/settings/billing');
+ }}
+ >
+ Open billing settings
+ </Button>
+ <div class="flex gap-2 sm:justify-end">
+ <Button
+ variant="ghost"
+ depth={3}
+ class="rounded-full px-3 py-1.5"
+ onClick={hideUsageLimit}
+ >
+ Dismiss
+ </Button>
+ <Suspense fallback={null}>
+ <Show
+ when={
+ summary.isSuccess &&
+ summary.data.can_manage_billing &&
+ summary.data.tier === 'premium'
+ }
+ >
+ <Button
+ variant="cta"
+ class="rounded-full px-3 py-1.5"
+ disabled={changePlan.isPending}
+ onClick={() => void upgradeToMax()}
+ >
+ Upgrade to Max
+ </Button>
+ </Show>
+ </Suspense>
+ </div>
+ </div>
+ </section>
+ </Surface>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.ts
index 3d12773155..939a776305 100644
--- a/apps/web/src/features/paywall/plans.ts
+++ b/apps/web/src/features/paywall/plans.ts
@@ -1,9 +1,14 @@
-export type PlanTier = 'free' | 'premium';
+export type PlanTier = 'free' | 'premium' | 'max';
export type Plan = {
tier: PlanTier;
name: string;
price: number;
highlighted: boolean;
+ /**
+ * AI usage included each month, in dollars at Macro's list rate. Equal to the
+ * plan price: the plan's AI allowance is worth what the plan costs.
+ */
+ aiIncluded: number;
};
/** Tiers that correspond to real Stripe products. Excludes 'free'. */
export type PaidPlanTier = Exclude<PlanTier, 'free'>;
@@ -14,15 +19,30 @@ export const PLANS = [
name: 'Free',
price: 0,
highlighted: false,
+ aiIncluded: 0,
},
{
tier: 'premium' as const,
name: 'Premium',
price: 40,
highlighted: true,
+ aiIncluded: 40,
+ },
+ {
+ tier: 'max' as const,
+ name: 'Max',
+ price: 200,
+ highlighted: false,
+ aiIncluded: 200,
},
] as const satisfies Plan[];
+export const PLAN_BY_TIER: Record<PlanTier, Plan> = {
+ free: PLANS[0],
+ premium: PLANS[1],
+ max: PLANS[2],
+};
+
interface PlanFeature {
label: string;
values: Record<PlanTier, string>;
@@ -30,10 +50,11 @@ interface PlanFeature {
export const PLAN_FEATURES: PlanFeature[] = [
{
- label: 'AI Tool Calls',
+ label: 'AI usage included',
values: {
- free: '—',
- premium: 'Unlimited',
+ free: 'Limited',
+ premium: '$40 / mo',
+ max: '$200 / mo',
},
},
{
@@ -41,6 +62,15 @@ export const PLAN_FEATURES: PlanFeature[] = [
values: {
free: 'Haiku',
premium: 'All models',
+ max: 'All models',
+ },
+ },
+ {
+ label: 'Beyond included',
+ values: {
+ free: '—',
+ premium: 'Credits or usage billing',
+ max: 'Credits or usage billing',
},
},
{
@@ -48,6 +78,7 @@ export const PLAN_FEATURES: PlanFeature[] = [
values: {
free: '5 GB',
premium: '1 TB',
+ max: '1 TB',
},
},
];
diff --git a/apps/web/src/features/settings/AiUsage.test.tsx b/apps/web/src/features/settings/AiUsage.test.tsx
new file mode 100644
index 0000000000..787e0ffaad
--- /dev/null
+++ b/apps/web/src/features/settings/AiUsage.test.tsx
@@ -0,0 +1,52 @@
+import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { AiUsageMeter } from './AiUsage';
+
+vi.mock('@ui', () => ({
+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),
+ Button: () => null,
+ ToggleSwitch: () => null,
+}));
+
+const snapshot = (seats: number): AiUsageSnapshot => ({
+ tier: 'premium',
+ unlimited: false,
+ payer: 'macro|[email protected]',
+ can_manage_billing: true,
+ seats,
+ period_start: '2026-09-01T00:00:00Z',
+ period_end: '2026-10-01T00:00:00Z',
+ included_cents: 4_000,
+ used_cents: 1_000,
+ credits_consumed_cents: 0,
+ credit_balance_cents: 2_500,
+ overage_enabled: true,
+ overage_limit_cents: 5_000,
+ overage_charged_cents: 1_000,
+ overage_suspended: false,
+ uncovered_cents: 0,
+ remaining_cents: 10_500,
+});
+
+afterEach(cleanup);
+
+describe('AiUsageMeter', () => {
+ it('shows a team member their own allowance and shared billing balances', () => {
+ render(() => <AiUsageMeter snapshot={snapshot(5)} />);
+
+ expect(screen.getAllByText('$10')).toHaveLength(2);
+ expect(screen.getByText(/of \$40 included/)).toBeTruthy();
+ expect(screen.queryByText(/across 5 seats/)).toBeNull();
+ expect(screen.getByText(/Team credits:/)).toBeTruthy();
+ expect(screen.getByText(/Team usage billing this period/)).toBeTruthy();
+ });
+
+ it('uses personal labels outside a team', () => {
+ render(() => <AiUsageMeter snapshot={snapshot(1)} />);
+
+ expect(screen.getByText(/Credits:/)).toBeTruthy();
+ expect(screen.getByText(/Usage billing this period/)).toBeTruthy();
+ expect(screen.queryByText(/Team credits:/)).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/settings/AiUsage.tsx b/apps/web/src/features/settings/AiUsage.tsx
new file mode 100644
index 0000000000..8104b4663d
--- /dev/null
+++ b/apps/web/src/features/settings/AiUsage.tsx
@@ -0,0 +1,277 @@
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ useAiBillingPlansQuery,
+ useCreateAiCreditCheckoutMutation,
+ useUpdateAiOverageMutation,
+} from '@queries/auth';
+import type {
+ AiDenyReason,
+ AiUsageSnapshot,
+} from '@service-auth/ai-billing-types';
+import { Button, cn, ToggleSwitch } from '@ui';
+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
+
+/** Whole dollars when even, otherwise dollars and cents. */
+export function formatCents(cents: number): string {
+ const dollars = cents / 100;
+ return Number.isInteger(dollars)
+ ? `$${dollars.toLocaleString()}`
+ : `$${dollars.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })}`;
+}
+
+function formatPeriodEnd(iso: string): string {
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return '';
+ return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+const BLOCKED_COPY: Record<AiDenyReason, string> = {
+ allowance_exhausted:
+ "You've used this period's included AI. Add credits, turn on usage billing, or upgrade to keep going.",
+ overage_limit_reached:
+ "You've reached your usage billing limit for this period. Raise the limit or add credits to keep going.",
+ overage_payment_failed:
+ "Your last AI usage charge didn't go through. Update your payment method in Manage, then turn usage billing back on.",
+};
+
+/** Fallback caps offered when the catalog has not loaded yet. */
+const DEFAULT_OVERAGE_LIMITS_CENTS = [2_500, 5_000, 10_000, 25_000];
+const DEFAULT_CREDIT_PACKS_CENTS = [1_000, 2_500, 5_000, 10_000];
+
+/**
+ * The period's AI position: a meter of included usage plus credits and overage
+ * headroom, and where the user stands right now.
+ */
+export function AiUsageMeter(props: { snapshot: AiUsageSnapshot }) {
+ const included = () => props.snapshot.included_cents;
+ const used = () => props.snapshot.used_cents;
+ const includedUsed = () => Math.min(used(), included());
+ const beyond = () => Math.max(0, used() - included());
+ // Both segments share one scale (the larger of included and used) so they
+ // total at most 100% and the beyond-included segment stays visible.
+ const scale = () => Math.max(included(), used());
+ const pct = () => (scale() > 0 ? (includedUsed() / scale()) * 100 : 0);
+ const beyondPct = () => (scale() > 0 ? (beyond() / scale()) * 100 : 0);
+ const blocked = () => !!props.snapshot.blocked_reason;
+
+ return (
+ <div class="flex flex-col gap-2">
+ <div class="flex items-baseline justify-between gap-3">
+ <span class="text-sm text-ink">
+ <span class="font-semibold">{formatCents(used())}</span>
+ <span class="text-ink-muted">
+ {' '}
+ of {formatCents(included())} included
+ </span>
+ </span>
+ <span class="text-xs text-ink-extra-muted">
+ Resets {formatPeriodEnd(props.snapshot.period_end)}
+ </span>
+ </div>
+ <div class="relative h-2 w-full overflow-hidden rounded-full bg-active">
+ <div
+ class={cn(
+ 'absolute inset-y-0 left-0 rounded-full transition-[width]',
+ blocked() ? 'bg-failure' : 'bg-accent'
+ )}
+ style={{ width: `${pct()}%` }}
+ />
+ <Show when={beyond() > 0}>
+ <div
+ class="absolute inset-y-0 rounded-full bg-warning/70"
+ style={{ left: `${pct()}%`, width: `${beyondPct()}%` }}
+ />
+ </Show>
+ </div>
+ <div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-muted">
+ <Show when={beyond() > 0}>
+ <span>{formatCents(beyond())} beyond included</span>
+ </Show>
+ <span>
+ {props.snapshot.seats > 1 ? 'Team credits' : 'Credits'}:{' '}
+ <span class="text-ink">
+ {formatCents(props.snapshot.credit_balance_cents)}
+ </span>
+ </span>
+ <Show when={props.snapshot.overage_enabled}>
+ <span>
+ {props.snapshot.seats > 1
+ ? 'Team usage billing this period'
+ : 'Usage billing this period'}
+ :{' '}
+ <span class="text-ink">
+ {formatCents(props.snapshot.overage_charged_cents)}
+ </span>{' '}
+ of {formatCents(props.snapshot.overage_limit_cents)}
+ </span>
+ </Show>
+ </div>
+ <Show when={props.snapshot.blocked_reason}>
+ {(reason) => (
+ <p class="text-xs text-failure">{BLOCKED_COPY[reason()]}</p>
+ )}
+ </Show>
+ </div>
+ );
+}
+
+/**
+ * The payer's controls: buy a credit pack, and turn usage billing on or off
+ * with a per-period cap. Members who are not the payer see who to ask.
+ */
+export function AiUsageControls(props: {
+ snapshot: AiUsageSnapshot;
+ /** Where Stripe returns after a credit purchase. */
+ returnUrl: string;
+}) {
+ const analytics = useAnalytics();
+ const plans = useAiBillingPlansQuery();
+ const updateOverage = useUpdateAiOverageMutation();
+ const creditCheckout = useCreateAiCreditCheckoutMutation();
+
+ const creditPacks = () =>
+ plans.isSuccess
+ ? plans.data.credit_packs_cents
+ : DEFAULT_CREDIT_PACKS_CENTS;
+ const overageLimits = createMemo(() => {
+ const current = props.snapshot.overage_limit_cents;
+ const options = [...DEFAULT_OVERAGE_LIMITS_CENTS];
+ if (current > 0 && !options.includes(current)) {
+ options.push(current);
+ options.sort((a, b) => a - b);
+ }
+ return options;
+ });
+ const [pendingLimit, setPendingLimit] = createSignal<number | null>(null);
+ const selectedLimit = () =>
+ pendingLimit() ??
+ (props.snapshot.overage_limit_cents > 0
+ ? props.snapshot.overage_limit_cents
+ : DEFAULT_OVERAGE_LIMITS_CENTS[1]);
+
+ const busy = () => updateOverage.isPending || creditCheckout.isPending;
+
+ const buyCredits = async (amountCents: number) => {
+ try {
+ analytics.track('ai_credits_checkout_start', { amountCents });
+ const url = await creditCheckout.mutateAsync({
+ amountCents,
+ successUrl: `${props.returnUrl}?aiCreditsSuccess=true`,
+ cancelUrl: `${props.returnUrl}?aiCreditsCancel=true`,
+ });
+ window.location.href = url;
+ } catch (error) {
+ console.error(error);
+ toast.failure("Couldn't start the credit purchase. Please try again.");
+ }
+ };
+
+ const setOverage = async (enabled: boolean, limitCents: number) => {
+ try {
+ await updateOverage.mutateAsync({ enabled, limitCents });
+ analytics.track('ai_overage_updated', { enabled, limitCents });
+ setPendingLimit(null);
+ toast.success(
+ enabled
+ ? `Usage billing on, up to ${formatCents(limitCents)} per period.`
+ : 'Usage billing off.'
+ );
+ } catch (error) {
+ console.error(error);
+ toast.failure("Couldn't update usage billing. Please try again.");
+ }
+ };
+
+ return (
+ <Show
+ when={props.snapshot.can_manage_billing}
+ fallback={
+ <p class="text-xs text-ink-extra-muted">
+ AI usage for your team is managed by the team owner. Ask them to add
+ credits or turn on usage billing, or ask a team admin to move your
+ seat to Max.
+ </p>
+ }
+ >
+ <div class="flex flex-col gap-5">
+ <div class="flex flex-col gap-2">
+ <div class="flex flex-col">
+ <span class="text-sm text-ink">Add credits</span>
+ <span class="text-xs text-ink-extra-muted">
+ Prepaid AI usage that applies after included usage and carries
+ over between periods.
+ </span>
+ </div>
+ <div class="flex flex-wrap gap-2">
+ <For each={creditPacks()}>
+ {(cents) => (
+ <Button
+ variant="outline"
+ size="sm"
+ depth={2}
+ class="rounded-full"
+ disabled={busy()}
+ onClick={() => void buyCredits(cents)}
+ >
+ {formatCents(cents)}
+ </Button>
+ )}
+ </For>
+ </div>
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <div class="flex items-start justify-between gap-4">
+ <div class="flex flex-col">
+ <span class="text-sm text-ink">Usage billing</span>
+ <span class="text-xs text-ink-extra-muted">
+ Bill AI beyond included usage and credits to your card in{' '}
+ {formatCents(1_000)} increments, up to a limit you set.
+ </span>
+ </div>
+ <ToggleSwitch
+ size="md"
+ checked={props.snapshot.overage_enabled}
+ disabled={busy()}
+ onChange={(checked) => void setOverage(checked, selectedLimit())}
+ />
+ </div>
+ <Switch>
+ <Match when={props.snapshot.overage_suspended}>
+ <p class="text-xs text-failure">
+ Paused after a failed charge. Fix your payment method under
+ Manage, then turn usage billing back on to retry.
+ </p>
+ </Match>
+ <Match when={props.snapshot.overage_enabled}>
+ <div class="flex flex-wrap items-center gap-2">
+ <span class="text-xs text-ink-muted">Limit per period</span>
+ <For each={overageLimits()}>
+ {(cents) => (
+ <Button
+ variant={selectedLimit() === cents ? 'accent' : 'outline'}
+ size="xs"
+ depth={2}
+ class="rounded-full px-2"
+ disabled={busy()}
+ onClick={() => {
+ setPendingLimit(cents);
+ void setOverage(true, cents);
+ }}
+ >
+ {formatCents(cents)}
+ </Button>
+ )}
+ </For>
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsx
index 64a28cbe36..06b28383e4 100644
--- a/apps/web/src/features/settings/Billing.tsx
+++ b/apps/web/src/features/settings/Billing.tsx
@@ -1,15 +1,24 @@
-import type { PlanTier } from '@app/features/paywall/plans';
+import { PLAN_BY_TIER, type PlanTier } from '@app/features/paywall/plans';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useHasPaidAccess } from '@core/auth';
+import { toast } from '@core/component/Toast/Toast';
import { PERMISSION_IDS } from '@core/constant/permissions';
import { usePermissions, useUserId } from '@core/context/user';
import { plural } from '@core/util/string';
import CheckIcon from '@phosphor/check.svg';
import EnvelopeIcon from '@phosphor/envelope.svg';
+import {
+ useAiBillingSummaryQuery,
+ useChangePlanMutation,
+ useCreateCheckoutSessionMutation,
+} from '@queries/auth';
import { useCurrentTeamQuery } from '@queries/team/teams';
+import type { PaidPlan } from '@service-auth/ai-billing-types';
+import type { TeamMember } from '@service-auth/generated/schemas/teamMember';
import { stripeServiceClient } from '@service-stripe/client';
import { Button, Layer } from '@ui';
import { createMemo, For, Match, Show, Switch } from 'solid-js';
+import { AiUsageControls, AiUsageMeter } from './AiUsage';
import { SettingsCard, SettingsPage, SettingsSection } from './primitives';
const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {
@@ -17,6 +26,7 @@ const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {
premium: [
'All agents',
'All models',
+ '$40 of AI usage each month',
'No watermark',
'AI projections',
'Multiple email inboxes',
@@ -24,6 +34,11 @@ const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {
'Teams',
'1 TB storage',
],
+ max: [
+ 'Everything in Premium',
+ '$200 of AI usage each month',
+ 'Priority support',
+ ],
};
const PlanFeatures = (props: { tier: PlanTier }) => (
@@ -37,14 +52,38 @@ const PlanFeatures = (props: { tier: PlanTier }) => (
</For>
);
+/** "3 Premium seats, 1 Max seat" for a team's members. */
+function describeSeatPlans(members: TeamMember[]): string {
+ const maxSeats = members.filter(
+ (member) => (member as TeamMember & { plan?: PaidPlan }).plan === 'max'
+ ).length;
+ const premiumSeats = members.length - maxSeats;
+ const parts: string[] = [];
+ if (premiumSeats > 0) {
+ parts.push(`${premiumSeats} Premium ${plural('seat', premiumSeats)}`);
+ }
+ if (maxSeats > 0) {
+ parts.push(`${maxSeats} Max ${plural('seat', maxSeats)}`);
+ }
+ return parts.join(', ');
+}
+
+const PlanPrice = (props: { tier: PaidPlan }) => (
+ <p class="text-ink-extra-muted text-xs">
+ ${PLAN_BY_TIER[props.tier].price} per seat / month · includes $
+ {PLAN_BY_TIER[props.tier].aiIncluded} of AI usage
+ </p>
+);
+
export const Billing = () => {
const permissions = usePermissions();
const analytics = useAnalytics();
const hasPaid = useHasPaidAccess();
-
const userId = useUserId();
-
const team = useCurrentTeamQuery();
+ const summary = useAiBillingSummaryQuery();
+ const changePlan = useChangePlanMutation();
+ const checkout = useCreateCheckoutSessionMutation();
const canManageSubscription = createMemo(() => {
return permissions()?.includes(PERMISSION_IDS.WRITE_STRIPE_SUBSCRIPTION);
@@ -67,15 +106,45 @@ export const Billing = () => {
return team.owner_id === uid ? 'owner' : 'member';
});
- const handleCheckout = async () => {
+ // The billing summary knows the tier (Premium vs Max); the license status is
+ // the fallback while it loads or when the user is on the free plan.
+ const tier = createMemo((): PlanTier => {
+ if (summary.isSuccess) return summary.data.tier;
+ return hasPaid() ? 'premium' : 'free';
+ });
+ // A member whose seat the team pays for manages nothing here; a member of
+ // a free team pays for themself and gets the same controls as a solo user.
+ const billedThroughTeam = () =>
+ summary.isSuccess &&
+ !summary.data.can_manage_billing &&
+ summary.data.tier !== 'free';
+ const isOwnerOrSolo = () =>
+ !teamRole() || teamRole() === 'owner' || !billedThroughTeam();
+ const canChangePlan = () => canManageSubscription() && isOwnerOrSolo();
+
+ const handleCheckout = async (plan: PaidPlan) => {
try {
- const url = await stripeServiceClient.createCheckoutSessionV2({});
- analytics.track('subscription_start', {
- type: 'premium',
- });
+ const url = await checkout.mutateAsync({ plan });
+ analytics.track('subscription_start', { type: plan });
window.location.href = url;
} catch (error) {
console.error(error);
+ toast.failure("Couldn't start checkout. Please try again.");
+ }
+ };
+
+ const handleChangePlan = async (plan: PaidPlan) => {
+ try {
+ await changePlan.mutateAsync({ plan });
+ analytics.track('plan_changed', { plan });
+ toast.success(
+ plan === 'max'
+ ? 'Upgraded to Max. Your larger AI allowance applies right away.'
+ : 'Switched to Premium.'
+ );
+ } catch (error) {
+ console.error(error);
+ toast.failure("Couldn't change your plan. Please try again.");
}
};
@@ -88,6 +157,8 @@ export const Billing = () => {
}
};
+ const returnUrl = () => `${window.location.origin}/app/settings/billing`;
+
return (
<SettingsPage
title="Billing"
@@ -111,9 +182,7 @@ export const Billing = () => {
<div class="flex flex-col gap-1">
<div class="flex items-center gap-2">
<h2 class="text-lg font-medium text-ink">
- <Show when={!hasPaid()} fallback={'Premium plan'}>
- Free plan
- </Show>
+ {PLAN_BY_TIER[tier()].name} plan
</h2>
<Layer depth={3}>
@@ -123,10 +192,17 @@ export const Billing = () => {
</Layer>
</div>
<Switch>
- <Match when={teamRole() === 'member'}>
+ <Match when={teamRole() === 'member' && billedThroughTeam()}>
<p class="text-ink-extra-muted text-xs">
- Your subscription is managed by your team owner. Contact
- them to make changes.
+ Your seat is billed through your team. Team admins choose
+ each seat's plan in{' '}
+ <a
+ class="text-link hover:text-link-hover"
+ href="/app/settings/team"
+ >
+ Team settings
+ </a>
+ .
</p>
</Match>
<Match
@@ -135,8 +211,15 @@ export const Billing = () => {
{(team) => (
<p class="text-ink-extra-muted text-xs">
{team().members.length}{' '}
- {plural('user', team().members.length)} • $40 per
- seat/per month
+ {plural('user', team().members.length)} •{' '}
+ {describeSeatPlans(team().members)} • set each seat's
+ plan in{' '}
+ <a
+ class="text-link hover:text-link-hover"
+ href="/app/settings/team"
+ >
+ Team settings
+ </a>
</p>
)}
</Match>
@@ -144,11 +227,7 @@ export const Billing = () => {
</div>
<Show
- when={
- canManageSubscription() &&
- hasPaid() &&
- (!teamRole() || teamRole() === 'owner')
- }
+ when={canManageSubscription() && hasPaid() && isOwnerOrSolo()}
>
<Button
class="ml-auto rounded-full bg-active"
@@ -162,45 +241,141 @@ export const Billing = () => {
</Show>
</header>
<ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">
- <PlanFeatures tier={hasPaid() ? 'premium' : 'free'} />
+ <PlanFeatures tier={tier()} />
</ul>
</section>
</SettingsCard>
</SettingsSection>
- <Show
- when={
- !hasPaid() &&
- canManageSubscription() &&
- (!teamRole() || teamRole() === 'owner')
- }
- >
- <SettingsSection>
- <SettingsCard>
- <section class="flex flex-col gap-4 p-4">
- <header class="flex items-center gap-2">
- <div class="flex flex-col">
- <h2 class="text-lg font-medium text-ink">Premium</h2>
- <p class="text-ink-extra-muted text-xs">
- $40 per seat / month
- </p>
- </div>
+ <Show when={hasPaid() && summary.isSuccess && summary.data}>
+ {(snapshot) => (
+ <SettingsSection
+ title="AI usage"
+ description="Your plan includes AI each month at Macro's usage rates. Beyond that, prepaid credits and usage billing keep you going."
+ >
+ <SettingsCard>
+ <section class="flex flex-col gap-5 p-4">
+ <Show
+ when={!snapshot().unlimited}
+ fallback={
+ <p class="text-sm text-ink-muted">
+ Your enterprise plan includes unlimited AI usage.
+ </p>
+ }
+ >
+ <AiUsageMeter snapshot={snapshot()} />
+ <div class="border-t border-t-edge-muted pt-4">
+ <AiUsageControls
+ snapshot={snapshot()}
+ returnUrl={returnUrl()}
+ />
+ </div>
+ </Show>
+ </section>
+ </SettingsCard>
+ </SettingsSection>
+ )}
+ </Show>
- <Button
- class="ml-auto rounded-full py-1.5 px-3"
- depth={2}
- variant="cta"
- onClick={handleCheckout}
+ <Show when={canChangePlan()}>
+ <Switch>
+ <Match when={!hasPaid()}>
+ <SettingsSection title="Upgrade">
+ <SettingsCard>
+ <section class="flex flex-col gap-4 p-4">
+ <header class="flex items-center gap-2">
+ <div class="flex flex-col">
+ <h2 class="text-lg font-medium text-ink">Premium</h2>
+ <PlanPrice tier="premium" />
+ </div>
+ <Button
+ class="ml-auto rounded-full py-1.5 px-3"
+ depth={2}
+ variant="cta"
+ onClick={() => void handleCheckout('premium')}
+ >
+ Upgrade now
+ </Button>
+ </header>
+ <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">
+ <PlanFeatures tier="premium" />
+ </ul>
+ </section>
+ </SettingsCard>
+ <SettingsCard>
+ <section class="flex flex-col gap-4 p-4">
+ <header class="flex items-center gap-2">
+ <div class="flex flex-col">
+ <h2 class="text-lg font-medium text-ink">Max</h2>
+ <PlanPrice tier="max" />
+ </div>
+ <Button
+ class="ml-auto rounded-full py-1.5 px-3"
+ depth={2}
+ variant="outline"
+ onClick={() => void handleCheckout('max')}
+ >
+ Get Max
+ </Button>
+ </header>
+ <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">
+ <PlanFeatures tier="max" />
+ </ul>
+ </section>
+ </SettingsCard>
+ </SettingsSection>
+ </Match>
+ <Match when={tier() === 'premium'}>
+ <SettingsSection title="Need more AI?">
+ <SettingsCard>
+ <section class="flex flex-col gap-4 p-4">
+ <header class="flex items-center gap-2">
+ <div class="flex flex-col">
+ <h2 class="text-lg font-medium text-ink">Max</h2>
+ <PlanPrice tier="max" />
+ </div>
+ <Button
+ class="ml-auto rounded-full py-1.5 px-3"
+ depth={2}
+ variant="cta"
+ disabled={changePlan.isPending}
+ onClick={() => void handleChangePlan('max')}
+ >
+ Upgrade to Max
+ </Button>
+ </header>
+ <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">
+ <PlanFeatures tier="max" />
+ </ul>
+ <p class="text-xs text-ink-extra-muted">
+ Prorated for the rest of this period.
+ <Show when={teamRole() === 'owner'}>
+ {' '}
+ This moves only your seat; teammates' plans are set per
+ seat in Team settings.
+ </Show>
+ </p>
+ </section>
+ </SettingsCard>
+ </SettingsSection>
+ </Match>
+ <Match when={tier() === 'max'}>
+ <SettingsSection>
+ <p class="px-6 text-xs text-ink-extra-muted">
+ Want a smaller plan?{' '}
+ <button
+ type="button"
+ class="text-link hover:text-link-hover"
+ disabled={changePlan.isPending}
+ onClick={() => void handleChangePlan('premium')}
>
- Upgrade now
- </Button>
- </header>
- <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">
- <PlanFeatures tier="premium" />
- </ul>
- </section>
- </SettingsCard>
- </SettingsSection>
+ Switch to Premium
+ </button>{' '}
+ ($40 per seat / month with $40 of AI usage).
+ </p>
+ </SettingsSection>
+ </Match>
+ </Switch>
</Show>
</SettingsPage>
);
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsx
index c58b21928e..4b4130c045 100644
--- a/apps/web/src/features/settings/Team.tsx
+++ b/apps/web/src/features/settings/Team.tsx
@@ -28,7 +28,10 @@ import SpinnerIcon from '@phosphor/spinner.svg';
import TrashIcon from '@phosphor/trash.svg';
import UsersIcon from '@phosphor/users.svg';
import XIcon from '@phosphor/x.svg';
-import { useGithubLinkStatusQuery } from '@queries/auth';
+import {
+ useAiBillingSummaryQuery,
+ useGithubLinkStatusQuery,
+} from '@queries/auth';
import {
useJoinTeamMutation,
useRejectInvitationMutation,
@@ -39,7 +42,10 @@ import {
useInviteToTeamMutation,
useTeamInvitesQuery,
} from '@queries/team/invites';
-import { useRemoveUserFromTeamMutation } from '@queries/team/members';
+import {
+ useRemoveUserFromTeamMutation,
+ useSetTeamMemberPlanMutation,
+} from '@queries/team/members';
import {
useCreateTeamWithInvitesMutation,
useDeleteTeamMutation,
@@ -49,6 +55,7 @@ import {
useToggleNonAdminInvitesMutation,
useUserTeamsQuery,
} from '@queries/team/teams';
+import type { PaidPlan } from '@service-auth/ai-billing-types';
import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';
import type { TeamMember } from '@service-auth/generated/schemas/teamMember';
import { TeamRole } from '@service-auth/generated/schemas/teamRole';
@@ -154,6 +161,77 @@ function RoleSelect(props: {
);
}
+type PlanOption = { value: PaidPlan; label: string; description: string };
+
+const planOptions: PlanOption[] = [
+ { value: 'premium', label: 'Premium', description: '$40 · $40 of AI' },
+ { value: 'max', label: 'Max', description: '$200 · $200 of AI' },
+];
+
+/**
+ * The plan a member's seat is billed at. Until the generated `TeamMember`
+ * schema carries `plan`, read it defensively; every seat starts on Premium.
+ */
+function memberPlan(member: TeamMember): PaidPlan {
+ const plan = (member as TeamMember & { plan?: PaidPlan }).plan;
+ return plan === 'max' ? 'max' : 'premium';
+}
+
+function PlanSelect(props: {
+ value: PaidPlan;
+ onChange: (plan: PaidPlan) => void;
+ disabled?: boolean;
+}) {
+ const selectedOption = () =>
+ planOptions.find((o) => o.value === props.value) ?? planOptions[0];
+
+ return (
+ <Select<PlanOption>
+ options={planOptions}
+ 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="z-action-menu border border-edge bg-surface rounded shadow-lg min-w-40 p-1">
+ <Select.Listbox />
+ </Select.Content>
+ </Select.Portal>
+ </Select>
+ );
+}
+
const emailSchema = z.string().email();
type InviteEntry = { email: string };
@@ -320,8 +398,13 @@ function MemberRow(props: {
isCurrentUser: boolean;
canManageRemovals: boolean;
canRemove: boolean;
+ /** Whether seat plans apply (paid team) and the viewer may change them. */
+ showPlan: boolean;
+ canEditPlan: boolean;
+ planPending: boolean;
onRemove: () => void;
onRoleChange: (role: TeamRole) => void;
+ onPlanChange: (plan: PaidPlan) => void;
}) {
const displayName = () => getDisplayName(tryMacroId(props.member.user_id));
const isMemberOwner = () => props.member.role === TeamRole.owner;
@@ -353,6 +436,22 @@ function MemberRow(props: {
</div>
</div>
<div class="flex items-center gap-2 shrink-0">
+ <Show when={props.showPlan}>
+ <Show
+ when={props.canEditPlan}
+ fallback={
+ <span class="text-xs text-ink-muted capitalize">
+ {memberPlan(props.member)}
+ </span>
+ }
+ >
+ <PlanSelect
+ value={memberPlan(props.member)}
+ onChange={props.onPlanChange}
+ disabled={props.planPending}
+ />
+ </Show>
+ </Show>
<Show
when={props.isOwner && !isMemberOwner()}
fallback={
@@ -963,6 +1062,30 @@ function TeamManagement(props: {
});
const isAdminOrOwner = () => isTeamAdminOrOwner(currentUserRole());
const canManageMemberRemovals = () => isAdminOrOwner();
+ // Seat plans only exist on teams billed per seat: enterprise teams, and
+ // paying teams, whose shared credits and overage are billed to the owner.
+ // The team API does not expose its subscription, so a paying team is
+ // recognised from the viewer's billing position: a paid tier whose payer is
+ // the team owner and whose seat count spans more than one member (a free-team
+ // owner with a personal subscription is billed for exactly one seat). A
+ // paying team of one therefore shows no seat menu; its owner moves their own
+ // seat from Billing.
+ const billingSummary = useAiBillingSummaryQuery();
+ const showSeatPlans = () => {
+ const team = teamQuery.data?.team;
+ if (!team) return false;
+ if (team.enterprise) return true;
+ return (
+ billingSummary.isSuccess &&
+ billingSummary.data.tier !== 'free' &&
+ billingSummary.data.payer === team.owner_id &&
+ billingSummary.data.seats > 1
+ );
+ };
+ const setMemberPlanMutation = useSetTeamMemberPlanMutation();
+ // Seat moves read and rewrite the subscription's item quantities, so only
+ // one may be in flight per team: every plan menu waits while one runs.
+ const planMovePending = () => setMemberPlanMutation.isPending;
const isOwner = createMemo(() => {
const currentUserId = userId();
if (!currentUserId) return false;
@@ -1455,6 +1578,18 @@ function TeamManagement(props: {
currentUserRole(),
member
)}
+ showPlan={showSeatPlans()}
+ canEditPlan={isAdminOrOwner()}
+ planPending={planMovePending()}
+ onPlanChange={(plan) => {
+ if (!props.teamId || plan === memberPlan(member))
+ return;
+ setMemberPlanMutation.mutate({
+ teamId: props.teamId,
+ userId: member.user_id,
+ plan,
+ });
+ }}
onRemove={() => setShowRemoveModal(member)}
onRoleChange={(newRole) => {
if (!props.teamId) return;
diff --git a/apps/web/src/features/settings/teamMemberPermissions.test.ts b/apps/web/src/features/settings/teamMemberPermissions.test.ts
index 9a24e2a31a..4fb4920ac5 100644
--- a/apps/web/src/features/settings/teamMemberPermissions.test.ts
+++ b/apps/web/src/features/settings/teamMemberPermissions.test.ts
@@ -1,4 +1,8 @@
-import { type TeamMember, TeamRole } from '@service-auth/generated/schemas';
+import {
+ SeatPlan,
+ type TeamMember,
+ TeamRole,
+} from '@service-auth/generated/schemas';
import { describe, expect, it } from 'vitest';
import {
canRemoveTeamMember,
@@ -10,6 +14,7 @@ const ACTING_USER_ID = 'acting-user-id';
function teamMember(userId: string, role: TeamRole): TeamMember {
return {
+ plan: SeatPlan.premium,
role,
team_id: TEAM_ID,
user_id: userId,
diff --git a/apps/web/src/features/setup/flow/OnboardingFlow.tsx b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
index 79b5a1a84f..0b0413a0cd 100644
--- a/apps/web/src/features/setup/flow/OnboardingFlow.tsx
+++ b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
@@ -1,3 +1,4 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { FEATURED_MCP_SERVERS } from '@core/component/AI/constant/mcpServers';
@@ -91,7 +92,7 @@ interface StepControls {
finishing: () => boolean;
finishFree: (planSkipped: boolean) => void;
/** Redirect to Stripe checkout without completing the flow. */
- startPremiumCheckout: (tier: 'premium') => void;
+ startPremiumCheckout: (tier: PaidPlanTier) => void;
/** Finish after checkout confirmed payment (or an existing license). */
finishPremium: () => void;
/** The free-month promotion an invite-link signup holds, once known. */
@@ -221,7 +222,7 @@ function buildSteps(
{
key: 'plan',
title: 'Choose your plan',
- subtitle: 'Start free, or go Premium. You can change this anytime.',
+ subtitle: 'Start free, or pick a paid plan. You can change this anytime.',
wide: true,
render: (controls) => (
<PlanStep
diff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsx
index 50f0db90b0..f72fedcbd6 100644
--- a/apps/web/src/features/setup/flow/PlanStep.tsx
+++ b/apps/web/src/features/setup/flow/PlanStep.tsx
@@ -1,5 +1,7 @@
import { InviteOfferPanel } from '@app/features/gtm-invite/InviteOfferPanel';
import {
+ type PaidPlanTier,
+ PLAN_BY_TIER,
PLAN_FEATURES,
PLANS,
type PlanTier,
@@ -29,8 +31,9 @@ export function PlanStep(props: {
/** The promotion an invite-link signup holds, once known. */
inviteOffer?: GtmInviteOffer | null;
onFree: (planSkipped: boolean) => void;
- onStartCheckout: (tier: Exclude<PlanTier, 'free'>) => void;
- onPremiumPaid: () => void;
+ onStartCheckout: (tier: PaidPlanTier) => void;
+ /** Payment confirmed (or a license already active) for `tier`. */
+ onPremiumPaid: (tier: PaidPlanTier) => void;
}) {
const [searchParams] = useSearchParams();
const userInfoQuery = useUserInfoQuery();
@@ -38,6 +41,11 @@ export function PlanStep(props: {
const [selected, setSelected] = createSignal<PlanTier>('free');
const returnedFromCheckout = searchParams.subscriptionSuccess === 'true';
+ // The success leg carries `type=<tier>` so the confirmation names the plan
+ // that was actually bought; anything else reads as Premium.
+ const paidTier = (): PaidPlanTier =>
+ searchParams.type === 'max' ? 'max' : 'premium';
+ const paidPlanName = () => PLAN_BY_TIER[paidTier()].name;
const hasPaidAccess = () =>
userInfoQuery.data?.licenseStatus === 'active' ||
userInfoQuery.data?.licenseStatus === 'trialing';
@@ -48,7 +56,7 @@ export function PlanStep(props: {
onMount(() => {
if (!returnedFromCheckout) return;
- analytics.track('subscription_success', { type: searchParams.type });
+ analytics.track('subscription_success', { type: paidTier() });
let cancelled = false;
onCleanup(() => {
cancelled = true;
@@ -84,12 +92,12 @@ export function PlanStep(props: {
<span class="text-sm font-semibold text-ink">
{returnedFromCheckout
? 'Payment successful'
- : 'Premium is already active'}
+ : `${paidPlanName()} is already active`}
</span>
<p class="text-sm leading-relaxed text-ink-muted">
{returnedFromCheckout
- ? 'Premium is now active on your account.'
- : 'Your account already has Premium access — no payment needed.'}
+ ? `${paidPlanName()} is now active on your account.`
+ : `Your account already has ${paidPlanName()} access — no payment needed.`}
</p>
</div>
</div>
@@ -97,7 +105,7 @@ export function PlanStep(props: {
variant="cta"
size="xl"
disabled={props.finishing}
- onClick={() => props.onPremiumPaid()}
+ onClick={() => props.onPremiumPaid(paidTier())}
>
{props.finishing ? 'Setting up your workspace…' : 'Continue'}
<ArrowRight class="size-5" />
@@ -130,7 +138,7 @@ export function PlanStep(props: {
);
}
-/** The regular free/premium picker. */
+/** The regular free/premium/max picker. */
function PlanPicker(props: {
finishing: boolean;
selected: PlanTier;
@@ -141,7 +149,7 @@ function PlanPicker(props: {
const selected = () => props.selected;
return (
<div class="flex flex-col gap-6">
- <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
<Index each={PLANS}>
{(plan) => (
<button
@@ -207,7 +215,7 @@ function PlanPicker(props: {
? selected() === 'free'
? 'Setting up your workspace…'
: 'Heading to checkout…'
- : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}
+ : `Continue with ${PLAN_BY_TIER[selected()].name}`}
<ArrowRight class="size-5" />
</Button>
<SkipButton
diff --git a/apps/web/src/features/setup/flow/createFlowFinish.ts b/apps/web/src/features/setup/flow/createFlowFinish.ts
index b5d6f5a081..d7b0235ada 100644
--- a/apps/web/src/features/setup/flow/createFlowFinish.ts
+++ b/apps/web/src/features/setup/flow/createFlowFinish.ts
@@ -1,8 +1,9 @@
import { AFTER_SETUP_ROUTE, DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { createOnboardingCheckoutSession } from '@app/features/onboarding/use-onboarding-checkout';
-import type { PaidPlanTier } from '@app/features/paywall/plans';
+import { onboardingCheckoutArgs } from '@app/features/onboarding/use-onboarding-checkout';
+import type { PaidPlanTier, PlanTier } from '@app/features/paywall/plans';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { toast } from '@core/component/Toast/Toast';
+import { useCreateCheckoutSessionMutation } from '@queries/auth';
import { authKeys } from '@queries/auth/keys';
import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
import type { UserInfoData } from '@queries/auth/user-info';
@@ -29,10 +30,11 @@ export function createFlowFinish(options?: {
const [searchParams] = useSearchParams();
const completeOnboarding = useCompleteOnboardingMutation();
const completeTutorial = useCompleteTutorialMutation();
+ const checkout = useCreateCheckoutSessionMutation();
const analytics = useAnalytics();
const [finishing, setFinishing] = createSignal(false);
- const trackCompleted = (plan: 'free' | 'premium', planSkipped: boolean) => {
+ const trackCompleted = (plan: PlanTier, planSkipped: boolean) => {
analytics.track('onboarding_v4_completed', {
plan,
plan_skipped: planSkipped,
@@ -124,7 +126,9 @@ export function createFlowFinish(options?: {
if (finishing()) return;
setFinishing(true);
try {
- const { checkoutUrl } = await createOnboardingCheckoutSession(tier);
+ const checkoutUrl = await checkout.mutateAsync(
+ onboardingCheckoutArgs(tier)
+ );
// Deliberately leave `finishing` set: the page is navigating away,
// and re-enabling the buttons mid-unload invites a double checkout.
window.location.href = checkoutUrl;
@@ -134,13 +138,14 @@ export function createFlowFinish(options?: {
}
};
- /** Finish after checkout confirmed payment (or an existing license). */
- const finishPremium = async () => {
+ /** Finish after checkout confirmed payment (or an existing license),
+ * recording the tier Stripe returned with rather than assuming Premium. */
+ const finishPremium = async (tier: PaidPlanTier = 'premium') => {
if (finishing()) return;
setFinishing(true);
try {
if (await completeFlow()) {
- trackCompleted('premium', false);
+ trackCompleted(tier, false);
navigate(afterTarget(), { replace: true });
}
} finally {
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index f84632144c..30aa88fefa 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -109,7 +109,7 @@ export type AppEvents = {
* everything connected along the way.
*/
onboarding_v4_completed: {
- plan: 'free' | 'premium';
+ plan: 'free' | 'premium' | 'max';
plan_skipped: boolean;
emails_connected: number;
connectors_connected: string[];
@@ -188,6 +188,12 @@ export type AppEvents = {
ai_message_sent: Record<string, unknown>;
ai_attachment_add: Record<string, unknown>;
+ /** A paid user opened Stripe Checkout for an AI credit pack. */
+ ai_credits_checkout_start: { amountCents: number };
+ /** A payer changed their AI usage billing (overage) settings. */
+ ai_overage_updated: { enabled: boolean; limitCents: number };
+ /** An existing subscriber moved between Premium and Max. */
+ plan_changed: { plan: 'premium' | 'max'; from?: string };
email_message_sent: Record<string, unknown>;
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index 389826def5..49f1912002 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -42,6 +42,9 @@ export async function clearLocalAuthSession() {
queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);
queryClient.removeQueries({ queryKey: emailKeys.links.queryKey });
queryClient.removeQueries({ queryKey: propertiesKeys._def });
+ // The billing position (usage, credits, overage settings) belongs to the
+ // account that fetched it; never let it render for the next sign-in.
+ queryClient.removeQueries({ queryKey: authKeys.aiBillingSummary.queryKey });
// Queued mutations are user intent; never allow them to replay under a
// subsequent account sharing this anonymous device cache scope.
diff --git a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
index f680b95a6d..35a2dcb183 100644
--- a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
+++ b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
@@ -4,6 +4,7 @@ import {
MODEL_PRETTYNAME,
MODEL_PROVIDER_ICON,
Model,
+ modelUsageHint,
} from '@core/component/AI/constant';
import type { TModel } from '@core/component/AI/types';
import { isMobile } from '@core/mobile/isMobile';
@@ -37,7 +38,9 @@ const ALL_AVAILABLE: ModelOption[] = (Object.values(Model) as TModel[]).map(
const MODEL_DESCRIPTION: Record<TModel, string> = {
[Model.sonnet5]: 'Everyday writing, coding, and questions',
[Model.opus5]: 'Complex tasks and deeper analysis',
+ [Model.fable51]: 'The most capable model for the hardest work',
[Model.haiku45]: 'Quick answers and lighter tasks',
+ [Model.gpt6Astra]: 'Frontier reasoning for the hardest problems',
[Model.gpt56]: 'Reasoning, writing, and problem solving',
[Model.gpt56Mini]: 'Fast help with everyday tasks',
};
@@ -95,6 +98,17 @@ export function ModelSelector(props: ModelSelectorProps) {
<span class="flex-1 truncate">
{MODEL_PRETTYNAME[option.id]}
</span>
+ {/* Decorative: the item's accessible name stays the model. */}
+ <Show when={modelUsageHint(option.id)}>
+ {(hint) => (
+ <span
+ aria-hidden="true"
+ class="shrink-0 text-[10px] text-ink-extra-muted"
+ >
+ {hint()}
+ </span>
+ )}
+ </Show>
<Show when={!option.available}>
<LockIcon class="size-3.5 shrink-0 text-ink-extra-muted" />
</Show>
@@ -171,8 +185,17 @@ export function ModelSelector(props: ModelSelectorProps) {
class="size-6 shrink-0 text-ink-muted"
/>
<span class="flex min-w-0 flex-1 flex-col gap-1">
- <span class="text-base font-medium leading-5">
- {MODEL_PRETTYNAME[option.id]}
+ <span class="flex items-baseline gap-2">
+ <span class="text-base font-medium leading-5">
+ {MODEL_PRETTYNAME[option.id]}
+ </span>
+ <Show when={modelUsageHint(option.id)}>
+ {(hint) => (
+ <span class="text-xs text-ink-extra-muted">
+ {hint()}
+ </span>
+ )}
+ </Show>
</span>
<span class="text-[13px] leading-[18px] text-ink-muted">
{MODEL_DESCRIPTION[option.id]}
diff --git a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
index 7b196559e0..00d5d7f230 100644
--- a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
+++ b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
@@ -4,7 +4,10 @@ import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';
import type { Attachment, Model, ToolSet } from '@core/component/AI/types';
import { isPaymentError } from '@core/util/handlePaymentError';
-import { cognitionApiServiceClient } from '@service-cognition/client';
+import {
+ AI_USAGE_LIMIT_ERROR,
+ cognitionApiServiceClient,
+} from '@service-cognition/client';
import type { ChatMessageStream } from '@service-connection/stream';
import { subscribe } from '@service-connection/stream';
@@ -18,7 +21,12 @@ export type ChatSendInput = {
type SendChatMessageResult =
| { stream: ChatMessageStream; chat_id: string }
- | { error: true; paymentError?: boolean };
+ | {
+ error: true;
+ paymentError?: boolean;
+ /** The billing gate refused the send; carries the backend reason code. */
+ usageLimit?: string;
+ };
export function useSendChatMessage() {
const additionalInstructions = useAdditionalInstructions();
@@ -39,6 +47,14 @@ export function useSendChatMessage() {
additional_instructions: additionalInstructions(chatId),
});
+ if (response.isErr()) {
+ const usageLimit = response.error.find(
+ (e) => e.code === AI_USAGE_LIMIT_ERROR
+ );
+ if (usageLimit) {
+ return { error: true, usageLimit: usageLimit.message };
+ }
+ }
if (isPaymentError(response)) {
return { error: true, paymentError: true };
}
diff --git a/apps/web/src/lib/core/component/AI/constant/model.test.ts b/apps/web/src/lib/core/component/AI/constant/model.test.ts
index 14cf635b55..e05ff0771e 100644
--- a/apps/web/src/lib/core/component/AI/constant/model.test.ts
+++ b/apps/web/src/lib/core/component/AI/constant/model.test.ts
@@ -8,6 +8,7 @@ import {
MODEL_PROVIDER,
Model,
modelsForPlan,
+ modelUsageHint,
type TModel,
} from './model';
@@ -32,6 +33,23 @@ describe('modelsForPlan / defaultModelForPlan', () => {
});
});
+describe('modelUsageHint', () => {
+ it('flags the heavy paid models and stays quiet for the default and cheaper', () => {
+ expect(modelUsageHint(Model.fable51)).toBe('5× usage');
+ expect(modelUsageHint(Model.gpt6Astra)).toBe('5× usage');
+ expect(modelUsageHint(Model.opus5)).toBe('2.5× usage');
+ expect(modelUsageHint(Model.sonnet5)).toBeUndefined();
+ expect(modelUsageHint(Model.haiku45)).toBeUndefined();
+ });
+
+ it('keeps Fable and Astra paid-only: free users see them locked, paid users select them', () => {
+ expect(modelsForPlan(false)).not.toContain(Model.fable51);
+ expect(modelsForPlan(false)).not.toContain(Model.gpt6Astra);
+ expect(modelsForPlan(true)).toContain(Model.fable51);
+ expect(modelsForPlan(true)).toContain(Model.gpt6Astra);
+ });
+});
+
describe('parseModel', () => {
it('passes through known model ids', () => {
for (const id of Object.values(Model)) {
diff --git a/apps/web/src/lib/core/component/AI/constant/model.ts b/apps/web/src/lib/core/component/AI/constant/model.ts
index 47ffa27c5d..0c96c28dcd 100644
--- a/apps/web/src/lib/core/component/AI/constant/model.ts
+++ b/apps/web/src/lib/core/component/AI/constant/model.ts
@@ -11,7 +11,9 @@ import ClaudeIcon from '@icon/wide-claude.svg';
export const Model = {
sonnet5: 'anthropic/claude-sonnet-5',
opus5: 'anthropic/claude-opus-5',
+ fable51: 'anthropic/claude-fable-5-1',
haiku45: 'anthropic/claude-haiku-4-5',
+ gpt6Astra: 'openai/gpt-6-astra',
gpt56: 'openai/gpt-5.6',
gpt56Mini: 'openai/gpt-5.6-mini',
} as const;
@@ -28,7 +30,9 @@ type ExhaustiveMap = {
export const MODEL_PRETTYNAME: ExhaustiveMap = {
'anthropic/claude-sonnet-5': 'Sonnet 5',
'anthropic/claude-opus-5': 'Opus 5',
+ 'anthropic/claude-fable-5-1': 'Fable 5.1',
'anthropic/claude-haiku-4-5': 'Haiku 4.5',
+ 'openai/gpt-6-astra': 'GPT-6 Astra',
'openai/gpt-5.6': 'GPT-5.6',
'openai/gpt-5.6-mini': 'GPT-5.6 mini',
} as const;
@@ -36,11 +40,40 @@ export const MODEL_PRETTYNAME: ExhaustiveMap = {
export const MODEL_PROVIDER_ICON: ExhaustiveMap = {
'anthropic/claude-sonnet-5': ClaudeIcon,
'anthropic/claude-opus-5': ClaudeIcon,
+ 'anthropic/claude-fable-5-1': ClaudeIcon,
'anthropic/claude-haiku-4-5': ClaudeIcon,
+ 'openai/gpt-6-astra': OpenAiIcon,
'openai/gpt-5.6': OpenAiIcon,
'openai/gpt-5.6-mini': OpenAiIcon,
};
+/**
+ * How fast each model draws down a paid plan's included AI, relative to the
+ * default model (Sonnet 5 = 1). Mirrors the per-token rates in `ai_pricing`
+ * (output price, which dominates chat cost): Haiku $5, Sonnet $10, Opus $25,
+ * Fable $50, GPT-6 Astra $50, GPT-5.6 $30, GPT-5.6 mini $4.50 per million
+ * tokens. Shown in the picker so choosing a heavy model is a deliberate trade.
+ */
+export const MODEL_USAGE_MULTIPLIER: { [K in TModel]: number } = {
+ 'anthropic/claude-sonnet-5': 1,
+ 'anthropic/claude-opus-5': 2.5,
+ 'anthropic/claude-fable-5-1': 5,
+ 'anthropic/claude-haiku-4-5': 0.5,
+ 'openai/gpt-6-astra': 5,
+ 'openai/gpt-5.6': 3,
+ 'openai/gpt-5.6-mini': 0.45,
+};
+
+/**
+ * The picker's usage hint for a model: "2.5× usage" for models that burn the
+ * allowance faster than the default, nothing for the default and cheaper.
+ */
+export function modelUsageHint(model: TModel): string | undefined {
+ const multiplier = MODEL_USAGE_MULTIPLIER[model];
+ if (multiplier <= 1) return undefined;
+ return `${Number.isInteger(multiplier) ? multiplier : multiplier.toFixed(1)}× usage`;
+}
+
/** Default model for paid users. */
export const DEFAULT_MODEL: TModel = Model.sonnet5;
@@ -58,7 +91,9 @@ export const PAID_MODELS: readonly TModel[] = Object.values(Model);
* Models a free user may select. Free users only get the fast model
* (`FREE_DEFAULT_MODEL`); every other model is paid-only and shows locked in
* the selector, where selecting one opens the paywall instead of being sent
- * and rejected by the backend.
+ * and rejected by the backend. The heavy models (Opus, Fable, GPT-6 Astra)
+ * are on every paid plan; they just draw the included AI down faster, see
+ * `MODEL_USAGE_MULTIPLIER`.
*/
export const FREE_MODELS: readonly TModel[] = [FREE_DEFAULT_MODEL];
@@ -76,7 +111,9 @@ export function modelsForPlan(hasPaidAccess: boolean): readonly TModel[] {
export const MODEL_PROVIDER: ExhaustiveMap = {
'anthropic/claude-sonnet-5': 'anthropic',
'anthropic/claude-opus-5': 'anthropic',
+ 'anthropic/claude-fable-5-1': 'anthropic',
'anthropic/claude-haiku-4-5': 'anthropic',
+ 'openai/gpt-6-astra': 'openai',
'openai/gpt-5.6': 'openai',
'openai/gpt-5.6-mini': 'openai',
} as const;
diff --git a/apps/web/src/lib/core/component/AI/state/chatState.ts b/apps/web/src/lib/core/component/AI/state/chatState.ts
index f121dba265..497fa189e7 100644
--- a/apps/web/src/lib/core/component/AI/state/chatState.ts
+++ b/apps/web/src/lib/core/component/AI/state/chatState.ts
@@ -16,7 +16,12 @@ export type ChatEvent =
type: 'send_started';
optimisticMessage: ChatMessageWithAttachments;
}
- | { type: 'send_failed'; paymentError?: boolean }
+ | {
+ type: 'send_failed';
+ paymentError?: boolean;
+ /** Refused by the AI billing gate; the backend's reason code. */
+ usageLimit?: string;
+ }
| { type: 'stream_connected' }
| {
type: 'stream_user_message';
@@ -40,7 +45,8 @@ export type SideEffect =
/** When set, the toast offers a "Switch model" action button. */
offerModelSwitch?: boolean;
}
- | { type: 'show_paywall' };
+ | { type: 'show_paywall' }
+ | { type: 'show_usage_limit'; reason: string };
// --- Transition result ---
@@ -96,9 +102,11 @@ export function transition(
.with([{ type: 'sending' }, { type: 'send_failed' }], ([, e]) => ({
phase: { type: 'idle' as const },
- effects: e.paymentError
- ? ([{ type: 'show_paywall' }] as SideEffect[])
- : [],
+ effects: e.usageLimit
+ ? ([{ type: 'show_usage_limit', reason: e.usageLimit }] as SideEffect[])
+ : e.paymentError
+ ? ([{ type: 'show_paywall' }] as SideEffect[])
+ : [],
}))
.with(
diff --git a/apps/web/src/lib/core/component/AI/state/createChatController.ts b/apps/web/src/lib/core/component/AI/state/createChatController.ts
index 38f50b813e..b2b3e355cb 100644
--- a/apps/web/src/lib/core/component/AI/state/createChatController.ts
+++ b/apps/web/src/lib/core/component/AI/state/createChatController.ts
@@ -61,6 +61,12 @@ export type ChatController = {
export type ChatControllerOptions = {
onShowPaywall?: () => void;
+ /**
+ * The send was refused by the AI billing gate (allowance used up, usage
+ * billing cap reached, or a failed usage charge). `reason` is the backend
+ * code; hosts open the usage-limit dialog.
+ */
+ onShowUsageLimit?: (reason: string) => void;
/**
* Switch the chat to a model from a different provider. When provided, a
* provider-outage error toast offers a "Switch model" button that calls this.
@@ -124,6 +130,9 @@ export function createChatController(
}
})
.with({ type: 'show_paywall' }, () => options?.onShowPaywall?.())
+ .with({ type: 'show_usage_limit' }, (e) =>
+ options?.onShowUsageLimit?.(e.reason)
+ )
.exhaustive();
}
}
diff --git a/apps/web/src/lib/core/constant/AiUsageLimitState.tsx b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
new file mode 100644
index 0000000000..086297a2a4
--- /dev/null
+++ b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
@@ -0,0 +1,34 @@
+import type { AiDenyCode } from '@service-auth/ai-billing-types';
+import { createSignal } from 'solid-js';
+
+/**
+ * Global open state for the AI usage-limit dialog, mirroring `PaywallState`:
+ * the chat surfaces raise it when the backend answers 402 with one of the
+ * billing codes, and the app layout mounts the dialog once.
+ */
+const [usageLimitOpen, setUsageLimitOpen] = createSignal(false);
+const [usageLimitCode, setUsageLimitCode] = createSignal<AiDenyCode | null>(
+ null
+);
+
+const KNOWN_CODES: readonly AiDenyCode[] = [
+ 'ai_allowance_exhausted',
+ 'ai_overage_limit_reached',
+ 'ai_overage_payment_failed',
+];
+
+export function isAiDenyCode(code: string | undefined): code is AiDenyCode {
+ return !!code && (KNOWN_CODES as readonly string[]).includes(code);
+}
+
+export const useAiUsageLimitState = () => {
+ const showUsageLimit = (code?: string) => {
+ setUsageLimitCode(isAiDenyCode(code) ? code : 'ai_allowance_exhausted');
+ setUsageLimitOpen(true);
+ };
+ const hideUsageLimit = () => {
+ setUsageLimitOpen(false);
+ setUsageLimitCode(null);
+ };
+ return { usageLimitOpen, usageLimitCode, showUsageLimit, hideUsageLimit };
+};
diff --git a/apps/web/src/lib/queries/auth/ai-billing.ts b/apps/web/src/lib/queries/auth/ai-billing.ts
new file mode 100644
index 0000000000..355c01a55d
--- /dev/null
+++ b/apps/web/src/lib/queries/auth/ai-billing.ts
@@ -0,0 +1,99 @@
+import { throwOnErr } from '@core/util/result';
+import type { PaidPlan } from '@service-auth/ai-billing-types';
+import { authServiceClient } from '@service-auth/client';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { authKeys } from './keys';
+import { invalidateUserInfo } from './user-info';
+
+const AI_BILLING_SUMMARY_STALE_TIME = 30_000; // 30 seconds
+const AI_BILLING_PLANS_STALE_TIME = 60 * 60 * 1000; // 1 hour
+
+type UseAiBillingSummaryQueryOptions = {
+ /** Whether the query should be enabled. Can be a boolean or accessor for reactivity. */
+ enabled?: boolean | (() => boolean);
+};
+
+/**
+ * The signed-in user's AI usage position for the current billing period:
+ * included allowance, usage, credits, and overage settings. The backend
+ * settles pending credits/overage before answering, so this is authoritative.
+ */
+export function useAiBillingSummaryQuery(
+ options?: UseAiBillingSummaryQueryOptions
+) {
+ return useQuery(() => {
+ const enabled =
+ typeof options?.enabled === 'function'
+ ? options.enabled()
+ : (options?.enabled ?? true);
+ return {
+ queryKey: authKeys.aiBillingSummary.queryKey,
+ queryFn: async () =>
+ await throwOnErr(
+ async () => await authServiceClient.getAiBillingSummary()
+ ),
+ staleTime: AI_BILLING_SUMMARY_STALE_TIME,
+ throwOnError: false,
+ retry: 1,
+ enabled,
+ };
+ });
+}
+
+/** The plan catalog, credit packs, and overage cap bounds. */
+export function useAiBillingPlansQuery() {
+ return useQuery(() => ({
+ queryKey: authKeys.aiBillingPlans.queryKey,
+ queryFn: async () =>
+ await throwOnErr(async () => await authServiceClient.getAiBillingPlans()),
+ staleTime: AI_BILLING_PLANS_STALE_TIME,
+ throwOnError: false,
+ }));
+}
+
+export function invalidateAiBillingSummary() {
+ return queryClient.invalidateQueries({
+ queryKey: authKeys.aiBillingSummary.queryKey,
+ });
+}
+
+/** Turn usage billing (overage) on or off with a per-period cap. */
+export function useUpdateAiOverageMutation() {
+ return useMutation(() => ({
+ mutationFn: async (args: { enabled: boolean; limitCents: number }) =>
+ await throwOnErr(
+ async () => await authServiceClient.updateAiOverage(args)
+ ),
+ onSuccess: (snapshot) => {
+ queryClient.setQueryData(authKeys.aiBillingSummary.queryKey, snapshot);
+ },
+ }));
+}
+
+/** Start a Stripe Checkout for a credit pack; resolves to the hosted URL. */
+export function useCreateAiCreditCheckoutMutation() {
+ return useMutation(() => ({
+ mutationFn: async (args: {
+ amountCents: number;
+ successUrl: string;
+ cancelUrl: string;
+ }) =>
+ await throwOnErr(
+ async () => await authServiceClient.createAiCreditCheckout(args)
+ ),
+ }));
+}
+
+/** Move the active subscription to another paid plan. */
+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.
+ void invalidateUserInfo();
+ void invalidateAiBillingSummary();
+ },
+ }));
+}
diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.ts
index 2b3ba1bc6a..b676db7391 100644
--- a/apps/web/src/lib/queries/auth/index.ts
+++ b/apps/web/src/lib/queries/auth/index.ts
@@ -4,6 +4,14 @@ export {
useUserId,
useUserInfo,
} from '@core/context/user';
+export {
+ invalidateAiBillingSummary,
+ useAiBillingPlansQuery,
+ useAiBillingSummaryQuery,
+ useChangePlanMutation,
+ useCreateAiCreditCheckoutMutation,
+ useUpdateAiOverageMutation,
+} from './ai-billing';
export {
type GithubLink,
type GithubLinkStatus,
@@ -17,6 +25,10 @@ export { useInitGmailLink } from './gmail-link';
export { authKeys } from './keys';
export { useSendMobileWelcomeEmail } from './mobile-welcome-email';
export {} from './mutations';
+export {
+ type CreateCheckoutSessionArgs,
+ useCreateCheckoutSessionMutation,
+} from './stripe-checkout';
export type { UserInfoData } from './user-info';
export {
normalizeUserNameQueryId,
diff --git a/apps/web/src/lib/queries/auth/keys.ts b/apps/web/src/lib/queries/auth/keys.ts
index 64ac727974..231195e113 100644
--- a/apps/web/src/lib/queries/auth/keys.ts
+++ b/apps/web/src/lib/queries/auth/keys.ts
@@ -1,6 +1,8 @@
import { createQueryKeys } from '@lukemorales/query-key-factory';
export const authKeys = createQueryKeys('auth', {
+ aiBillingPlans: null,
+ aiBillingSummary: null,
codexStatus: null,
codexEnvironments: null,
codexLogin: (attemptId: string) => ({ queryKey: [attemptId] }),
diff --git a/apps/web/src/lib/queries/auth/stripe-checkout.ts b/apps/web/src/lib/queries/auth/stripe-checkout.ts
new file mode 100644
index 0000000000..a3694175de
--- /dev/null
+++ b/apps/web/src/lib/queries/auth/stripe-checkout.ts
@@ -0,0 +1,24 @@
+import { stripeServiceClient } from '@service-stripe/client';
+import { useMutation } from '@tanstack/solid-query';
+
+/** The arguments the Stripe client's v2 checkout accepts. */
+export type CreateCheckoutSessionArgs = NonNullable<
+ Parameters<typeof stripeServiceClient.createCheckoutSessionV2>[0]
+>;
+
+/**
+ * Start a Stripe Checkout for a subscription plan; resolves to the hosted
+ * URL to redirect to. Every checkout (onboarding, Billing settings) goes
+ * through here so the network call lives in the queries package.
+ */
+export function useCreateCheckoutSessionMutation() {
+ return useMutation(() => ({
+ mutationFn: async (args: CreateCheckoutSessionArgs) => {
+ const url = await stripeServiceClient.createCheckoutSessionV2(args);
+ if (!url) {
+ throw new Error('No checkout URL returned');
+ }
+ return url;
+ },
+ }));
+}
diff --git a/apps/web/src/lib/queries/team/members.ts b/apps/web/src/lib/queries/team/members.ts
index 3438889477..0786ca585b 100644
--- a/apps/web/src/lib/queries/team/members.ts
+++ b/apps/web/src/lib/queries/team/members.ts
@@ -1,9 +1,11 @@
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
+import type { PaidPlan } from '@service-auth/ai-billing-types';
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 { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
@@ -76,3 +78,43 @@ export function useRemoveUserFromTeamMutation(
),
}));
}
+
+type SetTeamMemberPlanArgs = { teamId: string; userId: string; plan: PaidPlan };
+type SetTeamMemberPlanCallbacks = MutationCallbacks<
+ void,
+ Error,
+ SetTeamMemberPlanArgs
+>;
+
+/**
+ * Move one member's seat between Premium 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.
+ */
+export function useSetTeamMemberPlanMutation(
+ callbacks?: SetTeamMemberPlanCallbacks
+) {
+ return useMutation(() => ({
+ mutationFn: async ({ userId, plan }: SetTeamMemberPlanArgs) => {
+ await throwOnErr(() => authServiceClient.setTeamMemberPlan(userId, plan));
+ },
+
+ ...withCallbacks<void, Error, SetTeamMemberPlanArgs>(
+ {
+ onSuccess: (_data, { teamId, plan }) => {
+ invalidateTeam(teamId);
+ void invalidateAiBillingSummary();
+ toast.success(
+ plan === 'max' ? 'Seat moved to Max' : 'Seat moved to Premium'
+ );
+ },
+
+ onError: (error) => {
+ console.error('Failed to change team member plan', error);
+ toast.failure("Couldn't change the seat's plan. Please try again.");
+ },
+ },
+ callbacks
+ ),
+ }));
+}
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.ts
new file mode 100644
index 0000000000..b7080c776f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts
@@ -0,0 +1,67 @@
+/**
+ * Hand-written mirrors of the auth service's AI billing OpenAPI types
+ * (`crates/ai_billing`). Replace with the orval-generated schemas on the next
+ * client regeneration (`bun run gen-api auth-service`).
+ *
+ * Every money field is in cents at Macro's list rate.
+ */
+
+export type AiPlanTier = 'free' | 'premium' | 'max';
+
+export type AiDenyReason =
+ | 'allowance_exhausted'
+ | 'overage_limit_reached'
+ | 'overage_payment_failed';
+
+/** Machine-readable codes carried in 402 bodies from the AI endpoints. */
+export type AiDenyCode =
+ | 'ai_allowance_exhausted'
+ | 'ai_overage_limit_reached'
+ | 'ai_overage_payment_failed';
+
+export interface AiUsageSnapshot {
+ tier: AiPlanTier;
+ unlimited: boolean;
+ payer: string;
+ can_manage_billing: boolean;
+ seats: number;
+ period_start: string;
+ period_end: string;
+ included_cents: number;
+ used_cents: number;
+ credits_consumed_cents: number;
+ credit_balance_cents: number;
+ overage_enabled: boolean;
+ overage_limit_cents: number;
+ overage_charged_cents: number;
+ overage_suspended: boolean;
+ uncovered_cents: number;
+ remaining_cents: number;
+ blocked_reason?: AiDenyReason;
+}
+
+export interface AiPlanCatalogEntry {
+ tier: AiPlanTier;
+ monthly_price_cents: number;
+ included_ai_cents_per_seat: number;
+}
+
+export interface AiPlanCatalog {
+ plans: AiPlanCatalogEntry[];
+ credit_packs_cents: number[];
+ overage_limit_min_cents: number;
+ overage_limit_max_cents: number;
+}
+
+export type PaidPlan = 'premium' | 'max';
+
+/**
+ * A team member with the plan their seat is billed at. Mirrors the auth
+ * service's `TeamMember` once `plan` lands in the generated schema.
+ */
+export interface TeamMemberPlan {
+ team_id: string;
+ user_id: string;
+ role: 'member' | 'admin' | 'owner';
+ plan: PaidPlan;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 933232aa7d..d2e44c3330 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -13,6 +13,12 @@ import { Telemetry } from '@macro-inc/observability';
import { makePersisted } from '@solid-primitives/storage';
import { err, ok } from 'neverthrow';
import { createSignal } from 'solid-js';
+import type {
+ AiPlanCatalog,
+ AiUsageSnapshot,
+ PaidPlan,
+ TeamMemberPlan,
+} from './ai-billing-types';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
CursorApiKeyStatus,
@@ -600,6 +606,8 @@ export const authServiceClient = {
fbp?: string | null;
fbc?: string | null;
};
+ /** The plan to subscribe to. The backend defaults to Premium. */
+ plan?: PaidPlan;
}) {
return (
await fetchWithAuth<{ url: string }>(
@@ -611,6 +619,67 @@ export const authServiceClient = {
cancelUrl: args.cancelUrl,
discount: args.discount ?? undefined,
metadata: args.metadata,
+ plan: args.plan,
+ }),
+ }
+ )
+ ).map((result) => result.url);
+ },
+
+ /**
+ * Moves the active subscription to another paid plan. Proration is invoiced
+ * immediately; roles and the AI allowance follow from the Stripe webhook.
+ */
+ async changePlan(args: { plan: PaidPlan }) {
+ return (
+ await fetchWithAuth<{ plan: PaidPlan }>(`${authHost}/user/stripe/plan`, {
+ method: 'POST',
+ body: JSON.stringify({ plan: args.plan }),
+ })
+ ).map((result) => result.plan);
+ },
+
+ // AI billing: allowance, credits, overage.
+ async getAiBillingSummary() {
+ return await fetchWithAuth<AiUsageSnapshot>(
+ `${authHost}/ai-billing/summary`,
+ { method: 'GET' }
+ );
+ },
+
+ async getAiBillingPlans() {
+ return await fetchWithAuth<AiPlanCatalog>(`${authHost}/ai-billing/plans`, {
+ method: 'GET',
+ });
+ },
+
+ async updateAiOverage(args: { enabled: boolean; limitCents: number }) {
+ return await fetchWithAuth<AiUsageSnapshot>(
+ `${authHost}/ai-billing/overage`,
+ {
+ method: 'PATCH',
+ body: JSON.stringify({
+ enabled: args.enabled,
+ limitCents: args.limitCents,
+ }),
+ }
+ );
+ },
+
+ async createAiCreditCheckout(args: {
+ amountCents: number;
+ successUrl: string;
+ cancelUrl: string;
+ }) {
+ return (
+ await fetchWithAuth<{ url: string }>(
+ `${authHost}/ai-billing/credits/checkout`,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ amountCents: args.amountCents,
+ successUrl: args.successUrl,
+ cancelUrl: args.cancelUrl,
}),
}
)
@@ -1006,6 +1075,17 @@ export const authServiceClient = {
).map(() => undefined);
},
+ /** Move one team member's seat between paid plans (team admins only). */
+ async setTeamMemberPlan(userId: string, plan: PaidPlan) {
+ return await fetchWithAuth<TeamMemberPlan>(
+ `${authHost}/team/members/${encodeURIComponent(userId)}/plan`,
+ {
+ method: 'PATCH',
+ body: JSON.stringify({ plan }),
+ }
+ );
+ },
+
async removeUserFromTeam(userId: string) {
return (
await fetchWithAuth<{}>(`${authHost}/team/remove/${userId}`, {
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.ts
index 91ed201406..b6323421ef 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
@@ -5,7 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
import type {
+ AiBillingErrorBody,
AppleLoginRequest,
+ ChangePlanRequest,
+ ChangePlanResponse,
CodexConfigRequest,
CodexConnectionStatus,
CodexEnvironment,
@@ -18,6 +21,8 @@ import type {
CreatePortalSessionRequest,
CreateTeamRequest,
CreateUserRequest,
+ CreditCheckoutRequestBody,
+ CreditCheckoutResponse,
CursorApiKeyStatus,
CursorModelsResponse,
EmptyResponse,
@@ -53,11 +58,13 @@ import type {
PasswordRequest,
PatchTeamCrmSettingsRequest,
PatchTeamCrmSettingsResponse,
+ PatchTeamMemberPlanRequest,
PatchTeamRequest,
PatchUserGroupRequest,
PatchUserOnboardingRequest,
PatchUserTutorialRequest,
Permission,
+ PlanCatalogResponse,
PostGetNamesRequestBody,
ProfilePictures,
PublicGtmInviteLink,
@@ -75,9 +82,12 @@ import type {
StripeSessionResponse,
Team,
TeamInvitesResponse,
+ TeamMember,
TeamWithMembers,
ToggleAutoJoinDomainResponse,
ToggleNonAdminInvitesResponse,
+ UpdateOverageRequest,
+ UsageSnapshot,
UserLinkResponse,
UserName,
UserNames,
@@ -86,6 +96,257 @@ import type {
UserTokensResponse,
} from './schemas';
+/**
+ * @summary Start a Stripe Checkout for a credit pack. Payer only.
+ */
+export type createAiCreditCheckoutResponse200 = {
+ data: CreditCheckoutResponse;
+ status: 200;
+};
+
+export type createAiCreditCheckoutResponse400 = {
+ data: AiBillingErrorBody;
+ status: 400;
+};
+
+export type createAiCreditCheckoutResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type createAiCreditCheckoutResponse402 = {
+ data: AiBillingErrorBody;
+ status: 402;
+};
+
+export type createAiCreditCheckoutResponse403 = {
+ data: AiBillingErrorBody;
+ status: 403;
+};
+
+export type createAiCreditCheckoutResponse500 = {
+ data: AiBillingErrorBody;
+ status: 500;
+};
+
+export type createAiCreditCheckoutResponseSuccess =
+ createAiCreditCheckoutResponse200 & {
+ headers: Headers;
+ };
+export type createAiCreditCheckoutResponseError = (
+ | createAiCreditCheckoutResponse400
+ | createAiCreditCheckoutResponse401
+ | createAiCreditCheckoutResponse402
+ | createAiCreditCheckoutResponse403
+ | createAiCreditCheckoutResponse500
+) & {
+ headers: Headers;
+};
+
+export type createAiCreditCheckoutResponse =
+ | createAiCreditCheckoutResponseSuccess
+ | createAiCreditCheckoutResponseError;
+
+export const getCreateAiCreditCheckoutUrl = () => {
+ return `/ai-billing/credits/checkout`;
+};
+
+export const createAiCreditCheckout = async (
+ creditCheckoutRequestBody: CreditCheckoutRequestBody,
+ options?: RequestInit
+): Promise<createAiCreditCheckoutResponse> => {
+ const res = await fetch(getCreateAiCreditCheckoutUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(creditCheckoutRequestBody),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createAiCreditCheckoutResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createAiCreditCheckoutResponse;
+};
+
+/**
+ * @summary Turn overage billing on or off and set the per-period cap. Payer only.
+ */
+export type updateAiBillingOverageResponse200 = {
+ data: UsageSnapshot;
+ status: 200;
+};
+
+export type updateAiBillingOverageResponse400 = {
+ data: AiBillingErrorBody;
+ status: 400;
+};
+
+export type updateAiBillingOverageResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type updateAiBillingOverageResponse402 = {
+ data: AiBillingErrorBody;
+ status: 402;
+};
+
+export type updateAiBillingOverageResponse403 = {
+ data: AiBillingErrorBody;
+ status: 403;
+};
+
+export type updateAiBillingOverageResponse500 = {
+ data: AiBillingErrorBody;
+ status: 500;
+};
+
+export type updateAiBillingOverageResponseSuccess =
+ updateAiBillingOverageResponse200 & {
+ headers: Headers;
+ };
+export type updateAiBillingOverageResponseError = (
+ | updateAiBillingOverageResponse400
+ | updateAiBillingOverageResponse401
+ | updateAiBillingOverageResponse402
+ | updateAiBillingOverageResponse403
+ | updateAiBillingOverageResponse500
+) & {
+ headers: Headers;
+};
+
+export type updateAiBillingOverageResponse =
+ | updateAiBillingOverageResponseSuccess
+ | updateAiBillingOverageResponseError;
+
+export const getUpdateAiBillingOverageUrl = () => {
+ return `/ai-billing/overage`;
+};
+
+export const updateAiBillingOverage = async (
+ updateOverageRequest: UpdateOverageRequest,
+ options?: RequestInit
+): Promise<updateAiBillingOverageResponse> => {
+ const res = await fetch(getUpdateAiBillingOverageUrl(), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(updateOverageRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: updateAiBillingOverageResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as updateAiBillingOverageResponse;
+};
+
+/**
+ * @summary The plan catalog, credit packs, and overage cap bounds.
+ */
+export type getAiBillingPlansResponse200 = {
+ data: PlanCatalogResponse;
+ status: 200;
+};
+
+export type getAiBillingPlansResponseSuccess = getAiBillingPlansResponse200 & {
+ headers: Headers;
+};
+
+export type getAiBillingPlansResponse = getAiBillingPlansResponseSuccess;
+
+export const getGetAiBillingPlansUrl = () => {
+ return `/ai-billing/plans`;
+};
+
+export const getAiBillingPlans = async (
+ options?: RequestInit
+): Promise<getAiBillingPlansResponse> => {
+ const res = await fetch(getGetAiBillingPlansUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAiBillingPlansResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAiBillingPlansResponse;
+};
+
+/**
+ * Runs a settlement first so the position reflects any credits or overage
+that were waiting to be booked.
+ * @summary The caller's current-period AI usage, credits, and overage settings.
+ */
+export type getAiBillingSummaryResponse200 = {
+ data: UsageSnapshot;
+ status: 200;
+};
+
+export type getAiBillingSummaryResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type getAiBillingSummaryResponse500 = {
+ data: AiBillingErrorBody;
+ status: 500;
+};
+
+export type getAiBillingSummaryResponseSuccess =
+ getAiBillingSummaryResponse200 & {
+ headers: Headers;
+ };
+export type getAiBillingSummaryResponseError = (
+ | getAiBillingSummaryResponse401
+ | getAiBillingSummaryResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAiBillingSummaryResponse =
+ | getAiBillingSummaryResponseSuccess
+ | getAiBillingSummaryResponseError;
+
+export const getGetAiBillingSummaryUrl = () => {
+ return `/ai-billing/summary`;
+};
+
+export const getAiBillingSummary = async (
+ options?: RequestInit
+): Promise<getAiBillingSummaryResponse> => {
+ const res = await fetch(getGetAiBillingSummaryUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAiBillingSummaryResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAiBillingSummaryResponse;
+};
+
export type getCodexConnectionResponse200 = {
data: CodexConnectionStatus;
status: 200;
@@ -3841,6 +4102,88 @@ export const rejectInvitation = async (
} as rejectInvitationResponse;
};
+/**
+ * Team admins and owners only. The team's subscription is re-billed for
+the seat at once (prorated); the member's tier role and individual AI
+allowance follow immediately.
+ * @summary Moves one team member's seat between paid plans.
+ */
+export type patchTeamMemberPlanResponse200 = {
+ data: TeamMember;
+ status: 200;
+};
+
+export type patchTeamMemberPlanResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type patchTeamMemberPlanResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type patchTeamMemberPlanResponse402 = {
+ data: ErrorResponse;
+ status: 402;
+};
+
+export type patchTeamMemberPlanResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type patchTeamMemberPlanResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type patchTeamMemberPlanResponseSuccess =
+ patchTeamMemberPlanResponse200 & {
+ headers: Headers;
+ };
+export type patchTeamMemberPlanResponseError = (
+ | patchTeamMemberPlanResponse400
+ | patchTeamMemberPlanResponse401
+ | patchTeamMemberPlanResponse402
+ | patchTeamMemberPlanResponse404
+ | patchTeamMemberPlanResponse500
+) & {
+ headers: Headers;
+};
+
+export type patchTeamMemberPlanResponse =
+ | patchTeamMemberPlanResponseSuccess
+ | patchTeamMemberPlanResponseError;
+
+export const getPatchTeamMemberPlanUrl = (memberUserId: string) => {
+ return `/team/members/${memberUserId}/plan`;
+};
+
+export const patchTeamMemberPlan = async (
+ memberUserId: string,
+ patchTeamMemberPlanRequest: PatchTeamMemberPlanRequest,
+ options?: RequestInit
+): Promise<patchTeamMemberPlanResponse> => {
+ const res = await fetch(getPatchTeamMemberPlanUrl(memberUserId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchTeamMemberPlanRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: patchTeamMemberPlanResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as patchTeamMemberPlanResponse;
+};
+
/**
* @summary Toggles whether non-admin members may invite users to the team. Teams
start with this on (any member can invite); turning it off restricts
@@ -5099,6 +5442,94 @@ export const createCheckoutSessionV2 = async (
} as createCheckoutSessionV2Response;
};
+/**
+ * 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.
+ */
+export type changePlanResponse200 = {
+ data: ChangePlanResponse;
+ status: 200;
+};
+
+export type changePlanResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type changePlanResponse402 = {
+ data: ErrorResponse;
+ status: 402;
+};
+
+export type changePlanResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type changePlanResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type changePlanResponse409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type changePlanResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type changePlanResponseSuccess = changePlanResponse200 & {
+ headers: Headers;
+};
+export type changePlanResponseError = (
+ | changePlanResponse400
+ | changePlanResponse402
+ | changePlanResponse403
+ | changePlanResponse404
+ | changePlanResponse409
+ | changePlanResponse500
+) & {
+ headers: Headers;
+};
+
+export type changePlanResponse =
+ | changePlanResponseSuccess
+ | changePlanResponseError;
+
+export const getChangePlanUrl = () => {
+ return `/user/stripe/plan`;
+};
+
+export const changePlan = async (
+ changePlanRequest: ChangePlanRequest,
+ options?: RequestInit
+): Promise<changePlanResponse> => {
+ const res = await fetch(getChangePlanUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(changePlanRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: changePlanResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as changePlanResponse;
+};
+
/**
* @summary Creates a Stripe billing portal session.
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/aiBillingErrorBody.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/aiBillingErrorBody.ts
new file mode 100644
index 0000000000..6c4cf600d0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/aiBillingErrorBody.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Error response body.
+ */
+export interface AiBillingErrorBody {
+ /** Human-readable error description. */
+ error: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanRequest.ts
new file mode 100644
index 0000000000..9fde87df0d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanRequest.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 { SeatPlan } from './seatPlan';
+
+/**
+ * Request body for switching plans
+ */
+export interface ChangePlanRequest {
+ /** The plan to move the active subscription to */
+ plan: SeatPlan;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanResponse.ts
new file mode 100644
index 0000000000..3efc62d140
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/changePlanResponse.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 { SeatPlan } from './seatPlan';
+
+/**
+ * Response for a plan change
+ */
+export interface ChangePlanResponse {
+ /** The plan the subscription is now on */
+ plan: SeatPlan;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
index 2bd30db6c9..806e841793 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
@@ -7,6 +7,7 @@
import type { CheckoutSessionMetadata } from './checkoutSessionMetadata';
import type { CreateCheckoutSessionV2RequestDiscount } from './createCheckoutSessionV2RequestDiscount';
+import type { CreateCheckoutSessionV2RequestPlan } from './createCheckoutSessionV2RequestPlan';
/**
* Request body for creating a Stripe checkout session
@@ -18,6 +19,7 @@ export interface CreateCheckoutSessionV2Request {
discount?: CreateCheckoutSessionV2RequestDiscount;
/** Tracking metadata for conversion attribution */
metadata?: CheckoutSessionMetadata;
+ plan?: CreateCheckoutSessionV2RequestPlan;
/** The URL to redirect to on successful checkout */
successUrl: string;
}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestPlan.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestPlan.ts
new file mode 100644
index 0000000000..34fde429ba
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestPlan.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 { SeatPlan } from './seatPlan';
+
+export type CreateCheckoutSessionV2RequestPlan = null | SeatPlan;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutRequestBody.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutRequestBody.ts
new file mode 100644
index 0000000000..0f7525e4b4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutRequestBody.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for [`create_credit_checkout_handler`].
+ */
+export interface CreditCheckoutRequestBody {
+ /** Pack size, cents; one of the catalog's `credit_packs_cents`. */
+ amountCents: number;
+ /** Where Stripe returns the user on cancel. Same rules as `success_url`. */
+ cancelUrl: string;
+ /** Where Stripe returns the user after paying. Must be an `https` URL
+on the origin the request came from. */
+ successUrl: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutResponse.ts
new file mode 100644
index 0000000000..94be8ff650
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditCheckoutResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response for [`create_credit_checkout_handler`].
+ */
+export interface CreditCheckoutResponse {
+ /** The hosted Checkout URL to redirect to. */
+ url: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts
new file mode 100644
index 0000000000..6e98d2a292
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Why a request was refused.
+ */
+export type DenyReason = (typeof DenyReason)[keyof typeof DenyReason];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const DenyReason = {
+ allowance_exhausted: 'allowance_exhausted',
+ overage_limit_reached: 'overage_limit_reached',
+ overage_payment_failed: 'overage_payment_failed',
+} as const;
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.ts
index 85fa9bcd87..93995c0342 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
@@ -6,7 +6,10 @@
*/
export * from './aBGroup';
+export * from './aiBillingErrorBody';
export * from './appleLoginRequest';
+export * from './changePlanRequest';
+export * from './changePlanResponse';
export * from './checkoutSessionMetadata';
export * from './checkoutSessionMetadataFbc';
export * from './checkoutSessionMetadataFbp';
@@ -25,6 +28,7 @@ export * from './codexLoginState';
export * from './createAccountMergeRequest';
export * from './createCheckoutSessionV2Request';
export * from './createCheckoutSessionV2RequestDiscount';
+export * from './createCheckoutSessionV2RequestPlan';
export * from './createGtmInviteLinkRequest';
export * from './createGtmInviteLinkRequestNote';
export * from './createGtmInviteLinkRequestRecipientEmail';
@@ -32,11 +36,14 @@ export * from './createInProgressLinkResponse';
export * from './createPortalSessionRequest';
export * from './createTeamRequest';
export * from './createUserRequest';
+export * from './creditCheckoutRequestBody';
+export * from './creditCheckoutResponse';
export * from './cursorApiKeyStatus';
export * from './cursorApiKeyStatusDefaultModelId';
export * from './cursorApiKeyStatusUpdatedAt';
export * from './cursorModelOption';
export * from './cursorModelsResponse';
+export * from './denyReason';
export * from './emptyResponse';
export * from './enrichedGithubPullRequest';
export * from './enrichedGithubPullRequestAdditions';
@@ -118,6 +125,7 @@ export * from './passwordlessStartedResponseCode';
export * from './passwordRequest';
export * from './patchTeamCrmSettingsRequest';
export * from './patchTeamCrmSettingsResponse';
+export * from './patchTeamMemberPlanRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestDefaultLinkShare';
export * from './patchTeamRequestName';
@@ -128,6 +136,9 @@ export * from './patchUserGroupRequest';
export * from './patchUserOnboardingRequest';
export * from './patchUserTutorialRequest';
export * from './permission';
+export * from './planCatalogEntry';
+export * from './planCatalogResponse';
+export * from './planTier';
export * from './postGetNamesRequestBody';
export * from './profilePictureQueryParams';
export * from './profilePictures';
@@ -142,6 +153,7 @@ export * from './putUserNameQueryParamsFirstName';
export * from './putUserNameQueryParamsLastName';
export * from './redeemGtmInviteLinkRequest';
export * from './resendFusionauthVerifyUserEmailRequest';
+export * from './seatPlan';
export * from './sendInviteBody';
export * from './sendMobileWelcomeEmailRequest';
export * from './sendMobileWelcomeEmailResponse';
@@ -160,6 +172,9 @@ export * from './teamWithMembers';
export * from './toggleAutoJoinDomainResponse';
export * from './toggleAutoJoinDomainResponseAutoJoinDomain';
export * from './toggleNonAdminInvitesResponse';
+export * from './updateOverageRequest';
+export * from './usageSnapshot';
+export * from './usageSnapshotBlockedReason';
export * from './userLinkResponse';
export * from './userName';
export * from './userNameFirstName';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamMemberPlanRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamMemberPlanRequest.ts
new file mode 100644
index 0000000000..51ffcc1b0b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamMemberPlanRequest.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 { SeatPlan } from './seatPlan';
+
+/**
+ * Request body for `PATCH /team/members/{member_user_id}/plan`.
+ */
+export interface PatchTeamMemberPlanRequest {
+ /** The plan to bill the member's seat at from now on. */
+ plan: SeatPlan;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts
new file mode 100644
index 0000000000..0b5d98553e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PlanTier } from './planTier';
+
+/**
+ * One plan in the catalog.
+ */
+export interface PlanCatalogEntry {
+ /** Included AI per seat per period, list-rate cents. */
+ included_ai_cents_per_seat: number;
+ /** Monthly list price per seat, cents. */
+ monthly_price_cents: number;
+ /** The tier. */
+ tier: PlanTier;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts
new file mode 100644
index 0000000000..373aaf0003
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PlanCatalogEntry } from './planCatalogEntry';
+
+/**
+ * The plan catalog and the knobs the billing UI offers.
+ */
+export interface PlanCatalogResponse {
+ /** Credit packs a payer may buy, cents. */
+ credit_packs_cents: number[];
+ /** Largest allowed overage cap, cents. */
+ overage_limit_max_cents: number;
+ /** Smallest allowed overage cap, cents. */
+ overage_limit_min_cents: number;
+ /** Every plan, cheapest first. */
+ plans: PlanCatalogEntry[];
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planTier.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planTier.ts
new file mode 100644
index 0000000000..df6e9d2b00
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planTier.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The plans a user can be on, cheapest first.
+ */
+export type PlanTier = (typeof PlanTier)[keyof typeof PlanTier];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PlanTier = {
+ free: 'free',
+ premium: 'premium',
+ max: 'max',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/seatPlan.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/seatPlan.ts
new file mode 100644
index 0000000000..305ac3c949
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/seatPlan.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * 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
+plan in use.
+ */
+export type SeatPlan = (typeof SeatPlan)[keyof typeof SeatPlan];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SeatPlan = {
+ premium: 'premium',
+ max: 'max',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamMember.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamMember.ts
index 20a382405f..9627ea295d 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamMember.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamMember.ts
@@ -4,12 +4,16 @@
* authentication_service
* OpenAPI spec version: 0.1.0
*/
+import type { SeatPlan } from './seatPlan';
import type { TeamRole } from './teamRole';
/**
* The team member struct
*/
export interface TeamMember {
+ /** The paid plan the member's seat is billed at. Meaningful on paying
+and enterprise teams; free-team members carry the default. */
+ plan: SeatPlan;
/** The role of the team member */
role: TeamRole;
/** The id of the team */
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateOverageRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateOverageRequest.ts
new file mode 100644
index 0000000000..1f84a742bc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateOverageRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for [`update_overage_handler`].
+ */
+export interface UpdateOverageRequest {
+ /** Bill usage past allowance and credits. */
+ enabled: boolean;
+ /** Per-period cap on overage spend, cents. Required when enabling. */
+ limitCents?: number;
+}
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.ts
new file mode 100644
index 0000000000..a225f33e92
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts
@@ -0,0 +1,56 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { PlanTier } from './planTier';
+import type { UsageSnapshotBlockedReason } from './usageSnapshotBlockedReason';
+
+/**
+ * The payer's current-period position, as shown in Billing settings and used
+by the gate.
+ */
+export interface UsageSnapshot {
+ blocked_reason?: UsageSnapshotBlockedReason;
+ /** Whether the requesting user is the payer. */
+ can_manage_billing: boolean;
+ /** Shared prepaid credit balance. */
+ credit_balance_cents: number;
+ /** Shared payer credits already applied to this period. */
+ credits_consumed_cents: number;
+ /** Included AI for this user's seat this period, in list-rate cents. */
+ included_cents: number;
+ /** Shared overage charged so far this period. */
+ overage_charged_cents: number;
+ /** Whether overage billing is on. */
+ overage_enabled: boolean;
+ /** Per-period overage cap. */
+ overage_limit_cents: number;
+ /** Whether overage is paused after a failed charge. */
+ overage_suspended: boolean;
+ /** The payer for this user's AI. */
+ payer: string;
+ /** Period end (exclusive). */
+ period_end: string;
+ /** Period start. */
+ period_start: string;
+ /** This seat's remaining allowance plus shared credit/overage headroom; 0
+when blocked. */
+ remaining_cents: number;
+ /**
+ * Seats billed to the payer.
+ * @minimum 0
+ */
+ seats: number;
+ /** The plan. */
+ tier: PlanTier;
+ /** Team-wide usage beyond per-seat allowances that is not yet covered by
+shared credits or charges (awaiting settlement). */
+ uncovered_cents: number;
+ /** Enterprise: never metered. */
+ unlimited: boolean;
+ /** AI used by this user this period, in list-rate cents. */
+ used_cents: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotBlockedReason.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotBlockedReason.ts
new file mode 100644
index 0000000000..f91102a646
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotBlockedReason.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 { DenyReason } from './denyReason';
+
+export type UsageSnapshotBlockedReason = null | DenyReason;
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index b5d54c074b..5daf18f3bc 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -10,6 +10,202 @@
"version": "0.1.0"
},
"paths": {
+ "/ai-billing/credits/checkout": {
+ "post": {
+ "tags": ["ai_billing"],
+ "summary": "Start a Stripe Checkout for a credit pack. Payer only.",
+ "operationId": "create_ai_credit_checkout",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreditCheckoutRequestBody"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Checkout URL",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreditCheckoutResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid pack, untrusted return URL, or no payment account",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "402": {
+ "description": "A paid plan is required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only the payer may buy credits",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/overage": {
+ "patch": {
+ "tags": ["ai_billing"],
+ "summary": "Turn overage billing on or off and set the per-period cap. Payer only.",
+ "operationId": "update_ai_billing_overage",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateOverageRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Updated position",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageSnapshot"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "402": {
+ "description": "A paid plan is required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only the payer may change billing",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/plans": {
+ "get": {
+ "tags": ["ai_billing"],
+ "summary": "The plan catalog, credit packs, and overage cap bounds.",
+ "operationId": "get_ai_billing_plans",
+ "responses": {
+ "200": {
+ "description": "Plan catalog",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PlanCatalogResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/summary": {
+ "get": {
+ "tags": ["ai_billing"],
+ "summary": "The caller's current-period AI usage, credits, and overage settings.",
+ "description": "Runs a settlement first so the position reflects any credits or overage\nthat were waiting to be booked.",
+ "operationId": "get_ai_billing_summary",
+ "responses": {
+ "200": {
+ "description": "Current-period position",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageSnapshot"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/codex": {
"get": {
"tags": ["crate::api::codex"],
@@ -3200,6 +3396,97 @@
}
}
},
+ "/team/members/{member_user_id}/plan": {
+ "patch": {
+ "tags": ["teams::inbound::axum_router::patch_team_member_plan"],
+ "summary": "Moves one team member's seat between paid plans.",
+ "description": "Team admins and owners only. The team's subscription is re-billed for\nthe seat at once (prorated); the member's tier role and individual AI\nallowance follow immediately.",
+ "operationId": "patch_team_member_plan",
+ "parameters": [
+ {
+ "name": "member_user_id",
+ "in": "path",
+ "description": "The member whose seat plan changes",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchTeamMemberPlanRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TeamMember"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "402": {
+ "description": "The team has no active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/non-admin-invites/toggle": {
"post": {
"tags": ["teams::inbound::axum_router::toggle_non_admin_invites"],
@@ -4230,6 +4517,96 @@
}
}
},
+ "/user/stripe/plan": {
+ "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.",
+ "operationId": "change_plan",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePlanRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePlanResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Plan not available",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "402": {
+ "description": "The team has no active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only team admins change plans on a team",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Already on this plan, or more than one active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/user/stripe/portal": {
"post": {
"tags": ["user::stripe::create_portal_session"],
@@ -4345,6 +4722,17 @@
"type": "string",
"enum": ["A", "B"]
},
+ "AiBillingErrorBody": {
+ "type": "object",
+ "description": "Error response body.",
+ "required": ["error"],
+ "properties": {
+ "error": {
+ "type": "string",
+ "description": "Human-readable error description."
+ }
+ }
+ },
"AppleLoginRequest": {
"type": "object",
"required": ["id_token", "code"],
@@ -4357,6 +4745,28 @@
}
}
},
+ "ChangePlanRequest": {
+ "type": "object",
+ "description": "Request body for switching plans",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to move the active subscription to"
+ }
+ }
+ },
+ "ChangePlanResponse": {
+ "type": "object",
+ "description": "Response for a plan change",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan the subscription is now on"
+ }
+ }
+ },
"CheckoutSessionMetadata": {
"type": "object",
"description": "Tracking metadata for conversion attribution",
@@ -4531,6 +4941,17 @@
"$ref": "#/components/schemas/CheckoutSessionMetadata",
"description": "Tracking metadata for conversion attribution"
},
+ "plan": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to subscribe to. Defaults to Premium."
+ }
+ ]
+ },
"successUrl": {
"type": "string",
"description": "The URL to redirect to on successful checkout"
@@ -4607,6 +5028,37 @@
}
}
},
+ "CreditCheckoutRequestBody": {
+ "type": "object",
+ "description": "Request body for [`create_credit_checkout_handler`].",
+ "required": ["amountCents", "successUrl", "cancelUrl"],
+ "properties": {
+ "amountCents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Pack size, cents; one of the catalog's `credit_packs_cents`."
+ },
+ "cancelUrl": {
+ "type": "string",
+ "description": "Where Stripe returns the user on cancel. Same rules as `success_url`."
+ },
+ "successUrl": {
+ "type": "string",
+ "description": "Where Stripe returns the user after paying. Must be an `https` URL\non the origin the request came from."
+ }
+ }
+ },
+ "CreditCheckoutResponse": {
+ "type": "object",
+ "description": "Response for [`create_credit_checkout_handler`].",
+ "required": ["url"],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The hosted Checkout URL to redirect to."
+ }
+ }
+ },
"CursorApiKeyStatus": {
"type": "object",
"description": "What settings needs to render the Cursor connection.\n\nDeliberately thin. `registered` drives the whole UI; `updatedAt` lets it say\nwhen the key was last replaced, which is the only thing a user can check\nagainst their own memory when a session starts failing.\n\nDeliberately *not* reporting anything about the deployment itself. That is\noperator information: a user who sees it cannot act on it, and a service\nthat cannot reach KMS does not start.",
@@ -4660,6 +5112,15 @@
}
}
},
+ "DenyReason": {
+ "type": "string",
+ "description": "Why a request was refused.",
+ "enum": [
+ "allowance_exhausted",
+ "overage_limit_reached",
+ "overage_payment_failed"
+ ]
+ },
"EmptyResponse": {
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
@@ -5472,6 +5933,17 @@
}
}
},
+ "PatchTeamMemberPlanRequest": {
+ "type": "object",
+ "description": "Request body for `PATCH /team/members/{member_user_id}/plan`.",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to bill the member's seat at from now on."
+ }
+ }
+ },
"PatchTeamRequest": {
"type": "object",
"description": "Request to update a team",
@@ -5575,6 +6047,73 @@
}
}
},
+ "PlanCatalogEntry": {
+ "type": "object",
+ "description": "One plan in the catalog.",
+ "required": [
+ "tier",
+ "monthly_price_cents",
+ "included_ai_cents_per_seat"
+ ],
+ "properties": {
+ "included_ai_cents_per_seat": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Included AI per seat per period, list-rate cents."
+ },
+ "monthly_price_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Monthly list price per seat, cents."
+ },
+ "tier": {
+ "$ref": "#/components/schemas/PlanTier",
+ "description": "The tier."
+ }
+ }
+ },
+ "PlanCatalogResponse": {
+ "type": "object",
+ "description": "The plan catalog and the knobs the billing UI offers.",
+ "required": [
+ "plans",
+ "credit_packs_cents",
+ "overage_limit_min_cents",
+ "overage_limit_max_cents"
+ ],
+ "properties": {
+ "credit_packs_cents": {
+ "type": "array",
+ "items": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "description": "Credit packs a payer may buy, cents."
+ },
+ "overage_limit_max_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Largest allowed overage cap, cents."
+ },
+ "overage_limit_min_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Smallest allowed overage cap, cents."
+ },
+ "plans": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PlanCatalogEntry"
+ },
+ "description": "Every plan, cheapest first."
+ }
+ }
+ },
+ "PlanTier": {
+ "type": "string",
+ "description": "The plans a user can be on, cheapest first.",
+ "enum": ["free", "premium", "max"]
+ },
"PostGetNamesRequestBody": {
"type": "object",
"required": ["user_ids"],
@@ -5684,6 +6223,11 @@
}
}
},
+ "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.",
+ "enum": ["premium", "max"]
+ },
"SendInviteBody": {
"type": "object",
"description": "The body which is used to describe the recipient email",
@@ -5855,8 +6399,12 @@
"TeamMember": {
"type": "object",
"description": "The team member struct",
- "required": ["team_id", "user_id", "role"],
+ "required": ["team_id", "user_id", "role", "plan"],
"properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The paid plan the member's seat is billed at. Meaningful on paying\nand enterprise teams; free-team members carry the default."
+ },
"role": {
"$ref": "#/components/schemas/TeamRole",
"description": "The role of the team member"
@@ -5921,6 +6469,138 @@
}
}
},
+ "UpdateOverageRequest": {
+ "type": "object",
+ "description": "Request body for [`update_overage_handler`].",
+ "required": ["enabled"],
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "Bill usage past allowance and credits."
+ },
+ "limitCents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Per-period cap on overage spend, cents. Required when enabling."
+ }
+ }
+ },
+ "UsageSnapshot": {
+ "type": "object",
+ "description": "The payer's current-period position, as shown in Billing settings and used\nby the gate.",
+ "required": [
+ "tier",
+ "unlimited",
+ "payer",
+ "can_manage_billing",
+ "seats",
+ "period_start",
+ "period_end",
+ "included_cents",
+ "used_cents",
+ "credits_consumed_cents",
+ "credit_balance_cents",
+ "overage_enabled",
+ "overage_limit_cents",
+ "overage_charged_cents",
+ "overage_suspended",
+ "uncovered_cents",
+ "remaining_cents"
+ ],
+ "properties": {
+ "blocked_reason": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/DenyReason",
+ "description": "Why requests are refused right now, if they are."
+ }
+ ]
+ },
+ "can_manage_billing": {
+ "type": "boolean",
+ "description": "Whether the requesting user is the payer."
+ },
+ "credit_balance_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared prepaid credit balance."
+ },
+ "credits_consumed_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared payer credits already applied to this period."
+ },
+ "included_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Included AI for this user's seat this period, in list-rate cents."
+ },
+ "overage_charged_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared overage charged so far this period."
+ },
+ "overage_enabled": {
+ "type": "boolean",
+ "description": "Whether overage billing is on."
+ },
+ "overage_limit_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Per-period overage cap."
+ },
+ "overage_suspended": {
+ "type": "boolean",
+ "description": "Whether overage is paused after a failed charge."
+ },
+ "payer": {
+ "type": "string",
+ "description": "The payer for this user's AI."
+ },
+ "period_end": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Period end (exclusive)."
+ },
+ "period_start": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Period start."
+ },
+ "remaining_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "This seat's remaining allowance plus shared credit/overage headroom; 0\nwhen blocked."
+ },
+ "seats": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Seats billed to the payer.",
+ "minimum": 0
+ },
+ "tier": {
+ "$ref": "#/components/schemas/PlanTier",
+ "description": "The plan."
+ },
+ "uncovered_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Team-wide usage beyond per-seat allowances that is not yet covered by\nshared credits or charges (awaiting settlement)."
+ },
+ "unlimited": {
+ "type": "boolean",
+ "description": "Enterprise: never metered."
+ },
+ "used_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "AI used by this user this period, in list-rate cents."
+ }
+ }
+ },
"UserLinkResponse": {
"type": "object",
"required": ["link_exists"],
diff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.ts
index c94b863f1f..5799d96c9f 100644
--- a/apps/web/src/lib/service-clients/service-cognition/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts
@@ -65,6 +65,49 @@ function dcsFetch<T extends ObjectLike = never>(
}
type Success = { success: boolean };
+/**
+ * Error code for a chat send refused by the AI billing gate (HTTP 402). The
+ * error's `message` carries the backend's reason code
+ * (`ai_allowance_exhausted`, `ai_overage_limit_reached`,
+ * `ai_overage_payment_failed`) so the UI can explain and offer the fix.
+ */
+export const AI_USAGE_LIMIT_ERROR = 'AI_USAGE_LIMIT' as const;
+
+async function chatSendErrorHandler(
+ response: Response
+): Promise<ResultError<FetchWithTokenErrorCode | typeof AI_USAGE_LIMIT_ERROR>> {
+ switch (response.status) {
+ case 402: {
+ let body: { error?: string; code?: string } | null = null;
+ try {
+ body = (await response.json()) as { error?: string; code?: string };
+ } catch {
+ body = null;
+ }
+ return {
+ code: AI_USAGE_LIMIT_ERROR,
+ message: body?.code ?? 'ai_allowance_exhausted',
+ description: body?.error,
+ };
+ }
+ case 401:
+ return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
+ case 403:
+ return { code: 'FORBIDDEN', message: 'Forbidden' };
+ case 404:
+ return { code: 'NOT_FOUND', message: 'Resource not found' };
+ case 409:
+ return { code: 'CONFLICT', message: 'Resource conflict' };
+ case 500:
+ return { code: 'SERVER_ERROR', message: 'Internal server error' };
+ default:
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ }
+}
+
type IdMappingResponse = { target_id: string | null };
// Hand-written mirrors of the DCS OpenAPI types for the Pipedream MCP
@@ -339,9 +382,13 @@ export const cognitionApiServiceClient = {
/** Send a chat message via HTTP stream API. Response chunks arrive via connection_gateway. */
async sendStreamChatMessage(args: HttpSendChatMessageRequest) {
return (
- await dcsFetch<SendChatMessageResponse>(`/stream/chat/message`, {
+ await fetchWithToken<
+ SendChatMessageResponse,
+ typeof AI_USAGE_LIMIT_ERROR
+ >(`${dcsHost}/stream/chat/message`, {
method: 'POST',
body: JSON.stringify(args),
+ errorResponseHandler: chatSendErrorHandler,
})
).map((result) => result);
},
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
index 85fe086c05..0f0f603725 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
@@ -2422,12 +2422,12 @@ export type sendChatMessageResponse401 = {
};
export type sendChatMessageResponse402 = {
- data: void;
+ data: ChatMessageError;
status: 402;
};
export type sendChatMessageResponse403 = {
- data: void;
+ data: ChatMessageError;
status: 403;
};
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
index 85f1c5035b..3644ad825b 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
@@ -4,12 +4,15 @@
* Document Cognition Service
* OpenAPI spec version: 1.0.0
*/
+import type { ChatMessageErrorCode } from './chatMessageErrorCode';
import type { ChatMessageErrorStreamId } from './chatMessageErrorStreamId';
/**
* Error response for chat message endpoints
*/
export interface ChatMessageError {
+ /** Stable machine-readable code for payment-required errors. */
+ code?: ChatMessageErrorCode;
error: string;
stream_id?: ChatMessageErrorStreamId;
}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts
new file mode 100644
index 0000000000..6ff0bdc3ed
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Stable machine-readable code for payment-required errors.
+ */
+export type ChatMessageErrorCode = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
index 3169b50c84..bce9b62295 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
@@ -50,6 +50,7 @@ export * from './chatHistoryBatchMessagesRequest';
export * from './chatMessage';
export * from './chatMessageContent';
export * from './chatMessageError';
+export * from './chatMessageErrorCode';
export * from './chatMessageErrorStreamId';
export * from './chatMessageModel';
export * from './chatMessageWithAttachments';
@@ -224,6 +225,7 @@ export * from './streamErrorOneOfThree';
export * from './streamErrorOneOfThreeStreamError';
export * from './stringIDResponse';
export * from './structuredCompletionError';
+export * from './structuredCompletionErrorCode';
export * from './structuredCompletionRequest';
export * from './structuredCompletionRequestAdditionalInstructions';
export * from './structuredCompletionResponse';
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
index cf8b797c58..e6fe795433 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
@@ -4,7 +4,10 @@
* Document Cognition Service
* OpenAPI spec version: 1.0.0
*/
+import type { StructuredCompletionErrorCode } from './structuredCompletionErrorCode';
export interface StructuredCompletionError {
+ /** Stable machine-readable code for payment-required errors. */
+ code?: StructuredCompletionErrorCode;
error: string;
}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts
new file mode 100644
index 0000000000..e27f8bc8bc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Stable machine-readable code for payment-required errors.
+ */
+export type StructuredCompletionErrorCode = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 13f6531e34..5f89f1d533 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -2002,10 +2002,24 @@
"description": "Unauthorized"
},
"402": {
- "description": "Payment required — user lacks access to the requested model"
+ "description": "Payment required — the user's AI allowance is used up",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
},
"403": {
- "description": "Forbidden"
+ "description": "Forbidden — user lacks access to the requested model",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
}
}
}
@@ -2553,6 +2567,10 @@
"description": "Error response for chat message endpoints",
"required": ["error"],
"properties": {
+ "code": {
+ "type": ["string", "null"],
+ "description": "Stable machine-readable code for payment-required errors."
+ },
"error": {
"type": "string"
},
@@ -4568,6 +4586,10 @@
"type": "object",
"required": ["error"],
"properties": {
+ "code": {
+ "type": ["string", "null"],
+ "description": "Stable machine-readable code for payment-required errors."
+ },
"error": {
"type": "string"
}
diff --git a/apps/web/src/lib/service-clients/service-stripe/client.ts b/apps/web/src/lib/service-clients/service-stripe/client.ts
index 053e653339..2866ba3f0d 100644
--- a/apps/web/src/lib/service-clients/service-stripe/client.ts
+++ b/apps/web/src/lib/service-clients/service-stripe/client.ts
@@ -1,4 +1,5 @@
import { registerClient } from '@core/util/mockClient';
+import type { PaidPlan } from '@service-auth/ai-billing-types';
import { authServiceClient } from '@service-auth/client';
/**
@@ -46,9 +47,11 @@ export const stripeServiceClient = {
successUrl?: string;
/** Override the default cancel URL. Useful for flows that want cancellation to return to a specific page. */
cancelUrl?: string;
+ /** The plan to subscribe to; defaults to Premium. */
+ plan?: PaidPlan;
} = {}
) => {
- const { type = '', discount, successUrl, cancelUrl } = args;
+ const { type = '', discount, successUrl, cancelUrl, plan } = args;
const gaClientId = await getGaClientId();
const { fbp, fbc } = getMetaIds();
@@ -64,6 +67,7 @@ export const stripeServiceClient = {
fbp: fbp ?? null,
fbc: fbc ?? null,
},
+ plan,
});
if (!result.isOk()) {
diff --git a/crates/agent/src/model/openai.rs b/crates/agent/src/model/openai.rs
index 0ac99b6bad..0724b33f44 100644
--- a/crates/agent/src/model/openai.rs
+++ b/crates/agent/src/model/openai.rs
@@ -38,7 +38,8 @@ impl<'a> OpenAiChatCompletionsModel<'a> {
/// `None` if the model doesn't support it.
///
/// The Chat Completions API takes a flat `reasoning_effort` field, accepted
- /// only by reasoning models (the GPT-5 family and the `o`-series); anything
+ /// only by reasoning models (the GPT-5 and GPT-6 families and the
+ /// `o`-series); anything
/// else returns `None`, since sending it elsewhere 400s. `mini` / `nano`
/// variants get a lower effort. `temperature` is never set (reasoning models
/// reject it).
@@ -46,6 +47,7 @@ impl<'a> OpenAiChatCompletionsModel<'a> {
let model = self.model.name().to_lowercase();
let is_reasoning = model.contains("gpt-5")
+ || model.contains("gpt-6")
|| model.starts_with("o1")
|| model.starts_with("o3")
|| model.starts_with("o4");
@@ -100,6 +102,7 @@ impl<'a> OpenAiResponsesModel<'a> {
let model = self.model.name().to_lowercase();
let is_reasoning = model.contains("gpt-5")
+ || model.contains("gpt-6")
|| model.starts_with("o1")
|| model.starts_with("o3")
|| model.starts_with("o4");
diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.toml
new file mode 100644
index 0000000000..8a99d34082
--- /dev/null
+++ b/crates/ai_billing/Cargo.toml
@@ -0,0 +1,39 @@
+[package]
+edition = "2024"
+name = "ai_billing"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+ai_usage = { path = "../ai_usage" }
+anyhow = { workspace = true }
+async-stripe = { workspace = true, default-features = false, features = [
+ "billing",
+ "checkout",
+ "runtime-tokio-hyper-rustls-webpki",
+] }
+authentication_service_client = { path = "../authentication_service_client" }
+axum = { workspace = true }
+chrono = { workspace = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+] }
+macro_user_id = { path = "../macro_user_id", features = ["schema"] }
+macro_uuid = { path = "../macro_uuid" }
+roles_and_permissions = { path = "../roles_and_permissions", default-features = false, features = [
+ "ports",
+] }
+rootcause = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+strum = { workspace = true }
+teams = { path = "../teams", default-features = false, features = ["ports"] }
+thiserror = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+utoipa = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
new file mode 100644
index 0000000000..951f4cf948
--- /dev/null
+++ b/crates/ai_billing/src/domain.rs
@@ -0,0 +1,21 @@
+//! Domain layer: plans and margin math, the settlement ledger, ports, and the
+//! billing service.
+
+pub mod ledger;
+pub mod models;
+pub mod ports;
+pub mod service;
+
+pub use ledger::{SettlementPlan, SettlementPolicy, SettlementState, plan_settlement};
+pub use models::{
+ AllowanceDecision, BillingError, BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS,
+ DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS, OVERAGE_CHARGE_THRESHOLD_CENTS,
+ OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope,
+ PeriodAllowance, PeriodLedger, PlanTier, Result, SeatAllowance, SeatUsage,
+ TARGET_GROSS_MARGIN_BPS, UsageSnapshot, list_rate_cents,
+};
+pub use ports::{
+ BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
+ PaymentGateway, PendingCharge, SettlementOutcome, SettlementTrigger, UsageReader,
+};
+pub use service::BillingServiceImpl;
diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rs
new file mode 100644
index 0000000000..a453059587
--- /dev/null
+++ b/crates/ai_billing/src/domain/ledger.rs
@@ -0,0 +1,175 @@
+//! The settlement arithmetic, kept pure so the repository can run it inside
+//! its row lock and the service can run it for snapshots.
+//!
+//! For a payer and period, each seat first consumes only its own included
+//! allowance. The remaining usage is chargeable to the payer's shared credits
+//! and overage:
+//!
+//! ```text
+//! chargeable = sum(max(0, seat_used - seat_included))
+//! covered = credits_consumed + overage_charged
+//! uncovered = max(0, chargeable - covered)
+//! headroom = (covered - chargeable) + credit_balance + overage_room
+//! ```
+//!
+//! Settlement moves `uncovered` into `credits_consumed` (from the balance) and
+//! then into `overage_charged` (when overage is on, within the cap, and the
+//! chunk is worth charging). Between settlements `uncovered` is simply usage
+//! that has not been booked yet; the gate accounts for it through `headroom`.
+
+#[cfg(test)]
+mod test;
+
+use super::models::{
+ AllowanceDecision, BillingPeriod, BillingSettings, DenyReason, Entitlement,
+ MIN_STRIPE_CHARGE_CENTS, PeriodLedger, PlanTier, UsageSnapshot,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// The overage policy in force for one settlement.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SettlementPolicy {
+ /// Whether overage may be charged at all.
+ pub overage_active: bool,
+ /// Per-period overage cap.
+ pub overage_limit_cents: i64,
+ /// Charge accrued overage once it reaches this.
+ pub charge_threshold_cents: i64,
+ /// The period is over: flush any chargeable remainder.
+ pub period_ended: bool,
+}
+
+/// The ledger position a settlement plans against.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SettlementState {
+ /// Sum of each seat's usage beyond its own allowance this period.
+ pub chargeable_cents: i64,
+ /// Credits already applied this period.
+ pub credits_consumed_cents: i64,
+ /// Overage already charged this period (pending or paid).
+ pub overage_charged_cents: i64,
+ /// Current credit balance.
+ pub credit_balance_cents: i64,
+}
+
+impl SettlementState {
+ /// Chargeable usage not yet covered by credits or charges.
+ pub fn uncovered_cents(&self) -> i64 {
+ (self.chargeable_cents - (self.credits_consumed_cents + self.overage_charged_cents)).max(0)
+ }
+}
+
+/// What a settlement should book.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct SettlementPlan {
+ /// Credits to consume against the period.
+ pub consume_credits_cents: i64,
+ /// Overage to charge now (0 when nothing is chargeable yet).
+ pub charge_overage_cents: i64,
+}
+
+/// Decide how much of the uncovered usage to book from credits and how much
+/// to charge as overage.
+pub fn plan_settlement(state: SettlementState, policy: SettlementPolicy) -> SettlementPlan {
+ let uncovered = state.uncovered_cents();
+ if uncovered == 0 {
+ return SettlementPlan::default();
+ }
+
+ let consume = uncovered.min(state.credit_balance_cents.max(0));
+ let rest = uncovered - consume;
+
+ let charge = if policy.overage_active && rest > 0 {
+ let room = (policy.overage_limit_cents - state.overage_charged_cents).max(0);
+ let chargeable = rest.min(room);
+ let worth_charging = chargeable >= policy.charge_threshold_cents
+ || (policy.period_ended && chargeable >= MIN_STRIPE_CHARGE_CENTS);
+ if worth_charging { chargeable } else { 0 }
+ } else {
+ 0
+ };
+
+ SettlementPlan {
+ consume_credits_cents: consume,
+ charge_overage_cents: charge,
+ }
+}
+
+/// Assemble the API-facing snapshot from the resolved inputs.
+#[expect(
+ clippy::too_many_arguments,
+ reason = "snapshot assembly keeps its resolved billing inputs explicit"
+)]
+pub fn build_snapshot(
+ user: &MacroUserIdStr<'_>,
+ entitlement: &Entitlement,
+ settings: &BillingSettings,
+ period: BillingPeriod,
+ used_cents: i64,
+ shared_chargeable_cents: i64,
+ ledger: PeriodLedger,
+ credit_balance_cents: i64,
+) -> UsageSnapshot {
+ let included_cents = entitlement.included_ai_cents();
+ let shared_covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;
+ let uncovered_cents = (shared_chargeable_cents - shared_covered).max(0);
+ let overage_room = if settings.overage_active() {
+ (settings.overage_limit_cents - ledger.overage_charged_cents).max(0)
+ } else {
+ 0
+ };
+ let remaining_cents = if entitlement.unlimited {
+ i64::MAX
+ } else {
+ let seat_remaining = (included_cents - used_cents).max(0);
+ let shared_headroom = ((shared_covered - shared_chargeable_cents)
+ + credit_balance_cents.max(0)
+ + overage_room)
+ .max(0);
+ seat_remaining.saturating_add(shared_headroom)
+ };
+
+ let mut snapshot = UsageSnapshot {
+ tier: entitlement.tier,
+ unlimited: entitlement.unlimited,
+ payer: entitlement.payer.clone(),
+ can_manage_billing: entitlement.is_payer(user),
+ seats: entitlement.seats(),
+ period_start: period.start,
+ period_end: period.end,
+ included_cents,
+ used_cents,
+ credits_consumed_cents: ledger.credits_consumed_cents,
+ credit_balance_cents,
+ overage_enabled: settings.overage_enabled,
+ overage_limit_cents: settings.overage_limit_cents,
+ overage_charged_cents: ledger.overage_charged_cents,
+ overage_suspended: settings.overage_suspended_at.is_some(),
+ uncovered_cents,
+ remaining_cents,
+ blocked_reason: None,
+ };
+ snapshot.blocked_reason = match decide(&snapshot) {
+ AllowanceDecision::Allow => None,
+ AllowanceDecision::Deny(reason) => Some(reason),
+ };
+ snapshot
+}
+
+/// The gate: may this user start another AI request?
+///
+/// Free users are not metered here (the free tier has its own limits), and
+/// enterprise users are never metered. Everyone else needs headroom.
+pub fn decide(snapshot: &UsageSnapshot) -> AllowanceDecision {
+ if snapshot.unlimited || snapshot.tier == PlanTier::Free || snapshot.remaining_cents > 0 {
+ return AllowanceDecision::Allow;
+ }
+ let reason = if snapshot.overage_suspended {
+ DenyReason::OveragePaymentFailed
+ } else if snapshot.overage_enabled && snapshot.overage_limit_cents > 0 {
+ DenyReason::OverageLimitReached
+ } else {
+ DenyReason::AllowanceExhausted
+ };
+ AllowanceDecision::Deny(reason)
+}
diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rs
new file mode 100644
index 0000000000..cddb089c7b
--- /dev/null
+++ b/crates/ai_billing/src/domain/ledger/test.rs
@@ -0,0 +1,407 @@
+use super::*;
+use crate::domain::models::{OVERAGE_CHARGE_THRESHOLD_CENTS, PayerScope, list_rate_cents};
+use chrono::{TimeZone, Utc};
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()
+}
+
+fn policy(active: bool, limit: i64, ended: bool) -> SettlementPolicy {
+ SettlementPolicy {
+ overage_active: active,
+ overage_limit_cents: limit,
+ charge_threshold_cents: OVERAGE_CHARGE_THRESHOLD_CENTS,
+ period_ended: ended,
+ }
+}
+
+fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) -> SettlementState {
+ SettlementState {
+ chargeable_cents: (used - included).max(0),
+ credits_consumed_cents: consumed,
+ overage_charged_cents: charged,
+ credit_balance_cents: balance,
+ }
+}
+
+#[test]
+fn list_rate_marks_provider_cost_up_to_the_target_margin() {
+ // $16 of provider cost is exactly the Premium allowance at 60% margin.
+ assert_eq!(list_rate_cents(16.0), 4_000);
+ assert_eq!(list_rate_cents(80.0), 20_000);
+ // Fractions of a cent round up.
+ assert_eq!(list_rate_cents(0.001), 1);
+ assert_eq!(list_rate_cents(0.0), 0);
+ assert_eq!(list_rate_cents(-3.0), 0);
+ assert_eq!(list_rate_cents(f64::NAN), 0);
+}
+
+#[test]
+fn included_allowance_equals_plan_price_per_seat() {
+ assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), 4_000);
+ assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 20_000);
+ assert_eq!(PlanTier::Free.included_ai_cents_per_seat(), 0);
+
+ let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);
+ team.billed_users.push(user("[email protected]"));
+ team.seat_tiers.push(PlanTier::Premium);
+ team.billed_users.push(user("[email protected]"));
+ team.seat_tiers.push(PlanTier::Premium);
+ team.scope = PayerScope::TeamOwner {
+ team_id: macro_uuid::generate_uuid_v7(),
+ };
+ assert_eq!(team.seats(), 3);
+ assert_eq!(team.included_ai_cents(), 4_000);
+ assert_eq!(
+ team.seat_allowances()
+ .into_iter()
+ .map(|seat| seat.included_cents)
+ .collect::<Vec<_>>(),
+ vec![4_000, 4_000, 4_000]
+ );
+}
+
+#[test]
+fn mixed_seat_plans_keep_each_seats_allowance_separate() {
+ let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);
+ team.billed_users.push(user("[email protected]"));
+ team.seat_tiers.push(PlanTier::Max);
+ team.billed_users.push(user("[email protected]"));
+ team.seat_tiers.push(PlanTier::Premium);
+ team.scope = PayerScope::TeamOwner {
+ team_id: macro_uuid::generate_uuid_v7(),
+ };
+ assert_eq!(team.seats(), 3);
+ assert_eq!(team.included_ai_cents(), 4_000);
+ assert_eq!(
+ team.seat_allowances()
+ .into_iter()
+ .map(|seat| seat.included_cents)
+ .collect::<Vec<_>>(),
+ vec![4_000, 20_000, 4_000]
+ );
+ assert_eq!(team.tier, PlanTier::Premium);
+}
+
+#[test]
+fn nothing_to_settle_under_allowance() {
+ let plan = plan_settlement(state(3_000, 4_000, 0, 0, 5_000), policy(true, 5_000, false));
+ assert_eq!(plan, SettlementPlan::default());
+}
+
+#[test]
+fn credits_cover_overflow_before_overage() {
+ let plan = plan_settlement(state(4_700, 4_000, 0, 0, 5_000), policy(true, 5_000, false));
+ assert_eq!(plan.consume_credits_cents, 700);
+ assert_eq!(plan.charge_overage_cents, 0);
+}
+
+#[test]
+fn already_consumed_credits_are_not_double_counted() {
+ // 700 over, 700 already consumed: settled.
+ let plan = plan_settlement(
+ state(4_700, 4_000, 700, 0, 4_300),
+ policy(true, 5_000, false),
+ );
+ assert_eq!(plan, SettlementPlan::default());
+}
+
+#[test]
+fn overage_waits_for_the_charge_threshold() {
+ // 900 uncovered, no credits: below the $10 chunk, nothing charged yet.
+ let plan = plan_settlement(state(4_900, 4_000, 0, 0, 0), policy(true, 5_000, false));
+ assert_eq!(plan.charge_overage_cents, 0);
+ // 1_000 uncovered: charged.
+ let plan = plan_settlement(state(5_000, 4_000, 0, 0, 0), policy(true, 5_000, false));
+ assert_eq!(plan.charge_overage_cents, 1_000);
+}
+
+#[test]
+fn period_end_flushes_small_remainders_above_the_stripe_minimum() {
+ let plan = plan_settlement(state(4_300, 4_000, 0, 0, 0), policy(true, 5_000, true));
+ assert_eq!(plan.charge_overage_cents, 300);
+ // Below Stripe's $0.50 floor the remainder is forgiven.
+ let plan = plan_settlement(state(4_030, 4_000, 0, 0, 0), policy(true, 5_000, true));
+ assert_eq!(plan.charge_overage_cents, 0);
+}
+
+#[test]
+fn overage_respects_the_cap_and_prior_charges() {
+ // 6_000 uncovered, cap 5_000 with 4_500 already charged: only 500 room,
+ // and 500 is below the threshold mid-period.
+ let plan = plan_settlement(
+ state(14_500, 4_000, 0, 4_500, 0),
+ policy(true, 5_000, false),
+ );
+ assert_eq!(plan.charge_overage_cents, 0);
+ // At period end the 500 is flushed.
+ let plan = plan_settlement(state(14_500, 4_000, 0, 4_500, 0), policy(true, 5_000, true));
+ assert_eq!(plan.charge_overage_cents, 500);
+}
+
+#[test]
+fn overage_off_only_consumes_credits() {
+ let plan = plan_settlement(state(9_000, 4_000, 0, 0, 2_000), policy(false, 0, false));
+ assert_eq!(plan.consume_credits_cents, 2_000);
+ assert_eq!(plan.charge_overage_cents, 0);
+}
+
+fn snapshot_for(
+ tier: PlanTier,
+ settings: BillingSettings,
+ used: i64,
+ ledger: PeriodLedger,
+ balance: i64,
+) -> UsageSnapshot {
+ let u = user("[email protected]");
+ let ent = Entitlement::personal(u.clone(), tier);
+ let period = BillingPeriod::calendar_month(Utc::now());
+ let chargeable = (used - ent.included_ai_cents()).max(0);
+ build_snapshot(
+ &u, &ent, &settings, period, used, chargeable, ledger, balance,
+ )
+}
+
+#[test]
+fn gate_allows_within_allowance_and_blocks_after() {
+ let s = snapshot_for(
+ PlanTier::Premium,
+ BillingSettings::default(),
+ 3_999,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert_eq!(s.remaining_cents, 1);
+ assert_eq!(decide(&s), AllowanceDecision::Allow);
+
+ let s = snapshot_for(
+ PlanTier::Premium,
+ BillingSettings::default(),
+ 4_000,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert_eq!(s.remaining_cents, 0);
+ assert_eq!(
+ decide(&s),
+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)
+ );
+ assert_eq!(s.blocked_reason, Some(DenyReason::AllowanceExhausted));
+}
+
+#[test]
+fn gate_counts_unsettled_usage_against_credits() {
+ // 500 over allowance, not yet settled, 300 of credit: 300 - 500 < 0.
+ let s = snapshot_for(
+ PlanTier::Premium,
+ BillingSettings::default(),
+ 4_500,
+ PeriodLedger::default(),
+ 300,
+ );
+ assert_eq!(s.uncovered_cents, 500);
+ assert_eq!(s.remaining_cents, 0);
+ assert_eq!(
+ decide(&s),
+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)
+ );
+
+ // Once settled (500 consumed), the balance is what remains.
+ let s = snapshot_for(
+ PlanTier::Premium,
+ BillingSettings::default(),
+ 4_500,
+ PeriodLedger {
+ credits_consumed_cents: 500,
+ overage_charged_cents: 0,
+ },
+ 800,
+ );
+ assert_eq!(s.uncovered_cents, 0);
+ assert_eq!(s.remaining_cents, 800);
+ assert_eq!(decide(&s), AllowanceDecision::Allow);
+}
+
+#[test]
+fn gate_uses_overage_room_and_reports_the_cap() {
+ let settings = BillingSettings {
+ overage_enabled: true,
+ overage_limit_cents: 2_000,
+ ..Default::default()
+ };
+ let s = snapshot_for(
+ PlanTier::Premium,
+ settings.clone(),
+ 5_500,
+ PeriodLedger::default(),
+ 0,
+ );
+ // 1_500 uncovered against 2_000 of room.
+ assert_eq!(s.remaining_cents, 500);
+ assert_eq!(decide(&s), AllowanceDecision::Allow);
+
+ let s = snapshot_for(
+ PlanTier::Premium,
+ settings,
+ 6_000,
+ PeriodLedger {
+ credits_consumed_cents: 0,
+ overage_charged_cents: 2_000,
+ },
+ 0,
+ );
+ assert_eq!(s.remaining_cents, 0);
+ assert_eq!(
+ decide(&s),
+ AllowanceDecision::Deny(DenyReason::OverageLimitReached)
+ );
+}
+
+#[test]
+fn gate_reports_failed_payment_when_suspended() {
+ let settings = BillingSettings {
+ overage_enabled: true,
+ overage_limit_cents: 2_000,
+ overage_suspended_at: Some(Utc::now()),
+ ..Default::default()
+ };
+ let s = snapshot_for(
+ PlanTier::Premium,
+ settings,
+ 4_500,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert_eq!(
+ decide(&s),
+ AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)
+ );
+}
+
+#[test]
+fn free_and_unlimited_are_never_blocked() {
+ let s = snapshot_for(
+ PlanTier::Free,
+ BillingSettings::default(),
+ 99_999,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert_eq!(decide(&s), AllowanceDecision::Allow);
+
+ let u = user("[email protected]");
+ let mut ent = Entitlement::personal(u.clone(), PlanTier::Premium);
+ ent.unlimited = true;
+ let s = build_snapshot(
+ &u,
+ &ent,
+ &BillingSettings::default(),
+ BillingPeriod::calendar_month(Utc::now()),
+ 99_999,
+ 95_999,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert_eq!(decide(&s), AllowanceDecision::Allow);
+ assert_eq!(s.remaining_cents, i64::MAX);
+}
+
+#[test]
+fn team_member_is_not_the_payer() {
+ let owner = user("[email protected]");
+ let member = user("[email protected]");
+ let ent = Entitlement {
+ tier: PlanTier::Max,
+ seat_tiers: vec![PlanTier::Max, PlanTier::Max],
+ unlimited: false,
+ payer: owner.clone(),
+ billed_users: vec![owner, member.clone()],
+ scope: PayerScope::TeamMember {
+ team_id: macro_uuid::generate_uuid_v7(),
+ },
+ };
+ let s = build_snapshot(
+ &member,
+ &ent,
+ &BillingSettings::default(),
+ BillingPeriod::calendar_month(Utc::now()),
+ 0,
+ 0,
+ PeriodLedger::default(),
+ 0,
+ );
+ assert!(!s.can_manage_billing);
+ assert_eq!(s.seats, 2);
+ assert_eq!(s.included_cents, 20_000);
+}
+
+#[test]
+fn billing_period_uses_anchor_and_rolls_forward() {
+ let start = Utc.with_ymd_and_hms(2026, 1, 15, 0, 0, 0).unwrap();
+ let end = Utc.with_ymd_and_hms(2026, 2, 15, 0, 0, 0).unwrap();
+
+ let inside = Utc.with_ymd_and_hms(2026, 2, 1, 0, 0, 0).unwrap();
+ assert_eq!(
+ BillingPeriod::current(Some((start, end)), inside),
+ BillingPeriod { start, end }
+ );
+
+ // Webhook has not moved the anchor yet: roll forward two periods.
+ let later = Utc.with_ymd_and_hms(2026, 3, 20, 0, 0, 0).unwrap();
+ let rolled = BillingPeriod::current(Some((start, end)), later);
+ assert_eq!(
+ rolled.start,
+ Utc.with_ymd_and_hms(2026, 3, 15, 0, 0, 0).unwrap()
+ );
+ assert_eq!(
+ rolled.end,
+ Utc.with_ymd_and_hms(2026, 4, 15, 0, 0, 0).unwrap()
+ );
+ assert_eq!(
+ rolled.previous(),
+ BillingPeriod {
+ start: end,
+ end: rolled.start
+ }
+ );
+ assert!(rolled.previous().has_ended(later));
+ assert!(!rolled.has_ended(later));
+}
+
+#[test]
+fn billing_period_falls_back_to_the_calendar_month() {
+ let now = Utc.with_ymd_and_hms(2026, 9, 10, 12, 0, 0).unwrap();
+ let period = BillingPeriod::current(None, now);
+ assert_eq!(
+ period.start,
+ Utc.with_ymd_and_hms(2026, 9, 1, 0, 0, 0).unwrap()
+ );
+ assert_eq!(
+ period.end,
+ Utc.with_ymd_and_hms(2026, 10, 1, 0, 0, 0).unwrap()
+ );
+ // An inverted anchor is ignored.
+ assert_eq!(
+ BillingPeriod::current(Some((period.end, period.start)), now),
+ period
+ );
+}
+
+#[test]
+fn plan_tier_from_roles_prefers_max() {
+ use roles_and_permissions::domain::model::RoleId;
+ use std::collections::HashSet;
+
+ let mut roles = HashSet::from([RoleId::ProfessionalSubscriber, RoleId::SubOpus]);
+ assert_eq!(PlanTier::from_roles(&roles), PlanTier::Premium);
+ roles.insert(RoleId::SubMax);
+ assert_eq!(PlanTier::from_roles(&roles), PlanTier::Max);
+ assert_eq!(
+ PlanTier::from_roles(&HashSet::from([RoleId::SelfServe])),
+ PlanTier::Free
+ );
+ assert_eq!(
+ PlanTier::from_roles(&HashSet::from([RoleId::TeamSubscriber])),
+ PlanTier::Premium
+ );
+}
diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rs
new file mode 100644
index 0000000000..48ae8928cb
--- /dev/null
+++ b/crates/ai_billing/src/domain/models.rs
@@ -0,0 +1,466 @@
+//! Plans, the margin math, billing periods, and the API-facing snapshot.
+
+use chrono::{DateTime, Datelike, Months, TimeZone, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use roles_and_permissions::domain::model::RoleId;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use thiserror::Error;
+use utoipa::ToSchema;
+
+/// Target gross margin on AI, in basis points. The list rate is provider cost
+/// divided by `(1 - margin)`; at 60% that is a 2.5x markup.
+pub const TARGET_GROSS_MARGIN_BPS: i64 = 6_000;
+
+const BPS_PER_UNIT: i64 = 10_000;
+
+/// Convert a provider cost in USD to Macro's list rate in whole cents,
+/// rounding up so fractional cents never accrue in the customer's favour.
+pub fn list_rate_cents(provider_cost_usd: f64) -> i64 {
+ if !provider_cost_usd.is_finite() || provider_cost_usd <= 0.0 {
+ return 0;
+ }
+ let markup = BPS_PER_UNIT as f64 / (BPS_PER_UNIT - TARGET_GROSS_MARGIN_BPS) as f64;
+ (provider_cost_usd * 100.0 * markup).ceil() as i64
+}
+
+/// One-off credit packs a payer may buy, in list-rate cents.
+pub const CREDIT_PACKS_CENTS: [i64; 4] = [1_000, 2_500, 5_000, 10_000];
+
+/// Smallest per-period overage cap a payer may set.
+pub const OVERAGE_LIMIT_MIN_CENTS: i64 = 500;
+/// Largest per-period overage cap a payer may set.
+pub const OVERAGE_LIMIT_MAX_CENTS: i64 = 500_000;
+/// Accrued overage is charged once it reaches this much (or when the period
+/// ends), so a payer sees a few predictable charges rather than one per
+/// completion.
+pub const OVERAGE_CHARGE_THRESHOLD_CENTS: i64 = 1_000;
+/// Stripe rejects charges under $0.50; a smaller period-end remainder is
+/// forgiven rather than retried forever.
+pub const MIN_STRIPE_CHARGE_CENTS: i64 = 50;
+
+/// The plans a user can be on, cheapest first.
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ PartialEq,
+ Eq,
+ PartialOrd,
+ Ord,
+ Hash,
+ Serialize,
+ Deserialize,
+ ToSchema,
+ strum::Display,
+ strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum PlanTier {
+ /// No subscription. AI on the free model only; metered elsewhere.
+ Free,
+ /// The $40/seat/month plan (recorded as the legacy `sub_opus` role).
+ Premium,
+ /// The $200/seat/month plan with a 5x AI allowance.
+ Max,
+}
+
+impl PlanTier {
+ /// Monthly list price per seat, in cents.
+ pub const fn monthly_price_cents(self) -> i64 {
+ match self {
+ PlanTier::Free => 0,
+ PlanTier::Premium => 4_000,
+ PlanTier::Max => 20_000,
+ }
+ }
+
+ /// AI usage included per seat per period, in list-rate cents. Equal to the
+ /// plan price by construction: spending it all costs Macro
+ /// `price x (1 - margin)`, which is exactly the target margin.
+ pub const fn included_ai_cents_per_seat(self) -> i64 {
+ self.monthly_price_cents()
+ }
+
+ /// Whether this tier pays for AI at all (credits and overage need a plan).
+ pub const fn is_paid(self) -> bool {
+ !matches!(self, PlanTier::Free)
+ }
+
+ /// Derive the tier from a user's roles. `sub_max` wins over every other
+ /// paid role; any other paid subscription role is Premium.
+ pub fn from_roles(roles: &HashSet<RoleId>) -> Self {
+ if roles.contains(&RoleId::SubMax) {
+ PlanTier::Max
+ } else if roles.iter().any(RoleId::is_paid_subscription) {
+ PlanTier::Premium
+ } else {
+ PlanTier::Free
+ }
+ }
+}
+
+impl From<teams::domain::model::SeatPlan> for PlanTier {
+ fn from(plan: teams::domain::model::SeatPlan) -> Self {
+ match plan {
+ teams::domain::model::SeatPlan::Premium => PlanTier::Premium,
+ teams::domain::model::SeatPlan::Max => PlanTier::Max,
+ }
+ }
+}
+
+/// A half-open `[start, end)` window that usage is metered against.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct BillingPeriod {
+ /// Inclusive start.
+ pub start: DateTime<Utc>,
+ /// Exclusive end.
+ pub end: DateTime<Utc>,
+}
+
+impl BillingPeriod {
+ /// The period containing `now`.
+ ///
+ /// With a Stripe anchor (the subscription's most recently synced
+ /// `current_period_start/end`) the window is the anchor itself, rolled
+ /// forward by its own length in months when the webhook that would have
+ /// moved it has not landed yet. Without an anchor, the UTC calendar month.
+ pub fn current(anchor: Option<(DateTime<Utc>, DateTime<Utc>)>, now: DateTime<Utc>) -> Self {
+ if let Some((start, end)) = anchor
+ && start < end
+ {
+ if now < end {
+ return Self { start, end };
+ }
+ let anchor_days = (end - start).num_days().max(1) as f64;
+ let months_per_period = (anchor_days / 30.44).round().max(1.0) as u32;
+ let mut index = 1u32;
+ // A stale anchor is at most a few periods old; cap the walk so a
+ // pathological anchor can never spin.
+ while index <= 1_200 {
+ let candidate = start
+ .checked_add_months(Months::new(index * months_per_period))
+ .zip(start.checked_add_months(Months::new((index + 1) * months_per_period)));
+ match candidate {
+ Some((s, e)) if now < e => return Self { start: s, end: e },
+ Some(_) => index += 1,
+ None => break,
+ }
+ }
+ }
+ Self::calendar_month(now)
+ }
+
+ /// The period immediately before this one, assuming the same length in
+ /// whole months (one month for calendar periods).
+ pub fn previous(&self) -> Self {
+ let anchor_days = (self.end - self.start).num_days().max(1) as f64;
+ let months = Months::new((anchor_days / 30.44).round().max(1.0) as u32);
+ let start = self.start.checked_sub_months(months).unwrap_or(self.start);
+ Self {
+ start,
+ end: self.start,
+ }
+ }
+
+ /// The UTC calendar month containing `now`.
+ pub fn calendar_month(now: DateTime<Utc>) -> Self {
+ let start = Utc
+ .with_ymd_and_hms(now.year(), now.month(), 1, 0, 0, 0)
+ .single()
+ .unwrap_or(now);
+ let end = start.checked_add_months(Months::new(1)).unwrap_or(start);
+ Self { start, end }
+ }
+
+ /// Whether `now` is at or past the end of this period.
+ pub fn has_ended(&self, now: DateTime<Utc>) -> bool {
+ now >= self.end
+ }
+}
+
+/// Who pays for a user's AI, and through what.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PayerScope {
+ /// A personal subscription (or no subscription).
+ Personal,
+ /// The user owns a paying team and pays for members' shared credits and
+ /// overage.
+ TeamOwner {
+ /// The team.
+ team_id: Uuid,
+ },
+ /// The user's paid access comes through a team; the owner pays.
+ TeamMember {
+ /// The team.
+ team_id: Uuid,
+ },
+}
+
+/// The included AI assigned to one billed seat for a period.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SeatAllowance {
+ /// The user occupying the seat.
+ pub user: MacroUserIdStr<'static>,
+ /// Included AI for this seat, in list-rate cents.
+ pub included_cents: i64,
+}
+
+/// AI usage attributed to one billed seat in a period.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SeatUsage {
+ /// The user occupying the seat.
+ pub user: MacroUserIdStr<'static>,
+ /// Usage at Macro's list rate, in cents.
+ pub used_cents: i64,
+}
+
+/// A user's resolved plan and payer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Entitlement {
+ /// The plan the user's own seat is on.
+ pub tier: PlanTier,
+ /// The plan of every billed seat, in the same order as [`Self::billed_users`].
+ /// A team may mix Premium and Max seats.
+ pub seat_tiers: Vec<PlanTier>,
+ /// Enterprise teams are billed out of band and never metered.
+ pub unlimited: bool,
+ /// The account that owns credits, overage settings, and the Stripe
+ /// customer. The user themself unless they are a team member.
+ pub payer: MacroUserIdStr<'static>,
+ /// Every user whose usage can consume the payer's shared credits and
+ /// overage. Contains at least the payer.
+ pub billed_users: Vec<MacroUserIdStr<'static>>,
+ /// How the payer relates to the user.
+ pub scope: PayerScope,
+}
+
+impl Entitlement {
+ /// A user with no team, paying (or not) for themself.
+ pub fn personal(user: MacroUserIdStr<'static>, tier: PlanTier) -> Self {
+ Self {
+ tier,
+ seat_tiers: vec![tier],
+ unlimited: false,
+ payer: user.clone(),
+ billed_users: vec![user],
+ scope: PayerScope::Personal,
+ }
+ }
+
+ /// Seats billed to the payer.
+ pub fn seats(&self) -> u32 {
+ self.billed_users.len().max(1) as u32
+ }
+
+ /// Included AI for this user's seat, in list-rate cents.
+ pub fn included_ai_cents(&self) -> i64 {
+ self.tier.included_ai_cents_per_seat()
+ }
+
+ /// Each billed seat with its own included AI. Unused allowance never moves
+ /// between seats; only credits and overage are shared by the payer.
+ pub fn seat_allowances(&self) -> Vec<SeatAllowance> {
+ self.billed_users
+ .iter()
+ .enumerate()
+ .map(|(index, user)| {
+ let tier = self.seat_tiers.get(index).copied().unwrap_or(self.tier);
+ SeatAllowance {
+ user: user.clone(),
+ included_cents: tier.included_ai_cents_per_seat(),
+ }
+ })
+ .collect()
+ }
+
+ /// Whether `user` is the payer (and may change billing settings).
+ pub fn is_payer(&self, user: &MacroUserIdStr<'_>) -> bool {
+ self.payer.as_ref() == user.as_ref()
+ }
+}
+
+/// The payer's overage settings and Stripe period anchor.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct BillingSettings {
+ /// Whether usage past allowance and credits is billed as overage.
+ pub overage_enabled: bool,
+ /// Per-period cap on overage, in list-rate cents.
+ pub overage_limit_cents: i64,
+ /// Set when an overage charge failed to collect.
+ pub overage_suspended_at: Option<DateTime<Utc>>,
+ /// The subscription period last synced from Stripe.
+ pub period_anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,
+}
+
+impl BillingSettings {
+ /// Whether overage can currently be charged.
+ pub fn overage_active(&self) -> bool {
+ self.overage_enabled && self.overage_suspended_at.is_none() && self.overage_limit_cents > 0
+ }
+}
+
+/// What has already been settled against a period.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PeriodLedger {
+ /// Credits applied to this period's usage, in cents (positive).
+ pub credits_consumed_cents: i64,
+ /// Overage charged for this period, in cents. Includes pending and paid
+ /// charges, plus failed charges whose Stripe invoice may still collect.
+ pub overage_charged_cents: i64,
+}
+
+/// The allowance observed for a payer while a period was still open.
+///
+/// Closed-period settlement uses this instead of the live entitlement so a
+/// later plan or seat change cannot skip last period's overage (upgrade) or
+/// charge usage that was included (downgrade).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PeriodAllowance {
+ /// Included AI frozen for each seat in the period.
+ pub seats: Vec<SeatAllowance>,
+}
+
+/// Lifecycle of an overage charge pushed to Stripe.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum OverageChargeStatus {
+ /// Reserved in the ledger; Stripe not yet confirmed.
+ Pending,
+ /// Collected.
+ Paid,
+ /// Collection failed and overage is suspended. The charge stops covering
+ /// usage only when no Stripe invoice was opened for it.
+ Failed,
+}
+
+/// Why a request was refused.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema, strum::Display)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum DenyReason {
+ /// The plan's included AI is used up and no credits or overage remain.
+ AllowanceExhausted,
+ /// Overage is on but the payer's per-period cap has been reached.
+ OverageLimitReached,
+ /// An overage charge failed; overage is paused until the payer re-enables it.
+ OveragePaymentFailed,
+}
+
+impl DenyReason {
+ /// A stable machine-readable code for API error bodies.
+ pub fn code(self) -> &'static str {
+ match self {
+ DenyReason::AllowanceExhausted => "ai_allowance_exhausted",
+ DenyReason::OverageLimitReached => "ai_overage_limit_reached",
+ DenyReason::OveragePaymentFailed => "ai_overage_payment_failed",
+ }
+ }
+
+ /// A short human-readable explanation.
+ pub fn message(self) -> &'static str {
+ match self {
+ DenyReason::AllowanceExhausted => {
+ "You've used this period's included AI. Add credits, turn on usage billing, or upgrade to keep going."
+ }
+ DenyReason::OverageLimitReached => {
+ "You've reached your AI spending limit for this period. Raise the limit or add credits to keep going."
+ }
+ DenyReason::OveragePaymentFailed => {
+ "Your last AI usage charge didn't go through. Update your payment method and re-enable usage billing."
+ }
+ }
+ }
+}
+
+/// The gate's verdict for one request.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AllowanceDecision {
+ /// Proceed.
+ Allow,
+ /// Refuse, for the given reason.
+ Deny(DenyReason),
+}
+
+/// The payer's current-period position, as shown in Billing settings and used
+/// by the gate.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct UsageSnapshot {
+ /// The plan.
+ pub tier: PlanTier,
+ /// Enterprise: never metered.
+ pub unlimited: bool,
+ /// The payer for this user's AI.
+ #[schema(value_type = String)]
+ pub payer: MacroUserIdStr<'static>,
+ /// Whether the requesting user is the payer.
+ pub can_manage_billing: bool,
+ /// Seats billed to the payer.
+ pub seats: u32,
+ /// Period start.
+ pub period_start: DateTime<Utc>,
+ /// Period end (exclusive).
+ pub period_end: DateTime<Utc>,
+ /// Included AI for this user's seat this period, in list-rate cents.
+ pub included_cents: i64,
+ /// AI used by this user this period, in list-rate cents.
+ pub used_cents: i64,
+ /// Shared payer credits already applied to this period.
+ pub credits_consumed_cents: i64,
+ /// Shared prepaid credit balance.
+ pub credit_balance_cents: i64,
+ /// Whether overage billing is on.
+ pub overage_enabled: bool,
+ /// Per-period overage cap.
+ pub overage_limit_cents: i64,
+ /// Shared overage charged so far this period.
+ pub overage_charged_cents: i64,
+ /// Whether overage is paused after a failed charge.
+ pub overage_suspended: bool,
+ /// Team-wide usage beyond per-seat allowances that is not yet covered by
+ /// shared credits or charges (awaiting settlement).
+ pub uncovered_cents: i64,
+ /// This seat's remaining allowance plus shared credit/overage headroom; 0
+ /// when blocked.
+ pub remaining_cents: i64,
+ /// Why requests are refused right now, if they are.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blocked_reason: Option<DenyReason>,
+}
+
+/// Errors raised by the billing domain.
+#[derive(Debug, Error)]
+pub enum BillingError {
+ /// Only the payer may change billing settings or buy credits.
+ #[error("only the account that pays for this plan can change its billing")]
+ NotPayer,
+ /// Credits and overage need a paid plan.
+ #[error("a paid plan is required")]
+ FreePlan,
+ /// Not one of [`CREDIT_PACKS_CENTS`].
+ #[error("credit amount is not an offered pack")]
+ InvalidCreditAmount,
+ /// Outside the allowed overage cap range.
+ #[error("overage limit must be between ${} and ${}", OVERAGE_LIMIT_MIN_CENTS / 100, OVERAGE_LIMIT_MAX_CENTS / 100)]
+ InvalidOverageLimit,
+ /// The payer has no Stripe customer to bill.
+ #[error("no payment account on file")]
+ NoStripeCustomer,
+ /// The payment provider failed.
+ #[error("payment provider error: {0}")]
+ Payment(anyhow::Error),
+ /// Storage failed.
+ #[error("storage error: {0}")]
+ Storage(anyhow::Error),
+ /// Entitlement lookup failed.
+ #[error("entitlement lookup failed: {0}")]
+ Entitlement(anyhow::Error),
+}
+
+/// Convenience result alias for the crate.
+pub type Result<T> = std::result::Result<T, BillingError>;
diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rs
new file mode 100644
index 0000000000..c2f9a8c42e
--- /dev/null
+++ b/crates/ai_billing/src/domain/ports.rs
@@ -0,0 +1,333 @@
+//! Ports: what the billing service needs from the outside world, and what it
+//! offers inbound adapters.
+
+use super::ledger::SettlementPolicy;
+use super::models::{
+ AllowanceDecision, BillingPeriod, BillingSettings, Entitlement, OverageChargeStatus,
+ PeriodAllowance, PeriodLedger, Result, SeatAllowance, SeatUsage, UsageSnapshot,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+/// Resolves who a user is billed as.
+pub trait EntitlementSource: Send + Sync + 'static {
+ /// The user's plan, payer, and billed seats.
+ fn entitlement(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Entitlement>> + Send;
+
+ /// The Stripe customer id on file for a user, if any.
+ fn stripe_customer_id(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<String>>> + Send;
+}
+
+/// Reads recorded AI usage at Macro's list rate.
+pub trait UsageReader: Send + Sync + 'static {
+ /// List-rate usage for each of `users` within `period`.
+ fn list_rate_usage_cents_by_user(
+ &self,
+ users: &[MacroUserIdStr<'static>],
+ period: BillingPeriod,
+ ) -> impl Future<Output = Result<Vec<SeatUsage>>> + Send;
+}
+
+/// A charge reserved in the ledger that still has to be collected.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PendingCharge {
+ /// The `ai_overage_charge` row.
+ pub id: Uuid,
+ /// Amount to collect, list-rate cents.
+ pub amount_cents: i64,
+ /// The Stripe invoice an earlier attempt opened for this charge, if any.
+ /// A retry pays that invoice instead of opening a second one.
+ pub stripe_invoice_id: Option<String>,
+}
+
+/// What a settlement booked.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SettlementOutcome {
+ /// Credits consumed against the period.
+ pub consumed_credits_cents: i64,
+ /// An overage charge reserved for collection, if any.
+ pub pending_charge: Option<PendingCharge>,
+}
+
+/// The billing tables.
+pub trait BillingRepo: Send + Sync + 'static {
+ /// The payer's settings (defaults when no row exists).
+ fn settings(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<BillingSettings>> + Send;
+
+ /// Set overage on/off and the cap. Clears any suspension.
+ fn update_overage(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ enabled: bool,
+ limit_cents: i64,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Record the subscription period synced from Stripe.
+ fn set_period(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Pause overage after a failed collection.
+ fn suspend_overage(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Lift a suspension (a later charge collected).
+ fn clear_overage_suspension(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Current prepaid balance, list-rate cents.
+ fn credit_balance_cents(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<i64>> + Send;
+
+ /// What has been booked against a period.
+ fn period_ledger(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> impl Future<Output = Result<PeriodLedger>> + Send;
+
+ /// The allowance last observed for this payer while `period_start` was
+ /// the open period, if any.
+ fn period_allowance(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Option<PeriodAllowance>>> + Send;
+
+ /// Record each seat's live allowance against the open period. Upserts so
+ /// a mid-period plan or seat change is reflected until the period closes;
+ /// callers must only pass the current period's start.
+ fn remember_period_allowance(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ seats: &[SeatAllowance],
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Book a credit purchase. Returns `false` when `stripe_reference` was
+ /// already booked (webhook retry).
+ fn record_credit_purchase(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ stripe_reference: &str,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
+ /// Atomically settle a period: under the payer's row lock, re-read the
+ /// ledger, run [`plan_settlement`](super::ledger::plan_settlement) with the
+ /// stored overage settings, book credit consumption, and reserve a
+ /// pending overage charge. `chargeable_cents` is the sum of each seat's
+ /// usage beyond its own allowance. The overage policy is read inside the lock, with
+ /// `charge_threshold_cents` and `period_ended` taken from `policy`.
+ ///
+ /// A charge that was reserved earlier but never collected is handed back
+ /// before anything new is reserved, so retries reuse its id (and so its
+ /// Stripe idempotency keys and invoice) rather than billing the same
+ /// usage twice:
+ ///
+ /// - a `pending` charge with no invoice whose collection never finished
+ /// (the process died between reserving and opening the invoice);
+ /// - a `failed` charge with a Stripe invoice, once overage is active
+ /// again. It remains ledger coverage because Stripe may still collect
+ /// it, so later credits do not replace it with a smaller charge;
+ /// - a `failed` charge without a Stripe invoice, once overage is active
+ /// and the plan would charge at least its amount anyway. A charge whose
+ /// usage has since been covered another way stays failed.
+ fn apply_settlement(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ chargeable_cents: i64,
+ policy: SettlementPolicy,
+ ) -> impl Future<Output = Result<SettlementOutcome>> + Send;
+
+ /// Record the result of collecting a reserved charge.
+ fn finish_overage_charge(
+ &self,
+ charge_id: Uuid,
+ stripe_invoice_id: Option<&str>,
+ status: OverageChargeStatus,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Update a charge by its Stripe invoice (webhook). Returns the payer when
+ /// the invoice was one of ours *and* the status changed. `Paid` is
+ /// terminal: a late or duplicate failure event never un-pays a charge, and
+ /// re-reporting the current status is a no-op.
+ fn resolve_overage_invoice(
+ &self,
+ stripe_invoice_id: &str,
+ status: OverageChargeStatus,
+ ) -> impl Future<Output = Result<Option<MacroUserIdStr<'static>>>> + Send;
+
+ /// The status of the payer's most recently reserved charge, if any. The
+ /// newest outcome is what decides whether overage stays suspended; older
+ /// invoices' webhooks may arrive out of order.
+ fn latest_charge_status(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<OverageChargeStatus>>> + Send;
+}
+
+/// A one-off credit purchase to start.
+#[derive(Debug, Clone)]
+pub struct CreditCheckoutRequest {
+ /// The payer's Stripe customer.
+ pub customer_id: String,
+ /// The payer, stamped on the session so the webhook can book it.
+ pub payer: MacroUserIdStr<'static>,
+ /// Pack size, list-rate cents.
+ pub amount_cents: i64,
+ /// Where Stripe returns the user after paying.
+ pub success_url: String,
+ /// Where Stripe returns the user on cancel.
+ pub cancel_url: String,
+}
+
+/// An overage chunk to invoice.
+#[derive(Debug, Clone)]
+pub struct OverageChargeRequest {
+ /// The payer's Stripe customer.
+ pub customer_id: String,
+ /// The reserved charge; doubles as the idempotency key, so opening the
+ /// same charge twice yields the same invoice.
+ pub charge_id: Uuid,
+ /// Amount, list-rate cents.
+ pub amount_cents: i64,
+ /// Line description shown on the invoice.
+ pub description: String,
+}
+
+/// The payment provider.
+pub trait PaymentGateway: Send + Sync + 'static {
+ /// Start a Checkout Session for a credit pack; returns the hosted URL.
+ fn create_credit_checkout(
+ &self,
+ request: CreditCheckoutRequest,
+ ) -> impl Future<Output = Result<String>> + Send;
+
+ /// Open a finalized invoice for exactly this overage chunk (and nothing
+ /// else pending on the customer). Returns the invoice id. Idempotent on
+ /// `charge_id`.
+ fn open_overage_invoice(
+ &self,
+ request: OverageChargeRequest,
+ ) -> impl Future<Output = Result<String>> + Send;
+
+ /// Attempt to collect an open overage invoice now. `Ok(true)` when it is
+ /// paid, `Ok(false)` when the card was declined and the invoice stays
+ /// open for Stripe's own retries (the webhook reports the outcome), `Err`
+ /// when the provider could not be reached or rejected the request.
+ fn pay_overage_invoice(
+ &self,
+ charge_id: Uuid,
+ invoice_id: &str,
+ ) -> impl Future<Output = Result<bool>> + Send;
+}
+
+/// Asks whoever owns Stripe to settle a payer. Fire-and-forget: services that
+/// only read billing state (the gate in DCS) use this instead of settling.
+pub trait SettlementTrigger: Send + Sync + 'static {
+ /// Request settlement for `payer`.
+ fn request_settlement(&self, payer: MacroUserIdStr<'static>);
+}
+
+/// A [`SettlementTrigger`] that does nothing, for services that settle
+/// in-process or never need to.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoOpSettlementTrigger;
+
+impl SettlementTrigger for NoOpSettlementTrigger {
+ fn request_settlement(&self, _payer: MacroUserIdStr<'static>) {}
+}
+
+/// The use cases offered to inbound adapters and other services.
+pub trait BillingService: Send + Sync + 'static {
+ /// May `user` start another AI request?
+ ///
+ /// Admission is a read of the position at this instant; usage is
+ /// metered after the completion, so requests that are in flight together
+ /// can each be admitted against the same headroom. The overshoot is
+ /// bounded by one completion per concurrent request, is billed at list
+ /// rate like everything else, and can only exceed the payer's overage cap
+ /// by that much. Reserving capacity per request would need a second
+ /// ledger write on every completion; the gate deliberately does not.
+ fn check_allowance(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<AllowanceDecision>> + Send;
+
+ /// The user's current-period position.
+ fn snapshot(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<UsageSnapshot>> + Send;
+
+ /// Book each seat's usage beyond its own allowance for the payer of `user`
+ /// (previous and current period) from shared credits and then shared
+ /// overage, collecting overage via the payment gateway. The previous
+ /// period is settled against the per-seat allowances frozen while it was
+ /// open, not the live plan or seat list.
+ fn settle(&self, user: &MacroUserIdStr<'_>) -> impl Future<Output = Result<()>> + Send;
+
+ /// Turn overage on/off with a per-period cap. Payer only. Re-enabling
+ /// retries collection.
+ fn update_overage(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ enabled: bool,
+ limit_cents: i64,
+ ) -> impl Future<Output = Result<UsageSnapshot>> + Send;
+
+ /// Start a credit-pack purchase. Payer only. Returns the Checkout URL.
+ fn create_credit_checkout(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ success_url: String,
+ cancel_url: String,
+ ) -> impl Future<Output = Result<String>> + Send;
+
+ /// Book a completed credit purchase (webhook). Idempotent on
+ /// `stripe_reference`.
+ fn apply_credit_purchase(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ stripe_reference: &str,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Record the payer's subscription period (webhook).
+ fn sync_period(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Record the outcome of an overage invoice (webhook). Unknown invoices
+ /// are ignored.
+ fn mark_overage_invoice(
+ &self,
+ stripe_invoice_id: &str,
+ paid: bool,
+ ) -> impl Future<Output = Result<()>> + Send;
+}
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
new file mode 100644
index 0000000000..4df127a583
--- /dev/null
+++ b/crates/ai_billing/src/domain/service.rs
@@ -0,0 +1,498 @@
+//! The billing service: the gate, the summary, settings, credit purchases, and
+//! settlement.
+
+#[cfg(test)]
+mod test;
+
+use super::ledger::{SettlementPolicy, build_snapshot, decide};
+use super::models::{
+ AllowanceDecision, BillingError, BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS,
+ Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,
+ OverageChargeStatus, PeriodAllowance, PlanTier, Result, SeatAllowance, SeatUsage,
+ UsageSnapshot,
+};
+use super::ports::{
+ BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
+ PaymentGateway, PendingCharge, UsageReader,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+/// The billing service over its four ports.
+#[derive(Clone)]
+pub struct BillingServiceImpl<E, U, R, P> {
+ entitlements: E,
+ usage: U,
+ repo: R,
+ payments: P,
+}
+
+impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
+ /// Construct the service.
+ pub fn new(entitlements: E, usage: U, repo: R, payments: P) -> Self {
+ Self {
+ entitlements,
+ usage,
+ repo,
+ payments,
+ }
+ }
+}
+
+/// Everything resolved for one user at one instant.
+struct Position {
+ entitlement: Entitlement,
+ settings: BillingSettings,
+ period: BillingPeriod,
+}
+
+fn usage_for(user: &MacroUserIdStr<'_>, usage: &[SeatUsage]) -> i64 {
+ usage
+ .iter()
+ .find(|entry| entry.user.as_ref() == user.as_ref())
+ .map(|entry| entry.used_cents)
+ .unwrap_or(0)
+}
+
+fn chargeable_usage_cents(seats: &[SeatAllowance], usage: &[SeatUsage]) -> i64 {
+ seats
+ .iter()
+ .map(|seat| (usage_for(&seat.user, usage) - seat.included_cents).max(0))
+ .sum()
+}
+
+impl<E, U, R, P> BillingServiceImpl<E, U, R, P>
+where
+ E: EntitlementSource,
+ U: UsageReader,
+ R: BillingRepo,
+ P: PaymentGateway,
+{
+ async fn position(&self, user: &MacroUserIdStr<'_>, now: DateTime<Utc>) -> Result<Position> {
+ let entitlement = self.entitlements.entitlement(user).await?;
+ let settings = self.repo.settings(&entitlement.payer).await?;
+ let period = BillingPeriod::current(settings.period_anchor, now);
+ // Freeze the open period's allowance so a later plan or seat change
+ // cannot rewrite it after the period closes. Mid-period changes
+ // refresh this row while the period is still current.
+ if entitlement.tier.is_paid() && !entitlement.unlimited {
+ self.repo
+ .remember_period_allowance(
+ &entitlement.payer,
+ period.start,
+ &entitlement.seat_allowances(),
+ )
+ .await?;
+ }
+ Ok(Position {
+ entitlement,
+ settings,
+ period,
+ })
+ }
+
+ async fn snapshot_at(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ position: &Position,
+ ) -> Result<UsageSnapshot> {
+ let Position {
+ entitlement,
+ settings,
+ period,
+ } = position;
+ let (used_cents, chargeable_cents, ledger, credit_balance_cents) =
+ if entitlement.tier.is_paid() {
+ let seats = entitlement.seat_allowances();
+ let users: Vec<_> = seats.iter().map(|seat| seat.user.clone()).collect();
+ let usage = self
+ .usage
+ .list_rate_usage_cents_by_user(&users, *period)
+ .await?;
+ let used = usage_for(user, &usage);
+ let chargeable = chargeable_usage_cents(&seats, &usage);
+ let ledger = self
+ .repo
+ .period_ledger(&entitlement.payer, period.start)
+ .await?;
+ let balance = self.repo.credit_balance_cents(&entitlement.payer).await?;
+ (used, chargeable, ledger, balance)
+ } else {
+ // Free users are not metered here; skip the ledger reads.
+ Default::default()
+ };
+ Ok(build_snapshot(
+ user,
+ entitlement,
+ settings,
+ *period,
+ used_cents,
+ chargeable_cents,
+ ledger,
+ credit_balance_cents,
+ ))
+ }
+
+ /// Per-seat allowances to settle `period` with.
+ ///
+ /// A closed period uses the freeze recorded while it was open. An open
+ /// period (or a closed one that was never observed) uses the live
+ /// entitlement.
+ async fn allowance_for_period(
+ &self,
+ entitlement: &Entitlement,
+ period: BillingPeriod,
+ now: DateTime<Utc>,
+ ) -> Result<Vec<SeatAllowance>> {
+ if period.has_ended(now) {
+ match self
+ .repo
+ .period_allowance(&entitlement.payer, period.start)
+ .await?
+ {
+ Some(PeriodAllowance { seats }) => return Ok(seats),
+ None => {
+ tracing::warn!(
+ period_start = %period.start,
+ "settling a closed period with no frozen allowance; using current entitlement"
+ );
+ }
+ }
+ }
+ Ok(entitlement.seat_allowances())
+ }
+
+ /// Settle one period for a payer: book uncovered usage from credits, then
+ /// reserve and collect an overage chunk.
+ #[tracing::instrument(skip(self, entitlement), fields(payer = %entitlement.payer), err)]
+ async fn settle_period(
+ &self,
+ entitlement: &Entitlement,
+ period: BillingPeriod,
+ now: DateTime<Utc>,
+ ) -> Result<()> {
+ let seats = self.allowance_for_period(entitlement, period, now).await?;
+ let users: Vec<_> = seats.iter().map(|seat| seat.user.clone()).collect();
+ let usage = self
+ .usage
+ .list_rate_usage_cents_by_user(&users, period)
+ .await?;
+ let chargeable_cents = chargeable_usage_cents(&seats, &usage);
+ if chargeable_cents == 0 {
+ return Ok(());
+ }
+
+ let outcome = self
+ .repo
+ .apply_settlement(
+ &entitlement.payer,
+ period.start,
+ chargeable_cents,
+ SettlementPolicy {
+ // The repo reads the live overage settings under its lock;
+ // these two are the caller's contribution.
+ overage_active: true,
+ overage_limit_cents: 0,
+ charge_threshold_cents: OVERAGE_CHARGE_THRESHOLD_CENTS,
+ period_ended: period.has_ended(now),
+ },
+ )
+ .await?;
+
+ if outcome.consumed_credits_cents > 0 {
+ tracing::info!(
+ cents = outcome.consumed_credits_cents,
+ "applied prepaid credits to ai usage"
+ );
+ }
+
+ if let Some(charge) = outcome.pending_charge {
+ self.collect(entitlement, period, charge).await?;
+ }
+ Ok(())
+ }
+
+ /// Collect a reserved overage charge: open its invoice (or pick up the
+ /// one an earlier attempt opened) and try to pay it. A provider failure
+ /// marks the charge failed and suspends overage until the payer re-enables
+ /// it. A recorded invoice continues covering usage because Stripe may
+ /// still collect it; re-enabling retries that same invoice.
+ async fn collect(
+ &self,
+ entitlement: &Entitlement,
+ period: BillingPeriod,
+ charge: PendingCharge,
+ ) -> Result<()> {
+ let payer = &entitlement.payer;
+ let customer_id = match self.entitlements.stripe_customer_id(payer).await {
+ Ok(Some(customer_id)) => customer_id,
+ Ok(None) => {
+ tracing::warn!("overage charge reserved but payer has no stripe customer");
+ self.fail_charge(payer, charge.id).await?;
+ return Err(BillingError::NoStripeCustomer);
+ }
+ Err(e) => {
+ // Left pending, the charge would cover usage that is never
+ // invoiced. Fail it so the next settlement retries it.
+ self.fail_charge(payer, charge.id).await?;
+ return Err(e);
+ }
+ };
+
+ let invoice_id = match charge.stripe_invoice_id.clone() {
+ Some(invoice_id) => invoice_id,
+ None => {
+ let description = format!(
+ "Macro AI usage beyond plan, {} to {}",
+ period.start.format("%b %-d"),
+ period.end.format("%b %-d, %Y")
+ );
+ match self
+ .payments
+ .open_overage_invoice(OverageChargeRequest {
+ customer_id,
+ charge_id: charge.id,
+ amount_cents: charge.amount_cents,
+ description,
+ })
+ .await
+ {
+ Ok(invoice_id) => invoice_id,
+ Err(e) => {
+ tracing::error!(
+ error = ?e,
+ cents = charge.amount_cents,
+ "ai overage invoice could not be opened"
+ );
+ self.fail_charge(payer, charge.id).await?;
+ return Err(e);
+ }
+ }
+ }
+ };
+ // Record the invoice before collecting: if this process dies here the
+ // next settlement pays this invoice instead of opening another.
+ self.repo
+ .finish_overage_charge(charge.id, Some(&invoice_id), OverageChargeStatus::Pending)
+ .await?;
+
+ match self
+ .payments
+ .pay_overage_invoice(charge.id, &invoice_id)
+ .await
+ {
+ Ok(true) => {
+ self.repo
+ .finish_overage_charge(charge.id, Some(&invoice_id), OverageChargeStatus::Paid)
+ .await?;
+ tracing::info!(
+ cents = charge.amount_cents,
+ invoice = %invoice_id,
+ "collected ai overage"
+ );
+ Ok(())
+ }
+ Ok(false) => {
+ // Declined: the invoice stays open for Stripe's retries and
+ // the webhook reports the outcome either way.
+ tracing::info!(
+ cents = charge.amount_cents,
+ invoice = %invoice_id,
+ "ai overage invoice awaiting payment"
+ );
+ Ok(())
+ }
+ Err(e) => {
+ tracing::error!(
+ error = ?e,
+ cents = charge.amount_cents,
+ invoice = %invoice_id,
+ "ai overage charge failed"
+ );
+ self.fail_charge(payer, charge.id).await?;
+ Err(e)
+ }
+ }
+ }
+
+ /// A charge that could not be collected: overage pauses until the payer
+ /// re-enables it. A recorded Stripe invoice continues covering usage.
+ async fn fail_charge(&self, payer: &MacroUserIdStr<'_>, charge_id: Uuid) -> Result<()> {
+ self.repo
+ .finish_overage_charge(charge_id, None, OverageChargeStatus::Failed)
+ .await?;
+ self.repo.suspend_overage(payer).await
+ }
+
+ fn require_payer(entitlement: &Entitlement, user: &MacroUserIdStr<'_>) -> Result<()> {
+ if !entitlement.is_payer(user) {
+ return Err(BillingError::NotPayer);
+ }
+ if !entitlement.tier.is_paid() {
+ return Err(BillingError::FreePlan);
+ }
+ Ok(())
+ }
+}
+
+impl<E, U, R, P> BillingService for BillingServiceImpl<E, U, R, P>
+where
+ E: EntitlementSource,
+ U: UsageReader,
+ R: BillingRepo,
+ P: PaymentGateway,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {
+ let position = self.position(user, Utc::now()).await?;
+ if position.entitlement.unlimited || position.entitlement.tier == PlanTier::Free {
+ return Ok(AllowanceDecision::Allow);
+ }
+ let snapshot = self.snapshot_at(user, &position).await?;
+ Ok(decide(&snapshot))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn snapshot(&self, user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {
+ let position = self.position(user, Utc::now()).await?;
+ self.snapshot_at(user, &position).await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn settle(&self, user: &MacroUserIdStr<'_>) -> Result<()> {
+ let now = Utc::now();
+ let position = self.position(user, now).await?;
+ if position.entitlement.unlimited || !position.entitlement.tier.is_paid() {
+ return Ok(());
+ }
+ // The previous period first, so a tail that ran past the boundary is
+ // flushed before the current one accrues. Closed-period settlement
+ // uses the freeze recorded while that period was open, not the live
+ // plan or seat list.
+ self.settle_period(&position.entitlement, position.period.previous(), now)
+ .await?;
+ self.settle_period(&position.entitlement, position.period, now)
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn update_overage(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ enabled: bool,
+ limit_cents: i64,
+ ) -> Result<UsageSnapshot> {
+ let entitlement = self.entitlements.entitlement(user).await?;
+ Self::require_payer(&entitlement, user)?;
+ if enabled && !(OVERAGE_LIMIT_MIN_CENTS..=OVERAGE_LIMIT_MAX_CENTS).contains(&limit_cents) {
+ return Err(BillingError::InvalidOverageLimit);
+ }
+ let limit_cents = if enabled { limit_cents } else { 0 };
+ self.repo
+ .update_overage(&entitlement.payer, enabled, limit_cents)
+ .await?;
+ if enabled {
+ // Retry anything that was waiting on overage (or a failed charge);
+ // a collection failure re-suspends and is reported in the snapshot.
+ if let Err(e) = self.settle(user).await {
+ tracing::warn!(error = ?e, "settlement after enabling overage failed");
+ }
+ }
+ self.snapshot(user).await
+ }
+
+ #[tracing::instrument(skip(self, success_url, cancel_url), err)]
+ async fn create_credit_checkout(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ success_url: String,
+ cancel_url: String,
+ ) -> Result<String> {
+ let entitlement = self.entitlements.entitlement(user).await?;
+ Self::require_payer(&entitlement, user)?;
+ if !CREDIT_PACKS_CENTS.contains(&amount_cents) {
+ return Err(BillingError::InvalidCreditAmount);
+ }
+ let customer_id = self
+ .entitlements
+ .stripe_customer_id(&entitlement.payer)
+ .await?
+ .ok_or(BillingError::NoStripeCustomer)?;
+ self.payments
+ .create_credit_checkout(CreditCheckoutRequest {
+ customer_id,
+ payer: entitlement.payer.clone(),
+ amount_cents,
+ success_url,
+ cancel_url,
+ })
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn apply_credit_purchase(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ stripe_reference: &str,
+ ) -> Result<()> {
+ if amount_cents <= 0 {
+ return Err(BillingError::InvalidCreditAmount);
+ }
+ let inserted = self
+ .repo
+ .record_credit_purchase(payer, amount_cents, stripe_reference)
+ .await?;
+ if !inserted {
+ tracing::info!("credit purchase already booked; ignoring retry");
+ return Ok(());
+ }
+ // Newly bought credits cover any usage that was waiting on them.
+ if let Err(e) = self.settle(payer).await {
+ tracing::warn!(error = ?e, "settlement after credit purchase failed");
+ }
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn sync_period(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<()> {
+ if start >= end {
+ tracing::warn!("ignoring inverted subscription period");
+ return Ok(());
+ }
+ self.repo.set_period(payer, start, end).await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn mark_overage_invoice(&self, stripe_invoice_id: &str, paid: bool) -> Result<()> {
+ let status = if paid {
+ OverageChargeStatus::Paid
+ } else {
+ OverageChargeStatus::Failed
+ };
+ let Some(payer) = self
+ .repo
+ .resolve_overage_invoice(stripe_invoice_id, status)
+ .await?
+ else {
+ // Not ours, already paid, or already in this state.
+ return Ok(());
+ };
+ // Webhooks arrive in any order. A late `paid` for an older invoice must
+ // not lift the suspension a newer failure caused, and a late failure
+ // must not re-suspend a payer whose newer charge went through: the
+ // newest charge's outcome decides.
+ match self.repo.latest_charge_status(&payer).await? {
+ Some(OverageChargeStatus::Paid) => self.repo.clear_overage_suspension(&payer).await,
+ Some(OverageChargeStatus::Failed) => self.repo.suspend_overage(&payer).await,
+ Some(OverageChargeStatus::Pending) | None => Ok(()),
+ }
+ }
+}
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
new file mode 100644
index 0000000000..9321126ccd
--- /dev/null
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -0,0 +1,1116 @@
+use super::*;
+use crate::domain::ledger::plan_settlement;
+use crate::domain::models::{DenyReason, PayerScope, PeriodAllowance, PeriodLedger};
+use crate::domain::ports::SettlementOutcome;
+use macro_user_id::cowlike::CowLike;
+use macro_uuid::Uuid;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()
+}
+
+#[derive(Clone, Default)]
+struct FakeEntitlements {
+ by_user: Arc<Mutex<HashMap<String, Entitlement>>>,
+ customers: Arc<Mutex<HashMap<String, String>>>,
+}
+
+impl FakeEntitlements {
+ fn with(self, ent: Entitlement) -> Self {
+ self.set(ent);
+ self
+ }
+ fn set(&self, ent: Entitlement) {
+ let mut by_user = self.by_user.lock().unwrap();
+ for (index, user) in ent.billed_users.iter().enumerate() {
+ let mut resolved = ent.clone();
+ resolved.tier = ent.seat_tiers.get(index).copied().unwrap_or(ent.tier);
+ resolved.scope = match &ent.scope {
+ PayerScope::TeamOwner { team_id } | PayerScope::TeamMember { team_id } => {
+ if user.as_ref() == ent.payer.as_ref() {
+ PayerScope::TeamOwner { team_id: *team_id }
+ } else {
+ PayerScope::TeamMember { team_id: *team_id }
+ }
+ }
+ PayerScope::Personal => PayerScope::Personal,
+ };
+ by_user.insert(user.to_string(), resolved);
+ }
+ }
+ fn with_customer(self, u: &MacroUserIdStr<'_>, customer: &str) -> Self {
+ self.customers
+ .lock()
+ .unwrap()
+ .insert(u.to_string(), customer.to_string());
+ self
+ }
+}
+
+impl EntitlementSource for FakeEntitlements {
+ async fn entitlement(&self, user: &MacroUserIdStr<'_>) -> Result<Entitlement> {
+ Ok(self
+ .by_user
+ .lock()
+ .unwrap()
+ .get(user.as_ref())
+ .cloned()
+ .unwrap_or_else(|| Entitlement::personal(user.clone().into_owned(), PlanTier::Free)))
+ }
+ async fn stripe_customer_id(&self, user: &MacroUserIdStr<'_>) -> Result<Option<String>> {
+ Ok(self.customers.lock().unwrap().get(user.as_ref()).cloned())
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeUsage {
+ cents: Arc<Mutex<i64>>,
+ /// Usage at a specific instant, attributed to one user.
+ entries: Arc<Mutex<Vec<UsageEntry>>>,
+}
+
+struct UsageEntry {
+ user: String,
+ at: DateTime<Utc>,
+ cents: i64,
+}
+
+impl FakeUsage {
+ fn add(&self, user: &MacroUserIdStr<'_>, at: DateTime<Utc>, cents: i64) {
+ self.entries.lock().unwrap().push(UsageEntry {
+ user: user.to_string(),
+ at,
+ cents,
+ });
+ }
+}
+
+impl UsageReader for FakeUsage {
+ /// `cents` is treated as current usage for the first requested user.
+ /// `entries` are summed when their timestamp falls in the requested period.
+ async fn list_rate_usage_cents_by_user(
+ &self,
+ users: &[MacroUserIdStr<'static>],
+ period: BillingPeriod,
+ ) -> Result<Vec<SeatUsage>> {
+ let now = Utc::now();
+ let mut totals: HashMap<String, i64> =
+ users.iter().map(|user| (user.to_string(), 0)).collect();
+ if period.start <= now
+ && now < period.end
+ && let Some(user) = users.first()
+ {
+ *totals.entry(user.to_string()).or_default() += *self.cents.lock().unwrap();
+ }
+ for entry in self.entries.lock().unwrap().iter() {
+ if totals.contains_key(&entry.user) && period.start <= entry.at && entry.at < period.end
+ {
+ *totals.entry(entry.user.clone()).or_default() += entry.cents;
+ }
+ }
+ totals
+ .into_iter()
+ .map(|(user, used_cents)| {
+ Ok(SeatUsage {
+ user: MacroUserIdStr::try_from(user)
+ .map_err(|error| BillingError::Storage(error.into()))?,
+ used_cents,
+ })
+ })
+ .collect()
+ }
+}
+
+/// One `ai_overage_charge` row.
+#[derive(Debug, Clone)]
+struct FakeCharge {
+ id: Uuid,
+ period_start: DateTime<Utc>,
+ amount_cents: i64,
+ status: OverageChargeStatus,
+ invoice: Option<String>,
+}
+
+#[derive(Default)]
+struct RepoState {
+ settings: BillingSettings,
+ balance: i64,
+ /// Credits consumed per period; charges are summed from `charges`.
+ consumed: HashMap<DateTime<Utc>, i64>,
+ purchases: Vec<String>,
+ charges: Vec<FakeCharge>,
+ suspended: bool,
+ allowances: HashMap<DateTime<Utc>, PeriodAllowance>,
+}
+
+impl RepoState {
+ fn ledger(&self, period_start: DateTime<Utc>) -> PeriodLedger {
+ PeriodLedger {
+ credits_consumed_cents: self.consumed.get(&period_start).copied().unwrap_or(0),
+ // An invoiced charge can still collect even after a failure.
+ overage_charged_cents: self
+ .charges
+ .iter()
+ .filter(|c| {
+ c.period_start == period_start
+ && (c.status != OverageChargeStatus::Failed || c.invoice.is_some())
+ })
+ .map(|c| c.amount_cents)
+ .sum(),
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeRepo {
+ state: Arc<Mutex<RepoState>>,
+}
+
+impl FakeRepo {
+ fn charges(&self) -> Vec<FakeCharge> {
+ self.state.lock().unwrap().charges.clone()
+ }
+ fn freeze(&self, period_start: DateTime<Utc>, allowance: PeriodAllowance) {
+ self.state
+ .lock()
+ .unwrap()
+ .allowances
+ .insert(period_start, allowance);
+ }
+ fn allowance(&self, period_start: DateTime<Utc>) -> Option<PeriodAllowance> {
+ self.state
+ .lock()
+ .unwrap()
+ .allowances
+ .get(&period_start)
+ .cloned()
+ }
+}
+
+impl BillingRepo for FakeRepo {
+ async fn settings(&self, _payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {
+ let s = self.state.lock().unwrap();
+ let mut settings = s.settings.clone();
+ settings.overage_suspended_at = s.suspended.then(Utc::now);
+ Ok(settings)
+ }
+ async fn update_overage(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ enabled: bool,
+ limit_cents: i64,
+ ) -> Result<()> {
+ let mut s = self.state.lock().unwrap();
+ s.settings.overage_enabled = enabled;
+ s.settings.overage_limit_cents = limit_cents;
+ s.suspended = false;
+ Ok(())
+ }
+ async fn set_period(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<()> {
+ self.state.lock().unwrap().settings.period_anchor = Some((start, end));
+ Ok(())
+ }
+ async fn suspend_overage(&self, _payer: &MacroUserIdStr<'_>) -> Result<()> {
+ self.state.lock().unwrap().suspended = true;
+ Ok(())
+ }
+ async fn clear_overage_suspension(&self, _payer: &MacroUserIdStr<'_>) -> Result<()> {
+ self.state.lock().unwrap().suspended = false;
+ Ok(())
+ }
+ async fn credit_balance_cents(&self, _payer: &MacroUserIdStr<'_>) -> Result<i64> {
+ Ok(self.state.lock().unwrap().balance)
+ }
+ async fn period_ledger(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> Result<PeriodLedger> {
+ Ok(self.state.lock().unwrap().ledger(period_start))
+ }
+ async fn period_allowance(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> Result<Option<PeriodAllowance>> {
+ Ok(self
+ .state
+ .lock()
+ .unwrap()
+ .allowances
+ .get(&period_start)
+ .cloned())
+ }
+ async fn remember_period_allowance(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ seats: &[SeatAllowance],
+ ) -> Result<()> {
+ self.state.lock().unwrap().allowances.insert(
+ period_start,
+ PeriodAllowance {
+ seats: seats.to_vec(),
+ },
+ );
+ Ok(())
+ }
+ async fn record_credit_purchase(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ stripe_reference: &str,
+ ) -> Result<bool> {
+ let mut s = self.state.lock().unwrap();
+ if s.purchases.iter().any(|r| r == stripe_reference) {
+ return Ok(false);
+ }
+ s.purchases.push(stripe_reference.to_string());
+ s.balance += amount_cents;
+ Ok(true)
+ }
+ /// Mirrors the Postgres adapter: credits first, then hand back a charge
+ /// still owed. A failed invoiced charge remains coverage and is always
+ /// retried once overage is active; an uninvoiced one must still fit the
+ /// new charge plan.
+ async fn apply_settlement(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ chargeable_cents: i64,
+ policy: SettlementPolicy,
+ ) -> Result<SettlementOutcome> {
+ let mut s = self.state.lock().unwrap();
+ let ledger = s.ledger(period_start);
+ let overage_active =
+ s.settings.overage_enabled && !s.suspended && s.settings.overage_limit_cents > 0;
+ let plan = plan_settlement(
+ crate::domain::ledger::SettlementState {
+ chargeable_cents,
+ credits_consumed_cents: ledger.credits_consumed_cents,
+ overage_charged_cents: ledger.overage_charged_cents,
+ credit_balance_cents: s.balance,
+ },
+ SettlementPolicy {
+ overage_active,
+ overage_limit_cents: s.settings.overage_limit_cents,
+ ..policy
+ },
+ );
+ *s.consumed.entry(period_start).or_default() += plan.consume_credits_cents;
+ s.balance -= plan.consume_credits_cents;
+
+ let owed = s.charges.iter().position(|c| {
+ c.period_start == period_start
+ && ((c.status == OverageChargeStatus::Pending && c.invoice.is_none())
+ || (c.status == OverageChargeStatus::Failed
+ && overage_active
+ && (c.invoice.is_some() || c.amount_cents <= plan.charge_overage_cents)))
+ });
+ let pending_charge = if let Some(i) = owed {
+ s.charges[i].status = OverageChargeStatus::Pending;
+ let c = &s.charges[i];
+ Some(PendingCharge {
+ id: c.id,
+ amount_cents: c.amount_cents,
+ stripe_invoice_id: c.invoice.clone(),
+ })
+ } else if plan.charge_overage_cents > 0 {
+ let id = macro_uuid::generate_uuid_v7();
+ s.charges.push(FakeCharge {
+ id,
+ period_start,
+ amount_cents: plan.charge_overage_cents,
+ status: OverageChargeStatus::Pending,
+ invoice: None,
+ });
+ Some(PendingCharge {
+ id,
+ amount_cents: plan.charge_overage_cents,
+ stripe_invoice_id: None,
+ })
+ } else {
+ None
+ };
+ Ok(SettlementOutcome {
+ consumed_credits_cents: plan.consume_credits_cents,
+ pending_charge,
+ })
+ }
+ async fn finish_overage_charge(
+ &self,
+ charge_id: Uuid,
+ stripe_invoice_id: Option<&str>,
+ status: OverageChargeStatus,
+ ) -> Result<()> {
+ let mut s = self.state.lock().unwrap();
+ for c in s.charges.iter_mut().filter(|c| c.id == charge_id) {
+ c.status = status;
+ if let Some(inv) = stripe_invoice_id {
+ c.invoice = Some(inv.to_string());
+ }
+ }
+ Ok(())
+ }
+ async fn resolve_overage_invoice(
+ &self,
+ stripe_invoice_id: &str,
+ status: OverageChargeStatus,
+ ) -> Result<Option<MacroUserIdStr<'static>>> {
+ let mut s = self.state.lock().unwrap();
+ let found = s.charges.iter_mut().find(|c| {
+ c.invoice.as_deref() == Some(stripe_invoice_id)
+ && c.status != OverageChargeStatus::Paid
+ && c.status != status
+ });
+ Ok(found.map(|c| {
+ c.status = status;
+ }))
+ }
+ async fn latest_charge_status(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ ) -> Result<Option<OverageChargeStatus>> {
+ Ok(self.state.lock().unwrap().charges.last().map(|c| c.status))
+ }
+}
+
+/// How the fake provider answers the next payment attempts.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+enum PayOutcome {
+ #[default]
+ Paid,
+ /// Card declined: the invoice stays open for Stripe's retries.
+ Declined,
+ /// The provider could not be reached.
+ Error,
+}
+
+#[derive(Clone, Default)]
+struct FakePayments {
+ fail_open: Arc<Mutex<bool>>,
+ pay_outcome: Arc<Mutex<PayOutcome>>,
+ checkouts: Arc<Mutex<Vec<CreditCheckoutRequest>>>,
+ opened: Arc<Mutex<Vec<OverageChargeRequest>>>,
+ payments: Arc<Mutex<Vec<(Uuid, String)>>>,
+}
+
+impl FakePayments {
+ fn set_pay(&self, outcome: PayOutcome) {
+ *self.pay_outcome.lock().unwrap() = outcome;
+ }
+ fn opened(&self) -> Vec<OverageChargeRequest> {
+ self.opened.lock().unwrap().clone()
+ }
+ fn payments(&self) -> Vec<(Uuid, String)> {
+ self.payments.lock().unwrap().clone()
+ }
+}
+
+impl PaymentGateway for FakePayments {
+ async fn create_credit_checkout(&self, request: CreditCheckoutRequest) -> Result<String> {
+ self.checkouts.lock().unwrap().push(request);
+ Ok("https://checkout.stripe.test/session".to_string())
+ }
+ async fn open_overage_invoice(&self, request: OverageChargeRequest) -> Result<String> {
+ if *self.fail_open.lock().unwrap() {
+ return Err(BillingError::Payment(anyhow::anyhow!("stripe unavailable")));
+ }
+ let invoice = format!("in_{}", request.charge_id);
+ self.opened.lock().unwrap().push(request);
+ Ok(invoice)
+ }
+ async fn pay_overage_invoice(&self, charge_id: Uuid, invoice_id: &str) -> Result<bool> {
+ self.payments
+ .lock()
+ .unwrap()
+ .push((charge_id, invoice_id.to_string()));
+ match *self.pay_outcome.lock().unwrap() {
+ PayOutcome::Paid => Ok(true),
+ PayOutcome::Declined => Ok(false),
+ PayOutcome::Error => Err(BillingError::Payment(anyhow::anyhow!("card declined"))),
+ }
+ }
+}
+
+type Service = BillingServiceImpl<FakeEntitlements, FakeUsage, FakeRepo, FakePayments>;
+
+fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsage) {
+ let payer = user("[email protected]");
+ let ents = FakeEntitlements::default()
+ .with(Entitlement::personal(payer.clone(), PlanTier::Premium))
+ .with_customer(&payer, "cus_123");
+ let usage = FakeUsage {
+ cents: Arc::new(Mutex::new(used_cents)),
+ entries: Default::default(),
+ };
+ let repo = FakeRepo::default();
+ let payments = FakePayments::default();
+ (
+ BillingServiceImpl::new(ents, usage.clone(), repo.clone(), payments.clone()),
+ repo,
+ payments,
+ usage,
+ )
+}
+
+#[tokio::test]
+async fn allows_within_allowance_and_denies_past_it() {
+ let (svc, _, _, usage) = premium_service(3_000);
+ let payer = user("[email protected]");
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+ *usage.cents.lock().unwrap() = 4_000;
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)
+ );
+}
+
+#[tokio::test]
+async fn free_users_are_not_gated() {
+ let (svc, ..) = premium_service(1_000_000);
+ let free = user("[email protected]");
+ assert_eq!(
+ svc.check_allowance(&free).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(snap.tier, PlanTier::Free);
+ assert_eq!(snap.used_cents, 0);
+}
+
+#[tokio::test]
+async fn credits_unblock_and_settlement_consumes_them() {
+ let (svc, repo, ..) = premium_service(4_600);
+ let payer = user("[email protected]");
+ assert!(matches!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(_)
+ ));
+
+ svc.apply_credit_purchase(&payer, 2_500, "cs_1")
+ .await
+ .unwrap();
+ // The purchase settles: 600 consumed, 1_900 left.
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.credits_consumed_cents, 600);
+ assert_eq!(snap.credit_balance_cents, 1_900);
+ assert_eq!(snap.uncovered_cents, 0);
+ assert_eq!(snap.remaining_cents, 1_900);
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+
+ // A webhook retry books nothing twice.
+ svc.apply_credit_purchase(&payer, 2_500, "cs_1")
+ .await
+ .unwrap();
+ assert_eq!(repo.state.lock().unwrap().balance, 1_900);
+}
+
+#[tokio::test]
+async fn overage_is_charged_in_chunks_and_respects_the_cap() {
+ let (svc, repo, payments, usage) = premium_service(4_500);
+ let payer = user("[email protected]");
+
+ let snap = svc.update_overage(&payer, true, 2_000).await.unwrap();
+ assert!(snap.overage_enabled);
+ // 500 over: under the $10 chunk, nothing charged yet but plenty of room.
+ assert_eq!(snap.overage_charged_cents, 0);
+ assert_eq!(snap.remaining_cents, 1_500);
+
+ *usage.cents.lock().unwrap() = 5_200;
+ svc.settle(&payer).await.unwrap();
+ let opened = payments.opened();
+ assert_eq!(opened.len(), 1);
+ assert_eq!(opened[0].amount_cents, 1_200);
+ assert_eq!(opened[0].customer_id, "cus_123");
+ let charges = repo.charges();
+ let charge = &charges[0];
+ assert_eq!(charge.status, OverageChargeStatus::Paid);
+ assert_eq!(
+ charge.invoice.as_deref(),
+ Some(format!("in_{}", charge.id).as_str())
+ );
+
+ // Past the cap: the last 800 of room is under the charge chunk, so it
+ // waits for period end, and the payer is blocked with the right reason.
+ *usage.cents.lock().unwrap() = 7_000;
+ svc.settle(&payer).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.overage_charged_cents, 1_200);
+ assert_eq!(snap.remaining_cents, 0);
+ assert_eq!(snap.blocked_reason, Some(DenyReason::OverageLimitReached));
+}
+
+#[tokio::test]
+async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated() {
+ let (svc, repo, payments, _) = premium_service(5_500);
+ let payer = user("[email protected]");
+ payments.set_pay(PayOutcome::Error);
+
+ // Enabling settles; the collection failure is swallowed into the snapshot.
+ let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();
+ assert!(snap.overage_suspended);
+ assert_eq!(snap.blocked_reason, Some(DenyReason::OveragePaymentFailed));
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].status, OverageChargeStatus::Failed);
+ // The invoice was recorded before the payment attempt.
+ let invoice = charges[0].invoice.clone().expect("invoice recorded");
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)
+ );
+
+ // Fixing the card and re-enabling retries the same charge: the existing
+ // invoice is paid, no second invoice is opened, no second row reserved.
+ payments.set_pay(PayOutcome::Paid);
+ let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();
+ assert!(!snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 1_500);
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].status, OverageChargeStatus::Paid);
+ assert_eq!(payments.opened().len(), 1);
+ let paid = payments.payments();
+ assert_eq!(paid.len(), 2);
+ assert!(
+ paid.iter()
+ .all(|(id, inv)| *id == charges[0].id && *inv == invoice)
+ );
+}
+
+#[tokio::test]
+async fn opening_the_invoice_failing_marks_the_charge_failed() {
+ let (svc, repo, payments, _) = premium_service(5_500);
+ let payer = user("[email protected]");
+ *payments.fail_open.lock().unwrap() = true;
+
+ let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();
+ assert!(snap.overage_suspended);
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].status, OverageChargeStatus::Failed);
+ assert!(charges[0].invoice.is_none());
+ assert!(payments.payments().is_empty());
+
+ // Once Stripe is back the retry opens the invoice for the same charge.
+ *payments.fail_open.lock().unwrap() = false;
+ svc.update_overage(&payer, true, 5_000).await.unwrap();
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].status, OverageChargeStatus::Paid);
+ assert_eq!(payments.opened()[0].charge_id, charges[0].id);
+}
+
+#[tokio::test]
+async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried() {
+ let (svc, repo, payments, _) = premium_service(5_800);
+ let payer = user("[email protected]");
+ *payments.fail_open.lock().unwrap() = true;
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ assert_eq!(repo.charges()[0].status, OverageChargeStatus::Failed);
+ assert!(repo.charges()[0].invoice.is_none());
+
+ // Credits arrive and cover the 1_800 that was never invoiced.
+ *payments.fail_open.lock().unwrap() = false;
+ svc.apply_credit_purchase(&payer, 2_500, "cs_1")
+ .await
+ .unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.credits_consumed_cents, 1_800);
+ assert_eq!(snap.uncovered_cents, 0);
+
+ // Re-enabling overage must not collect that stale charge.
+ let snap = svc.update_overage(&payer, true, 10_000).await.unwrap();
+ assert_eq!(snap.overage_charged_cents, 0);
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].status, OverageChargeStatus::Failed);
+ assert!(payments.opened().is_empty());
+ assert!(payments.payments().is_empty());
+}
+
+#[tokio::test]
+async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {
+ let (svc, repo, payments, _) = premium_service(7_000);
+ let payer = user("[email protected]");
+ payments.set_pay(PayOutcome::Error);
+
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ let first = repo.charges().into_iter().next().unwrap();
+ assert_eq!(first.amount_cents, 3_000);
+ assert_eq!(first.status, OverageChargeStatus::Failed);
+ assert!(first.invoice.is_some());
+
+ payments.set_pay(PayOutcome::Declined);
+ svc.apply_credit_purchase(&payer, 1_000, "cs_shrink")
+ .await
+ .unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.credits_consumed_cents, 0);
+ assert_eq!(snap.credit_balance_cents, 1_000);
+ assert_eq!(snap.overage_charged_cents, 3_000);
+
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 1);
+ assert_eq!(charges[0].id, first.id);
+ assert_eq!(charges[0].status, OverageChargeStatus::Pending);
+ assert_eq!(charges[0].amount_cents, 3_000);
+ assert_eq!(charges[0].invoice, first.invoice);
+ assert_eq!(payments.opened().len(), 1);
+ assert_eq!(payments.payments().len(), 2);
+}
+
+#[tokio::test]
+async fn a_declined_card_leaves_the_invoice_open_for_the_webhook() {
+ let (svc, repo, payments, _) = premium_service(5_500);
+ let payer = user("[email protected]");
+ payments.set_pay(PayOutcome::Declined);
+
+ let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();
+ // Not suspended yet: Stripe retries, the webhook decides.
+ assert!(!snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 1_500);
+ let charges = repo.charges();
+ assert_eq!(charges[0].status, OverageChargeStatus::Pending);
+ let invoice = charges[0].invoice.clone().unwrap();
+
+ svc.mark_overage_invoice(&invoice, false).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(snap.overage_suspended);
+ // Stripe may still retry the open invoice, so it remains coverage.
+ assert_eq!(snap.overage_charged_cents, 1_500);
+}
+
+#[tokio::test]
+async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {
+ let owner = user("[email protected]");
+ let member = user("[email protected]");
+ let team = Entitlement {
+ tier: PlanTier::Premium,
+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],
+ unlimited: false,
+ payer: owner.clone(),
+ billed_users: vec![owner.clone(), member.clone()],
+ scope: PayerScope::TeamOwner {
+ team_id: macro_uuid::generate_uuid_v7(),
+ },
+ };
+ let ents = FakeEntitlements::default()
+ .with(team)
+ .with_customer(&owner, "cus_owner");
+ let svc = BillingServiceImpl::new(
+ ents,
+ FakeUsage::default(),
+ FakeRepo::default(),
+ FakePayments::default(),
+ );
+
+ assert!(matches!(
+ svc.update_overage(&member, true, 1_000).await,
+ Err(BillingError::NotPayer)
+ ));
+ assert!(matches!(
+ svc.create_credit_checkout(&member, 1_000, "s".into(), "c".into())
+ .await,
+ Err(BillingError::NotPayer)
+ ));
+ assert!(matches!(
+ svc.create_credit_checkout(&owner, 1_234, "s".into(), "c".into())
+ .await,
+ Err(BillingError::InvalidCreditAmount)
+ ));
+ assert!(matches!(
+ svc.update_overage(&owner, true, 100).await,
+ Err(BillingError::InvalidOverageLimit)
+ ));
+ let url = svc
+ .create_credit_checkout(&owner, 2_500, "s".into(), "c".into())
+ .await
+ .unwrap();
+ assert!(url.starts_with("https://checkout.stripe.test"));
+
+ let free = user("[email protected]");
+ assert!(matches!(
+ svc.create_credit_checkout(&free, 1_000, "s".into(), "c".into())
+ .await,
+ Err(BillingError::FreePlan)
+ ));
+
+ // A member's snapshot shows their own seat allowance but no payer controls.
+ let snap = svc.snapshot(&member).await.unwrap();
+ assert!(!snap.can_manage_billing);
+ assert_eq!(snap.seats, 2);
+ assert_eq!(snap.included_cents, 4_000);
+}
+
+#[tokio::test]
+async fn team_seats_keep_allowances_separate_and_share_credits() {
+ let owner = user("[email protected]");
+ let member = user("[email protected]");
+ let team = Entitlement {
+ tier: PlanTier::Premium,
+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],
+ unlimited: false,
+ payer: owner.clone(),
+ billed_users: vec![owner.clone(), member.clone()],
+ scope: PayerScope::TeamOwner {
+ team_id: macro_uuid::generate_uuid_v7(),
+ },
+ };
+ let entitlements = FakeEntitlements::default()
+ .with(team)
+ .with_customer(&owner, "cus_owner");
+ let usage = FakeUsage::default();
+ usage.add(&member, Utc::now(), 5_000);
+ let repo = FakeRepo::default();
+ let service =
+ BillingServiceImpl::new(entitlements, usage, repo.clone(), FakePayments::default());
+
+ let owner_snapshot = service.snapshot(&owner).await.unwrap();
+ assert_eq!(owner_snapshot.used_cents, 0);
+ assert_eq!(owner_snapshot.included_cents, 4_000);
+ let member_snapshot = service.snapshot(&member).await.unwrap();
+ assert_eq!(member_snapshot.used_cents, 5_000);
+ assert_eq!(member_snapshot.included_cents, 4_000);
+ assert_eq!(
+ member_snapshot.blocked_reason,
+ Some(DenyReason::AllowanceExhausted)
+ );
+
+ service
+ .apply_credit_purchase(&owner, 2_500, "cs_team")
+ .await
+ .unwrap();
+ let member_snapshot = service.snapshot(&member).await.unwrap();
+ assert_eq!(member_snapshot.credits_consumed_cents, 1_000);
+ assert_eq!(member_snapshot.credit_balance_cents, 1_500);
+ assert_eq!(member_snapshot.blocked_reason, None);
+ assert_eq!(repo.state.lock().unwrap().balance, 1_500);
+}
+
+#[tokio::test]
+async fn overage_invoice_webhooks_update_suspension() {
+ let (svc, repo, payments, _) = premium_service(5_500);
+ let payer = user("[email protected]");
+ payments.set_pay(PayOutcome::Declined);
+ svc.update_overage(&payer, true, 5_000).await.unwrap();
+ let invoice = repo.charges()[0].invoice.clone().unwrap();
+
+ svc.mark_overage_invoice(&invoice, false).await.unwrap();
+ assert!(svc.snapshot(&payer).await.unwrap().overage_suspended);
+
+ // Stripe's own retry collected it.
+ svc.mark_overage_invoice(&invoice, true).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(!snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 1_500);
+
+ // Paid is terminal: a late or duplicate failure changes nothing.
+ svc.mark_overage_invoice(&invoice, false).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(!snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 1_500);
+ assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);
+
+ // Unknown invoices are ignored.
+ svc.mark_overage_invoice("in_unknown", false).await.unwrap();
+ assert!(!svc.snapshot(&payer).await.unwrap().overage_suspended);
+}
+
+#[tokio::test]
+async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {
+ let (svc, repo, payments, usage) = premium_service(6_000);
+ let payer = user("[email protected]");
+ payments.set_pay(PayOutcome::Declined);
+ // Charge A: 2_000 over, declined, awaiting Stripe.
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ // Charge B: another 1_500, also declined.
+ *usage.cents.lock().unwrap() = 7_500;
+ svc.settle(&payer).await.unwrap();
+ let charges = repo.charges();
+ assert_eq!(charges.len(), 2);
+ let (a, b) = (
+ charges[0].invoice.clone().unwrap(),
+ charges[1].invoice.clone().unwrap(),
+ );
+
+ // B fails: suspended.
+ svc.mark_overage_invoice(&b, false).await.unwrap();
+ assert!(svc.snapshot(&payer).await.unwrap().overage_suspended);
+ // A late `paid` for the older A must not lift B's suspension.
+ svc.mark_overage_invoice(&a, true).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 3_500);
+ // B eventually collects: cleared, everything covered.
+ svc.mark_overage_invoice(&b, true).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(!snap.overage_suspended);
+ assert_eq!(snap.overage_charged_cents, 3_500);
+
+ // The mirror image: a late failure for an older invoice after the newest
+ // charge went through does not re-suspend.
+ let (svc, repo, payments, usage) = premium_service(6_000);
+ payments.set_pay(PayOutcome::Declined);
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ *usage.cents.lock().unwrap() = 7_500;
+ svc.settle(&payer).await.unwrap();
+ let charges = repo.charges();
+ let (a, b) = (
+ charges[0].invoice.clone().unwrap(),
+ charges[1].invoice.clone().unwrap(),
+ );
+ svc.mark_overage_invoice(&b, true).await.unwrap();
+ svc.mark_overage_invoice(&a, false).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert!(!snap.overage_suspended);
+ // A remains coverage because its invoice can still collect. Settlement
+ // retries that same invoice rather than replacing it.
+ assert_eq!(snap.overage_charged_cents, 3_500);
+ assert_eq!(repo.charges()[0].status, OverageChargeStatus::Failed);
+}
+
+#[tokio::test]
+async fn synced_period_anchors_the_snapshot() {
+ let (svc, ..) = premium_service(0);
+ let payer = user("[email protected]");
+ let start = Utc::now() - chrono::Duration::days(3);
+ let end = start + chrono::Duration::days(30);
+ svc.sync_period(&payer, start, end).await.unwrap();
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.period_start, start);
+ assert_eq!(snap.period_end, end);
+ // Inverted periods are ignored.
+ svc.sync_period(&payer, end, start).await.unwrap();
+ assert_eq!(svc.snapshot(&payer).await.unwrap().period_start, start);
+}
+
+fn anchored_premium(
+ used_cents: i64,
+) -> (
+ Service,
+ FakeRepo,
+ FakePayments,
+ FakeUsage,
+ FakeEntitlements,
+ MacroUserIdStr<'static>,
+ BillingPeriod,
+ BillingPeriod,
+) {
+ let payer = user("[email protected]");
+ let ents = FakeEntitlements::default()
+ .with(Entitlement::personal(payer.clone(), PlanTier::Premium))
+ .with_customer(&payer, "cus_123");
+ let usage = FakeUsage {
+ cents: Arc::new(Mutex::new(used_cents)),
+ entries: Default::default(),
+ };
+ let repo = FakeRepo::default();
+ let payments = FakePayments::default();
+ let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone());
+ let current_start = Utc::now() - chrono::Duration::days(3);
+ let current_end = current_start + chrono::Duration::days(30);
+ let current = BillingPeriod {
+ start: current_start,
+ end: current_end,
+ };
+ let previous = current.previous();
+ (svc, repo, payments, usage, ents, payer, previous, current)
+}
+
+#[tokio::test]
+async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {
+ let (svc, repo, _, _, ents, payer, _, current) = anchored_premium(0);
+ svc.sync_period(&payer, current.start, current.end)
+ .await
+ .unwrap();
+ svc.snapshot(&payer).await.unwrap();
+ let frozen = repo.allowance(current.start).expect("open period frozen");
+ assert_eq!(
+ frozen.seats,
+ vec![SeatAllowance {
+ user: payer.clone(),
+ included_cents: 4_000,
+ }]
+ );
+
+ ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));
+ svc.snapshot(&payer).await.unwrap();
+ let frozen = repo
+ .allowance(current.start)
+ .expect("open period refreshed");
+ assert_eq!(frozen.seats[0].included_cents, 20_000);
+}
+
+#[tokio::test]
+async fn previous_period_overage_survives_an_upgrade() {
+ let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
+ svc.sync_period(&payer, current.start, current.end)
+ .await
+ .unwrap();
+ repo.freeze(
+ previous.start,
+ PeriodAllowance {
+ seats: vec![SeatAllowance {
+ user: payer.clone(),
+ included_cents: 4_000,
+ }],
+ },
+ );
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ usage.add(&payer, previous.start + chrono::Duration::days(2), 5_500);
+
+ ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));
+ svc.settle(&payer).await.unwrap();
+
+ let opened = payments.opened();
+ assert_eq!(opened.len(), 1);
+ // 5_500 used against the frozen Premium 4_000, not Max's 20_000.
+ assert_eq!(opened[0].amount_cents, 1_500);
+ assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);
+ // The open period freeze now reflects Max; the closed one does not.
+ assert_eq!(
+ repo.allowance(previous.start).unwrap().seats[0].included_cents,
+ 4_000
+ );
+ assert_eq!(
+ repo.allowance(current.start).unwrap().seats[0].included_cents,
+ 20_000
+ );
+}
+
+#[tokio::test]
+async fn previous_period_does_not_charge_included_usage_after_a_downgrade() {
+ let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
+ svc.sync_period(&payer, current.start, current.end)
+ .await
+ .unwrap();
+ repo.freeze(
+ previous.start,
+ PeriodAllowance {
+ seats: vec![SeatAllowance {
+ user: payer.clone(),
+ included_cents: 20_000,
+ }],
+ },
+ );
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ usage.add(&payer, previous.start + chrono::Duration::days(2), 10_000);
+
+ ents.set(Entitlement::personal(payer.clone(), PlanTier::Premium));
+ svc.settle(&payer).await.unwrap();
+
+ assert!(payments.opened().is_empty());
+ assert!(repo.charges().is_empty());
+}
+
+#[tokio::test]
+async fn previous_period_usage_uses_the_frozen_billed_users() {
+ let owner = user("[email protected]");
+ let member_a = user("[email protected]");
+ let member_b = user("[email protected]");
+ let team_id = macro_uuid::generate_uuid_v7();
+ let old_team = Entitlement {
+ tier: PlanTier::Premium,
+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],
+ unlimited: false,
+ payer: owner.clone(),
+ billed_users: vec![owner.clone(), member_a.clone()],
+ scope: PayerScope::TeamOwner { team_id },
+ };
+ let new_team = Entitlement {
+ billed_users: vec![owner.clone(), member_b.clone()],
+ ..old_team.clone()
+ };
+ let ents = FakeEntitlements::default()
+ .with(old_team.clone())
+ .with_customer(&owner, "cus_owner");
+ let usage = FakeUsage::default();
+ let repo = FakeRepo::default();
+ let payments = FakePayments::default();
+ let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone());
+ let current_start = Utc::now() - chrono::Duration::days(3);
+ let current_end = current_start + chrono::Duration::days(30);
+ let current = BillingPeriod {
+ start: current_start,
+ end: current_end,
+ };
+ let previous = current.previous();
+ svc.sync_period(&owner, current.start, current.end)
+ .await
+ .unwrap();
+ repo.freeze(
+ previous.start,
+ PeriodAllowance {
+ seats: vec![
+ SeatAllowance {
+ user: owner.clone(),
+ included_cents: 4_000,
+ },
+ SeatAllowance {
+ user: member_a.clone(),
+ included_cents: 4_000,
+ },
+ ],
+ },
+ );
+ usage.add(&member_a, previous.start + chrono::Duration::days(2), 9_200);
+ usage.add(
+ &member_b,
+ previous.start + chrono::Duration::days(2),
+ 50_000,
+ );
+ ents.set(new_team);
+ svc.update_overage(&owner, true, 10_000).await.unwrap();
+ svc.settle(&owner).await.unwrap();
+
+ let opened = payments.opened();
+ assert_eq!(opened.len(), 1);
+ // Member A gets only their own $40 allowance, so 5_200 is chargeable.
+ // The owner's unused allowance does not offset it. Member B's usage is
+ // ignored because they were not a billed user in that period.
+ assert_eq!(opened[0].amount_cents, 5_200);
+}
+
+#[tokio::test]
+async fn current_period_uses_the_live_allowance_after_an_upgrade() {
+ let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
+ svc.sync_period(&payer, current.start, current.end)
+ .await
+ .unwrap();
+ repo.freeze(
+ previous.start,
+ PeriodAllowance {
+ seats: vec![SeatAllowance {
+ user: payer.clone(),
+ included_cents: 4_000,
+ }],
+ },
+ );
+ svc.update_overage(&payer, true, 10_000).await.unwrap();
+ // Current-period usage that exceeds Premium but sits inside Max.
+ *usage.cents.lock().unwrap() = 10_000;
+ ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));
+ svc.settle(&payer).await.unwrap();
+ assert!(payments.opened().is_empty());
+ let snap = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(snap.included_cents, 20_000);
+ assert_eq!(snap.used_cents, 10_000);
+ assert_eq!(snap.uncovered_cents, 0);
+}
diff --git a/crates/ai_billing/src/inbound.rs b/crates/ai_billing/src/inbound.rs
new file mode 100644
index 0000000000..72a2c65cb2
--- /dev/null
+++ b/crates/ai_billing/src/inbound.rs
@@ -0,0 +1,5 @@
+//! Inbound adapters: the axum router.
+
+pub mod axum_router;
+
+pub use axum_router::{AiBillingRouterState, ai_billing_router};
diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..18d591e986
--- /dev/null
+++ b/crates/ai_billing/src/inbound/axum_router.rs
@@ -0,0 +1,466 @@
+//! HTTP API for AI billing: the payer's position, overage settings, credit
+//! purchases, the plan catalog, and the internal settle hook.
+
+use crate::domain::{
+ BillingError, BillingService, CREDIT_PACKS_CENTS, OVERAGE_LIMIT_MAX_CENTS,
+ OVERAGE_LIMIT_MIN_CENTS, PlanTier, UsageSnapshot,
+};
+use axum::{
+ Json, Router,
+ extract::{FromRef, State},
+ http::{HeaderMap, StatusCode, Uri, header::ORIGIN},
+ response::{IntoResponse, Response},
+ routing::{get, patch, post},
+};
+use macro_authorization::{
+ InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ UserOrInternal,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use utoipa::ToSchema;
+
+/// Error response body.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct AiBillingErrorBody {
+ /// Human-readable error description.
+ pub error: String,
+}
+
+/// One plan in the catalog.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct PlanCatalogEntry {
+ /// The tier.
+ pub tier: PlanTier,
+ /// Monthly list price per seat, cents.
+ pub monthly_price_cents: i64,
+ /// Included AI per seat per period, list-rate cents.
+ pub included_ai_cents_per_seat: i64,
+}
+
+/// The plan catalog and the knobs the billing UI offers.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct PlanCatalogResponse {
+ /// Every plan, cheapest first.
+ pub plans: Vec<PlanCatalogEntry>,
+ /// Credit packs a payer may buy, cents.
+ pub credit_packs_cents: Vec<i64>,
+ /// Smallest allowed overage cap, cents.
+ pub overage_limit_min_cents: i64,
+ /// Largest allowed overage cap, cents.
+ pub overage_limit_max_cents: i64,
+}
+
+/// Request body for [`update_overage_handler`].
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateOverageRequest {
+ /// Bill usage past allowance and credits.
+ pub enabled: bool,
+ /// Per-period cap on overage spend, cents. Required when enabling.
+ #[serde(default)]
+ pub limit_cents: i64,
+}
+
+/// Request body for [`create_credit_checkout_handler`].
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreditCheckoutRequestBody {
+ /// Pack size, cents; one of the catalog's `credit_packs_cents`.
+ pub amount_cents: i64,
+ /// Where Stripe returns the user after paying. Must be an `https` URL
+ /// on the origin the request came from.
+ pub success_url: String,
+ /// Where Stripe returns the user on cancel. Same rules as `success_url`.
+ pub cancel_url: String,
+}
+
+/// Why a Checkout return URL was refused.
+#[derive(Debug, PartialEq, Eq)]
+enum ReturnUrlError {
+ Unparseable,
+ Scheme,
+ Credentials,
+ Origin,
+}
+
+impl std::fmt::Display for ReturnUrlError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ ReturnUrlError::Unparseable => "is not an absolute URL",
+ ReturnUrlError::Scheme => "must use https (http only for localhost)",
+ ReturnUrlError::Credentials => "must not carry credentials",
+ ReturnUrlError::Origin => "must be on the origin the request came from",
+ })
+ }
+}
+
+/// Stripe sends the payer wherever these URLs point after Checkout, so they
+/// must not be an open redirect: absolute `https` (plain `http` only for a
+/// local frontend), no embedded credentials, and, when the browser told us
+/// where the request came from, that same origin.
+fn validate_return_url(url: &str, request_origin: Option<&str>) -> Result<(), ReturnUrlError> {
+ let uri: Uri = url.parse().map_err(|_| ReturnUrlError::Unparseable)?;
+ let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else {
+ return Err(ReturnUrlError::Unparseable);
+ };
+ if authority.as_str().contains('@') {
+ return Err(ReturnUrlError::Credentials);
+ }
+ let host = authority.host();
+ let local = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "[::1]";
+ if !(scheme == "https" || (scheme == "http" && local)) {
+ return Err(ReturnUrlError::Scheme);
+ }
+ if let Some(origin) = request_origin.filter(|o| *o != "null") {
+ // Browsers omit the default port from `Origin`; match that.
+ let default_port = if scheme == "https" { "443" } else { "80" };
+ let expected = match authority.port_u16().map(|p| p.to_string()) {
+ Some(port) if port != default_port => format!("{scheme}://{host}:{port}"),
+ _ => format!("{scheme}://{host}"),
+ };
+ if !origin.eq_ignore_ascii_case(&expected) {
+ return Err(ReturnUrlError::Origin);
+ }
+ }
+ Ok(())
+}
+
+/// Validate both return URLs of a checkout request, naming the offending
+/// field in the error so the client can surface it.
+fn validate_return_urls(
+ req: &CreditCheckoutRequestBody,
+ headers: &HeaderMap,
+) -> Result<(), AiBillingErrorBody> {
+ let origin = headers.get(ORIGIN).and_then(|v| v.to_str().ok());
+ for (name, url) in [
+ ("successUrl", &req.success_url),
+ ("cancelUrl", &req.cancel_url),
+ ] {
+ if let Err(e) = validate_return_url(url, origin) {
+ return Err(AiBillingErrorBody {
+ error: format!("{name} {e}"),
+ });
+ }
+ }
+ Ok(())
+}
+
+/// Response for [`create_credit_checkout_handler`].
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreditCheckoutResponse {
+ /// The hosted Checkout URL to redirect to.
+ pub url: String,
+}
+
+/// Request body for [`settle_handler`].
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SettleRequest {
+ /// Any user billed to the payer to settle.
+ pub user_id: String,
+}
+
+/// Router state: the billing service plus the authorization state the
+/// extractors need.
+pub struct AiBillingRouterState<B, Auth> {
+ /// The billing service.
+ pub service: Arc<B>,
+ /// Authorization state for the request extractors.
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<B, Auth> Clone for AiBillingRouterState<B, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for Arc<B> {
+ fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {
+ state.service.clone()
+ }
+}
+
+impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Build the AI billing router.
+pub fn ai_billing_router<B, Auth, S>(state: AiBillingRouterState<B, Auth>) -> Router<S>
+where
+ B: BillingService,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + Clone + 'static,
+{
+ Router::new()
+ .route("/ai-billing/summary", get(get_summary_handler::<B, Auth>))
+ .route("/ai-billing/plans", get(get_plans_handler))
+ .route(
+ "/ai-billing/overage",
+ patch(update_overage_handler::<B, Auth>),
+ )
+ .route(
+ "/ai-billing/credits/checkout",
+ post(create_credit_checkout_handler::<B, Auth>),
+ )
+ .route(
+ "/internal/ai-billing/settle",
+ post(settle_handler::<B, Auth>),
+ )
+ .with_state(state)
+}
+
+fn error_response(e: BillingError) -> Response {
+ let status = match &e {
+ BillingError::NotPayer => StatusCode::FORBIDDEN,
+ BillingError::FreePlan => StatusCode::PAYMENT_REQUIRED,
+ BillingError::InvalidCreditAmount
+ | BillingError::InvalidOverageLimit
+ | BillingError::NoStripeCustomer => StatusCode::BAD_REQUEST,
+ BillingError::Payment(_) | BillingError::Storage(_) | BillingError::Entitlement(_) => {
+ tracing::error!(error = ?e, "ai billing request failed");
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+ let error = if status == StatusCode::INTERNAL_SERVER_ERROR {
+ "internal error".to_string()
+ } else {
+ e.to_string()
+ };
+ (status, Json(AiBillingErrorBody { error })).into_response()
+}
+
+/// The caller's current-period AI usage, credits, and overage settings.
+///
+/// Runs a settlement first so the position reflects any credits or overage
+/// that were waiting to be booked.
+#[utoipa::path(
+ get,
+ path = "/ai-billing/summary",
+ operation_id = "get_ai_billing_summary",
+ responses(
+ (status = 200, description = "Current-period position", body = UsageSnapshot),
+ (status = 401, description = "Unauthorized"),
+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),
+ ),
+ tag = "ai_billing"
+)]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
+pub async fn get_summary_handler<B: BillingService, Auth: MacroAuthorizationService>(
+ State(service): State<Arc<B>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+) -> Response {
+ let user_id = &user.authorization.user.macro_user_id;
+ if let Err(e) = service.settle(user_id).await {
+ // Collection problems show up in the snapshot; don't fail the read.
+ tracing::warn!(error = ?e, "settlement before summary failed");
+ }
+ match service.snapshot(user_id).await {
+ Ok(snapshot) => Json(snapshot).into_response(),
+ Err(e) => error_response(e),
+ }
+}
+
+/// The plan catalog, credit packs, and overage cap bounds.
+#[utoipa::path(
+ get,
+ path = "/ai-billing/plans",
+ operation_id = "get_ai_billing_plans",
+ responses(
+ (status = 200, description = "Plan catalog", body = PlanCatalogResponse),
+ ),
+ tag = "ai_billing"
+)]
+pub async fn get_plans_handler() -> Json<PlanCatalogResponse> {
+ Json(PlanCatalogResponse {
+ plans: [PlanTier::Free, PlanTier::Premium, PlanTier::Max]
+ .into_iter()
+ .map(|tier| PlanCatalogEntry {
+ tier,
+ monthly_price_cents: tier.monthly_price_cents(),
+ included_ai_cents_per_seat: tier.included_ai_cents_per_seat(),
+ })
+ .collect(),
+ credit_packs_cents: CREDIT_PACKS_CENTS.to_vec(),
+ overage_limit_min_cents: OVERAGE_LIMIT_MIN_CENTS,
+ overage_limit_max_cents: OVERAGE_LIMIT_MAX_CENTS,
+ })
+}
+
+/// Turn overage billing on or off and set the per-period cap. Payer only.
+#[utoipa::path(
+ patch,
+ path = "/ai-billing/overage",
+ operation_id = "update_ai_billing_overage",
+ request_body = UpdateOverageRequest,
+ responses(
+ (status = 200, description = "Updated position", body = UsageSnapshot),
+ (status = 400, description = "Invalid limit", body = AiBillingErrorBody),
+ (status = 401, description = "Unauthorized"),
+ (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
+ (status = 403, description = "Only the payer may change billing", body = AiBillingErrorBody),
+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),
+ ),
+ tag = "ai_billing"
+)]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
+pub async fn update_overage_handler<B: BillingService, Auth: MacroAuthorizationService>(
+ State(service): State<Arc<B>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Json(req): Json<UpdateOverageRequest>,
+) -> Response {
+ match service
+ .update_overage(
+ &user.authorization.user.macro_user_id,
+ req.enabled,
+ req.limit_cents,
+ )
+ .await
+ {
+ Ok(snapshot) => Json(snapshot).into_response(),
+ Err(e) => error_response(e),
+ }
+}
+
+/// Start a Stripe Checkout for a credit pack. Payer only.
+#[utoipa::path(
+ post,
+ path = "/ai-billing/credits/checkout",
+ operation_id = "create_ai_credit_checkout",
+ request_body = CreditCheckoutRequestBody,
+ responses(
+ (status = 200, description = "Checkout URL", body = CreditCheckoutResponse),
+ (status = 400, description = "Invalid pack, untrusted return URL, or no payment account", body = AiBillingErrorBody),
+ (status = 401, description = "Unauthorized"),
+ (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
+ (status = 403, description = "Only the payer may buy credits", body = AiBillingErrorBody),
+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),
+ ),
+ tag = "ai_billing"
+)]
+#[tracing::instrument(skip(service, user, req), fields(user_id = %user.authorization.user.macro_user_id, cents = req.amount_cents))]
+pub async fn create_credit_checkout_handler<B: BillingService, Auth: MacroAuthorizationService>(
+ State(service): State<Arc<B>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ headers: HeaderMap,
+ Json(req): Json<CreditCheckoutRequestBody>,
+) -> Response {
+ if let Err(body) = validate_return_urls(&req, &headers) {
+ return (StatusCode::BAD_REQUEST, Json(body)).into_response();
+ }
+ match service
+ .create_credit_checkout(
+ &user.authorization.user.macro_user_id,
+ req.amount_cents,
+ req.success_url,
+ req.cancel_url,
+ )
+ .await
+ {
+ Ok(url) => Json(CreditCheckoutResponse { url }).into_response(),
+ Err(e) => error_response(e),
+ }
+}
+
+/// Settle a payer's AI billing. Internal services only; called by the usage
+/// recorder in other services when a payer has usage past their allowance.
+#[utoipa::path(
+ post,
+ path = "/internal/ai-billing/settle",
+ operation_id = "settle_ai_billing",
+ request_body = SettleRequest,
+ responses(
+ (status = 204, description = "Settled"),
+ (status = 400, description = "Invalid user id", body = AiBillingErrorBody),
+ (status = 401, description = "Unauthorized"),
+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),
+ ),
+ tag = "ai_billing"
+)]
+#[tracing::instrument(skip(service, _internal), fields(user_id = %req.user_id))]
+pub async fn settle_handler<B: BillingService, Auth: MacroAuthorizationService>(
+ State(service): State<Arc<B>>,
+ _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
+ Json(req): Json<SettleRequest>,
+) -> Response {
+ let user_id = match MacroUserIdStr::try_from(req.user_id) {
+ Ok(id) => id,
+ Err(e) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(AiBillingErrorBody {
+ error: format!("invalid user id: {e}"),
+ }),
+ )
+ .into_response();
+ }
+ };
+ match service.settle(&user_id).await {
+ Ok(()) => StatusCode::NO_CONTENT.into_response(),
+ // A declined card is reported through the payer's snapshot, not to
+ // the internal caller.
+ Err(BillingError::Payment(_) | BillingError::NoStripeCustomer) => {
+ StatusCode::NO_CONTENT.into_response()
+ }
+ Err(e) => error_response(e),
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::{ReturnUrlError, validate_return_url};
+
+ #[test]
+ fn return_urls_must_be_https_on_the_calling_origin() {
+ let origin = Some("https://macro.com");
+ assert_eq!(
+ validate_return_url("https://macro.com/app/settings/billing?x=1", origin),
+ Ok(())
+ );
+ // Without an Origin header any https URL without credentials passes.
+ assert_eq!(
+ validate_return_url("https://preview.macro.com/app", None),
+ Ok(())
+ );
+ assert_eq!(
+ validate_return_url("http://localhost:3000/app", Some("http://localhost:3000")),
+ Ok(())
+ );
+ assert_eq!(
+ validate_return_url("https://macro.com:443/app", origin),
+ Ok(())
+ );
+ assert_eq!(
+ validate_return_url("https://macro.com:8443/app", origin),
+ Err(ReturnUrlError::Origin)
+ );
+ assert_eq!(
+ validate_return_url("https://evil.example/app", origin),
+ Err(ReturnUrlError::Origin)
+ );
+ assert_eq!(
+ validate_return_url("http://macro.com/app", None),
+ Err(ReturnUrlError::Scheme)
+ );
+ assert_eq!(
+ validate_return_url("javascript:alert(1)", None),
+ Err(ReturnUrlError::Unparseable)
+ );
+ assert_eq!(
+ validate_return_url("/app/settings/billing", None),
+ Err(ReturnUrlError::Unparseable)
+ );
+ assert_eq!(
+ validate_return_url("https://user:[email protected]/app", None),
+ Err(ReturnUrlError::Credentials)
+ );
+ }
+}
diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rs
new file mode 100644
index 0000000000..c50d79c712
--- /dev/null
+++ b/crates/ai_billing/src/lib.rs
@@ -0,0 +1,45 @@
+#![deny(missing_docs)]
+
+//! AI billing — plan allowances, prepaid credits, and post-paid overage.
+//!
+//! # The margin model
+//!
+//! Every paid plan includes a monthly AI allowance equal to its list price,
+//! measured at Macro's **list rate**. The list rate is provider cost marked up
+//! so that a fully consumed allowance yields the target gross margin:
+//!
+//! ```text
+//! list = cost / (1 - margin) margin = 60% => list = 2.5 x cost
+//! Premium: $40/mo includes $40 of AI at list ( = $16 of provider cost)
+//! Max: $200/mo includes $200 of AI at list ( = $80 of provider cost)
+//! ```
+//!
+//! Usage past the allowance is covered, in order, by prepaid credits (bought
+//! in one-off Stripe Checkout payments) and then by opt-in overage, billed to
+//! the payer's Stripe customer in chunks at the same list rate. Both keep the
+//! same margin as the plan itself.
+//!
+//! # Layout
+//!
+//! - [`domain`] — plan catalog, the margin math, the settlement ledger (pure),
+//! ports, and the service.
+//! - [`outbound`] — Postgres repos over `ai_usage` and the billing tables, the
+//! Stripe gateway, the roles + teams entitlement resolver, and the recorder
+//! wrapper that triggers settlement after usage lands.
+//! - [`inbound`] — the axum router (summary, overage settings, credit
+//! checkout, internal settle).
+//!
+//! The *payer* is the account that owns credits, overage settings, and the
+//! Stripe customer: the personal subscriber, or the team owner for members
+//! whose paid access comes through a team subscription. Each team seat uses
+//! only its own plan allowance; credits and overage are shared by the payer.
+
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
+
+pub use domain::{
+ AllowanceDecision, BillingError, BillingPeriod, BillingService, BillingSettings,
+ CREDIT_PACKS_CENTS, DenyReason, Entitlement, PayerScope, PlanTier, TARGET_GROSS_MARGIN_BPS,
+ UsageSnapshot, list_rate_cents,
+};
diff --git a/crates/ai_billing/src/outbound.rs b/crates/ai_billing/src/outbound.rs
new file mode 100644
index 0000000000..520be79436
--- /dev/null
+++ b/crates/ai_billing/src/outbound.rs
@@ -0,0 +1,16 @@
+//! Outbound adapters: Postgres, Stripe, the roles + teams entitlement resolver,
+//! the internal settlement trigger, and the settling usage recorder.
+
+pub mod entitlement;
+pub mod http_settlement_trigger;
+pub mod pg_billing_repo;
+pub mod pg_usage_reader;
+pub mod settling_recorder;
+pub mod stripe_gateway;
+
+pub use entitlement::RolesTeamsEntitlementSource;
+pub use http_settlement_trigger::HttpSettlementTrigger;
+pub use pg_billing_repo::PgBillingRepo;
+pub use pg_usage_reader::PgUsageReader;
+pub use settling_recorder::SettlingUsageRecorder;
+pub use stripe_gateway::{NoOpPaymentGateway, StripePaymentGateway};
diff --git a/crates/ai_billing/src/outbound/entitlement.rs b/crates/ai_billing/src/outbound/entitlement.rs
new file mode 100644
index 0000000000..e271257042
--- /dev/null
+++ b/crates/ai_billing/src/outbound/entitlement.rs
@@ -0,0 +1,141 @@
+//! Resolves a user's plan and payer from their roles and team membership.
+
+use crate::domain::{BillingError, Entitlement, EntitlementSource, PayerScope, PlanTier, Result};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
+use teams::domain::team_repo::TeamRepository;
+
+/// [`EntitlementSource`] over the roles service and the teams repository.
+///
+/// - A member of a paying (or enterprise) team is billed through the team
+/// owner: every seat keeps its own plan allowance, while credits and overage
+/// are shared by the owner (a team may mix Premium and Max seats). Each
+/// member's plan is the one recorded on their membership; enterprise teams
+/// are unlimited.
+/// - Everyone else is a personal account on whatever tier their roles say.
+#[derive(Clone)]
+pub struct RolesTeamsEntitlementSource<P, T> {
+ permissions: P,
+ teams: T,
+}
+
+impl<P, T> RolesTeamsEntitlementSource<P, T> {
+ /// Build the resolver.
+ pub fn new(permissions: P, teams: T) -> Self {
+ Self { permissions, teams }
+ }
+}
+
+fn entitlement_err(e: impl std::error::Error + Send + Sync + 'static) -> BillingError {
+ BillingError::Entitlement(e.into())
+}
+
+impl<P, T> RolesTeamsEntitlementSource<P, T>
+where
+ P: UserRolesAndPermissionsService,
+ T: TeamRepository,
+{
+ async fn tier_of(&self, user: &MacroUserIdStr<'_>) -> Result<PlanTier> {
+ let roles = self
+ .permissions
+ .get_user_roles(user)
+ .await
+ .map_err(entitlement_err)?;
+ Ok(PlanTier::from_roles(&roles))
+ }
+}
+
+impl<P, T> EntitlementSource for RolesTeamsEntitlementSource<P, T>
+where
+ P: UserRolesAndPermissionsService,
+ T: TeamRepository,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn entitlement(&self, user: &MacroUserIdStr<'_>) -> Result<Entitlement> {
+ let user_owned = user.clone().into_owned();
+ let own_tier = self.tier_of(user).await?;
+
+ let teams = self
+ .teams
+ .get_user_teams(user)
+ .await
+ .map_err(entitlement_err)?;
+ let Some(team) = teams.into_iter().next() else {
+ return Ok(Entitlement::personal(user_owned, own_tier));
+ };
+
+ let subscription = self
+ .teams
+ .get_team_subscription_id(team.id())
+ .await
+ .map_err(entitlement_err)?;
+ if !team.enterprise() && subscription.is_none() {
+ // A free team: everyone pays for themself.
+ return Ok(Entitlement::personal(user_owned, own_tier));
+ }
+
+ let owner = MacroUserIdStr::parse_from_str(team.owner_id())
+ .map_err(entitlement_err)?
+ .into_owned();
+ let is_owner = owner.as_ref() == user.as_ref();
+
+ // Every membership row (the owner has one too) carries the plan its
+ // seat is billed at. A team member row that somehow lacks one, or an
+ // owner without a row, counts as a Premium seat: that is the plan
+ // every seat starts on.
+ let members = self
+ .teams
+ .get_team_members(team.id())
+ .await
+ .map_err(entitlement_err)?;
+ let mut seats: Vec<(MacroUserIdStr<'static>, PlanTier)> =
+ Vec::with_capacity(members.len() + 1);
+ for member in members {
+ let member_id = member.user_id.into_owned();
+ if seats
+ .iter()
+ .any(|(id, _)| id.as_ref() == member_id.as_ref())
+ {
+ continue;
+ }
+ seats.push((member_id, PlanTier::from(member.plan)));
+ }
+ if !seats.iter().any(|(id, _)| id.as_ref() == owner.as_ref()) {
+ seats.insert(0, (owner.clone(), PlanTier::Premium));
+ }
+ let tier = seats
+ .iter()
+ .find(|(id, _)| id.as_ref() == user.as_ref())
+ .map(|(_, tier)| *tier)
+ .unwrap_or(PlanTier::Premium);
+ let (billed_users, seat_tiers): (Vec<_>, Vec<_>) = seats.into_iter().unzip();
+
+ Ok(Entitlement {
+ tier,
+ seat_tiers,
+ unlimited: team.enterprise(),
+ payer: owner,
+ billed_users,
+ scope: if is_owner {
+ PayerScope::TeamOwner {
+ team_id: *team.id(),
+ }
+ } else {
+ PayerScope::TeamMember {
+ team_id: *team.id(),
+ }
+ },
+ })
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn stripe_customer_id(&self, user: &MacroUserIdStr<'_>) -> Result<Option<String>> {
+ Ok(self
+ .teams
+ .get_stripe_customer_id(user)
+ .await
+ .map_err(entitlement_err)?
+ .map(|id| id.to_string()))
+ }
+}
diff --git a/crates/ai_billing/src/outbound/http_settlement_trigger.rs b/crates/ai_billing/src/outbound/http_settlement_trigger.rs
new file mode 100644
index 0000000000..628ebc4d32
--- /dev/null
+++ b/crates/ai_billing/src/outbound/http_settlement_trigger.rs
@@ -0,0 +1,55 @@
+//! Asks the authentication service (which owns Stripe) to settle a payer.
+
+use crate::domain::SettlementTrigger;
+use authentication_service_client::AuthServiceClient;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+use std::time::Duration;
+
+/// Pauses between attempts; the last entry is the number of attempts.
+const RETRY_BACKOFF: [Duration; 2] = [Duration::from_secs(1), Duration::from_secs(5)];
+
+/// [`SettlementTrigger`] over the internal auth-service API. Runs on a
+/// background task with a short bounded retry. Settlement is idempotent and
+/// is requested again by the payer's next completion and by every Billing
+/// page view (the summary endpoint settles first), so a request that still
+/// fails after the retries is picked up there rather than queued durably.
+#[derive(Clone)]
+pub struct HttpSettlementTrigger {
+ client: Arc<AuthServiceClient>,
+}
+
+impl HttpSettlementTrigger {
+ /// Wrap an internal auth-service client.
+ pub fn new(client: Arc<AuthServiceClient>) -> Self {
+ Self { client }
+ }
+}
+
+impl SettlementTrigger for HttpSettlementTrigger {
+ fn request_settlement(&self, payer: MacroUserIdStr<'static>) {
+ let client = self.client.clone();
+ tokio::spawn(async move {
+ let mut backoff = RETRY_BACKOFF.iter();
+ loop {
+ let Err(e) = client.settle_ai_billing(payer.as_ref()).await else {
+ return;
+ };
+ match backoff.next() {
+ Some(pause) => {
+ tracing::warn!(error = ?e, "ai billing settlement request failed; retrying");
+ tokio::time::sleep(*pause).await;
+ }
+ None => {
+ tracing::error!(
+ error = ?e,
+ attempts = RETRY_BACKOFF.len() + 1,
+ "ai billing settlement request failed; the next completion or billing page view retries"
+ );
+ return;
+ }
+ }
+ }
+ });
+ }
+}
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rs
new file mode 100644
index 0000000000..216c434a2d
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs
@@ -0,0 +1,572 @@
+//! Postgres adapter for the billing tables (`ai_billing_account`,
+//! `ai_credit_ledger`, `ai_overage_charge`, `ai_billing_period_allowance`).
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ BillingError, BillingRepo, BillingSettings, OverageChargeStatus, PendingCharge,
+ PeriodAllowance, PeriodLedger, Result, SeatAllowance, SettlementOutcome, SettlementPolicy,
+ SettlementState, plan_settlement,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+use std::str::FromStr;
+
+/// Postgres-backed [`BillingRepo`].
+#[derive(Clone)]
+pub struct PgBillingRepo {
+ pool: PgPool,
+}
+
+impl PgBillingRepo {
+ /// Create a repo over a connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn storage(e: sqlx::Error) -> BillingError {
+ BillingError::Storage(e.into())
+}
+
+impl BillingRepo for PgBillingRepo {
+ async fn settings(&self, payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {
+ let row = sqlx::query!(
+ r#"
+ SELECT overage_enabled, overage_limit_cents, overage_suspended_at,
+ period_start, period_end
+ FROM ai_billing_account
+ WHERE user_id = $1
+ "#,
+ payer.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+
+ Ok(row
+ .map(|r| BillingSettings {
+ overage_enabled: r.overage_enabled,
+ overage_limit_cents: r.overage_limit_cents,
+ overage_suspended_at: r.overage_suspended_at,
+ period_anchor: r.period_start.zip(r.period_end),
+ })
+ .unwrap_or_default())
+ }
+
+ async fn update_overage(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ enabled: bool,
+ limit_cents: i64,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_billing_account (user_id, overage_enabled, overage_limit_cents)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id) DO UPDATE
+ SET overage_enabled = EXCLUDED.overage_enabled,
+ overage_limit_cents = EXCLUDED.overage_limit_cents,
+ overage_suspended_at = NULL,
+ updated_at = NOW()
+ "#,
+ payer.as_ref(),
+ enabled,
+ limit_cents,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn set_period(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_billing_account (user_id, period_start, period_end)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id) DO UPDATE
+ SET period_start = EXCLUDED.period_start,
+ period_end = EXCLUDED.period_end,
+ updated_at = NOW()
+ "#,
+ payer.as_ref(),
+ start,
+ end,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn suspend_overage(&self, payer: &MacroUserIdStr<'_>) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_billing_account (user_id, overage_suspended_at)
+ VALUES ($1, NOW())
+ ON CONFLICT (user_id) DO UPDATE
+ SET overage_suspended_at = COALESCE(ai_billing_account.overage_suspended_at, NOW()),
+ updated_at = NOW()
+ "#,
+ payer.as_ref(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn clear_overage_suspension(&self, payer: &MacroUserIdStr<'_>) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE ai_billing_account
+ SET overage_suspended_at = NULL, updated_at = NOW()
+ WHERE user_id = $1
+ "#,
+ payer.as_ref(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn credit_balance_cents(&self, payer: &MacroUserIdStr<'_>) -> Result<i64> {
+ let balance = sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
+ FROM ai_credit_ledger
+ WHERE user_id = $1
+ "#,
+ payer.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(balance)
+ }
+
+ async fn period_ledger(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> Result<PeriodLedger> {
+ let mut conn = self.pool.acquire().await.map_err(storage)?;
+ read_period_ledger(&mut conn, payer.as_ref(), period_start).await
+ }
+
+ async fn period_allowance(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ ) -> Result<Option<PeriodAllowance>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT billed_users as "billed_users!",
+ included_cents_by_user as "included_cents_by_user!"
+ FROM ai_billing_period_allowance
+ WHERE user_id = $1 AND period_start = $2
+ "#,
+ payer.as_ref(),
+ period_start,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(|r| {
+ Ok(PeriodAllowance {
+ seats: parse_seat_allowances(r.billed_users, r.included_cents_by_user)?,
+ })
+ })
+ .transpose()
+ }
+
+ async fn remember_period_allowance(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ seats: &[SeatAllowance],
+ ) -> Result<()> {
+ let billed_users: Vec<String> = seats
+ .iter()
+ .map(|seat| seat.user.as_ref().to_string())
+ .collect();
+ let included_cents_by_user: Vec<i64> =
+ seats.iter().map(|seat| seat.included_cents).collect();
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_billing_period_allowance (
+ user_id, period_start, billed_users, included_cents_by_user
+ )
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (user_id, period_start) DO UPDATE
+ SET billed_users = EXCLUDED.billed_users,
+ included_cents_by_user = EXCLUDED.included_cents_by_user,
+ updated_at = NOW()
+ WHERE ai_billing_period_allowance.billed_users
+ IS DISTINCT FROM EXCLUDED.billed_users
+ OR ai_billing_period_allowance.included_cents_by_user
+ IS DISTINCT FROM EXCLUDED.included_cents_by_user
+ "#,
+ payer.as_ref(),
+ period_start,
+ &billed_users,
+ &included_cents_by_user,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn record_credit_purchase(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ amount_cents: i64,
+ stripe_reference: &str,
+ ) -> Result<bool> {
+ let id = macro_uuid::generate_uuid_v7();
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)
+ VALUES ($1, $2, 'purchase', $3, $4, 'Credit pack purchase')
+ ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING
+ "#,
+ id,
+ payer.as_ref(),
+ amount_cents,
+ stripe_reference,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(result.rows_affected() == 1)
+ }
+
+ async fn apply_settlement(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period_start: DateTime<Utc>,
+ chargeable_cents: i64,
+ policy: SettlementPolicy,
+ ) -> Result<SettlementOutcome> {
+ let payer = payer.as_ref();
+ let mut tx = self.pool.begin().await.map_err(storage)?;
+
+ // Serialize settlements per payer on the account row.
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_billing_account (user_id) VALUES ($1)
+ ON CONFLICT (user_id) DO NOTHING
+ "#,
+ payer,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(storage)?;
+ let account = sqlx::query!(
+ r#"
+ SELECT overage_enabled, overage_limit_cents, overage_suspended_at
+ FROM ai_billing_account
+ WHERE user_id = $1
+ FOR UPDATE
+ "#,
+ payer,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(storage)?;
+
+ let balance = sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
+ FROM ai_credit_ledger
+ WHERE user_id = $1
+ "#,
+ payer,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(storage)?;
+ let ledger = read_period_ledger(&mut tx, payer, period_start).await?;
+ let overage_active = account.overage_enabled
+ && account.overage_suspended_at.is_none()
+ && account.overage_limit_cents > 0;
+
+ let plan = plan_settlement(
+ SettlementState {
+ chargeable_cents,
+ credits_consumed_cents: ledger.credits_consumed_cents,
+ overage_charged_cents: ledger.overage_charged_cents,
+ credit_balance_cents: balance,
+ },
+ SettlementPolicy {
+ overage_active,
+ overage_limit_cents: account.overage_limit_cents,
+ charge_threshold_cents: policy.charge_threshold_cents,
+ period_ended: policy.period_ended,
+ },
+ );
+
+ if plan.consume_credits_cents > 0 {
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, period_start, note)
+ VALUES ($1, $2, 'consumption', $3, $4, 'AI usage beyond plan allowance')
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ payer,
+ -plan.consume_credits_cents,
+ period_start,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(storage)?;
+ }
+
+ // A charge still owed from an earlier pass comes first, so a retry
+ // reuses its id (and with it its Stripe idempotency keys and invoice)
+ // instead of reserving a second charge for the same usage. A failed
+ // charge with an invoice remains in the ledger because Stripe may
+ // still collect it, and is retried whenever overage is active. A
+ // failed charge without an invoice is excluded from the ledger and is
+ // retried only when the new plan still covers its full amount.
+ let owed = sqlx::query!(
+ r#"
+ SELECT id, amount_cents, stripe_invoice_id, status::text AS "status!"
+ FROM ai_overage_charge
+ WHERE user_id = $1
+ AND period_start = $2
+ AND (
+ status = 'failed'
+ OR (
+ status = 'pending'
+ AND stripe_invoice_id IS NULL
+ AND updated_at < NOW() - INTERVAL '10 minutes'
+ )
+ )
+ ORDER BY created_at
+ FOR UPDATE
+ "#,
+ payer,
+ period_start,
+ )
+ .fetch_all(&mut *tx)
+ .await
+ .map_err(storage)?;
+ let orphaned = owed.iter().find(|row| row.status == "pending");
+ let retryable = owed.iter().find(|row| {
+ row.status == "failed"
+ && overage_active
+ && (row.stripe_invoice_id.is_some()
+ || row.amount_cents <= plan.charge_overage_cents)
+ });
+
+ let pending_charge = if let Some(row) = orphaned {
+ // Reserved but never collected (the collector died before it
+ // opened an invoice). It already counts as covered; collect it.
+ Some(PendingCharge {
+ id: row.id,
+ amount_cents: row.amount_cents,
+ stripe_invoice_id: row.stripe_invoice_id.clone(),
+ })
+ } else if let Some(row) = retryable {
+ sqlx::query!(
+ r#"
+ UPDATE ai_overage_charge
+ SET status = 'pending', updated_at = NOW()
+ WHERE id = $1
+ "#,
+ row.id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(storage)?;
+ Some(PendingCharge {
+ id: row.id,
+ amount_cents: row.amount_cents,
+ stripe_invoice_id: row.stripe_invoice_id.clone(),
+ })
+ } else if plan.charge_overage_cents > 0 {
+ let id = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status)
+ VALUES ($1, $2, $3, $4, 'pending')
+ "#,
+ id,
+ payer,
+ period_start,
+ plan.charge_overage_cents,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(storage)?;
+ Some(PendingCharge {
+ id,
+ amount_cents: plan.charge_overage_cents,
+ stripe_invoice_id: None,
+ })
+ } else {
+ None
+ };
+
+ tx.commit().await.map_err(storage)?;
+ Ok(SettlementOutcome {
+ consumed_credits_cents: plan.consume_credits_cents,
+ pending_charge,
+ })
+ }
+
+ async fn finish_overage_charge(
+ &self,
+ charge_id: Uuid,
+ stripe_invoice_id: Option<&str>,
+ status: OverageChargeStatus,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE ai_overage_charge
+ SET stripe_invoice_id = COALESCE($2, stripe_invoice_id),
+ status = ($3::text)::ai_overage_charge_status,
+ updated_at = NOW()
+ WHERE id = $1
+ "#,
+ charge_id,
+ stripe_invoice_id,
+ status.to_string(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn resolve_overage_invoice(
+ &self,
+ stripe_invoice_id: &str,
+ status: OverageChargeStatus,
+ ) -> Result<Option<MacroUserIdStr<'static>>> {
+ // `paid` is terminal and re-reporting the current status changes
+ // nothing, so a late or duplicate webhook cannot un-pay a charge or
+ // count twice.
+ let row = sqlx::query!(
+ r#"
+ UPDATE ai_overage_charge
+ SET status = ($2::text)::ai_overage_charge_status, updated_at = NOW()
+ WHERE stripe_invoice_id = $1
+ AND status <> 'paid'
+ AND status <> ($2::text)::ai_overage_charge_status
+ RETURNING user_id
+ "#,
+ stripe_invoice_id,
+ status.to_string(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(|r| {
+ MacroUserIdStr::try_from(r.user_id)
+ .map_err(|e| BillingError::Storage(anyhow::anyhow!("invalid payer id: {e}")))
+ })
+ .transpose()
+ }
+
+ async fn latest_charge_status(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> Result<Option<OverageChargeStatus>> {
+ let status = sqlx::query_scalar!(
+ r#"
+ SELECT status::text AS "status!"
+ FROM ai_overage_charge
+ WHERE user_id = $1
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1
+ "#,
+ payer.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ status
+ .map(|s| {
+ OverageChargeStatus::from_str(&s).map_err(|e| {
+ BillingError::Storage(anyhow::anyhow!("unknown overage charge status {s}: {e}"))
+ })
+ })
+ .transpose()
+ }
+}
+
+/// Sum consumption and charges that can still collect for a period, on any
+/// connection so the settlement transaction can reuse it under its lock.
+async fn read_period_ledger(
+ conn: &mut sqlx::PgConnection,
+ payer: &str,
+ period_start: DateTime<Utc>,
+) -> Result<PeriodLedger> {
+ let consumed = sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(-SUM(delta_cents), 0)::bigint AS "consumed!"
+ FROM ai_credit_ledger
+ WHERE user_id = $1 AND kind = 'consumption' AND period_start = $2
+ "#,
+ payer,
+ period_start,
+ )
+ .fetch_one(&mut *conn)
+ .await
+ .map_err(storage)?;
+ let charged = sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(SUM(amount_cents), 0)::bigint AS "charged!"
+ FROM ai_overage_charge
+ WHERE user_id = $1
+ AND period_start = $2
+ AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)
+ "#,
+ payer,
+ period_start,
+ )
+ .fetch_one(&mut *conn)
+ .await
+ .map_err(storage)?;
+ Ok(PeriodLedger {
+ credits_consumed_cents: consumed,
+ overage_charged_cents: charged,
+ })
+}
+
+fn parse_seat_allowances(
+ billed_users: Vec<String>,
+ included_cents_by_user: Vec<i64>,
+) -> Result<Vec<SeatAllowance>> {
+ if billed_users.len() != included_cents_by_user.len() {
+ return Err(BillingError::Storage(anyhow::anyhow!(
+ "billed users and per-user allowances have different lengths"
+ )));
+ }
+ billed_users
+ .into_iter()
+ .zip(included_cents_by_user)
+ .map(|(id, included_cents)| {
+ let user = MacroUserIdStr::try_from(id).map_err(|e| {
+ BillingError::Storage(anyhow::anyhow!("invalid billed user id: {e}"))
+ })?;
+ Ok(SeatAllowance {
+ user,
+ included_cents,
+ })
+ })
+ .collect()
+}
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
new file mode 100644
index 0000000000..6c51a6000b
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
@@ -0,0 +1,501 @@
+use super::*;
+use crate::domain::OVERAGE_CHARGE_THRESHOLD_CENTS;
+use chrono::DurationRound;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn payer() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()
+}
+
+fn policy(period_ended: bool) -> SettlementPolicy {
+ SettlementPolicy {
+ overage_active: true,
+ overage_limit_cents: 0,
+ charge_threshold_cents: OVERAGE_CHARGE_THRESHOLD_CENTS,
+ period_ended,
+ }
+}
+
+/// How many `ai_overage_charge` rows the test payer has.
+async fn charge_rows(pool: &PgPool) -> i64 {
+ let payer = payer();
+ sqlx::query_scalar!(
+ r#"SELECT COUNT(*)::bigint AS "count!" FROM ai_overage_charge WHERE user_id = $1"#,
+ payer.as_ref(),
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settings_default_and_roundtrip(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ assert_eq!(
+ repo.settings(&payer()).await.unwrap(),
+ BillingSettings::default()
+ );
+
+ repo.update_overage(&payer(), true, 2_500).await.unwrap();
+ // timestamptz keeps microseconds; compare at that precision.
+ let start = Utc::now()
+ .duration_trunc(chrono::Duration::microseconds(1))
+ .unwrap();
+ let end = start + chrono::Duration::days(30);
+ repo.set_period(&payer(), start, end).await.unwrap();
+ let s = repo.settings(&payer()).await.unwrap();
+ assert!(s.overage_enabled);
+ assert_eq!(s.overage_limit_cents, 2_500);
+ assert_eq!(s.period_anchor, Some((start, end)));
+ assert!(s.overage_suspended_at.is_none());
+
+ repo.suspend_overage(&payer()).await.unwrap();
+ assert!(
+ repo.settings(&payer())
+ .await
+ .unwrap()
+ .overage_suspended_at
+ .is_some()
+ );
+ // Re-enabling clears the suspension.
+ repo.update_overage(&payer(), true, 2_500).await.unwrap();
+ assert!(
+ repo.settings(&payer())
+ .await
+ .unwrap()
+ .overage_suspended_at
+ .is_none()
+ );
+ repo.suspend_overage(&payer()).await.unwrap();
+ repo.clear_overage_suspension(&payer()).await.unwrap();
+ assert!(
+ repo.settings(&payer())
+ .await
+ .unwrap()
+ .overage_suspended_at
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn credit_purchases_are_idempotent_on_stripe_reference(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ assert!(
+ repo.record_credit_purchase(&payer(), 2_500, "cs_a")
+ .await
+ .unwrap()
+ );
+ assert!(
+ !repo
+ .record_credit_purchase(&payer(), 2_500, "cs_a")
+ .await
+ .unwrap()
+ );
+ assert!(
+ repo.record_credit_purchase(&payer(), 1_000, "cs_b")
+ .await
+ .unwrap()
+ );
+ assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 3_500);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settlement_consumes_credits_then_reserves_overage(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.record_credit_purchase(&payer(), 500, "cs_1")
+ .await
+ .unwrap();
+
+ // 1_800 beyond per-seat allowances with 500 of credit and overage off.
+ let outcome = repo
+ .apply_settlement(&payer(), period_start, 1_800, policy(false))
+ .await
+ .unwrap();
+ assert_eq!(outcome.consumed_credits_cents, 500);
+ assert!(outcome.pending_charge.is_none());
+ assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 0);
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ assert_eq!(ledger.credits_consumed_cents, 500);
+
+ // Same inputs again: nothing double-booked, remainder waits for overage.
+ let again = repo
+ .apply_settlement(&payer(), period_start, 1_800, policy(false))
+ .await
+ .unwrap();
+ assert_eq!(again, SettlementOutcome::default());
+
+ // Overage on: the 1_300 remainder is reserved as a pending charge.
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+ let charged = repo
+ .apply_settlement(&payer(), period_start, 1_800, policy(false))
+ .await
+ .unwrap();
+ let pending = charged.pending_charge.expect("charge reserved");
+ assert_eq!(pending.amount_cents, 1_300);
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ assert_eq!(ledger.overage_charged_cents, 1_300);
+
+ // Collected: invoice recorded and resolvable by the webhook.
+ repo.finish_overage_charge(pending.id, Some("in_1"), OverageChargeStatus::Paid)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.latest_charge_status(&payer()).await.unwrap(),
+ Some(OverageChargeStatus::Paid)
+ );
+ // Paid is terminal: a late failure webhook changes nothing and keeps the
+ // usage covered.
+ assert!(
+ repo.resolve_overage_invoice("in_1", OverageChargeStatus::Failed)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ assert_eq!(ledger.overage_charged_cents, 1_300);
+ assert!(
+ repo.resolve_overage_invoice("in_unknown", OverageChargeStatus::Paid)
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn invoice_webhooks_apply_out_of_order_without_unpaying(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+ let pending = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge reserved");
+ assert_eq!(pending.amount_cents, 1_300);
+ assert!(pending.stripe_invoice_id.is_none());
+ // The collector records the invoice before attempting payment.
+ repo.finish_overage_charge(pending.id, Some("in_1"), OverageChargeStatus::Pending)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.latest_charge_status(&payer()).await.unwrap(),
+ Some(OverageChargeStatus::Pending)
+ );
+
+ // Declined: the failure webhook lands first.
+ let who = repo
+ .resolve_overage_invoice("in_1", OverageChargeStatus::Failed)
+ .await
+ .unwrap();
+ assert_eq!(who.unwrap().as_ref(), payer().as_ref());
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ // Payment failure is not terminal in Stripe: the open invoice may retry,
+ // so it continues covering the usage.
+ assert_eq!(ledger.overage_charged_cents, 1_300);
+ // Re-reporting the same status is a no-op.
+ assert!(
+ repo.resolve_overage_invoice("in_1", OverageChargeStatus::Failed)
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ // Stripe's retry collected it.
+ assert!(
+ repo.resolve_overage_invoice("in_1", OverageChargeStatus::Paid)
+ .await
+ .unwrap()
+ .is_some()
+ );
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ assert_eq!(ledger.overage_charged_cents, 1_300);
+
+ // A duplicate or late failure after that cannot un-pay it.
+ assert!(
+ repo.resolve_overage_invoice("in_1", OverageChargeStatus::Failed)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ let ledger = repo.period_ledger(&payer(), period_start).await.unwrap();
+ assert_eq!(ledger.overage_charged_cents, 1_300);
+ assert_eq!(
+ repo.latest_charge_status(&payer()).await.unwrap(),
+ Some(OverageChargeStatus::Paid)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settlement_retries_a_failed_charge_instead_of_reserving_a_new_one(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool.clone());
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+
+ let first = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge reserved");
+ // The invoice was opened but payment failed at the provider.
+ repo.finish_overage_charge(first.id, Some("in_1"), OverageChargeStatus::Failed)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.period_ledger(&payer(), period_start)
+ .await
+ .unwrap()
+ .overage_charged_cents,
+ 1_300
+ );
+
+ // The next settlement hands the same charge back, with its invoice, even
+ // though its continued ledger coverage leaves no new amount to plan.
+ let retry = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge retried");
+ assert_eq!(retry.id, first.id);
+ assert_eq!(retry.amount_cents, 1_300);
+ assert_eq!(retry.stripe_invoice_id.as_deref(), Some("in_1"));
+ assert_eq!(charge_rows(&pool).await, 1);
+ assert_eq!(
+ repo.period_ledger(&payer(), period_start)
+ .await
+ .unwrap()
+ .overage_charged_cents,
+ 1_300
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn credits_can_replace_a_failed_charge_that_was_never_invoiced(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool.clone());
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+
+ let first = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge reserved");
+ assert!(first.stripe_invoice_id.is_none());
+ repo.finish_overage_charge(first.id, None, OverageChargeStatus::Failed)
+ .await
+ .unwrap();
+ repo.record_credit_purchase(&payer(), 2_000, "cs_1")
+ .await
+ .unwrap();
+ let covered = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap();
+ assert_eq!(covered.consumed_credits_cents, 1_300);
+ assert!(covered.pending_charge.is_none());
+ let again = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap();
+ assert_eq!(again, SettlementOutcome::default());
+ assert_eq!(
+ repo.latest_charge_status(&payer()).await.unwrap(),
+ Some(OverageChargeStatus::Failed)
+ );
+ assert_eq!(charge_rows(&pool).await, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn credits_do_not_replace_a_failed_charge_with_a_collectible_invoice(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool.clone());
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+
+ let first = repo
+ .apply_settlement(&payer(), period_start, 3_000, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge reserved");
+ assert_eq!(first.amount_cents, 3_000);
+ repo.finish_overage_charge(first.id, Some("in_open"), OverageChargeStatus::Failed)
+ .await
+ .unwrap();
+ repo.suspend_overage(&payer()).await.unwrap();
+ repo.record_credit_purchase(&payer(), 1_000, "cs_shrink")
+ .await
+ .unwrap();
+
+ let suspended = repo
+ .apply_settlement(&payer(), period_start, 3_000, policy(false))
+ .await
+ .unwrap();
+ assert_eq!(suspended.consumed_credits_cents, 0);
+ assert!(suspended.pending_charge.is_none());
+ assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 1_000);
+ assert_eq!(
+ repo.period_ledger(&payer(), period_start)
+ .await
+ .unwrap()
+ .overage_charged_cents,
+ 3_000
+ );
+
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+ let retry = repo
+ .apply_settlement(&payer(), period_start, 3_000, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("existing invoice retried");
+ assert_eq!(retry.id, first.id);
+ assert_eq!(retry.amount_cents, 3_000);
+ assert_eq!(retry.stripe_invoice_id.as_deref(), Some("in_open"));
+ assert_eq!(charge_rows(&pool).await, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settlement_collects_a_reservation_whose_collector_died(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool.clone());
+ let period_start = Utc::now() - chrono::Duration::days(10);
+ repo.update_overage(&payer(), true, 10_000).await.unwrap();
+
+ let reserved = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("charge reserved");
+ // Fresh reservations are left to their collector...
+ assert!(
+ repo.apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .is_none()
+ );
+ // ...but one that never got an invoice after a while is handed back.
+ sqlx::query!(
+ "UPDATE ai_overage_charge SET updated_at = NOW() - INTERVAL '1 hour' WHERE id = $1",
+ reserved.id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let orphan = repo
+ .apply_settlement(&payer(), period_start, 1_300, policy(false))
+ .await
+ .unwrap()
+ .pending_charge
+ .expect("orphaned charge handed back");
+ assert_eq!(orphan.id, reserved.id);
+ assert!(orphan.stripe_invoice_id.is_none());
+ assert_eq!(charge_rows(&pool).await, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settlement_uses_stored_overage_policy_and_flushes_at_period_end(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ let period_start = Utc::now() - chrono::Duration::days(40);
+ repo.update_overage(&payer(), true, 600).await.unwrap();
+
+ // 900 over, cap 600, mid-period: 600 chargeable but under the $10 chunk.
+ let outcome = repo
+ .apply_settlement(&payer(), period_start, 900, policy(false))
+ .await
+ .unwrap();
+ assert!(outcome.pending_charge.is_none());
+
+ // Period ended: the 600 is flushed.
+ let outcome = repo
+ .apply_settlement(&payer(), period_start, 900, policy(true))
+ .await
+ .unwrap();
+ assert_eq!(outcome.pending_charge.unwrap().amount_cents, 600);
+
+ // Suspended: nothing more is reserved even with room.
+ repo.update_overage(&payer(), true, 5_000).await.unwrap();
+ repo.suspend_overage(&payer()).await.unwrap();
+ let outcome = repo
+ .apply_settlement(&payer(), period_start, 900, policy(true))
+ .await
+ .unwrap();
+ assert!(outcome.pending_charge.is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ let start = Utc::now()
+ .duration_trunc(chrono::Duration::microseconds(1))
+ .unwrap();
+ let earlier = start - chrono::Duration::days(30);
+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let seats = vec![
+ SeatAllowance {
+ user: payer(),
+ included_cents: 4_000,
+ },
+ SeatAllowance {
+ user: member,
+ included_cents: 20_000,
+ },
+ ];
+
+ assert!(
+ repo.period_allowance(&payer(), start)
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ repo.remember_period_allowance(&payer(), start, &seats)
+ .await
+ .unwrap();
+ let frozen = repo
+ .period_allowance(&payer(), start)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(frozen.seats, seats);
+
+ // A later observation of the same (open) period refreshes.
+ let max_payer = vec![SeatAllowance {
+ user: payer(),
+ included_cents: 20_000,
+ }];
+ repo.remember_period_allowance(&payer(), start, &max_payer)
+ .await
+ .unwrap();
+ let frozen = repo
+ .period_allowance(&payer(), start)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(frozen.seats, max_payer);
+
+ // A different period is independent.
+ repo.remember_period_allowance(&payer(), earlier, &seats)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.period_allowance(&payer(), start)
+ .await
+ .unwrap()
+ .unwrap()
+ .seats,
+ max_payer
+ );
+ assert_eq!(
+ repo.period_allowance(&payer(), earlier)
+ .await
+ .unwrap()
+ .unwrap()
+ .seats,
+ seats
+ );
+}
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader.rs b/crates/ai_billing/src/outbound/pg_usage_reader.rs
new file mode 100644
index 0000000000..50c5b9501e
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_usage_reader.rs
@@ -0,0 +1,75 @@
+//! Reads recorded AI usage from `ai_usage` at Macro's list rate.
+
+use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, list_rate_cents};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Rows recorded before a model had pricing carry a NULL total. Bill them at
+/// the Opus 5 rate rather than for free; `set_pricing` backfills them later.
+///
+/// These mirror the `claude-opus-5` row seeded into `ai_pricing` by
+/// `20260724182218_seed_claude_opus_5_pricing.sql` ($5 in / $25 out per
+/// million tokens), the dearest model the picker offered when the fallback
+/// was chosen. Keep them in step with that seed.
+const FALLBACK_PRICE_PER_MILLION_IN: f64 = 5.0;
+const FALLBACK_PRICE_PER_MILLION_OUT: f64 = 25.0;
+
+/// Postgres-backed [`UsageReader`] over the `ai_usage` table.
+#[derive(Clone)]
+pub struct PgUsageReader {
+ pool: PgPool,
+}
+
+impl PgUsageReader {
+ /// Create a reader over a connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl UsageReader for PgUsageReader {
+ async fn list_rate_usage_cents_by_user(
+ &self,
+ users: &[MacroUserIdStr<'static>],
+ period: BillingPeriod,
+ ) -> Result<Vec<SeatUsage>> {
+ if users.is_empty() {
+ 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
+ )
+ ), 0)::float8 AS "usd!"
+ FROM ai_usage
+ WHERE user_id = ANY($1)
+ AND created_at >= $2
+ AND created_at < $3
+ GROUP BY user_id
+ "#,
+ &ids,
+ period.start,
+ period.end,
+ FALLBACK_PRICE_PER_MILLION_IN,
+ FALLBACK_PRICE_PER_MILLION_OUT,
+ )
+ .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: list_rate_cents(row.usd),
+ })
+ })
+ .collect()
+ }
+}
diff --git a/crates/ai_billing/src/outbound/settling_recorder.rs b/crates/ai_billing/src/outbound/settling_recorder.rs
new file mode 100644
index 0000000000..536f793e54
--- /dev/null
+++ b/crates/ai_billing/src/outbound/settling_recorder.rs
@@ -0,0 +1,96 @@
+//! A [`UsageRecorder`] that books usage and then asks for settlement when the
+//! payer has usage past their allowance.
+
+use crate::domain::{BillingService, SettlementTrigger};
+use ai_usage::domain::service::UsageServiceImpl;
+use ai_usage::{SYSTEM_USER_ID, UsageEvent, UsageRecorder, UsageRepo};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// Pauses between attempts to land a usage row; the length is the number of
+/// retries after the first attempt.
+const RECORD_RETRY_BACKOFF: [Duration; 3] = [
+ Duration::from_millis(200),
+ Duration::from_secs(1),
+ Duration::from_secs(5),
+];
+
+/// Wraps the Postgres usage recorder. After each row lands it reads the
+/// payer's position and, when there is uncovered usage, triggers settlement
+/// (credit consumption and overage collection) in the service that owns
+/// Stripe. Recording stays best-effort and never delays the completion.
+///
+/// A row that cannot be written is billable usage lost, so the write is
+/// retried with backoff before it is given up on. The retry is bounded and
+/// in-process: usage rows carry no idempotency key, so a durable queue that
+/// re-delivered after an ambiguous failure could double count instead.
+pub struct SettlingUsageRecorder<Repo, B, T> {
+ inner: Arc<UsageServiceImpl<Repo>>,
+ billing: Arc<B>,
+ trigger: T,
+}
+
+impl<Repo, B, T> SettlingUsageRecorder<Repo, B, T> {
+ /// Build the recorder.
+ pub fn new(inner: Arc<UsageServiceImpl<Repo>>, billing: Arc<B>, trigger: T) -> Self {
+ Self {
+ inner,
+ billing,
+ trigger,
+ }
+ }
+}
+
+impl<Repo, B, T> UsageRecorder for SettlingUsageRecorder<Repo, B, T>
+where
+ Repo: UsageRepo + Clone + 'static,
+ B: BillingService,
+ T: SettlementTrigger + Clone,
+{
+ fn record(&self, event: UsageEvent) {
+ let inner = self.inner.clone();
+ let billing = self.billing.clone();
+ let trigger = self.trigger.clone();
+ tokio::spawn(async move {
+ let user = event.user.clone();
+ let mut backoff = RECORD_RETRY_BACKOFF.iter();
+ loop {
+ let Err(e) = inner.record_now(event.clone()).await else {
+ break;
+ };
+ match backoff.next() {
+ Some(pause) => {
+ tracing::warn!(error = ?e, "failed to record ai usage; retrying");
+ tokio::time::sleep(*pause).await;
+ }
+ None => {
+ tracing::error!(
+ error = ?e,
+ attempts = RECORD_RETRY_BACKOFF.len() + 1,
+ model = %event.model,
+ amount = ?event.amount,
+ "failed to record ai usage; giving up"
+ );
+ return;
+ }
+ }
+ }
+ if user.as_ref() == SYSTEM_USER_ID.as_ref() {
+ return;
+ }
+ match billing.snapshot(&user).await {
+ Ok(snapshot) => {
+ if snapshot.tier.is_paid()
+ && !snapshot.unlimited
+ && snapshot.uncovered_cents > 0
+ {
+ trigger.request_settlement(snapshot.payer);
+ }
+ }
+ Err(e) => {
+ tracing::warn!(error = ?e, "failed to read ai billing position");
+ }
+ }
+ });
+ }
+}
diff --git a/crates/ai_billing/src/outbound/stripe_gateway.rs b/crates/ai_billing/src/outbound/stripe_gateway.rs
new file mode 100644
index 0000000000..aaac1adfb9
--- /dev/null
+++ b/crates/ai_billing/src/outbound/stripe_gateway.rs
@@ -0,0 +1,249 @@
+//! Stripe adapter: one-off Checkout for credit packs, and immediate invoices
+//! for overage chunks.
+
+use crate::domain::{
+ BillingError, CreditCheckoutRequest, OverageChargeRequest, PaymentGateway, Result,
+};
+use chrono::Utc;
+use macro_uuid::Uuid;
+use std::collections::HashMap;
+use std::sync::Arc;
+use stripe::{
+ CheckoutSession, CheckoutSessionMode, CollectionMethod, CreateCheckoutSession,
+ CreateCheckoutSessionLineItems, CreateCheckoutSessionLineItemsPriceData,
+ CreateCheckoutSessionLineItemsPriceDataProductData, CreateCheckoutSessionPaymentIntentData,
+ CreateInvoice, CreateInvoiceItem, Currency, CustomerId, FinalizeInvoiceParams, Invoice,
+ InvoiceId, InvoiceItem, InvoicePendingInvoiceItemsBehavior, InvoiceStatus, RequestStrategy,
+};
+
+/// Metadata key stamped on every Stripe object this crate creates.
+pub const PURPOSE_METADATA_KEY: &str = "macro_purpose";
+/// [`PURPOSE_METADATA_KEY`] value for a credit-pack Checkout Session.
+pub const PURPOSE_AI_CREDITS: &str = "ai_credits";
+/// [`PURPOSE_METADATA_KEY`] value for an overage invoice.
+pub const PURPOSE_AI_OVERAGE: &str = "ai_overage";
+/// Metadata key carrying the payer's Macro user id.
+pub const PAYER_METADATA_KEY: &str = "macro_user_id";
+/// Metadata key carrying the `ai_overage_charge` id on overage invoices.
+pub const CHARGE_METADATA_KEY: &str = "macro_charge_id";
+
+/// [`PaymentGateway`] backed by Stripe.
+#[derive(Clone)]
+pub struct StripePaymentGateway {
+ client: Arc<stripe::Client>,
+}
+
+impl StripePaymentGateway {
+ /// Wrap a configured Stripe client.
+ pub fn new(client: Arc<stripe::Client>) -> Self {
+ Self { client }
+ }
+
+ /// A client that sends `key` as the idempotency key on its next request,
+ /// so a retried settlement never creates a second invoice.
+ fn idempotent(&self, key: String) -> stripe::Client {
+ (*self.client)
+ .clone()
+ .with_strategy(RequestStrategy::Idempotent(key))
+ }
+}
+
+fn payment(e: stripe::StripeError) -> BillingError {
+ BillingError::Payment(e.into())
+}
+
+fn parse_customer(id: &str) -> Result<CustomerId> {
+ id.parse::<CustomerId>()
+ .map_err(|e| BillingError::Payment(anyhow::anyhow!("invalid stripe customer id: {e}")))
+}
+
+fn dollars(cents: i64) -> String {
+ format!("${}.{:02}", cents / 100, cents % 100)
+}
+
+impl PaymentGateway for StripePaymentGateway {
+ #[tracing::instrument(skip(self, request), fields(payer = %request.payer, cents = request.amount_cents), err)]
+ async fn create_credit_checkout(&self, request: CreditCheckoutRequest) -> Result<String> {
+ let customer = parse_customer(&request.customer_id)?;
+ let metadata: HashMap<String, String> = HashMap::from([
+ (
+ PURPOSE_METADATA_KEY.to_string(),
+ PURPOSE_AI_CREDITS.to_string(),
+ ),
+ (PAYER_METADATA_KEY.to_string(), request.payer.to_string()),
+ ("amount_cents".to_string(), request.amount_cents.to_string()),
+ ]);
+
+ let params = CreateCheckoutSession {
+ customer: Some(customer),
+ mode: Some(CheckoutSessionMode::Payment),
+ success_url: Some(request.success_url.as_str()),
+ cancel_url: Some(request.cancel_url.as_str()),
+ line_items: Some(vec![CreateCheckoutSessionLineItems {
+ quantity: Some(1),
+ price_data: Some(CreateCheckoutSessionLineItemsPriceData {
+ currency: Currency::USD,
+ unit_amount: Some(request.amount_cents),
+ product_data: Some(CreateCheckoutSessionLineItemsPriceDataProductData {
+ name: format!("Macro AI credits ({})", dollars(request.amount_cents)),
+ description: Some(
+ "Prepaid AI usage, applied after your plan's included AI is used."
+ .to_string(),
+ ),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }]),
+ metadata: Some(metadata.clone()),
+ payment_intent_data: Some(CreateCheckoutSessionPaymentIntentData {
+ description: Some("Macro AI credits".to_string()),
+ metadata: Some(metadata),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ let session = CheckoutSession::create(&self.client, params)
+ .await
+ .map_err(payment)?;
+ session
+ .url
+ .ok_or_else(|| BillingError::Payment(anyhow::anyhow!("checkout session has no url")))
+ }
+
+ #[tracing::instrument(skip(self, request), fields(charge = %request.charge_id, cents = request.amount_cents), err)]
+ async fn open_overage_invoice(&self, request: OverageChargeRequest) -> Result<String> {
+ let customer = parse_customer(&request.customer_id)?;
+ let key = format!("ai_overage:{}", request.charge_id);
+ let metadata: HashMap<String, String> = HashMap::from([
+ (
+ PURPOSE_METADATA_KEY.to_string(),
+ PURPOSE_AI_OVERAGE.to_string(),
+ ),
+ (
+ CHARGE_METADATA_KEY.to_string(),
+ request.charge_id.to_string(),
+ ),
+ ]);
+
+ // 1. An empty draft invoice that takes nothing else pending on the
+ // customer, so it can never bill more than this one charge.
+ // `auto_advance` keeps Stripe's retry schedule on a declined card;
+ // the outcome arrives via webhook.
+ let mut invoice = CreateInvoice::new();
+ invoice.customer = Some(customer.clone());
+ invoice.auto_advance = Some(true);
+ invoice.collection_method = Some(CollectionMethod::ChargeAutomatically);
+ invoice.pending_invoice_items_behavior = Some(InvoicePendingInvoiceItemsBehavior::Exclude);
+ invoice.description = Some("Macro AI usage beyond plan");
+ invoice.metadata = Some(metadata.clone());
+ let invoice = Invoice::create(&self.idempotent(format!("{key}:invoice")), invoice)
+ .await
+ .map_err(payment)?;
+
+ // 2. The line item, attached to that invoice rather than left pending
+ // on the customer where another invoice could sweep it up.
+ let mut item = CreateInvoiceItem::new(customer);
+ item.invoice = Some(invoice.id.clone());
+ item.amount = Some(request.amount_cents);
+ item.currency = Some(Currency::USD);
+ item.description = Some(request.description.as_str());
+ item.metadata = Some(metadata);
+ if let Err(e) = InvoiceItem::create(&self.idempotent(format!("{key}:item")), item).await {
+ // Nothing is owed on a draft with no lines; drop it so nothing else
+ // can finalize it. Best effort: a retry replays the same keys and
+ // lands on the same draft either way.
+ if let Err(delete_err) = Invoice::delete(&self.client, &invoice.id).await {
+ tracing::warn!(
+ error = ?delete_err,
+ invoice = %invoice.id,
+ "could not delete an empty overage draft invoice"
+ );
+ }
+ return Err(payment(e));
+ }
+
+ // 3. Finalize so it is collectable now rather than in an hour.
+ Invoice::finalize(
+ &self.idempotent(format!("{key}:finalize")),
+ &invoice.id,
+ FinalizeInvoiceParams {
+ auto_advance: Some(true),
+ },
+ )
+ .await
+ .map_err(payment)?;
+
+ Ok(invoice.id.to_string())
+ }
+
+ #[tracing::instrument(skip(self), fields(charge = %charge_id, invoice = %invoice_id), err)]
+ async fn pay_overage_invoice(&self, charge_id: Uuid, invoice_id: &str) -> Result<bool> {
+ let invoice_id: InvoiceId = invoice_id.parse().map_err(|e| {
+ BillingError::Payment(anyhow::anyhow!("invalid stripe invoice id: {e}"))
+ })?;
+ // Every attempt is its own request: replaying the first attempt's key
+ // would replay its decline instead of trying the payer's (new) card.
+ let key = format!(
+ "ai_overage:{charge_id}:pay:{}",
+ Utc::now().timestamp_millis()
+ );
+ match Invoice::pay(&self.idempotent(key), &invoice_id).await {
+ Ok(invoice) => Ok(invoice.status == Some(InvoiceStatus::Paid)),
+ Err(e) => {
+ // A decline is a failed collection, not a failed request: the
+ // invoice stays open and Stripe retries it. The invoice's own
+ // status also tells a retry that Stripe already collected it.
+ let invoice = Invoice::retrieve(&self.client, &invoice_id, &[])
+ .await
+ .map_err(|retrieve_err| {
+ tracing::warn!(
+ error = ?e,
+ "overage invoice payment failed and the invoice could not be read"
+ );
+ payment(retrieve_err)
+ })?;
+ match invoice.status {
+ Some(InvoiceStatus::Paid) => Ok(true),
+ Some(InvoiceStatus::Open) => {
+ tracing::warn!(
+ error = ?e,
+ "overage invoice payment did not succeed; left open for stripe retries"
+ );
+ Ok(false)
+ }
+ other => Err(BillingError::Payment(anyhow::anyhow!(
+ "overage invoice is {other:?} after a failed payment attempt: {e}"
+ ))),
+ }
+ }
+ }
+ }
+}
+
+/// A [`PaymentGateway`] for services that never settle (they only read
+/// billing state and gate requests). Any attempt to pay is a bug.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoOpPaymentGateway;
+
+impl PaymentGateway for NoOpPaymentGateway {
+ async fn create_credit_checkout(&self, _request: CreditCheckoutRequest) -> Result<String> {
+ Err(BillingError::Payment(anyhow::anyhow!(
+ "payments are not configured in this service"
+ )))
+ }
+
+ async fn open_overage_invoice(&self, _request: OverageChargeRequest) -> Result<String> {
+ Err(BillingError::Payment(anyhow::anyhow!(
+ "payments are not configured in this service"
+ )))
+ }
+
+ async fn pay_overage_invoice(&self, _charge_id: Uuid, _invoice_id: &str) -> Result<bool> {
+ Err(BillingError::Payment(anyhow::anyhow!(
+ "payments are not configured in this service"
+ )))
+ }
+}
diff --git a/crates/ai_usage/src/domain/mod.rs b/crates/ai_usage/src/domain/mod.rs
index 769dfae42e..9daaafa6bc 100644
--- a/crates/ai_usage/src/domain/mod.rs
+++ b/crates/ai_usage/src/domain/mod.rs
@@ -6,6 +6,6 @@ pub mod service;
pub use ports::{
AiFeature, CompletionUsage, FeatureUsage, ModelPricing, NoOpUsageRecorder, Price, Result,
SYSTEM_USER_ID, Usage, UsageAmount, UsageApiParams, UsageContext, UsageError, UsageEvent,
- UsageRecorder, UsageRepo, UsageService, UsageSummary,
+ UsageRecorder, UsageRepo, UsageService, UsageSummary, normalize_model_id,
};
pub use service::UsageServiceImpl;
diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rs
index 21e921074b..1bedc29037 100644
--- a/crates/ai_usage/src/domain/ports.rs
+++ b/crates/ai_usage/src/domain/ports.rs
@@ -68,6 +68,19 @@ pub enum AiFeature {
Dictation,
}
+/// Strip a provider prefix from a routing id, yielding the bare model api id
+/// that [`ai_pricing`](UsageRepo::get_pricing) is keyed on.
+///
+/// Chat routes models as `provider/model` (`anthropic/claude-opus-5`) while
+/// one-shot callers pass the bare id. Pricing and stored usage always use the
+/// bare form so a price resolves either way.
+pub fn normalize_model_id(model: &str) -> &str {
+ match model.rsplit_once('/') {
+ Some((_, bare)) if !bare.is_empty() => bare,
+ _ => model,
+ }
+}
+
/// The billable quantity for one AI invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UsageAmount {
diff --git a/crates/ai_usage/src/domain/service.rs b/crates/ai_usage/src/domain/service.rs
index e621a3d700..d72b0bc6a6 100644
--- a/crates/ai_usage/src/domain/service.rs
+++ b/crates/ai_usage/src/domain/service.rs
@@ -49,14 +49,16 @@ where
usage.priced = tracing::field::Empty,
))]
async fn record_event(repo: &Repo, event: UsageEvent) -> Result<()> {
+ // Store and price by the bare api id; chat hands us `provider/model`.
+ let model = normalize_model_id(&event.model).to_string();
let mut cost = Usage {
amount: event.amount,
- model: event.model.clone(),
+ model: model.clone(),
price: None,
created_at: Utc::now(),
};
- if let Some(pricing) = repo.get_pricing(&event.model).await? {
+ if let Some(pricing) = repo.get_pricing(&model).await? {
cost.price = Price::compute(pricing, cost.amount);
}
let span = tracing::Span::current();
@@ -74,6 +76,14 @@ where
repo.insert_usage(&row).await
}
+
+ /// Resolve pricing and persist `event`, returning once the row is written.
+ ///
+ /// [`UsageRecorder::record`] is the fire-and-forget form. Callers that
+ /// need to act after the row exists (billing settlement) await this one.
+ pub async fn record_now(&self, event: UsageEvent) -> Result<()> {
+ Self::record_event(&self.repo, event).await
+ }
}
impl<Repo> UsageRecorder for UsageServiceImpl<Repo>
diff --git a/crates/ai_usage/src/domain/service/test.rs b/crates/ai_usage/src/domain/service/test.rs
index b118083fc5..ceb88ccbfd 100644
--- a/crates/ai_usage/src/domain/service/test.rs
+++ b/crates/ai_usage/src/domain/service/test.rs
@@ -98,6 +98,18 @@ fn system_user_is_valid() {
assert_eq!(SYSTEM_USER_ID.as_ref(), "macro|[email protected]");
}
+#[test]
+fn normalize_model_id_strips_provider_prefix() {
+ assert_eq!(
+ normalize_model_id("anthropic/claude-opus-5"),
+ "claude-opus-5"
+ );
+ assert_eq!(normalize_model_id("openai/gpt-5.6"), "gpt-5.6");
+ assert_eq!(normalize_model_id("claude-haiku-4-5"), "claude-haiku-4-5");
+ // A trailing slash is not a provider prefix; leave the id alone.
+ assert_eq!(normalize_model_id("weird/"), "weird/");
+}
+
#[derive(Clone, Default)]
struct FakeRepo {
pricing: std::sync::Arc<std::sync::Mutex<Option<ModelPricing>>>,
diff --git a/crates/ai_usage/src/lib.rs b/crates/ai_usage/src/lib.rs
index fe5fba4d0d..3917f3d18b 100644
--- a/crates/ai_usage/src/lib.rs
+++ b/crates/ai_usage/src/lib.rs
@@ -19,7 +19,7 @@ pub mod outbound;
pub use domain::{
AiFeature, CompletionUsage, FeatureUsage, ModelPricing, NoOpUsageRecorder, Price,
SYSTEM_USER_ID, Usage, UsageAmount, UsageApiParams, UsageContext, UsageEvent, UsageRecorder,
- UsageRepo, UsageService, UsageSummary,
+ UsageRepo, UsageService, UsageSummary, normalize_model_id,
};
use std::sync::Arc;
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo.rs b/crates/ai_usage/src/outbound/pg_usage_repo.rs
index 7ec42f1cfb..e70b27b579 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo.rs
@@ -5,7 +5,7 @@ mod test;
use crate::domain::{
AiFeature, CompletionUsage, ModelPricing, Price, Result, Usage, UsageAmount, UsageApiParams,
- UsageError, UsageRepo,
+ UsageError, UsageRepo, normalize_model_id,
};
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
@@ -81,7 +81,7 @@ impl UsageRepo for PgUsageRepo {
FROM ai_pricing
WHERE model = $1
"#,
- model,
+ normalize_model_id(model),
)
.fetch_optional(&self.inner)
.await?;
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
index f2ce7e762f..7fcef7278c 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
@@ -137,6 +137,32 @@ async fn query_filters_by_user(pool: PgPool) {
assert_eq!(only_other[0].user.as_ref(), "macro|[email protected]");
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pricing_resolves_provider_qualified_ids(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool);
+ assert_eq!(
+ repo.get_pricing("anthropic/claude-opus-5").await.unwrap(),
+ Some(ModelPricing::Tokens {
+ input: 5.0,
+ output: 25.0
+ })
+ );
+ assert_eq!(
+ repo.get_pricing("claude-sonnet-5").await.unwrap(),
+ Some(ModelPricing::Tokens {
+ input: 2.0,
+ output: 10.0
+ })
+ );
+ assert_eq!(
+ repo.get_pricing("openai/gpt-6-astra").await.unwrap(),
+ Some(ModelPricing::Tokens {
+ input: 10.0,
+ output: 50.0
+ })
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn duration_usage_roundtrips_and_reprices_without_affecting_tokens(pool: PgPool) {
let repo = PgUsageRepo::new(pool);
diff --git a/crates/authentication_service_client/src/ai_billing.rs b/crates/authentication_service_client/src/ai_billing.rs
new file mode 100644
index 0000000000..5c8802b64f
--- /dev/null
+++ b/crates/authentication_service_client/src/ai_billing.rs
@@ -0,0 +1,49 @@
+use crate::AuthServiceClient;
+use crate::error::{AuthServiceClientError, GenericErrorResponse};
+
+#[derive(Debug, serde::Serialize)]
+struct SettleAiBillingRequest<'a> {
+ user_id: &'a str,
+}
+
+impl AuthServiceClient {
+ /// Ask the authentication service to settle AI billing for `user_id`'s
+ /// payer: apply prepaid credits to usage past the allowance and collect
+ /// any chargeable overage. Idempotent; safe to call often.
+ ///
+ /// `user_id` is the payer's `macro|email` identity, so it stays out of
+ /// the span.
+ #[tracing::instrument(skip(self, user_id))]
+ pub async fn settle_ai_billing(&self, user_id: &str) -> Result<(), AuthServiceClientError> {
+ let res = self
+ .client
+ .post(format!("{}/internal/ai-billing/settle", self.url))
+ .json(&SettleAiBillingRequest { user_id })
+ .send()
+ .await
+ .map_err(|e| AuthServiceClientError::RequestBuildError {
+ details: e.to_string(),
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK | reqwest::StatusCode::NO_CONTENT => Ok(()),
+ reqwest::StatusCode::UNAUTHORIZED => Err(AuthServiceClientError::Unauthorized),
+ reqwest::StatusCode::FORBIDDEN => Err(AuthServiceClientError::Forbidden),
+ reqwest::StatusCode::NOT_FOUND => Err(AuthServiceClientError::NotFound),
+ status => {
+ let body = res.text().await.map_err(|e| {
+ AuthServiceClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+ if status == reqwest::StatusCode::INTERNAL_SERVER_ERROR {
+ Err(AuthServiceClientError::InternalServerError { details: body })
+ } else {
+ Err(AuthServiceClientError::Generic(GenericErrorResponse {
+ message: body,
+ }))
+ }
+ }
+ }
+ }
+}
diff --git a/crates/authentication_service_client/src/lib.rs b/crates/authentication_service_client/src/lib.rs
index 4e66b61424..0a49cf154f 100644
--- a/crates/authentication_service_client/src/lib.rs
+++ b/crates/authentication_service_client/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod ai_billing;
pub mod delete_inbox_grant_user;
pub mod error;
pub mod google_access_token;
diff --git a/crates/chat/src/domain/models/model_access.rs b/crates/chat/src/domain/models/model_access.rs
index 05552a586b..ebe91c0339 100644
--- a/crates/chat/src/domain/models/model_access.rs
+++ b/crates/chat/src/domain/models/model_access.rs
@@ -7,7 +7,11 @@
pub const CHAT_MODELS: &[&str] = &[
"anthropic/claude-sonnet-5",
"anthropic/claude-opus-5",
+ "anthropic/claude-fable-5-1",
"anthropic/claude-haiku-4-5",
+ "openai/gpt-6-astra",
+ "openai/gpt-5.6",
+ "openai/gpt-5.6-mini",
"openai/gpt-5.5",
"openai/gpt-5-mini",
];
diff --git a/crates/macro_db_client/migrations/20260910135636_ai_billing_allowances_credits_overage.sql b/crates/macro_db_client/migrations/20260910135636_ai_billing_allowances_credits_overage.sql
new file mode 100644
index 0000000000..94858a8b6d
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260910135636_ai_billing_allowances_credits_overage.sql
@@ -0,0 +1,140 @@
+-- AI billing: plan allowances, prepaid credits, and post-paid overage.
+--
+-- Pricing model (see crates/ai_billing): every paid plan includes a monthly AI
+-- allowance equal to its list price, measured at Macro's list rate. The list
+-- rate is provider cost marked up so that a fully consumed allowance yields the
+-- target gross margin (60% => 2.5x provider cost). Usage past the allowance is
+-- covered by prepaid credits, then by opt-in overage billed to the payer's
+-- Stripe customer in chunks.
+
+-- ---------------------------------------------------------------------------
+-- 1. The Max plan ($200/mo) gets its own subscription role. Like sub_opus it
+-- grants the paid AI permission; professional_subscriber (added alongside
+-- by the Stripe webhook) carries read:professional_features.
+-- ---------------------------------------------------------------------------
+INSERT INTO "Role" (id, description)
+ VALUES ('sub_max', 'User is subscribed to the Max pricing plan')
+ON CONFLICT DO NOTHING;
+
+INSERT INTO "RolesOnPermissions" ("permissionId", "roleId")
+ VALUES ('write:proai', 'sub_max')
+ON CONFLICT DO NOTHING;
+
+-- ---------------------------------------------------------------------------
+-- 2. Pricing seeds for models the chat selector already offers but that had no
+-- ai_pricing row (their usage recorded a NULL price). USD per million tokens
+-- from the Claude pricing catalog. ON CONFLICT keeps any runtime override.
+-- ---------------------------------------------------------------------------
+INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out) VALUES
+ ('claude-sonnet-5', 2.0, 10.0),
+ ('claude-fable-5-1', 10.0, 50.0)
+ON CONFLICT (model) DO NOTHING;
+
+-- ---------------------------------------------------------------------------
+-- 3. Chat recorded the provider-qualified routing id ("anthropic/claude-opus-5")
+-- while ai_pricing is keyed by the bare api id ("claude-opus-5"), so most
+-- chat rows never resolved a price. The recorder now normalizes to the bare
+-- id before pricing; normalize the history the same way and backfill the
+-- price of every row that can now be priced.
+--
+-- Rollback: the provider prefix is a pure function of the bare id (chat
+-- only ever routed to Anthropic and OpenAI, whose ids never collide), so
+-- the original values are recoverable without a backup column:
+--
+-- UPDATE ai_usage
+-- SET model = CASE
+-- WHEN model LIKE 'claude-%' THEN 'anthropic/' || model
+-- WHEN model LIKE 'gpt-%' OR model LIKE 'o%' THEN 'openai/' || model
+-- ELSE model
+-- END
+-- WHERE model NOT LIKE '%/%'
+-- AND created_at < '<this migration''s run time>';
+--
+-- Rows recorded by non-chat features (imports, summaries) always carried
+-- the bare id and are unaffected in both directions. The backfilled
+-- price columns need no rollback: they are exactly what `set_pricing`
+-- recomputes, and NULL was never a meaningful value.
+-- ---------------------------------------------------------------------------
+UPDATE ai_usage
+SET model = split_part(model, '/', 2)
+WHERE model LIKE '%/%'
+ AND split_part(model, '/', 2) <> '';
+
+UPDATE ai_usage u
+SET price_per_million_in = p.price_per_million_in,
+ price_per_million_out = p.price_per_million_out,
+ total = (u.input_tokens::real / 1000000.0::real) * p.price_per_million_in
+ + (u.output_tokens::real / 1000000.0::real) * p.price_per_million_out
+FROM ai_pricing p
+WHERE u.model = p.model
+ AND u.total IS NULL;
+
+-- The (user_id, created_at) index the per-period billing sums need is built
+-- CONCURRENTLY by the two migrations that follow this one: ai_usage takes
+-- writes on every completion, and a plain CREATE/DROP INDEX would block them
+-- for the duration.
+
+-- ---------------------------------------------------------------------------
+-- 4. Billing state, keyed by the *payer*: the personal subscriber, or the team
+-- owner for members whose paid access comes through a team subscription.
+-- Rows are created lazily on first read/write; absence means defaults.
+-- ---------------------------------------------------------------------------
+CREATE TABLE ai_billing_account (
+ user_id TEXT PRIMARY KEY,
+ -- Opt-in: bill usage past the allowance and credits to the Stripe customer.
+ overage_enabled BOOLEAN NOT NULL DEFAULT FALSE,
+ -- Per-period cap on overage spend, in list-rate cents. 0 means no overage.
+ overage_limit_cents BIGINT NOT NULL DEFAULT 0,
+ -- Set when an overage charge failed to collect; overage stays off until the
+ -- payer re-enables it (which retries collection).
+ overage_suspended_at TIMESTAMPTZ,
+ -- The current Stripe subscription period, synced from webhooks. NULL falls
+ -- back to the UTC calendar month.
+ period_start TIMESTAMPTZ,
+ period_end TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+-- Prepaid credit ledger, in list-rate cents. The balance is the sum of deltas.
+CREATE TYPE ai_credit_entry_kind AS ENUM ('purchase', 'consumption', 'grant', 'adjustment');
+
+CREATE TABLE ai_credit_ledger (
+ id UUID PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ kind ai_credit_entry_kind NOT NULL,
+ -- Positive for purchases/grants, negative for consumption.
+ delta_cents BIGINT NOT NULL,
+ -- For consumption entries: the usage period the credits were applied to.
+ period_start TIMESTAMPTZ,
+ -- Stripe Checkout Session id for purchases; unique so webhook retries are
+ -- idempotent.
+ stripe_reference TEXT,
+ note TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE UNIQUE INDEX ai_credit_ledger_stripe_reference_key
+ ON ai_credit_ledger (stripe_reference) WHERE stripe_reference IS NOT NULL;
+CREATE INDEX ai_credit_ledger_user_id_created_at_idx
+ ON ai_credit_ledger (user_id, created_at DESC);
+
+-- Overage charges pushed to Stripe, in list-rate cents. `failed` charges do not
+-- count as covered usage and suspend further overage for the payer.
+CREATE TYPE ai_overage_charge_status AS ENUM ('pending', 'paid', 'failed');
+
+CREATE TABLE ai_overage_charge (
+ id UUID PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ amount_cents BIGINT NOT NULL,
+ stripe_invoice_id TEXT,
+ status ai_overage_charge_status NOT NULL DEFAULT 'pending',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE UNIQUE INDEX ai_overage_charge_stripe_invoice_id_key
+ ON ai_overage_charge (stripe_invoice_id) WHERE stripe_invoice_id IS NOT NULL;
+CREATE INDEX ai_overage_charge_user_id_period_start_idx
+ ON ai_overage_charge (user_id, period_start);
diff --git a/crates/macro_db_client/migrations/20260910135637_per_member_seat_plan.sql b/crates/macro_db_client/migrations/20260910135637_per_member_seat_plan.sql
new file mode 100644
index 0000000000..c100e5d437
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260910135637_per_member_seat_plan.sql
@@ -0,0 +1,35 @@
+-- Per-member seat plans.
+--
+-- A paying team may mix Premium ($40) and Max ($200) seats: each member's
+-- plan is recorded on their membership row, the team's Stripe subscription
+-- carries one seat item per plan (quantity = members on that plan), and the
+-- team's pooled AI allowance is the sum of every seat's allowance.
+
+CREATE TYPE "seat_plan" AS ENUM ('premium', 'max');
+
+ALTER TABLE "team_user"
+ ADD COLUMN "plan" "seat_plan" NOT NULL DEFAULT 'premium';
+
+-- Before this change the owner's subscription price set the plan for the whole
+-- team, and the webhook recorded it as `sub_max` on the owner. Carry that
+-- over: a team whose owner holds `sub_max` was a Max team, so every seat was
+-- billed at the Max price.
+UPDATE "team_user" tu
+ SET "plan" = 'max'
+ FROM "team" t
+ JOIN "RolesOnUsers" rou ON rou."userId" = t.owner_id AND rou."roleId" = 'sub_max'
+ WHERE tu.team_id = t.id;
+
+-- Members now carry their own tier role (sub_opus or sub_max) so the AI
+-- allowance and the paid-model permission follow the seat, not the owner.
+INSERT INTO "RolesOnUsers" ("userId", "roleId")
+SELECT tu.user_id, 'sub_max'
+ FROM "team_user" tu
+ WHERE tu."plan" = 'max'
+ON CONFLICT ("userId", "roleId") DO NOTHING;
+
+DELETE FROM "RolesOnUsers" rou
+ USING "team_user" tu
+ WHERE rou."userId" = tu.user_id
+ AND tu."plan" = 'max'
+ AND rou."roleId" = 'sub_opus';
diff --git a/crates/macro_db_client/migrations/20260910135638_seed_gpt_6_astra_pricing.sql b/crates/macro_db_client/migrations/20260910135638_seed_gpt_6_astra_pricing.sql
new file mode 100644
index 0000000000..99657fb712
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260910135638_seed_gpt_6_astra_pricing.sql
@@ -0,0 +1,7 @@
+-- Seed pricing for GPT-6 Astra (USD per million tokens), added to the chat
+-- model selector on paid plans. Standard-tier rates from OpenAI's pricing
+-- page (gpt-6-astra: $10 in / $50 out). ON CONFLICT keeps any price already
+-- set at runtime via the set_pricing endpoint.
+INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out) VALUES
+ ('gpt-6-astra', 10.0, 50.0)
+ON CONFLICT (model) DO NOTHING;
diff --git a/crates/macro_db_client/migrations/20260917175701_ai_usage_user_id_created_at_idx_concurrently.sql b/crates/macro_db_client/migrations/20260917175701_ai_usage_user_id_created_at_idx_concurrently.sql
new file mode 100644
index 0000000000..f8aa27c7ca
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260917175701_ai_usage_user_id_created_at_idx_concurrently.sql
@@ -0,0 +1,8 @@
+-- no-transaction
+-- Per-user, per-period sums over ai_usage are the hot AI billing query (see
+-- crates/ai_billing, PgUsageReader). Built CONCURRENTLY, in its own
+-- migration outside a transaction, so completions keep writing while it
+-- builds. IF NOT EXISTS makes a re-run after an interrupted build a no-op
+-- once the index is valid; an INVALID leftover must be dropped by hand first.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS ai_usage_user_id_created_at_idx
+ ON ai_usage (user_id, created_at DESC);
diff --git a/crates/macro_db_client/migrations/20260917175702_drop_ai_usage_user_id_idx_concurrently.sql b/crates/macro_db_client/migrations/20260917175702_drop_ai_usage_user_id_idx_concurrently.sql
new file mode 100644
index 0000000000..9c3610abd0
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260917175702_drop_ai_usage_user_id_idx_concurrently.sql
@@ -0,0 +1,5 @@
+-- no-transaction
+-- The composite (user_id, created_at) index created by the previous
+-- migration covers the old single-column user_id index (CS-06), so drop it,
+-- CONCURRENTLY so readers of ai_usage are not blocked while it goes.
+DROP INDEX CONCURRENTLY IF EXISTS ai_usage_user_id_idx;
diff --git a/crates/macro_db_client/migrations/20260918172140_ai_billing_period_allowance.sql b/crates/macro_db_client/migrations/20260918172140_ai_billing_period_allowance.sql
new file mode 100644
index 0000000000..470f6fd0a5
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918172140_ai_billing_period_allowance.sql
@@ -0,0 +1,19 @@
+-- Freeze each billing period's included allowance per billed user while the
+-- period is still open. Settlement of a closed period reads this row instead
+-- of the live entitlement, so a later plan or seat change cannot skip last
+-- period's overage (upgrade) or charge usage that was included (downgrade).
+--
+-- Keyed by payer + period start, matching ai_overage_charge / credit
+-- consumption. The service upserts the current period on each observation
+-- (gate, snapshot, settle) and never writes a closed period's row.
+
+CREATE TABLE ai_billing_period_allowance (
+ user_id TEXT NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ billed_users TEXT[] NOT NULL,
+ included_cents_by_user BIGINT[] NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (user_id, period_start),
+ CHECK (cardinality(billed_users) = cardinality(included_cents_by_user))
+);
diff --git a/crates/notification_state/src/postgres/test/migration.rs b/crates/notification_state/src/postgres/test/migration.rs
index 6558c415ef..06efafe0bd 100644
--- a/crates/notification_state/src/postgres/test/migration.rs
+++ b/crates/notification_state/src/postgres/test/migration.rs
@@ -1,5 +1,5 @@
use crate::NotificationState;
-use sqlx::PgPool;
+use sqlx::{Connection, PgPool};
const LEGACY_SCHEMA: &str = include_str!(
"../../../../macro_db_client/migrations/20260126170641_create_notification_tables.sql"
@@ -33,12 +33,18 @@ async fn migration_normalizes_legacy_states_without_changing_timestamps(
('invalid', '00000000-0000-0000-0000-000000000001', true, NULL, false, '2020-01-03', '2020-01-01');",
).execute(&pool).await?;
+ // One connection for the round-trip: DROP TYPE + CREATE TYPE assigns a new
+ // OID, and a pooled connection would otherwise reuse a prepared SELECT whose
+ // result type still names the dropped enum ("cached plan must not change
+ // result type").
+ let mut conn = pool.acquire().await?;
for _ in 0..2 {
- sqlx::raw_sql(UP).execute(&pool).await?;
+ sqlx::raw_sql(UP).execute(&mut *conn).await?;
+ conn.clear_cached_statements().await?;
let rows = sqlx::query!(
r#"SELECT user_id, state as "state!: NotificationState", seen_at, sent, deleted_at, created_at
FROM user_notification ORDER BY user_id"#,
- ).fetch_all(&pool).await?;
+ ).fetch_all(&mut *conn).await?;
assert_eq!(rows.len(), 4);
for row in rows {
assert_eq!(row.created_at.to_string(), "2020-01-01 00:00:00");
@@ -64,7 +70,7 @@ async fn migration_normalizes_legacy_states_without_changing_timestamps(
_ => panic!("unexpected fixture row"),
}
}
- sqlx::raw_sql(DOWN).execute(&pool).await?;
+ sqlx::raw_sql(DOWN).execute(&mut *conn).await?;
}
Ok(())
}
diff --git a/crates/roles_and_permissions/src/domain/model.rs b/crates/roles_and_permissions/src/domain/model.rs
index f81d9b6b66..0043472282 100644
--- a/crates/roles_and_permissions/src/domain/model.rs
+++ b/crates/roles_and_permissions/src/domain/model.rs
@@ -3,15 +3,38 @@
use std::{fmt::Display, str::FromStr};
/// The product tier the user is on
-#[derive(Debug, Default)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ProductTier {
/// Haiku tier - default
#[default]
Haiku,
/// Sonnet tier
Sonnet,
- /// Opus tier
+ /// Opus tier (the Premium plan)
Opus,
+ /// Max tier (the Max plan): the Premium entitlements with a larger
+ /// monthly AI allowance.
+ Max,
+}
+
+impl ProductTier {
+ /// Every tier, cheapest first.
+ pub const ALL: [ProductTier; 4] = [
+ ProductTier::Haiku,
+ ProductTier::Sonnet,
+ ProductTier::Opus,
+ ProductTier::Max,
+ ];
+
+ /// The subscription role that records this tier on a user.
+ pub fn role(&self) -> RoleId {
+ match self {
+ ProductTier::Haiku => RoleId::SubHaiku,
+ ProductTier::Sonnet => RoleId::SubSonnet,
+ ProductTier::Opus => RoleId::SubOpus,
+ ProductTier::Max => RoleId::SubMax,
+ }
+ }
}
impl Display for ProductTier {
@@ -20,6 +43,7 @@ impl Display for ProductTier {
ProductTier::Haiku => write!(f, "haiku"),
ProductTier::Sonnet => write!(f, "sonnet"),
ProductTier::Opus => write!(f, "opus"),
+ ProductTier::Max => write!(f, "max"),
}
}
}
@@ -59,6 +83,8 @@ pub enum RoleId {
SubSonnet,
/// The user is subscribed to opus plan
SubOpus,
+ /// The user is subscribed to the Max plan
+ SubMax,
}
impl FromStr for RoleId {
@@ -81,6 +107,7 @@ impl FromStr for RoleId {
"sub_haiku" => Ok(RoleId::SubHaiku),
"sub_sonnet" => Ok(RoleId::SubSonnet),
"sub_opus" => Ok(RoleId::SubOpus),
+ "sub_max" => Ok(RoleId::SubMax),
_ => anyhow::bail!("unknown role id: {s}"),
}
}
@@ -105,6 +132,7 @@ impl Display for RoleId {
RoleId::SubHaiku => write!(f, "sub_haiku"),
RoleId::SubSonnet => write!(f, "sub_sonnet"),
RoleId::SubOpus => write!(f, "sub_opus"),
+ RoleId::SubMax => write!(f, "sub_max"),
}
}
}
@@ -120,6 +148,7 @@ impl RoleId {
| Self::SubHaiku
| Self::SubSonnet
| Self::SubOpus
+ | Self::SubMax
)
}
}
diff --git a/crates/roles_and_permissions/src/domain/model/test.rs b/crates/roles_and_permissions/src/domain/model/test.rs
index d5b0383c20..d360867c48 100644
--- a/crates/roles_and_permissions/src/domain/model/test.rs
+++ b/crates/roles_and_permissions/src/domain/model/test.rs
@@ -9,6 +9,7 @@ fn paid_subscription_roles_include_legacy_and_pricing_tiers() {
RoleId::SubHaiku,
RoleId::SubSonnet,
RoleId::SubOpus,
+ RoleId::SubMax,
] {
assert!(
role.is_paid_subscription(),
@@ -31,3 +32,9 @@ fn non_subscription_roles_do_not_grant_paid_access() {
);
}
}
+
+#[test]
+fn max_role_roundtrips_through_its_string_id() {
+ assert_eq!(RoleId::SubMax.to_string(), "sub_max");
+ assert_eq!("sub_max".parse::<RoleId>().unwrap(), RoleId::SubMax);
+}
diff --git a/crates/roles_and_permissions/src/domain/service.rs b/crates/roles_and_permissions/src/domain/service.rs
index 7dd0313bf1..c36edd83fd 100644
--- a/crates/roles_and_permissions/src/domain/service.rs
+++ b/crates/roles_and_permissions/src/domain/service.rs
@@ -50,18 +50,24 @@ where
) -> Result<(), UserRolesAndPermissionsError> {
let user_id = self.user_repository.get_user_id_by_email(&email).await?;
- let sub_role = match product_tier {
- ProductTier::Haiku => RoleId::SubHaiku,
- ProductTier::Sonnet => RoleId::SubSonnet,
- ProductTier::Opus => RoleId::SubOpus,
- };
+ let sub_role = product_tier.role();
- let roles = [RoleId::ProfessionalSubscriber, sub_role];
+ let roles = [RoleId::ProfessionalSubscriber, sub_role.clone()];
match subscription_status {
SubscriptionStatus::Active => {
self.user_roles_and_permissions_repository
.add_roles_to_user(&user_id, &roles)
+ .await?;
+ // A plan change (Premium <-> Max) arrives as an activation of the
+ // new tier; drop the other tier roles so exactly one tier remains.
+ let other_tiers: Vec<RoleId> = ProductTier::ALL
+ .iter()
+ .map(ProductTier::role)
+ .filter(|role| *role != sub_role)
+ .collect();
+ self.user_roles_and_permissions_repository
+ .remove_roles_from_user(&user_id, &other_tiers)
.await
}
SubscriptionStatus::Canceled
diff --git a/crates/roles_and_permissions/src/domain/service/test.rs b/crates/roles_and_permissions/src/domain/service/test.rs
index c51ee0b8fe..e653157f2d 100644
--- a/crates/roles_and_permissions/src/domain/service/test.rs
+++ b/crates/roles_and_permissions/src/domain/service/test.rs
@@ -155,10 +155,44 @@ async fn test_user_respository_get_user_id_by_email() -> anyhow::Result<()> {
)
.await?;
+ // One removal for the sibling tiers on activation, one for the pause.
assert_eq!(
mock_user_roles_and_permissions_repository.get_remove_roles_from_user_calls(),
+ 2
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn activating_a_tier_removes_the_other_tier_roles() -> anyhow::Result<()> {
+ let mock_user_repository = MockUserRepository::default();
+ let mock_user_roles_and_permissions_repository =
+ MockUserRolesAndPermissionsRepository::default();
+
+ let user_service = UserRolesAndPermissionsServiceImpl::new(
+ mock_user_roles_and_permissions_repository.clone(),
+ mock_user_repository,
+ );
+
+ user_service
+ .update_user_roles_and_permissions_for_subscription(
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ SubscriptionStatus::Active,
+ ProductTier::Max,
+ )
+ .await?;
+
+ assert_eq!(
+ mock_user_roles_and_permissions_repository.get_add_roles_to_user_calls(),
1
);
+ let removed = mock_user_roles_and_permissions_repository.get_removed_roles_from_user_calls();
+ assert_eq!(removed.len(), 1);
+ assert!(removed[0].contains(&RoleId::SubOpus));
+ assert!(removed[0].contains(&RoleId::SubSonnet));
+ assert!(removed[0].contains(&RoleId::SubHaiku));
+ assert!(!removed[0].contains(&RoleId::SubMax));
+ assert!(!removed[0].contains(&RoleId::ProfessionalSubscriber));
Ok(())
}
diff --git a/crates/teams/src/domain/customer_repo.rs b/crates/teams/src/domain/customer_repo.rs
index 008dd81099..24bd2ad529 100644
--- a/crates/teams/src/domain/customer_repo.rs
+++ b/crates/teams/src/domain/customer_repo.rs
@@ -2,9 +2,13 @@
use macro_user_id::user_id::MacroUserIdStr;
-use crate::domain::model::CustomerError;
+use crate::domain::model::{CustomerError, SeatPlan};
/// The CustomerRepository defines a set of actions to perform on customer data
+///
+/// A team subscription carries one seat item per [`SeatPlan`] in use, each
+/// 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 {
/// Mark subscription as a team subscription
fn convert_subscription_to_team(
@@ -20,22 +24,35 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {
customer_id: &stripe::CustomerId,
) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;
- /// Increment the seat count on a subscription by the provided amount.
+ /// Add `amount` seats on `plan` to a subscription.
fn increment_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
- /// Decrement the seat count on a subscription by the provided amount.
+ /// Remove `amount` seats on `plan` from a subscription.
///
- /// Implementations must not let the resulting seat count drop below one.
+ /// Implementations must not let the subscription's total seat count
+ /// drop below one.
fn decrement_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
+ /// Move one seat from `from` to `to`, invoicing the proration at once.
+ /// Both items change in a single update so the customer sees one
+ /// adjustment.
+ fn move_seat(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ from: SeatPlan,
+ to: SeatPlan,
+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;
+
/// Cancels a subscription immediately.
fn cancel_subscription(
&self,
diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rs
index fd0869c7fd..2e6621ddd4 100644
--- a/crates/teams/src/domain/model.rs
+++ b/crates/teams/src/domain/model.rs
@@ -1,11 +1,13 @@
//! Contains the models for teams
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use chrono::{DateTime, Utc};
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
+use macro_user_id::{
+ cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
+};
use models_permissions::share_permission::LinkShare;
-use roles_and_permissions::domain::model::UserRolesAndPermissionsError;
+use roles_and_permissions::domain::model::{ProductTier, RoleId, UserRolesAndPermissionsError};
/// Team plans
#[derive(
@@ -132,6 +134,119 @@ impl std::fmt::Display for TeamRole {
}
}
+/// 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
+/// plan in use.
+#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
+#[cfg_attr(
+ feature = "outbound",
+ sqlx(type_name = "\"seat_plan\"", rename_all = "snake_case")
+)]
+#[serde(rename_all = "snake_case")]
+pub enum SeatPlan {
+ /// The $40/seat/month plan.
+ Premium,
+ /// The $200/seat/month plan with a 5x AI allowance.
+ Max,
+}
+
+impl SeatPlan {
+ /// Every plan.
+ pub const ALL: [SeatPlan; 2] = [SeatPlan::Premium, SeatPlan::Max];
+
+ /// The role tier recorded on a user holding this seat.
+ pub fn product_tier(self) -> ProductTier {
+ match self {
+ SeatPlan::Premium => ProductTier::Opus,
+ SeatPlan::Max => ProductTier::Max,
+ }
+ }
+
+ /// The subscription role that records this seat's tier on a user.
+ pub fn role(self) -> RoleId {
+ self.product_tier().role()
+ }
+
+ /// The tier roles of every other plan, to drop when a seat moves here.
+ pub fn other_tier_roles(self) -> Vec<RoleId> {
+ let keep = self.role();
+ ProductTier::ALL
+ .iter()
+ .map(ProductTier::role)
+ .filter(|role| *role != keep)
+ .collect()
+ }
+
+ /// The plan a user's roles say they are on. `sub_max` wins; any other
+ /// (or no) paid role is Premium, the plan every seat starts on.
+ pub fn from_roles(roles: &HashSet<RoleId>) -> Self {
+ if roles.contains(&RoleId::SubMax) {
+ SeatPlan::Max
+ } else {
+ SeatPlan::Premium
+ }
+ }
+}
+
+impl std::fmt::Display for SeatPlan {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ SeatPlan::Premium => write!(f, "premium"),
+ SeatPlan::Max => write!(f, "max"),
+ }
+ }
+}
+
+/// The Stripe price ids behind each plan's per-seat subscription item.
+#[derive(Debug, Clone)]
+pub struct SeatPrices {
+ /// Premium seat price.
+ pub premium: String,
+ /// Max seat price, when the plan is sold.
+ pub max: Option<String>,
+}
+
+impl SeatPrices {
+ /// The price a seat on `plan` is billed at.
+ pub fn price_id(&self, plan: SeatPlan) -> Result<&str, CustomerError> {
+ match plan {
+ SeatPlan::Premium => Ok(&self.premium),
+ SeatPlan::Max => self
+ .max
+ .as_deref()
+ .ok_or(CustomerError::PlanUnavailable(plan)),
+ }
+ }
+
+ /// Which plan a subscription item's price belongs to, if any.
+ pub fn plan_for_price(&self, price_id: &str) -> Option<SeatPlan> {
+ if price_id == self.premium {
+ Some(SeatPlan::Premium)
+ } else if self.max.as_deref() == Some(price_id) {
+ Some(SeatPlan::Max)
+ } else {
+ None
+ }
+ }
+
+ /// Every price that carries a seat item.
+ pub fn all(&self) -> Vec<String> {
+ std::iter::once(self.premium.clone())
+ .chain(self.max.clone())
+ .collect()
+ }
+}
+
+/// Request body for `PATCH /team/members/{member_user_id}/plan`.
+#[derive(Debug, Clone, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct PatchTeamMemberPlanRequest {
+ /// The plan to bill the member's seat at from now on.
+ pub plan: SeatPlan,
+}
+
/// The team member struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -143,6 +258,21 @@ pub struct TeamMember<'a> {
pub user_id: MacroUserIdStr<'a>,
/// The role of the team member
pub role: TeamRole,
+ /// The paid plan the member's seat is billed at. Meaningful on paying
+ /// and enterprise teams; free-team members carry the default.
+ pub plan: SeatPlan,
+}
+
+impl TeamMember<'_> {
+ /// Detach the member from any borrowed user id.
+ pub fn into_owned(self) -> TeamMember<'static> {
+ TeamMember {
+ team_id: self.team_id,
+ user_id: self.user_id.into_owned(),
+ role: self.role,
+ plan: self.plan,
+ }
+ }
}
/// A team with its members
@@ -586,11 +716,31 @@ pub enum CustomerError {
/// No subscription line item matched the configured Stripe price id.
#[error("No matching line item")]
NoMatchingLineItem,
+ /// The plan has no Stripe price configured.
+ #[error("The {0} plan is not available")]
+ PlanUnavailable(SeatPlan),
/// Storage layer error
#[error("Storage layer error {0}")]
StorageLayerError(#[from] anyhow::Error),
}
+/// Errors for moving a team member between seat plans.
+#[derive(Debug, thiserror::Error)]
+pub enum SetTeamMemberPlanError {
+ /// Seat plans only apply to paying (or enterprise) teams.
+ #[error("The team has no active subscription")]
+ TeamNotPaying,
+ /// Underlying team error
+ #[error("{0}")]
+ TeamError(#[from] TeamError),
+ /// Underlying customer error
+ #[error("{0}")]
+ CustomerError(#[from] CustomerError),
+ /// Roles could not be updated
+ #[error("Roles error: {0}")]
+ RolesError(#[from] UserRolesAndPermissionsError),
+}
+
/// Errors for removing a team invite
#[derive(Debug, thiserror::Error)]
pub enum RemoveTeamInviteError {
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index f9404a381c..84ac210da5 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -10,9 +10,10 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr
use crate::domain::model::{
AcceptedTeamInvite, CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
- RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
- TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
- ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, SeatPlan,
+ SetTeamMemberPlanError, Team, TeamError, TeamInvite, TeamInviteDetails, TeamMember,
+ TeamMembers, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,
+ TryJoinTeamByDomainError,
};
/// The TeamRepository defines a set of actions to perform on teams data
@@ -48,13 +49,15 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<bool, TeamError>> + Send;
/// Creates a new team with the provided normalized slug. `subscription_id` is `None` for
- /// free teams. Membership is not capped by team size.
+ /// free teams. Membership is not capped by team size. `owner_plan` is the plan the owner's
+ /// own seat is already billed at.
fn create_team(
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
+ owner_plan: SeatPlan,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
/// Moves any user-owned GitHub App installation rows to the given team.
@@ -237,6 +240,14 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_role: TeamRole,
) -> impl Future<Output = Result<(), TeamError>> + Send;
+ /// Records the plan the provided member's seat is billed at.
+ fn patch_team_member_plan(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ plan: SeatPlan,
+ ) -> impl Future<Output = Result<(), TeamError>> + Send;
+
/// Get the teams current seat count
fn get_team_seat_count(
&self,
@@ -404,6 +415,26 @@ pub trait TeamService: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
) -> impl Future<Output = Result<(), RestorePermissionsForTeamMembersError>> + Send;
+ /// Moves a member's seat to `plan`: swaps the seat between the team
+ /// subscription's per-plan items (invoicing the proration now), records
+ /// the plan on the membership, and re-stamps the member's tier role.
+ /// Team admins and above only; the team must be paying or enterprise.
+ /// Returns the member as they now stand; a no-op when already on `plan`.
+ fn set_team_member_plan(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
+ user_id: &MacroUserIdStr<'_>,
+ plan: SeatPlan,
+ ) -> impl Future<Output = Result<TeamMember<'static>, SetTeamMemberPlanError>> + Send;
+
+ /// Whether the team's seats are billed per plan through the team: a
+ /// paying team with a subscription, or an enterprise team. On a free team
+ /// every member pays for themself and seat plans do not apply.
+ fn team_bills_per_seat(
+ &self,
+ team_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;
+
/// Patches the team subscription id
/// NOTE: this is not exposed via axum and is meant for internal usage within stripe webhook only.
fn patch_team_subscription_id(
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index cf4f14081d..9aebf57e07 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -3,7 +3,10 @@
#[cfg(test)]
mod test;
-use std::{collections::HashSet, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::{Arc, LazyLock, Mutex, Weak},
+};
use channels::domain::{
models::{ChannelType, CreateChannelRequest, Sender},
@@ -42,15 +45,53 @@ use crate::domain::{
CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError,
RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,
- RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamMembers, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,
- TryJoinTeamByDomainError, is_generic_email_domain, team_slug_from_name,
+ RevokePermissionsForTeamMembersError, SeatPlan, SetTeamMemberPlanError, Team, TeamError,
+ TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamRole, TeamWithMembers,
+ ToggleAutoJoinDomainError, TryJoinTeamByDomainError, is_generic_email_domain,
+ team_slug_from_name,
},
team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},
team_crm_settings_repo::TeamCrmSettingsRepository,
team_repo::{TeamMembersService, TeamRepository, TeamService},
};
+/// The roles a member of a paying or enterprise team holds: the team
+/// subscriber role plus the tier role of their seat's plan.
+fn team_member_roles_to_add(plan: SeatPlan) -> Vec<RoleId> {
+ vec![RoleId::TeamSubscriber, plan.role()]
+}
+
+/// The roles stripped when a member leaves a team or its subscription lapses:
+/// the team subscriber role and every seat plan's tier role.
+fn team_member_roles_to_remove() -> Vec<RoleId> {
+ std::iter::once(RoleId::TeamSubscriber)
+ .chain(SeatPlan::ALL.iter().map(|plan| plan.role()))
+ .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
+}
+
/// Implementation of the TeamService using a TeamRepository
#[derive(Debug)]
pub struct TeamServiceImpl<
@@ -569,9 +610,18 @@ where
// happens later, on the disabled → enabled transition in
// `set_team_crm_enabled`.
let team_slug = team_slug_from_name(team_name);
+ // The owner's seat is already billed on their personal subscription;
+ // the tier role the Stripe webhook stamped says at which plan.
+ let owner_plan = SeatPlan::from_roles(
+ &self
+ .user_roles_and_permissions_service
+ .get_user_roles(user_id)
+ .await
+ .map_err(|e| CreateTeamError::StorageLayerError(e.into()))?,
+ );
let team = self
.team_repository
- .create_team(user_id, team_name, &team_slug, subscription_id)
+ .create_team(user_id, team_name, &team_slug, subscription_id, owner_plan)
.await?;
let owner_id = user_id.clone().into_owned();
self.channel_service
@@ -850,7 +900,7 @@ where
if let Some(subscription_id) = subscription_id.as_ref()
&& let Err(e) = self
.customer_repository
- .decrement_seat_count(subscription_id, 1)
+ .decrement_seat_count(subscription_id, removed_member.plan, 1)
.await
{
self.team_repository
@@ -875,7 +925,7 @@ where
Err(error) => {
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .increment_seat_count(subscription_id, 1)
+ .increment_seat_count(subscription_id, removed_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
@@ -901,7 +951,7 @@ where
}
};
- let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles_to_remove = team_member_roles_to_remove();
let roles = non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap();
if let Err(e) = self
@@ -921,7 +971,7 @@ where
.ok();
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .increment_seat_count(subscription_id, 1)
+ .increment_seat_count(subscription_id, removed_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
@@ -1248,7 +1298,7 @@ where
Some(subscription_id) => {
if let Err(e) = self
.customer_repository
- .increment_seat_count(&subscription_id, 1)
+ .increment_seat_count(&subscription_id, team_member.plan, 1)
.await
{
self.team_repository
@@ -1272,7 +1322,7 @@ where
// Premium roles come with a paid or enterprise team; free-team
// members keep their existing (free) entitlements.
let grants_premium = enterprise || subscription_id.is_some();
- let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles_to_add = team_member_roles_to_add(team_member.plan);
if grants_premium {
// subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier
@@ -1285,7 +1335,7 @@ where
{
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .decrement_seat_count(subscription_id, 1)
+ .decrement_seat_count(subscription_id, team_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
@@ -1329,7 +1379,7 @@ where
}
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .decrement_seat_count(subscription_id, 1)
+ .decrement_seat_count(subscription_id, team_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
@@ -1409,7 +1459,7 @@ where
}
for member in members {
- let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles_to_remove = team_member_roles_to_remove();
self.user_roles_and_permissions_service
.dangerous_remove_roles_from_user(
@@ -1435,18 +1485,185 @@ where
}
for member in members {
- let roles = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ 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(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn team_bills_per_seat(&self, team_id: &uuid::Uuid) -> Result<bool, TeamError> {
+ if self
+ .team_repository
+ .get_team_enterprise_status(team_id)
+ .await?
+ {
+ return Ok(true);
+ }
+ let paying = self
+ .team_repository
+ .get_team_payment_status(team_id)
+ .await?;
+ let subscribed = self
+ .team_repository
+ .get_team_subscription_id(team_id)
+ .await?
+ .is_some();
+ Ok(paying && subscribed)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn set_team_member_plan(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
+ user_id: &MacroUserIdStr<'_>,
+ plan: SeatPlan,
+ ) -> 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;
+ let changed_by = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|e| SetTeamMemberPlanError::TeamError(TeamError::AccessError(e)))?
+ .clone()
+ .into_owned();
+
+ let member = self
+ .team_repository
+ .get_team_member(&team_id, user_id)
+ .await?
+ .into_owned();
+ if member.plan == plan {
+ return Ok(member);
+ }
+
+ // Seat plans only mean something on a team that is billed per seat:
+ // paying teams move the seat on Stripe, enterprise teams (billed out
+ // of band) only record it and re-stamp the tier role.
+ let enterprise = self
+ .team_repository
+ .get_team_enterprise_status(&team_id)
+ .await?;
+ let subscription_id = if enterprise {
+ None
+ } else {
+ let paying = self
+ .team_repository
+ .get_team_payment_status(&team_id)
+ .await?;
+ let subscription_id = self
+ .team_repository
+ .get_team_subscription_id(&team_id)
+ .await?;
+ match subscription_id {
+ Some(subscription_id) if paying => Some(subscription_id),
+ _ => return Err(SetTeamMemberPlanError::TeamNotPaying),
+ }
+ };
+
+ if let Some(subscription_id) = subscription_id.as_ref() {
+ self.customer_repository
+ .move_seat(subscription_id, member.plan, plan)
+ .await?;
+ }
+
+ if let Err(e) = self
+ .team_repository
+ .patch_team_member_plan(&team_id, user_id, plan)
+ .await
+ {
+ if let Some(subscription_id) = subscription_id.as_ref() {
+ self.customer_repository
+ .move_seat(subscription_id, plan, member.plan)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback seat move after recording the member plan failed"
+ );
+ })
+ .ok();
+ }
+ return Err(e.into());
+ }
+
+ // Swap the tier role so the paid-model permission and the AI
+ // 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 {
+ self.user_roles_and_permissions_service
+ .dangerous_upsert_roles_for_user(
+ user_id,
+ non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap(),
+ )
+ .await?;
+ 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(user_id, &stale_tier_roles)
+ .await?;
+ }
+ Ok::<(), roles_and_permissions::domain::model::UserRolesAndPermissionsError>(())
+ }
+ .await;
+ if let Err(e) = role_result {
+ self.team_repository
+ .patch_team_member_plan(&team_id, user_id, member.plan)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback member plan after updating tier roles failed"
+ );
+ })
+ .ok();
+ if let Some(subscription_id) = subscription_id.as_ref() {
+ self.customer_repository
+ .move_seat(subscription_id, plan, member.plan)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback seat move after updating tier roles failed"
+ );
+ })
+ .ok();
+ }
+ return Err(e.into());
+ }
+
+ tracing::info!(
+ %team_id,
+ member = %user_id,
+ %changed_by,
+ from = %member.plan,
+ to = %plan,
+ "moved team member seat plan"
+ );
+
+ Ok(TeamMember { plan, ..member })
+ }
+
#[tracing::instrument(skip(self), err)]
async fn patch_team_subscription_id(
&self,
@@ -1810,7 +2027,7 @@ where
Some(subscription_id) => {
if let Err(e) = self
.customer_repository
- .increment_seat_count(&subscription_id, 1)
+ .increment_seat_count(&subscription_id, team_member.plan, 1)
.await
{
self.rollback_add_user_to_team(
@@ -1830,7 +2047,7 @@ where
// Premium roles come with a paid or enterprise team; free-team
// members keep their existing (free) entitlements.
let grants_premium = enterprise || subscription_id.is_some();
- let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles_to_add = team_member_roles_to_add(team_member.plan);
if grants_premium {
// subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier
@@ -1843,7 +2060,7 @@ where
{
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .decrement_seat_count(subscription_id, 1)
+ .decrement_seat_count(subscription_id, team_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
@@ -1879,7 +2096,7 @@ where
}
if let Some(subscription_id) = subscription_id.as_ref() {
self.customer_repository
- .decrement_seat_count(subscription_id, 1)
+ .decrement_seat_count(subscription_id, team_member.plan, 1)
.await
.inspect_err(|rollback_err| {
tracing::error!(
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index f1d4c86d43..4fd4d35bbe 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -59,9 +59,9 @@ use crate::domain::{
customer_repo::CustomerRepository,
model::{
AcceptedTeamInvite, CustomerError, PatchTeamRequest, PatchTeamUserRole,
- RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
- TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
- ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
+ RemoveTeamInviteError, RemoveUserFromTeamError, SeatPlan, SetTeamMemberPlanError, Team,
+ TeamError, TeamInvite, TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan,
+ TeamRole, TeamWithMembers, ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
},
team_repo::TeamRepository,
};
@@ -99,6 +99,8 @@ struct MockTeamRepository {
fail_rollback_remove: bool,
patch_team_user_role_calls: Arc<Mutex<Vec<(uuid::Uuid, String, TeamRole)>>>,
fail_patch_team_user_role_at: Option<usize>,
+ patch_team_member_plan_calls: Arc<Mutex<Vec<(uuid::Uuid, String, SeatPlan)>>>,
+ fail_patch_team_member_plan: bool,
patch_team_name_calls: Arc<Mutex<Vec<(uuid::Uuid, Option<String>, Option<String>)>>>,
fail_patch_team: bool,
created_team: Team,
@@ -163,6 +165,8 @@ impl MockTeamRepository {
fail_rollback_accept: false,
fail_rollback_remove: false,
patch_team_user_role_calls: Arc::new(Mutex::new(Vec::new())),
+ patch_team_member_plan_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_patch_team_member_plan: false,
fail_patch_team_user_role_at: None,
patch_team_name_calls: Arc::new(Mutex::new(Vec::new())),
fail_patch_team: false,
@@ -315,6 +319,7 @@ impl TeamRepository for MockTeamRepository {
team_name: &str,
team_slug: &str,
_: Option<&stripe::SubscriptionId>,
+ _: SeatPlan,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {
self.create_team_calls
.lock()
@@ -640,10 +645,39 @@ impl TeamRepository for MockTeamRepository {
fn get_team_member(
&self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<TeamMember<'_>, TeamError>> + Send {
- async { unimplemented!() }
+ let member = self
+ .team_members
+ .iter()
+ .find(|member| member.user_id.as_ref() == user_id.as_ref())
+ .cloned();
+ let team_id = *team_id;
+ async move { member.ok_or(TeamError::TeamMemberNotFound(team_id)) }
+ }
+
+ fn patch_team_member_plan(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ plan: SeatPlan,
+ ) -> impl Future<Output = Result<(), TeamError>> + Send {
+ self.patch_team_member_plan_calls.lock().unwrap().push((
+ *team_id,
+ user_id.as_ref().to_string(),
+ plan,
+ ));
+ let fail = self.fail_patch_team_member_plan;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "plan patch failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn patch_team_user_role(
@@ -772,6 +806,9 @@ struct MockCustomerRepository {
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)>>>,
+ fail_move_seat: bool,
convert_calls: Arc<Mutex<Vec<(String, uuid::Uuid, String)>>>,
subscription_lookup_calls: Arc<Mutex<usize>>,
fail_increment: bool,
@@ -785,6 +822,9 @@ impl Default for MockCustomerRepository {
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())),
+ fail_move_seat: false,
convert_calls: Arc::new(Mutex::new(Vec::new())),
subscription_lookup_calls: Arc::new(Mutex::new(0)),
fail_increment: false,
@@ -828,12 +868,17 @@ impl CustomerRepository for MockCustomerRepository {
fn increment_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send {
self.increment_calls
.lock()
.unwrap()
.push((subscription_id.to_string(), amount));
+ self.seat_plan_calls
+ .lock()
+ .unwrap()
+ .push((subscription_id.to_string(), plan, amount));
let fail = self.fail_increment;
async move {
if fail {
@@ -849,12 +894,17 @@ impl CustomerRepository for MockCustomerRepository {
fn decrement_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send {
self.decrement_calls
.lock()
.unwrap()
.push((subscription_id.to_string(), amount));
+ self.seat_plan_calls
+ .lock()
+ .unwrap()
+ .push((subscription_id.to_string(), plan, amount));
let fail = self.fail_decrement;
async move {
if fail {
@@ -867,6 +917,28 @@ impl CustomerRepository for MockCustomerRepository {
}
}
+ fn move_seat(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ from: SeatPlan,
+ to: SeatPlan,
+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {
+ self.move_seat_calls
+ .lock()
+ .unwrap()
+ .push((subscription_id.to_string(), from, to));
+ let fail = self.fail_move_seat;
+ async move {
+ if fail {
+ Err(CustomerError::StorageLayerError(anyhow::anyhow!(
+ "move seat failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
+ }
+
fn cancel_subscription(
&self,
_: &stripe::SubscriptionId,
@@ -1091,7 +1163,7 @@ impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {
&self,
_: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<HashSet<RoleId>, UserRolesAndPermissionsError>> + Send {
- async { unimplemented!() }
+ async { Ok(HashSet::new()) }
}
fn get_user_permissions(
@@ -1341,6 +1413,7 @@ fn make_team_member(team_id: uuid::Uuid, user_id: &str, role: TeamRole) -> TeamM
.unwrap()
.into_owned(),
role,
+ plan: SeatPlan::Premium,
}
}
@@ -1366,6 +1439,7 @@ fn make_accepted_invite(
team_id,
user_id: user_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
},
invite: TeamInviteSnapshot {
id: invite_id,
@@ -1408,6 +1482,7 @@ fn make_enterprise_domain_join_team_repository(
team_id,
user_id: user_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
};
let mut team_repository =
MockTeamRepository::new(Vec::new(), "Enterprise Team", mark_sent_calls)
@@ -1446,6 +1521,7 @@ fn make_enterprise_remove_user_repository(
team_id,
user_id: user_id.clone().into_owned(),
role,
+ plan: SeatPlan::Premium,
});
team_repository
}
@@ -1902,7 +1978,7 @@ async fn team_payment_revoke_removes_exact_premium_roles_from_members() {
make_team_member(team_id, "macro|[email protected]", TeamRole::Member),
make_team_member(team_id, "macro|[email protected]", TeamRole::Admin),
];
- let expected_roles = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let expected_roles = vec![RoleId::TeamSubscriber, RoleId::SubOpus, RoleId::SubMax];
let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
.with_team_members(members);
@@ -1975,6 +2051,223 @@ async fn team_payment_restore_adds_exact_premium_roles_to_members() {
);
}
+fn build_member_plan_service(
+ team_repo: MockTeamRepository,
+ customer_repo: MockCustomerRepository,
+ roles_service: MockUserRolesAndPermissionsService,
+) -> impl TeamService {
+ TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ RecordingChannelService::default(),
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+}
+
+#[tokio::test]
+async fn set_team_member_plan_moves_seat_records_plan_and_swaps_tier_role() {
+ 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]";
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .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_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 member = 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!(member.plan, SeatPlan::Max);
+ assert_eq!(member.role, TeamRole::Member);
+ assert_eq!(
+ *move_calls.lock().unwrap(),
+ vec![("sub_team".to_string(), SeatPlan::Premium, SeatPlan::Max)]
+ );
+ assert_eq!(
+ *plan_calls.lock().unwrap(),
+ vec![(team_id, member_id.to_string(), SeatPlan::Max)]
+ );
+ assert_eq!(
+ *upsert_calls.lock().unwrap(),
+ vec![(
+ member_id.to_string(),
+ vec![RoleId::TeamSubscriber, RoleId::SubMax]
+ )]
+ );
+ assert_eq!(
+ *remove_calls.lock().unwrap(),
+ vec![(
+ member_id.to_string(),
+ vec![RoleId::SubHaiku, RoleId::SubSonnet, RoleId::SubOpus]
+ )]
+ );
+}
+
+#[tokio::test]
+async fn set_team_member_plan_is_a_no_op_when_already_on_plan() {
+ let team_id = uuid::Uuid::from_u128(5101);
+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = "macro|[email protected]";
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .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 service = build_member_plan_service(
+ team_repo,
+ customer_repo,
+ MockUserRolesAndPermissionsService::default(),
+ );
+
+ let member = service
+ .set_team_member_plan(
+ test_team_receipt::<AdminTeamRole>(team_id, &admin_id),
+ &MacroUserIdStr::parse_from_str(member_id).unwrap(),
+ SeatPlan::Premium,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(member.plan, SeatPlan::Premium);
+ assert!(move_calls.lock().unwrap().is_empty());
+ assert!(plan_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn set_team_member_plan_rejects_free_teams() {
+ let team_id = uuid::Uuid::from_u128(5102);
+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = "macro|[email protected]";
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .with_team_members(vec![make_team_member(team_id, member_id, TeamRole::Member)]);
+ 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 service = build_member_plan_service(
+ team_repo,
+ customer_repo,
+ MockUserRolesAndPermissionsService::default(),
+ );
+
+ 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::TeamNotPaying));
+ assert!(move_calls.lock().unwrap().is_empty());
+ assert!(plan_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn set_team_member_plan_enterprise_skips_stripe_but_records_plan_and_roles() {
+ let team_id = uuid::Uuid::from_u128(5103);
+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = "macro|[email protected]";
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .with_team_members(vec![make_team_member(team_id, member_id, TeamRole::Member)]);
+ team_repo.enterprise = true;
+ 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_service = MockUserRolesAndPermissionsService::default();
+ let upsert_calls = roles_service.upsert_calls.clone();
+ let service = build_member_plan_service(team_repo, customer_repo, roles_service);
+
+ 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!(move_calls.lock().unwrap().is_empty());
+ assert_eq!(
+ *plan_calls.lock().unwrap(),
+ vec![(team_id, member_id.to_string(), SeatPlan::Max)]
+ );
+ assert_eq!(upsert_calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn set_team_member_plan_rolls_back_seat_move_when_recording_plan_fails() {
+ let team_id = uuid::Uuid::from_u128(5104);
+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = "macro|[email protected]";
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .with_team_members(vec![make_team_member(team_id, member_id, TeamRole::Member)]);
+ team_repo.team_subscription_id = Some("sub_team".parse().unwrap());
+ team_repo.fail_patch_team_member_plan = true;
+ let customer_repo = MockCustomerRepository::default();
+ let move_calls = customer_repo.move_seat_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let upsert_calls = roles_service.upsert_calls.clone();
+ let service = build_member_plan_service(team_repo, customer_repo, roles_service);
+
+ 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::TeamError(_)));
+ assert_eq!(
+ *move_calls.lock().unwrap(),
+ vec![
+ ("sub_team".to_string(), SeatPlan::Premium, SeatPlan::Max),
+ ("sub_team".to_string(), SeatPlan::Max, SeatPlan::Premium),
+ ]
+ );
+ assert!(upsert_calls.lock().unwrap().is_empty());
+}
+
+#[test]
+fn seat_plan_maps_to_tier_roles() {
+ assert_eq!(SeatPlan::Premium.role(), RoleId::SubOpus);
+ assert_eq!(SeatPlan::Max.role(), RoleId::SubMax);
+ assert!(!SeatPlan::Max.other_tier_roles().contains(&RoleId::SubMax));
+ assert!(SeatPlan::Max.other_tier_roles().contains(&RoleId::SubOpus));
+ assert_eq!(
+ SeatPlan::from_roles(&HashSet::from([RoleId::SubOpus])),
+ SeatPlan::Premium
+ );
+ assert_eq!(
+ SeatPlan::from_roles(&HashSet::from([RoleId::SubOpus, RoleId::SubMax])),
+ SeatPlan::Max
+ );
+ assert_eq!(SeatPlan::from_roles(&HashSet::new()), SeatPlan::Premium);
+}
+
#[tokio::test]
async fn team_payment_patch_payment_status_delegates_to_repository() {
let team_id = uuid::Uuid::from_u128(5002);
@@ -3030,6 +3323,7 @@ fn build_crm_enable_service(
team_id,
user_id: MacroUserIdStr::parse_from_str(id).unwrap().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
})
.collect();
let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
@@ -4259,6 +4553,7 @@ async fn test_remove_user_from_team_decrements_customer_seat_count() {
team_id,
user_id: member_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
});
team_repo.team_subscription_id = Some(subscription_id.clone());
let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
@@ -4321,6 +4616,7 @@ async fn team_analytics_remove_user_from_team_emits_left_event_with_team_id() {
team_id,
user_id: member_id.clone().into_owned(),
role: TeamRole::Admin,
+ plan: SeatPlan::Premium,
});
team_repo.team_subscription_id = Some(subscription_id.clone());
let customer_repo = MockCustomerRepository {
@@ -4411,6 +4707,7 @@ async fn test_remove_user_from_team_rolls_back_remove_when_customer_decrement_fa
team_id,
user_id: member_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
});
team_repo.team_subscription_id = Some(subscription_id.clone());
let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
@@ -4555,6 +4852,7 @@ async fn test_remove_user_from_team_rolls_back_customer_and_remove_when_channel_
team_id,
user_id: member_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
});
team_repo.team_subscription_id = Some(subscription_id.clone());
let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
@@ -4617,6 +4915,7 @@ async fn team_analytics_remove_user_from_team_does_not_emit_when_remove_is_rolle
team_id,
user_id: member_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
});
team_repo.team_subscription_id = Some(subscription_id.clone());
let customer_repo = MockCustomerRepository {
@@ -5203,7 +5502,7 @@ async fn remove_user_from_team_enterprise_bypasses_billing_and_preserves_side_ef
*roles_service.remove_calls.lock().unwrap(),
vec![(
member_id.as_ref().to_string(),
- vec![RoleId::TeamSubscriber, RoleId::SubOpus]
+ vec![RoleId::TeamSubscriber, RoleId::SubOpus, RoleId::SubMax]
)]
);
assert_eq!(
@@ -6101,6 +6400,7 @@ async fn try_join_team_by_domain_free_team_adds_sixth_member_without_billing_or_
team_id,
user_id: user_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
};
let mut team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);
team_repo.team_id_for_domain = Some(team_id);
diff --git a/crates/teams/src/inbound/axum_router.rs b/crates/teams/src/inbound/axum_router.rs
index 535ae1bb88..a294363653 100644
--- a/crates/teams/src/inbound/axum_router.rs
+++ b/crates/teams/src/inbound/axum_router.rs
@@ -22,6 +22,8 @@ pub mod join_team;
pub mod patch_team;
/// Enable / disable CRM for a team.
pub mod patch_team_crm_settings;
+/// Move a team member's seat between paid plans.
+pub mod patch_team_member_plan;
/// Extractor ensuring the authenticated user is premium.
pub mod premium_user;
/// Reject a team invitation.
@@ -51,8 +53,9 @@ use model_error_response::ErrorResponse;
use crate::domain::{
model::{
- CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
- RemoveTeamInviteError, RemoveUserFromTeamError, TeamError, ToggleAutoJoinDomainError,
+ CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
+ RemoveTeamInviteError, RemoveUserFromTeamError, SetTeamMemberPlanError, TeamError,
+ ToggleAutoJoinDomainError,
},
team_repo::TeamService,
};
@@ -134,6 +137,10 @@ where
"/remove/{remove_user_id}",
delete(remove_user_from_team::handler::<T, Eas, Auth>),
)
+ .route(
+ "/members/{member_user_id}/plan",
+ patch(patch_team_member_plan::handler::<T, Eas, Auth>),
+ )
.route(
"/invite/{team_invite_id}",
delete(delete_team_invite::handler::<T, Eas, Auth>),
@@ -327,6 +334,35 @@ impl IntoResponse for RemoveTeamInviteError {
}
}
+impl IntoResponse for SetTeamMemberPlanError {
+ fn into_response(self) -> Response {
+ match self {
+ SetTeamMemberPlanError::TeamNotPaying => (
+ StatusCode::PAYMENT_REQUIRED,
+ Json(ErrorResponse {
+ message: "the team has no active subscription".into(),
+ }),
+ )
+ .into_response(),
+ SetTeamMemberPlanError::CustomerError(CustomerError::PlanUnavailable(plan)) => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: format!("the {plan} plan is not available").into(),
+ }),
+ )
+ .into_response(),
+ SetTeamMemberPlanError::TeamError(e) => e.into_response(),
+ SetTeamMemberPlanError::CustomerError(_) | SetTeamMemberPlanError::RolesError(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "internal server error".into(),
+ }),
+ )
+ .into_response(),
+ }
+ }
+}
+
impl IntoResponse for RemoveUserFromTeamError {
fn into_response(self) -> Response {
match self {
diff --git a/crates/teams/src/inbound/axum_router/patch_team_member_plan.rs b/crates/teams/src/inbound/axum_router/patch_team_member_plan.rs
new file mode 100644
index 0000000000..69cc5356a5
--- /dev/null
+++ b/crates/teams/src/inbound/axum_router/patch_team_member_plan.rs
@@ -0,0 +1,61 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use entity_access::{
+ domain::{models::AdminTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractorV2,
+};
+use macro_authorization::MacroAuthorizationService;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_error_response::ErrorResponse;
+
+use crate::domain::{
+ model::{PatchTeamMemberPlanRequest, SetTeamMemberPlanError, TeamMember},
+ team_repo::TeamService,
+};
+
+use super::TeamRouterState;
+
+/// Path parameters for the member plan endpoint.
+#[derive(serde::Deserialize)]
+pub struct Param {
+ /// The member whose seat plan changes.
+ pub member_user_id: MacroUserIdStr<'static>,
+}
+
+/// Moves one team member's seat between paid plans.
+///
+/// Team admins and owners only. The team's subscription is re-billed for
+/// the seat at once (prorated); the member's tier role and individual AI
+/// allowance follow immediately.
+#[utoipa::path(
+ patch,
+ path = "/team/members/{member_user_id}/plan",
+ operation_id = "patch_team_member_plan",
+ params(
+ ("member_user_id" = String, Path, description = "The member whose seat plan changes")
+ ),
+ request_body = PatchTeamMemberPlanRequest,
+ responses(
+ (status = 200, body = TeamMember),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 402, description = "The team has no active subscription", body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(member = %member_user_id, plan = %req.plan))]
+pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: MacroUserTeamExtractorV2<AdminTeamRole, Eas, Auth>,
+ State(state): State<TeamRouterState<T, Eas, Auth>>,
+ Path(Param { member_user_id }): Path<Param>,
+ Json(req): Json<PatchTeamMemberPlanRequest>,
+) -> Result<Json<TeamMember<'static>>, SetTeamMemberPlanError> {
+ let member = state
+ .service
+ .set_team_member_plan(access.entity_access_receipt, &member_user_id, req.plan)
+ .await?;
+ Ok(Json(member))
+}
diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rs
index 63f746c20e..cb6eba169e 100644
--- a/crates/teams/src/inbound/axum_router/test.rs
+++ b/crates/teams/src/inbound/axum_router/test.rs
@@ -38,8 +38,9 @@ use crate::domain::{
CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError,
RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,
- RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamWithMembers, ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
+ RevokePermissionsForTeamMembersError, SeatPlan, SetTeamMemberPlanError, Team, TeamError,
+ TeamInvite, TeamInviteDetails, TeamMember, TeamWithMembers, ToggleAutoJoinDomainError,
+ TryJoinTeamByDomainError,
},
team_repo::TeamService,
};
@@ -367,6 +368,19 @@ impl TeamService for FakeTeamService {
panic!("unexpected patch_team call")
}
+ async fn set_team_member_plan(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
+ _user_id: &MacroUserIdStr<'_>,
+ _plan: SeatPlan,
+ ) -> Result<TeamMember<'static>, SetTeamMemberPlanError> {
+ panic!("unexpected set_team_member_plan call")
+ }
+
+ async fn team_bills_per_seat(&self, _team_id: &uuid::Uuid) -> Result<bool, TeamError> {
+ panic!("unexpected team_bills_per_seat call")
+ }
+
async fn get_team_user_permissions(
&self,
_user_id: &MacroUserIdStr<'_>,
diff --git a/crates/teams/src/outbound/customer_repo.rs b/crates/teams/src/outbound/customer_repo.rs
index 1b39cdd161..07bf397ae9 100644
--- a/crates/teams/src/outbound/customer_repo.rs
+++ b/crates/teams/src/outbound/customer_repo.rs
@@ -3,32 +3,44 @@
use std::{collections::HashMap, sync::Arc};
use anyhow::Context;
-use stripe::UpdateSubscription;
+use stripe::{UpdateSubscription, UpdateSubscriptionItems};
-use crate::domain::{customer_repo::CustomerRepository, model::CustomerError};
+use crate::domain::{
+ customer_repo::CustomerRepository,
+ model::{CustomerError, SeatPlan, SeatPrices},
+};
/// The CustomerRepositoryImpl struct is a wrapper around a stripe::Client connected to stripe.
#[derive(Clone)]
pub struct CustomerRepositoryImpl {
/// The underlying stripe::Client connected to stripe.
client: Arc<stripe::Client>,
- /// The stripe price id for the per-seat subscription item.
- stripe_price_id: String,
+ /// The Stripe price behind each plan's seat item. A team subscription
+ /// holds one item per plan its members are on.
+ seat_prices: SeatPrices,
+}
+
+/// One plan's seat item on a subscription.
+#[derive(Debug, Clone)]
+struct SeatItem {
+ id: String,
+ quantity: u64,
}
impl CustomerRepositoryImpl {
/// Creates a new instance of CustomerRepositoryImpl
- pub fn new(stripe_client: stripe::Client, stripe_price_id: String) -> Self {
+ pub fn new(stripe_client: stripe::Client, seat_prices: SeatPrices) -> Self {
Self {
client: Arc::new(stripe_client),
- stripe_price_id,
+ seat_prices,
}
}
- async fn get_seat_subscription_item(
+ /// The active subscription's seat items, keyed by plan.
+ async fn get_seat_items(
&self,
subscription_id: &stripe::SubscriptionId,
- ) -> Result<(String, u64), CustomerError> {
+ ) -> Result<HashMap<SeatPlan, SeatItem>, CustomerError> {
let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
.await
.map_err(|e| CustomerError::StorageLayerError(e.into()))?;
@@ -39,33 +51,64 @@ impl CustomerRepositoryImpl {
return Err(CustomerError::SubscriptionNotActive);
}
- let item = subscription
+ let items: HashMap<SeatPlan, SeatItem> = subscription
.items
.data
.iter()
- .find(|item| {
- item.price
- .as_ref()
- .map(|price| price.id == self.stripe_price_id)
- .unwrap_or(false)
+ .filter_map(|item| {
+ let price = item.price.as_ref()?;
+ let plan = self.seat_prices.plan_for_price(price.id.as_str())?;
+ Some((
+ plan,
+ SeatItem {
+ id: item.id.to_string(),
+ quantity: item.quantity.unwrap_or(1),
+ },
+ ))
})
- .ok_or(CustomerError::NoMatchingLineItem)?;
+ .collect();
+
+ if items.is_empty() {
+ return Err(CustomerError::NoMatchingLineItem);
+ }
- Ok((item.id.to_string(), item.quantity.unwrap_or(1)))
+ Ok(items)
}
- async fn update_seat_subscription_item(
+ /// The item update that leaves `plan` with `quantity` seats: a new item
+ /// when the plan had none, a deletion when it drops to zero.
+ fn seat_item_update(
&self,
- subscription_id: &stripe::SubscriptionId,
- subscription_item_id: String,
+ plan: SeatPlan,
+ existing: Option<&SeatItem>,
quantity: u64,
- ) -> Result<(), CustomerError> {
- let update_params = UpdateSubscription {
- items: Some(vec![stripe::UpdateSubscriptionItems {
- id: Some(subscription_item_id),
+ ) -> Result<UpdateSubscriptionItems, CustomerError> {
+ Ok(match existing {
+ Some(item) if quantity == 0 => UpdateSubscriptionItems {
+ id: Some(item.id.clone()),
+ deleted: Some(true),
+ ..Default::default()
+ },
+ Some(item) => UpdateSubscriptionItems {
+ id: Some(item.id.clone()),
quantity: Some(quantity),
..Default::default()
- }]),
+ },
+ None => UpdateSubscriptionItems {
+ price: Some(self.seat_prices.price_id(plan)?.to_string()),
+ quantity: Some(quantity),
+ ..Default::default()
+ },
+ })
+ }
+
+ async fn update_items(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ items: Vec<UpdateSubscriptionItems>,
+ ) -> Result<(), CustomerError> {
+ let update_params = UpdateSubscription {
+ items: Some(items),
proration_behavior: Some(
stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
),
@@ -85,30 +128,68 @@ impl CustomerRepository for CustomerRepositoryImpl {
async fn increment_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> Result<(), CustomerError> {
- let (subscription_item_id, current_quantity) =
- self.get_seat_subscription_item(subscription_id).await?;
- let quantity = current_quantity
+ let items = self.get_seat_items(subscription_id).await?;
+ let existing = items.get(&plan);
+ let quantity = existing
+ .map_or(0, |item| item.quantity)
.checked_add(amount)
.context("seat count overflow")?;
+ let update = self.seat_item_update(plan, existing, quantity)?;
- self.update_seat_subscription_item(subscription_id, subscription_item_id, quantity)
- .await
+ self.update_items(subscription_id, vec![update]).await
}
#[tracing::instrument(skip(self), err)]
async fn decrement_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ plan: SeatPlan,
amount: u64,
) -> Result<(), CustomerError> {
- let (subscription_item_id, current_quantity) =
- self.get_seat_subscription_item(subscription_id).await?;
- let quantity = current_quantity.saturating_sub(amount).max(1);
+ let items = self.get_seat_items(subscription_id).await?;
+ let Some(existing) = items.get(&plan) else {
+ return Err(CustomerError::NoMatchingLineItem);
+ };
+ let total: u64 = items.values().map(|item| item.quantity).sum();
+ // Never leave the subscription without a seat: the payer keeps one.
+ let removable = existing.quantity.min(total.saturating_sub(1));
+ let quantity = existing.quantity - amount.min(removable);
+ if quantity == existing.quantity {
+ return Ok(());
+ }
+ let update = self.seat_item_update(plan, Some(existing), quantity)?;
- self.update_seat_subscription_item(subscription_id, subscription_item_id, quantity)
- .await
+ self.update_items(subscription_id, vec![update]).await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn move_seat(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ from: SeatPlan,
+ to: SeatPlan,
+ ) -> Result<(), CustomerError> {
+ if from == to {
+ return Ok(());
+ }
+ // Make sure the target plan is sold before touching anything.
+ self.seat_prices.price_id(to)?;
+
+ let items = self.get_seat_items(subscription_id).await?;
+ let Some(source) = items.get(&from) else {
+ return Err(CustomerError::NoMatchingLineItem);
+ };
+ let target = items.get(&to);
+
+ let updates = vec![
+ self.seat_item_update(from, Some(source), source.quantity.saturating_sub(1))?,
+ self.seat_item_update(to, target, target.map_or(0, |item| item.quantity) + 1)?,
+ ];
+
+ self.update_items(subscription_id, updates).await
}
#[tracing::instrument(skip(self), err)]
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index 8c0d55f8e8..aa47bb665e 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -2,7 +2,7 @@
use crate::domain::{
model::{
AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,
- RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
+ RemoveTeamInviteError, RemoveUserFromTeamError, SeatPlan, Team, TeamError, TeamInvite,
TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamMembers, TeamPlan, TeamRole,
TeamWithMembers, ToggleAutoJoinDomainError, is_generic_email_domain, normalize_team_slug,
},
@@ -93,6 +93,7 @@ impl TeamRepositoryImpl {
team_name: &str,
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
+ owner_plan: SeatPlan,
) -> Result<Team, sqlx::Error> {
let mut transaction = self.pool.begin().await?;
@@ -134,11 +135,12 @@ impl TeamRepositoryImpl {
sqlx::query!(
r#"
- INSERT INTO team_user (team_id, user_id, team_role)
- VALUES ($1, $2, 'owner')
+ INSERT INTO team_user (team_id, user_id, team_role, plan)
+ VALUES ($1, $2, 'owner', $3)
"#,
&team.id,
user_id.as_ref(),
+ owner_plan as _,
)
.execute(&mut *transaction)
.await?;
@@ -337,12 +339,13 @@ impl TeamRepository for TeamRepositoryImpl {
team_name: &str,
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
+ owner_plan: SeatPlan,
) -> Result<Team, CreateTeamError> {
if team_name.is_empty() || team_name.len() > 50 {
return Err(CreateTeamError::InvalidTeamName(team_name.to_string()));
}
- self.create_team_inner(user_id, team_name, team_slug, subscription_id)
+ self.create_team_inner(user_id, team_name, team_slug, subscription_id, owner_plan)
.await
.map_err(|e| e.into())
}
@@ -554,7 +557,7 @@ impl TeamRepository for TeamRepositoryImpl {
r#"
DELETE FROM team_user
WHERE team_id = $1 AND user_id = $2
- RETURNING team_role
+ RETURNING team_role, plan
"#,
)
.bind(team_id)
@@ -570,6 +573,7 @@ impl TeamRepository for TeamRepositoryImpl {
team_id: *team_id,
user_id: user_id.clone().into_owned(),
role: row.try_get("team_role")?,
+ plan: row.try_get("plan")?,
};
TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, -1).await?;
@@ -724,7 +728,8 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole"
+ team_role as "team_role!: TeamRole",
+ plan as "plan!: SeatPlan"
FROM team_user
WHERE team_id = $1
"#,
@@ -743,6 +748,7 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(TeamMember {
user_id,
role: row.team_role,
+ plan: row.plan,
team_id: *team_id,
})
} else {
@@ -810,7 +816,7 @@ impl TeamRepository for TeamRepositoryImpl {
r#"
INSERT INTO team_user (team_id, user_id, team_role)
VALUES ($1, $2, $3)
- RETURNING user_id, team_role, team_id
+ RETURNING user_id, team_role, team_id, plan
"#,
)
.bind(invite_snapshot.team_id)
@@ -843,6 +849,7 @@ impl TeamRepository for TeamRepositoryImpl {
.map(|id| id.into_owned())
.map_err(|e| TeamError::StorageLayerError(e.into()))?,
role: team_member.try_get("team_role")?,
+ plan: team_member.try_get("plan")?,
team_id,
};
@@ -913,14 +920,15 @@ impl TeamRepository for TeamRepositoryImpl {
let inserted = sqlx::query(
r#"
- INSERT INTO team_user (team_id, user_id, team_role)
- VALUES ($1, $2, $3)
+ INSERT INTO team_user (team_id, user_id, team_role, plan)
+ VALUES ($1, $2, $3, $4)
ON CONFLICT DO NOTHING
"#,
)
.bind(removed_member.team_id)
.bind(removed_member.user_id.as_ref())
.bind(removed_member.role)
+ .bind(removed_member.plan)
.execute(&mut *transaction)
.await?;
@@ -961,7 +969,8 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole"
+ team_role as "team_role!: TeamRole",
+ plan as "plan!: SeatPlan"
FROM team_user
WHERE team_id = $1
"#,
@@ -980,6 +989,7 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(TeamMember {
user_id,
role: row.team_role,
+ plan: row.plan,
team_id: *team_id,
})
} else {
@@ -1070,7 +1080,8 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole"
+ team_role as "team_role!: TeamRole",
+ plan as "plan!: SeatPlan"
FROM team_user
WHERE team_id = $1
"#,
@@ -1086,6 +1097,7 @@ impl TeamRepository for TeamRepositoryImpl {
.map(|id| TeamMember {
user_id: id.into_owned(),
role: row.team_role,
+ plan: row.plan,
team_id: *team_id,
})
.ok()
@@ -1292,7 +1304,8 @@ impl TeamRepository for TeamRepositoryImpl {
let member = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole"
+ team_role as "team_role!: TeamRole",
+ plan as "plan!: SeatPlan"
FROM team_user
WHERE team_id = $1
AND user_id = $2
@@ -1307,6 +1320,7 @@ impl TeamRepository for TeamRepositoryImpl {
.into_owned(),
team_id: *team_id,
role: r.team_role,
+ plan: r.plan,
})
})
.fetch_one(&self.pool)
@@ -1343,6 +1357,34 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn patch_team_member_plan(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ plan: SeatPlan,
+ ) -> Result<(), TeamError> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE team_user
+ SET plan = $3
+ WHERE team_id = $1
+ AND user_id = $2
+ "#,
+ team_id,
+ user_id.as_ref(),
+ plan as _,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(TeamError::TeamMemberNotFound(*team_id));
+ }
+
+ Ok(())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn get_team_seat_count(&self, team_id: &uuid::Uuid) -> Result<i32, TeamError> {
let seat_count = sqlx::query!(
@@ -1539,6 +1581,7 @@ impl TeamRepository for TeamRepositoryImpl {
team_id: *team_id,
user_id: user_id.clone().into_owned(),
role: TeamRole::Member,
+ plan: SeatPlan::Premium,
}))
}
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index a5e5ba1b1d..084be85466 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -4,6 +4,7 @@ use sqlx::{Pool, Postgres, Row};
///! Tests for the team_repo implementation for teams
use super::*;
+use crate::domain::model::SeatPlan;
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
@@ -175,6 +176,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
"Product Team",
"PRODUCT_TEAM",
Some(&"sub_test".parse().unwrap()),
+ SeatPlan::Premium,
)
.await?;
@@ -186,7 +188,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
// Create team with too large a name
let err = team_repo
- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()))
+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()), SeatPlan::Premium)
.await
.err()
.unwrap();
@@ -230,6 +232,7 @@ async fn test_move_github_app_installation_to_team_moves_existing_user_rows(
"GitHub Owner Team",
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
+ SeatPlan::Premium,
)
.await?;
let team_id = team.id().to_string();
@@ -352,6 +355,7 @@ async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(
"GitHub Owner Team",
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
+ SeatPlan::Premium,
)
.await?;
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 0c95931436..c9b21e9b19 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -274,6 +274,20 @@ documents:
change it; someone with inherited owner access gets a "Failed to change team
access" toast.
+## AI usage limits
+
+Paid plans include a monthly AI allowance (Premium $40, Max $200, at Macro's
+usage rates). When it is used up and no credits or usage billing cover the
+request, sending a message answers HTTP 402 and the app opens the
+**AI usage limit** dialog (title `You've used this month's included AI`, or the
+spending-limit / failed-charge variants). It shows the same meter and controls
+as Settings → Billing: credit-pack buttons, the `Usage billing` toggle, an
+`Open billing settings` button, and `Upgrade to Max` for Premium payers (on a
+team this moves only the payer's own seat). Team members who are not the payer
+see a note to ask the team owner, or a team admin to move their seat to Max.
+Each team seat has its own allowance; unused allowance never moves between
+members. The team owner's prepaid credits and usage-billing cap are shared.
+
## Start a doc-scoped chat
Open a doc → side panel `Actions` → `Ask Macro`. Opens a chat pane with the document already
@@ -326,7 +340,10 @@ Desktop composer and conversation body text use 15px type. Mobile keeps its
existing text sizing.
- Contenteditable composer (placeholder `Ask AI, @mention anything` / `Describe the edit…`).
-- Model picker button showing the current model (e.g. `Haiku 4.5`).
+- Model picker button showing the current model (e.g. `Haiku 4.5`). Paid plans list
+ `Sonnet 5`, `Opus 5`, `Fable 5.1`, `Haiku 4.5`, `GPT-6 Astra`, `GPT-5.6`, `GPT-5.6 mini`;
+ heavy models carry a `2.5× usage` / `5× usage` hint. On the free plan everything but `Haiku 4.5` is
+ dimmed with a lock and opens the `Smart models are premium` paywall when clicked.
- `Send` button (disabled when empty). While streaming it becomes `Stop generating`.
On desktop, production AI, new agent, and channel composers use 28px circular
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index c6ad4ef037..36fc835665 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -905,9 +905,16 @@ and split navigation.
Left nav: General → `Account` (profile, delete account), `API Keys` (create /
list / delete personal keys; the secret is shown only once and is sent as
-`x-macro-user-api-key`), `Notifications`, `Billing`,
+`x-macro-user-api-key`), `Notifications`, `Billing` (current plan card with
+`Manage`; on paid plans an **AI usage** card with the period meter, credit
+balance, credit-pack buttons `$10`/`$25`/`$50`/`$100` that redirect to Stripe
+Checkout, and a `Usage billing` toggle with per-period limit pills; an
+`Upgrade`/`Upgrade to Max` card, or a `Switch to Premium` link on Max; on a team
+the plan change moves only the viewer's own seat),
`Appearance`, `Agents`, `Mobile App`, `Shortcuts` (interactive keyboard visualization, not a list);
-Workspace → `Team`, `Tags`, `CRM` (enable/disable; once enabled, a `Deal stages` section
+Workspace → `Team` (members list; on a paid team each row shows the seat's plan,
+and admins/owners change it with the `Seat plan` menu: `Premium` or `Max`,
+prorated at once), `Tags`, `CRM` (enable/disable; once enabled, a `Deal stages` section
with `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/down
buttons 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.ts
index 6ebe84b547..c9550f32aa 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-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, 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, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, 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, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, 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, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, 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, 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, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, 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, 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, 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, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, 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, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, 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, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, 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, 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, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, 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.ts
index 3c3860716d..c19b135ea3 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, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, 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, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, 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, 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, CreateUserData, CreateUserErrors, CreateUserResponses, 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, 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, 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> & {
/**
@@ -57,6 +57,51 @@ export class Sdk extends HeyApiClient {
Sdk.__registry.set(this, args?.key);
}
+ /**
+ * Start a Stripe Checkout for a credit pack. Payer only.
+ */
+ public createAiCreditCheckout<ThrowOnError extends boolean = false>(options: Options<CreateAiCreditCheckoutData, ThrowOnError>): RequestResult<CreateAiCreditCheckoutResponses, CreateAiCreditCheckoutErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<CreateAiCreditCheckoutResponses, CreateAiCreditCheckoutErrors, ThrowOnError>({
+ url: '/ai-billing/credits/checkout',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Turn overage billing on or off and set the per-period cap. Payer only.
+ */
+ public updateAiBillingOverage<ThrowOnError extends boolean = false>(options: Options<UpdateAiBillingOverageData, ThrowOnError>): RequestResult<UpdateAiBillingOverageResponses, UpdateAiBillingOverageErrors, ThrowOnError> {
+ return (options.client ?? this.client).patch<UpdateAiBillingOverageResponses, UpdateAiBillingOverageErrors, ThrowOnError>({
+ url: '/ai-billing/overage',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * The plan catalog, credit packs, and overage cap bounds.
+ */
+ public getAiBillingPlans<ThrowOnError extends boolean = false>(options?: Options<GetAiBillingPlansData, ThrowOnError>): RequestResult<GetAiBillingPlansResponses, unknown, ThrowOnError> {
+ return (options?.client ?? this.client).get<GetAiBillingPlansResponses, unknown, ThrowOnError>({ url: '/ai-billing/plans', ...options });
+ }
+
+ /**
+ * The caller's current-period AI usage, credits, and overage settings.
+ *
+ * Runs a settlement first so the position reflects any credits or overage
+ * that were waiting to be booked.
+ */
+ public getAiBillingSummary<ThrowOnError extends boolean = false>(options?: Options<GetAiBillingSummaryData, ThrowOnError>): RequestResult<GetAiBillingSummaryResponses, GetAiBillingSummaryErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<GetAiBillingSummaryResponses, GetAiBillingSummaryErrors, ThrowOnError>({ url: '/ai-billing/summary', ...options });
+ }
+
public disconnectCodex<ThrowOnError extends boolean = false>(options?: Options<DisconnectCodexData, ThrowOnError>): RequestResult<DisconnectCodexResponses, unknown, ThrowOnError> {
return (options?.client ?? this.client).delete<DisconnectCodexResponses, unknown, ThrowOnError>({ url: '/codex', ...options });
}
@@ -654,6 +699,24 @@ export class Sdk extends HeyApiClient {
return (options.client ?? this.client).get<JoinTeamResponses, JoinTeamErrors, ThrowOnError>({ url: '/team/join/{team_invite_id}', ...options });
}
+ /**
+ * Moves one team member's seat between paid plans.
+ *
+ * Team admins and owners only. The team's subscription is re-billed for
+ * the seat at once (prorated); the member's tier role and individual AI
+ * allowance follow immediately.
+ */
+ public patchTeamMemberPlan<ThrowOnError extends boolean = false>(options: Options<PatchTeamMemberPlanData, ThrowOnError>): RequestResult<PatchTeamMemberPlanResponses, PatchTeamMemberPlanErrors, ThrowOnError> {
+ return (options.client ?? this.client).patch<PatchTeamMemberPlanResponses, PatchTeamMemberPlanErrors, ThrowOnError>({
+ url: '/team/members/{member_user_id}/plan',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Toggles whether non-admin members may invite users to the team. Teams
* start with this on (any member can invite); turning it off restricts
@@ -851,6 +914,28 @@ 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.
+ */
+ public changePlan<ThrowOnError extends boolean = false>(options: Options<ChangePlanData, ThrowOnError>): RequestResult<ChangePlanResponses, ChangePlanErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<ChangePlanResponses, ChangePlanErrors, ThrowOnError>({
+ url: '/user/stripe/plan',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Creates a Stripe billing portal session.
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index ce5eea31a6..a80ceb20f6 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -6,11 +6,41 @@ export type ClientOptions = {
export type AbGroup = 'A' | 'B';
+/**
+ * Error response body.
+ */
+export type AiBillingErrorBody = {
+ /**
+ * Human-readable error description.
+ */
+ error: string;
+};
+
export type AppleLoginRequest = {
code: string;
id_token: string;
};
+/**
+ * Request body for switching plans
+ */
+export type ChangePlanRequest = {
+ /**
+ * The plan to move the active subscription to
+ */
+ plan: SeatPlan;
+};
+
+/**
+ * Response for a plan change
+ */
+export type ChangePlanResponse = {
+ /**
+ * The plan the subscription is now on
+ */
+ plan: SeatPlan;
+};
+
/**
* Tracking metadata for conversion attribution
*/
@@ -161,6 +191,7 @@ export type CreateCheckoutSessionV2Request = {
* Tracking metadata for conversion attribution
*/
metadata?: CheckoutSessionMetadata;
+ plan?: null | SeatPlan;
/**
* The URL to redirect to on successful checkout
*/
@@ -233,6 +264,35 @@ export type CreateUserRequest = {
username: string;
};
+/**
+ * Request body for [`create_credit_checkout_handler`].
+ */
+export type CreditCheckoutRequestBody = {
+ /**
+ * Pack size, cents; one of the catalog's `credit_packs_cents`.
+ */
+ amountCents: number;
+ /**
+ * Where Stripe returns the user on cancel. Same rules as `success_url`.
+ */
+ cancelUrl: string;
+ /**
+ * Where Stripe returns the user after paying. Must be an `https` URL
+ * on the origin the request came from.
+ */
+ successUrl: string;
+};
+
+/**
+ * Response for [`create_credit_checkout_handler`].
+ */
+export type CreditCheckoutResponse = {
+ /**
+ * The hosted Checkout URL to redirect to.
+ */
+ url: string;
+};
+
/**
* What settings needs to render the Cursor connection.
*
@@ -295,6 +355,11 @@ export type CursorModelsResponse = {
models: Array<CursorModelOption>;
};
+/**
+ * Why a request was refused.
+ */
+export type DenyReason = 'allowance_exhausted' | 'overage_limit_reached' | 'overage_payment_failed';
+
/**
* Empty response is required due to custom fetch forcing `response.json()`
*/
@@ -906,6 +971,16 @@ export type PatchTeamCrmSettingsResponse = {
enabled: boolean;
};
+/**
+ * Request body for `PATCH /team/members/{member_user_id}/plan`.
+ */
+export type PatchTeamMemberPlanRequest = {
+ /**
+ * The plan to bill the member's seat at from now on.
+ */
+ plan: SeatPlan;
+};
+
/**
* Request to update a team
*/
@@ -983,6 +1058,51 @@ export type Permission = {
id: string;
};
+/**
+ * One plan in the catalog.
+ */
+export type PlanCatalogEntry = {
+ /**
+ * Included AI per seat per period, list-rate cents.
+ */
+ included_ai_cents_per_seat: number;
+ /**
+ * Monthly list price per seat, cents.
+ */
+ monthly_price_cents: number;
+ /**
+ * The tier.
+ */
+ tier: PlanTier;
+};
+
+/**
+ * The plan catalog and the knobs the billing UI offers.
+ */
+export type PlanCatalogResponse = {
+ /**
+ * Credit packs a payer may buy, cents.
+ */
+ credit_packs_cents: Array<number>;
+ /**
+ * Largest allowed overage cap, cents.
+ */
+ overage_limit_max_cents: number;
+ /**
+ * Smallest allowed overage cap, cents.
+ */
+ overage_limit_min_cents: number;
+ /**
+ * Every plan, cheapest first.
+ */
+ plans: Array<PlanCatalogEntry>;
+};
+
+/**
+ * The plans a user can be on, cheapest first.
+ */
+export type PlanTier = 'free' | 'premium' | 'max';
+
export type PostGetNamesRequestBody = {
user_ids: Array<string>;
};
@@ -1062,6 +1182,13 @@ export type ResendFusionauthVerifyUserEmailRequest = {
email: string;
};
+/**
+ * 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
+ * plan in use.
+ */
+export type SeatPlan = 'premium' | 'max';
+
/**
* The body which is used to describe the recipient email
*/
@@ -1183,6 +1310,11 @@ export type TeamInvitesResponse = {
* The team member struct
*/
export type TeamMember = {
+ /**
+ * The paid plan the member's seat is billed at. Meaningful on paying
+ * and enterprise teams; free-team members carry the default.
+ */
+ plan: SeatPlan;
/**
* The role of the team member
*/
@@ -1243,6 +1375,98 @@ export type ToggleNonAdminInvitesResponse = {
allow_non_admin_invites: boolean;
};
+/**
+ * Request body for [`update_overage_handler`].
+ */
+export type UpdateOverageRequest = {
+ /**
+ * Bill usage past allowance and credits.
+ */
+ enabled: boolean;
+ /**
+ * Per-period cap on overage spend, cents. Required when enabling.
+ */
+ limitCents?: number;
+};
+
+/**
+ * The payer's current-period position, as shown in Billing settings and used
+ * by the gate.
+ */
+export type UsageSnapshot = {
+ blocked_reason?: null | DenyReason;
+ /**
+ * Whether the requesting user is the payer.
+ */
+ can_manage_billing: boolean;
+ /**
+ * Shared prepaid credit balance.
+ */
+ credit_balance_cents: number;
+ /**
+ * Shared payer credits already applied to this period.
+ */
+ credits_consumed_cents: number;
+ /**
+ * Included AI for this user's seat this period, in list-rate cents.
+ */
+ included_cents: number;
+ /**
+ * Shared overage charged so far this period.
+ */
+ overage_charged_cents: number;
+ /**
+ * Whether overage billing is on.
+ */
+ overage_enabled: boolean;
+ /**
+ * Per-period overage cap.
+ */
+ overage_limit_cents: number;
+ /**
+ * Whether overage is paused after a failed charge.
+ */
+ overage_suspended: boolean;
+ /**
+ * The payer for this user's AI.
+ */
+ payer: string;
+ /**
+ * Period end (exclusive).
+ */
+ period_end: string;
+ /**
+ * Period start.
+ */
+ period_start: string;
+ /**
+ * This seat's remaining allowance plus shared credit/overage headroom; 0
+ * when blocked.
+ */
+ remaining_cents: number;
+ /**
+ * Seats billed to the payer.
+ */
+ seats: number;
+ /**
+ * The plan.
+ */
+ tier: PlanTier;
+ /**
+ * Team-wide usage beyond per-seat allowances that is not yet covered by
+ * shared credits or charges (awaiting settlement).
+ */
+ uncovered_cents: number;
+ /**
+ * Enterprise: never metered.
+ */
+ unlimited: boolean;
+ /**
+ * AI used by this user this period, in list-rate cents.
+ */
+ used_cents: number;
+};
+
export type UserLinkResponse = {
/**
* Whether or not a link exists for the given idp
@@ -1310,6 +1534,133 @@ export type UserTokensResponse = {
refresh_token: string;
};
+export type CreateAiCreditCheckoutData = {
+ body: CreditCheckoutRequestBody;
+ path?: never;
+ query?: never;
+ url: '/ai-billing/credits/checkout';
+};
+
+export type CreateAiCreditCheckoutErrors = {
+ /**
+ * Invalid pack, untrusted return URL, or no payment account
+ */
+ 400: AiBillingErrorBody;
+ /**
+ * Unauthorized
+ */
+ 401: unknown;
+ /**
+ * A paid plan is required
+ */
+ 402: AiBillingErrorBody;
+ /**
+ * Only the payer may buy credits
+ */
+ 403: AiBillingErrorBody;
+ /**
+ * Internal server error
+ */
+ 500: AiBillingErrorBody;
+};
+
+export type CreateAiCreditCheckoutError = CreateAiCreditCheckoutErrors[keyof CreateAiCreditCheckoutErrors];
+
+export type CreateAiCreditCheckoutResponses = {
+ /**
+ * Checkout URL
+ */
+ 200: CreditCheckoutResponse;
+};
+
+export type CreateAiCreditCheckoutResponse = CreateAiCreditCheckoutResponses[keyof CreateAiCreditCheckoutResponses];
+
+export type UpdateAiBillingOverageData = {
+ body: UpdateOverageRequest;
+ path?: never;
+ query?: never;
+ url: '/ai-billing/overage';
+};
+
+export type UpdateAiBillingOverageErrors = {
+ /**
+ * Invalid limit
+ */
+ 400: AiBillingErrorBody;
+ /**
+ * Unauthorized
+ */
+ 401: unknown;
+ /**
+ * A paid plan is required
+ */
+ 402: AiBillingErrorBody;
+ /**
+ * Only the payer may change billing
+ */
+ 403: AiBillingErrorBody;
+ /**
+ * Internal server error
+ */
+ 500: AiBillingErrorBody;
+};
+
+export type UpdateAiBillingOverageError = UpdateAiBillingOverageErrors[keyof UpdateAiBillingOverageErrors];
+
+export type UpdateAiBillingOverageResponses = {
+ /**
+ * Updated position
+ */
+ 200: UsageSnapshot;
+};
+
+export type UpdateAiBillingOverageResponse = UpdateAiBillingOverageResponses[keyof UpdateAiBillingOverageResponses];
+
+export type GetAiBillingPlansData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/ai-billing/plans';
+};
+
+export type GetAiBillingPlansResponses = {
+ /**
+ * Plan catalog
+ */
+ 200: PlanCatalogResponse;
+};
+
+export type GetAiBillingPlansResponse = GetAiBillingPlansResponses[keyof GetAiBillingPlansResponses];
+
+export type GetAiBillingSummaryData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/ai-billing/summary';
+};
+
+export type GetAiBillingSummaryErrors = {
+ /**
+ * Unauthorized
+ */
+ 401: unknown;
+ /**
+ * Internal server error
+ */
+ 500: AiBillingErrorBody;
+};
+
+export type GetAiBillingSummaryError = GetAiBillingSummaryErrors[keyof GetAiBillingSummaryErrors];
+
+export type GetAiBillingSummaryResponses = {
+ /**
+ * Current-period position
+ */
+ 200: UsageSnapshot;
+};
+
+export type GetAiBillingSummaryResponse = GetAiBillingSummaryResponses[keyof GetAiBillingSummaryResponses];
+
export type DisconnectCodexData = {
body?: never;
path?: never;
@@ -2636,6 +2987,37 @@ export type JoinTeamResponses = {
200: unknown;
};
+export type PatchTeamMemberPlanData = {
+ body: PatchTeamMemberPlanRequest;
+ path: {
+ /**
+ * The member whose seat plan changes
+ */
+ member_user_id: string;
+ };
+ query?: never;
+ url: '/team/members/{member_user_id}/plan';
+};
+
+export type PatchTeamMemberPlanErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ /**
+ * The team has no active subscription
+ */
+ 402: ErrorResponse;
+ 404: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type PatchTeamMemberPlanError = PatchTeamMemberPlanErrors[keyof PatchTeamMemberPlanErrors];
+
+export type PatchTeamMemberPlanResponses = {
+ 200: TeamMember;
+};
+
+export type PatchTeamMemberPlanResponse = PatchTeamMemberPlanResponses[keyof PatchTeamMemberPlanResponses];
+
export type ToggleTeamNonAdminInvitesData = {
body?: never;
path?: never;
@@ -3076,6 +3458,45 @@ export type CreateCheckoutSessionV2Responses = {
export type CreateCheckoutSessionV2Response = CreateCheckoutSessionV2Responses[keyof CreateCheckoutSessionV2Responses];
+export type ChangePlanData = {
+ body: ChangePlanRequest;
+ path?: never;
+ query?: never;
+ url: '/user/stripe/plan';
+};
+
+export type ChangePlanErrors = {
+ /**
+ * Plan not available
+ */
+ 400: ErrorResponse;
+ /**
+ * The team has no active subscription
+ */
+ 402: ErrorResponse;
+ /**
+ * Only team admins change plans on a team
+ */
+ 403: ErrorResponse;
+ /**
+ * No active subscription
+ */
+ 404: ErrorResponse;
+ /**
+ * Already on this plan, or more than one active subscription
+ */
+ 409: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type ChangePlanError = ChangePlanErrors[keyof ChangePlanErrors];
+
+export type ChangePlanResponses = {
+ 200: ChangePlanResponse;
+};
+
+export type ChangePlanResponse2 = ChangePlanResponses[keyof ChangePlanResponses];
+
export type CreatePortalSessionData = {
body: CreatePortalSessionRequest;
path?: never;
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 66d77e7b9c..4d616e5b0c 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -293,6 +293,10 @@ export type ChatMessageContent = string | Array<AssistantMessagePart>;
* Error response for chat message endpoints
*/
export type ChatMessageError = {
+ /**
+ * Stable machine-readable code for payment-required errors.
+ */
+ code?: string | null;
error: string;
stream_id?: string | null;
};
@@ -1410,6 +1414,10 @@ export type StringIdResponse = {
};
export type StructuredCompletionError = {
+ /**
+ * Stable machine-readable code for payment-required errors.
+ */
+ code?: string | null;
error: string;
};
@@ -2734,13 +2742,13 @@ export type SendChatMessageErrors = {
*/
401: unknown;
/**
- * Payment required — user lacks access to the requested model
+ * Payment required — the user's AI allowance is used up
*/
- 402: unknown;
+ 402: ChatMessageError;
/**
- * Forbidden
+ * Forbidden — user lacks access to the requested model
*/
- 403: unknown;
+ 403: ChatMessageError;
};
export type SendChatMessageError = SendChatMessageErrors[keyof SendChatMessageErrors];
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index b5d54c074b..5daf18f3bc 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -10,6 +10,202 @@
"version": "0.1.0"
},
"paths": {
+ "/ai-billing/credits/checkout": {
+ "post": {
+ "tags": ["ai_billing"],
+ "summary": "Start a Stripe Checkout for a credit pack. Payer only.",
+ "operationId": "create_ai_credit_checkout",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreditCheckoutRequestBody"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Checkout URL",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreditCheckoutResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid pack, untrusted return URL, or no payment account",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "402": {
+ "description": "A paid plan is required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only the payer may buy credits",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/overage": {
+ "patch": {
+ "tags": ["ai_billing"],
+ "summary": "Turn overage billing on or off and set the per-period cap. Payer only.",
+ "operationId": "update_ai_billing_overage",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateOverageRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Updated position",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageSnapshot"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "402": {
+ "description": "A paid plan is required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only the payer may change billing",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/plans": {
+ "get": {
+ "tags": ["ai_billing"],
+ "summary": "The plan catalog, credit packs, and overage cap bounds.",
+ "operationId": "get_ai_billing_plans",
+ "responses": {
+ "200": {
+ "description": "Plan catalog",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PlanCatalogResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/ai-billing/summary": {
+ "get": {
+ "tags": ["ai_billing"],
+ "summary": "The caller's current-period AI usage, credits, and overage settings.",
+ "description": "Runs a settlement first so the position reflects any credits or overage\nthat were waiting to be booked.",
+ "operationId": "get_ai_billing_summary",
+ "responses": {
+ "200": {
+ "description": "Current-period position",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UsageSnapshot"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiBillingErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/codex": {
"get": {
"tags": ["crate::api::codex"],
@@ -3200,6 +3396,97 @@
}
}
},
+ "/team/members/{member_user_id}/plan": {
+ "patch": {
+ "tags": ["teams::inbound::axum_router::patch_team_member_plan"],
+ "summary": "Moves one team member's seat between paid plans.",
+ "description": "Team admins and owners only. The team's subscription is re-billed for\nthe seat at once (prorated); the member's tier role and individual AI\nallowance follow immediately.",
+ "operationId": "patch_team_member_plan",
+ "parameters": [
+ {
+ "name": "member_user_id",
+ "in": "path",
+ "description": "The member whose seat plan changes",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchTeamMemberPlanRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TeamMember"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "402": {
+ "description": "The team has no active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/non-admin-invites/toggle": {
"post": {
"tags": ["teams::inbound::axum_router::toggle_non_admin_invites"],
@@ -4230,6 +4517,96 @@
}
}
},
+ "/user/stripe/plan": {
+ "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.",
+ "operationId": "change_plan",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePlanRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangePlanResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Plan not available",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "402": {
+ "description": "The team has no active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Only team admins change plans on a team",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Already on this plan, or more than one active subscription",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/user/stripe/portal": {
"post": {
"tags": ["user::stripe::create_portal_session"],
@@ -4345,6 +4722,17 @@
"type": "string",
"enum": ["A", "B"]
},
+ "AiBillingErrorBody": {
+ "type": "object",
+ "description": "Error response body.",
+ "required": ["error"],
+ "properties": {
+ "error": {
+ "type": "string",
+ "description": "Human-readable error description."
+ }
+ }
+ },
"AppleLoginRequest": {
"type": "object",
"required": ["id_token", "code"],
@@ -4357,6 +4745,28 @@
}
}
},
+ "ChangePlanRequest": {
+ "type": "object",
+ "description": "Request body for switching plans",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to move the active subscription to"
+ }
+ }
+ },
+ "ChangePlanResponse": {
+ "type": "object",
+ "description": "Response for a plan change",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan the subscription is now on"
+ }
+ }
+ },
"CheckoutSessionMetadata": {
"type": "object",
"description": "Tracking metadata for conversion attribution",
@@ -4531,6 +4941,17 @@
"$ref": "#/components/schemas/CheckoutSessionMetadata",
"description": "Tracking metadata for conversion attribution"
},
+ "plan": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to subscribe to. Defaults to Premium."
+ }
+ ]
+ },
"successUrl": {
"type": "string",
"description": "The URL to redirect to on successful checkout"
@@ -4607,6 +5028,37 @@
}
}
},
+ "CreditCheckoutRequestBody": {
+ "type": "object",
+ "description": "Request body for [`create_credit_checkout_handler`].",
+ "required": ["amountCents", "successUrl", "cancelUrl"],
+ "properties": {
+ "amountCents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Pack size, cents; one of the catalog's `credit_packs_cents`."
+ },
+ "cancelUrl": {
+ "type": "string",
+ "description": "Where Stripe returns the user on cancel. Same rules as `success_url`."
+ },
+ "successUrl": {
+ "type": "string",
+ "description": "Where Stripe returns the user after paying. Must be an `https` URL\non the origin the request came from."
+ }
+ }
+ },
+ "CreditCheckoutResponse": {
+ "type": "object",
+ "description": "Response for [`create_credit_checkout_handler`].",
+ "required": ["url"],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The hosted Checkout URL to redirect to."
+ }
+ }
+ },
"CursorApiKeyStatus": {
"type": "object",
"description": "What settings needs to render the Cursor connection.\n\nDeliberately thin. `registered` drives the whole UI; `updatedAt` lets it say\nwhen the key was last replaced, which is the only thing a user can check\nagainst their own memory when a session starts failing.\n\nDeliberately *not* reporting anything about the deployment itself. That is\noperator information: a user who sees it cannot act on it, and a service\nthat cannot reach KMS does not start.",
@@ -4660,6 +5112,15 @@
}
}
},
+ "DenyReason": {
+ "type": "string",
+ "description": "Why a request was refused.",
+ "enum": [
+ "allowance_exhausted",
+ "overage_limit_reached",
+ "overage_payment_failed"
+ ]
+ },
"EmptyResponse": {
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
@@ -5472,6 +5933,17 @@
}
}
},
+ "PatchTeamMemberPlanRequest": {
+ "type": "object",
+ "description": "Request body for `PATCH /team/members/{member_user_id}/plan`.",
+ "required": ["plan"],
+ "properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The plan to bill the member's seat at from now on."
+ }
+ }
+ },
"PatchTeamRequest": {
"type": "object",
"description": "Request to update a team",
@@ -5575,6 +6047,73 @@
}
}
},
+ "PlanCatalogEntry": {
+ "type": "object",
+ "description": "One plan in the catalog.",
+ "required": [
+ "tier",
+ "monthly_price_cents",
+ "included_ai_cents_per_seat"
+ ],
+ "properties": {
+ "included_ai_cents_per_seat": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Included AI per seat per period, list-rate cents."
+ },
+ "monthly_price_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Monthly list price per seat, cents."
+ },
+ "tier": {
+ "$ref": "#/components/schemas/PlanTier",
+ "description": "The tier."
+ }
+ }
+ },
+ "PlanCatalogResponse": {
+ "type": "object",
+ "description": "The plan catalog and the knobs the billing UI offers.",
+ "required": [
+ "plans",
+ "credit_packs_cents",
+ "overage_limit_min_cents",
+ "overage_limit_max_cents"
+ ],
+ "properties": {
+ "credit_packs_cents": {
+ "type": "array",
+ "items": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "description": "Credit packs a payer may buy, cents."
+ },
+ "overage_limit_max_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Largest allowed overage cap, cents."
+ },
+ "overage_limit_min_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Smallest allowed overage cap, cents."
+ },
+ "plans": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PlanCatalogEntry"
+ },
+ "description": "Every plan, cheapest first."
+ }
+ }
+ },
+ "PlanTier": {
+ "type": "string",
+ "description": "The plans a user can be on, cheapest first.",
+ "enum": ["free", "premium", "max"]
+ },
"PostGetNamesRequestBody": {
"type": "object",
"required": ["user_ids"],
@@ -5684,6 +6223,11 @@
}
}
},
+ "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.",
+ "enum": ["premium", "max"]
+ },
"SendInviteBody": {
"type": "object",
"description": "The body which is used to describe the recipient email",
@@ -5855,8 +6399,12 @@
"TeamMember": {
"type": "object",
"description": "The team member struct",
- "required": ["team_id", "user_id", "role"],
+ "required": ["team_id", "user_id", "role", "plan"],
"properties": {
+ "plan": {
+ "$ref": "#/components/schemas/SeatPlan",
+ "description": "The paid plan the member's seat is billed at. Meaningful on paying\nand enterprise teams; free-team members carry the default."
+ },
"role": {
"$ref": "#/components/schemas/TeamRole",
"description": "The role of the team member"
@@ -5921,6 +6469,138 @@
}
}
},
+ "UpdateOverageRequest": {
+ "type": "object",
+ "description": "Request body for [`update_overage_handler`].",
+ "required": ["enabled"],
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "Bill usage past allowance and credits."
+ },
+ "limitCents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Per-period cap on overage spend, cents. Required when enabling."
+ }
+ }
+ },
+ "UsageSnapshot": {
+ "type": "object",
+ "description": "The payer's current-period position, as shown in Billing settings and used\nby the gate.",
+ "required": [
+ "tier",
+ "unlimited",
+ "payer",
+ "can_manage_billing",
+ "seats",
+ "period_start",
+ "period_end",
+ "included_cents",
+ "used_cents",
+ "credits_consumed_cents",
+ "credit_balance_cents",
+ "overage_enabled",
+ "overage_limit_cents",
+ "overage_charged_cents",
+ "overage_suspended",
+ "uncovered_cents",
+ "remaining_cents"
+ ],
+ "properties": {
+ "blocked_reason": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/DenyReason",
+ "description": "Why requests are refused right now, if they are."
+ }
+ ]
+ },
+ "can_manage_billing": {
+ "type": "boolean",
+ "description": "Whether the requesting user is the payer."
+ },
+ "credit_balance_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared prepaid credit balance."
+ },
+ "credits_consumed_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared payer credits already applied to this period."
+ },
+ "included_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Included AI for this user's seat this period, in list-rate cents."
+ },
+ "overage_charged_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Shared overage charged so far this period."
+ },
+ "overage_enabled": {
+ "type": "boolean",
+ "description": "Whether overage billing is on."
+ },
+ "overage_limit_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Per-period overage cap."
+ },
+ "overage_suspended": {
+ "type": "boolean",
+ "description": "Whether overage is paused after a failed charge."
+ },
+ "payer": {
+ "type": "string",
+ "description": "The payer for this user's AI."
+ },
+ "period_end": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Period end (exclusive)."
+ },
+ "period_start": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Period start."
+ },
+ "remaining_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "This seat's remaining allowance plus shared credit/overage headroom; 0\nwhen blocked."
+ },
+ "seats": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Seats billed to the payer.",
+ "minimum": 0
+ },
+ "tier": {
+ "$ref": "#/components/schemas/PlanTier",
+ "description": "The plan."
+ },
+ "uncovered_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Team-wide usage beyond per-seat allowances that is not yet covered by\nshared credits or charges (awaiting settlement)."
+ },
+ "unlimited": {
+ "type": "boolean",
+ "description": "Enterprise: never metered."
+ },
+ "used_cents": {
+ "type": "integer",
+ "format": "int64",
+ "description": "AI used by this user this period, in list-rate cents."
+ }
+ }
+ },
"UserLinkResponse": {
"type": "object",
"required": ["link_exists"],
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 13f6531e34..5f89f1d533 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -2002,10 +2002,24 @@
"description": "Unauthorized"
},
"402": {
- "description": "Payment required — user lacks access to the requested model"
+ "description": "Payment required — the user's AI allowance is used up",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
},
"403": {
- "description": "Forbidden"
+ "description": "Forbidden — user lacks access to the requested model",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
}
}
}
@@ -2553,6 +2567,10 @@
"description": "Error response for chat message endpoints",
"required": ["error"],
"properties": {
+ "code": {
+ "type": ["string", "null"],
+ "description": "Stable machine-readable code for payment-required errors."
+ },
"error": {
"type": "string"
},
@@ -4568,6 +4586,10 @@
"type": "object",
"required": ["error"],
"properties": {
+ "code": {
+ "type": ["string", "null"],
+ "description": "Stable machine-readable code for payment-required errors."
+ },
"error": {
"type": "string"
}
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index a434261585..5c7a4ec752 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -42,9 +42,11 @@ export const agentHarnessBacklog = [
export const authExcluded = [
'appleLogin',
'cancelCodexLogin',
+ 'changePlan',
'checkGithubLinkStatus',
'checkGmailLinkStatus',
'configureCodex',
+ 'createAiCreditCheckout',
'createCheckoutSessionV2',
'createGtmInviteLink',
'createInProgressLink',
@@ -60,6 +62,8 @@ export const authExcluded = [
'disconnectCodex',
'enrichGithubPullRequests',
'generateEmailLink',
+ 'getAiBillingPlans',
+ 'getAiBillingSummary',
'getCodexConnection',
'getCursorApiKey',
'getGtmInviteOffer',
@@ -91,6 +95,7 @@ export const authExcluded = [
'passwordlessLogin',
'patchTeam',
'patchTeamCrmSettings',
+ 'patchTeamMemberPlan',
'patchUserGroup',
'patchUserOnboarding',
'patchUserTutorial',
@@ -115,6 +120,7 @@ export const authExcluded = [
'startCodexLogin',
'toggleTeamAutoJoinDomain',
'toggleTeamNonAdminInvites',
+ 'updateAiBillingOverage',
'verifyEmailLink',
'verifyFusionauthUserEmail',
'verifyMergeRequest',
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index f8872b9d00..718c765c68 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -31,6 +31,7 @@ rate_limit = []
return_passwordless_code = []
[dependencies]
+ai_billing = { path = "../../crates/ai_billing" }
codex_connection = { path = "../../crates/codex_connection" }
codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }
cursor_api_key = { path = "../../crates/cursor_api_key" }
diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rs
index 2478d76f93..b2b6eb83b0 100644
--- a/services/authentication_service/src/api.rs
+++ b/services/authentication_service/src/api.rs
@@ -38,6 +38,8 @@ mod permissions_extractor;
mod session;
pub(crate) mod signup_policy;
mod user;
+
+pub use user::stripe::StripePrices;
mod webhooks;
// Misc
@@ -152,6 +154,12 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
)
.nest("/jwt", jwt::router())
.nest("/session", session::router())
+ .merge(ai_billing::inbound::ai_billing_router(
+ ai_billing::inbound::AiBillingRouterState {
+ service: state.ai_billing_service.clone(),
+ authorization_state: state.authorization_state.clone(),
+ },
+ ))
.merge(mobile_welcome_email::router(state.clone()))
.nest(
"/webhooks",
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 7d51a69b6d..e16b899c96 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -115,6 +115,18 @@ pub(crate) type FavoritesServiceType = favorites::domain::service::FavoritesServ
pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+/// The AI billing service: plan allowances, prepaid credits, and overage,
+/// resolved through roles + teams and collected through Stripe.
+pub(crate) type AiBillingServiceType = ai_billing::domain::BillingServiceImpl<
+ ai_billing::outbound::RolesTeamsEntitlementSource<
+ UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+ ai_billing::outbound::PgUsageReader,
+ ai_billing::outbound::PgBillingRepo,
+ ai_billing::outbound::StripePaymentGateway,
+>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
@@ -154,8 +166,10 @@ pub(crate) struct ApiContext {
pub referral_service: Arc<ReferralServiceType>,
pub gtm_invite_service: Arc<GtmInviteServiceType>,
pub rate_limit_service: RateLimiter,
- /// The stripe price id
- pub stripe_price_id: String,
+ /// The stripe price ids for each paid plan's seat
+ pub stripe_prices: crate::api::user::stripe::StripePrices,
+ /// AI allowances, credits, and overage
+ pub ai_billing_service: Arc<AiBillingServiceType>,
/// Whether Gmail link consent requests the Google Calendar scope.
pub calendar_scope_enabled: bool,
}
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 4963e8c601..b5e810be31 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -9,8 +9,9 @@ use gtm_invite::inbound::axum_router::dto::{
};
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamRequest, PatchTeamUserRole,
- Team, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamMemberPlanRequest,
+ PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember, TeamPlan, TeamRole,
+ TeamWithMembers,
};
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
@@ -40,9 +41,10 @@ use crate::api::user::patch_user_group::PatchUserGroupRequest;
use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;
use crate::api::user::post_get_names::PostGetNamesRequestBody;
use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;
-use crate::api::user::stripe::StripeSessionResponse;
+use crate::api::user::stripe::change_plan::{ChangePlanRequest, ChangePlanResponse};
use crate::api::user::stripe::create_checkout_session_v2::CreateCheckoutSessionV2Request;
use crate::api::user::stripe::create_portal_session::CreatePortalSessionRequest;
+use crate::api::user::stripe::{PaidPlan, StripeSessionResponse};
use crate::api::{
email, github_pull_requests, health, jwt, link, login, logout, merge, mobile_welcome_email,
oauth, oauth2, permissions, session, user,
@@ -136,6 +138,13 @@ use model::user::{
user::patch_tutorial::handler,
user::stripe::create_checkout_session_v2::create_checkout_session,
user::stripe::create_portal_session::create_portal_session,
+ user::stripe::change_plan::change_plan,
+
+ /// /ai-billing
+ ai_billing::inbound::axum_router::get_summary_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,
+ ai_billing::inbound::axum_router::get_plans_handler,
+ ai_billing::inbound::axum_router::update_overage_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,
+ ai_billing::inbound::axum_router::create_credit_checkout_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,
/// /session
session::session_login::handler,
@@ -162,6 +171,7 @@ use model::user::{
teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::remove_user_from_team::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
+ teams::inbound::axum_router::patch_team_member_plan::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::delete_team_invite::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
/// /referral
@@ -226,6 +236,20 @@ use model::user::{
GtmInviteOffer,
GtmInviteOfferStatus,
+ // Plans and AI billing
+ PaidPlan,
+ ChangePlanRequest,
+ ChangePlanResponse,
+ ai_billing::UsageSnapshot,
+ ai_billing::PlanTier,
+ ai_billing::DenyReason,
+ ai_billing::inbound::axum_router::AiBillingErrorBody,
+ ai_billing::inbound::axum_router::PlanCatalogEntry,
+ ai_billing::inbound::axum_router::PlanCatalogResponse,
+ ai_billing::inbound::axum_router::UpdateOverageRequest,
+ ai_billing::inbound::axum_router::CreditCheckoutRequestBody,
+ ai_billing::inbound::axum_router::CreditCheckoutResponse,
+
// GitHub pull requests
EnrichGithubPullRequestsProxyRequest,
EnrichGithubPullRequestsResponse,
@@ -260,6 +284,7 @@ use model::user::{
CreateTeamRequest,
InviteToTeamRequest,
PatchTeamRequest,
+ PatchTeamMemberPlanRequest,
PatchTeamUserRole,
PatchTeamCrmSettingsRequest,
PatchTeamCrmSettingsResponse,
diff --git a/services/authentication_service/src/api/user.rs b/services/authentication_service/src/api/user.rs
index d6e521010a..7adc99cb79 100644
--- a/services/authentication_service/src/api/user.rs
+++ b/services/authentication_service/src/api/user.rs
@@ -61,6 +61,7 @@ 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(
"/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.rs
new file mode 100644
index 0000000000..27912e05f3
--- /dev/null
+++ b/services/authentication_service/src/api/user/stripe/change_plan.rs
@@ -0,0 +1,163 @@
+use axum::{Json, extract::State};
+use entity_access::domain::{
+ models::{AdminTeamRole, Entity, EntityAccessReceipt, EntityPermission, EntityType},
+ ports::EntityAccessService,
+};
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
+use macro_user_id::cowlike::CowLike;
+use serde::{Deserialize, Serialize};
+use teams::domain::{model::SetTeamMemberPlanError, team_repo::TeamService};
+use utoipa::ToSchema;
+
+use super::{PaidPlan, StripeOperationError};
+use crate::api::context::{ApiContext, AuthorizationService};
+use model::response::ErrorResponse;
+
+/// Request body for switching plans
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangePlanRequest {
+ /// The plan to move the active subscription to
+ pub plan: PaidPlan,
+}
+
+/// Response for a plan change
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangePlanResponse {
+ /// The plan the subscription is now on
+ 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.
+#[utoipa::path(
+ post,
+ path = "/user/stripe/plan",
+ operation_id = "change_plan",
+ request_body = ChangePlanRequest,
+ responses(
+ (status = 200, body = ChangePlanResponse),
+ (status = 400, description = "Plan not available", body = ErrorResponse),
+ (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 = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, user), err, fields(user_id = %user.authorization.user.macro_user_id, plan = ?req.plan))]
+pub async fn change_plan(
+ State(ctx): State<ApiContext>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ Json(req): Json<ChangePlanRequest>,
+) -> Result<Json<ChangePlanResponse>, StripeOperationError> {
+ let target_price = ctx.stripe_prices.price_id(req.plan)?.to_string();
+ let user_id = &user.authorization.user.macro_user_id;
+
+ // A member of a team billed per seat is billed through the team: move
+ // their seat. A free team bills nobody, so its members (admin or not)
+ // change their own personal subscription below.
+ if let Some(team) = ctx
+ .entity_access_service
+ .get_user_team(user_id)
+ .await
+ .map_err(|e| StripeOperationError::TeamsErr(e.into()))?
+ && ctx.teams_service.team_bills_per_seat(&team.team_id).await?
+ {
+ let receipt = EntityAccessReceipt::<AdminTeamRole>::try_new_authenticated_user(
+ user_id.clone().into_owned(),
+ Entity {
+ entity_id: team.team_id.to_string(),
+ entity_type: EntityType::Team,
+ },
+ EntityPermission::TeamRole { role: team.role },
+ )
+ .map_err(|_| StripeOperationError::NotTeamAdmin)?;
+ match ctx
+ .teams_service
+ .set_team_member_plan(receipt, user_id, req.plan)
+ .await
+ {
+ Ok(member) => return Ok(Json(ChangePlanResponse { plan: member.plan })),
+ // The team stopped paying between the two calls: personal it is.
+ Err(SetTeamMemberPlanError::TeamNotPaying) => {}
+ Err(e) => return Err(e.into()),
+ }
+ }
+
+ 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)?;
+
+ if seat_item
+ .price
+ .as_ref()
+ .is_some_and(|price| price.id.as_str() == target_price)
+ {
+ return Err(StripeOperationError::AlreadyOnPlan);
+ }
+
+ 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 }))
+}
diff --git a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
index 93e2c9cb8a..52a1de2ae8 100644
--- a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
+++ b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
@@ -8,7 +8,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use serde::Deserialize;
use utoipa::ToSchema;
-use super::{StripeOperationError, StripeSessionResponse};
+use super::{PaidPlan, StripeOperationError, StripeSessionResponse};
use crate::api::context::{ApiContext, AuthorizationService};
use model::response::ErrorResponse;
@@ -37,6 +37,9 @@ pub struct CreateCheckoutSessionV2Request {
/// Tracking metadata for conversion attribution
#[serde(default)]
pub metadata: CheckoutSessionMetadata,
+ /// The plan to subscribe to. Defaults to Premium.
+ #[serde(default)]
+ pub plan: Option<PaidPlan>,
}
/// Creates a Stripe checkout session for the user to subscribe.
@@ -159,7 +162,8 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
..Default::default()
});
- let price_id = ctx.stripe_price_id;
+ let plan = req.plan.unwrap_or(PaidPlan::Premium);
+ let price_id = ctx.stripe_prices.price_id(plan)?.to_string();
// Create the checkout session
let params = stripe::CreateCheckoutSession {
diff --git a/services/authentication_service/src/api/user/stripe/mod.rs b/services/authentication_service/src/api/user/stripe/mod.rs
index 97cfab6e38..1dd35eec4d 100644
--- a/services/authentication_service/src/api/user/stripe/mod.rs
+++ b/services/authentication_service/src/api/user/stripe/mod.rs
@@ -1,5 +1,6 @@
+pub mod change_plan;
pub mod create_checkout_session_v2;
pub mod create_portal_session;
mod shared;
-pub use shared::{StripeOperationError, StripeSessionResponse};
+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.rs
index 609fca64eb..10bd6fdf54 100644
--- a/services/authentication_service/src/api/user/stripe/shared.rs
+++ b/services/authentication_service/src/api/user/stripe/shared.rs
@@ -7,9 +7,60 @@ use model::response::ErrorResponse;
use roles_and_permissions::domain::model::UserRolesAndPermissionsError;
use serde::Serialize;
use stripe::{ParseIdError, StripeError};
+use teams::domain::model::{CustomerError, SeatPrices, SetTeamMemberPlanError};
use thiserror::Error;
use utoipa::ToSchema;
+/// The paid plans a customer can subscribe to. One seat's plan; a team may
+/// mix them.
+pub use teams::domain::model::SeatPlan as PaidPlan;
+
+/// The Stripe price ids behind each paid plan's per-seat subscription item.
+#[derive(Debug, Clone)]
+pub struct StripePrices {
+ /// Premium seat price.
+ pub premium: String,
+ /// Max seat price, when configured.
+ pub max: Option<String>,
+}
+
+impl StripePrices {
+ /// The price to sell `plan` at.
+ pub fn price_id(&self, plan: PaidPlan) -> Result<&str, StripeOperationError> {
+ 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 {
+ Some(PaidPlan::Premium)
+ } else if self.max.as_deref() == Some(price_id) {
+ Some(PaidPlan::Max)
+ } else {
+ None
+ }
+ }
+
+ /// 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 {
+ premium: self.premium.clone(),
+ max: self.max.clone(),
+ }
+ }
+}
+
/// Shared error type for Stripe operations
#[derive(Debug, Error)]
pub enum StripeOperationError {
@@ -33,6 +84,18 @@ pub enum StripeOperationError {
TeamsErr(#[from] teams::domain::model::TeamError),
#[error("Roles and permissions error")]
RolesErr(#[from] UserRolesAndPermissionsError),
+ #[error("This plan is not available yet")]
+ PlanUnavailable,
+ #[error("No active subscription")]
+ NoSubscription,
+ #[error("More than one active subscription; contact support to change plans")]
+ AmbiguousSubscription,
+ #[error("Already on this plan")]
+ AlreadyOnPlan,
+ #[error("Only team admins can change plans on a team")]
+ NotTeamAdmin,
+ #[error("Team plan change failed")]
+ TeamPlanErr(#[from] SetTeamMemberPlanError),
}
impl IntoResponse for StripeOperationError {
@@ -51,6 +114,20 @@ impl IntoResponse for StripeOperationError {
StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,
StripeOperationError::TeamsErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
StripeOperationError::RolesErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ 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,
+ SetTeamMemberPlanError::CustomerError(CustomerError::PlanUnavailable(_)) => {
+ StatusCode::BAD_REQUEST
+ }
+ SetTeamMemberPlanError::TeamError(_)
+ | SetTeamMemberPlanError::CustomerError(_)
+ | SetTeamMemberPlanError::RolesError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ },
};
(
status,
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
index 0a115fd9fb..20f60284a4 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -2,7 +2,12 @@ use std::collections::HashMap;
use std::str::FromStr;
use crate::api::context::ApiContext;
+use crate::api::user::stripe::PaidPlan;
+use ai_billing::BillingService;
+use ai_billing::outbound::stripe_gateway::{
+ PAYER_METADATA_KEY, PURPOSE_AI_CREDITS, PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY,
+};
use analytics_client::{AnalyticsClient, MetaActionSource, MetaUserData};
use anyhow::Context;
use axum::{
@@ -11,6 +16,7 @@ use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
+use chrono::{DateTime, Utc};
use gtm_invite::domain::ports::GtmInviteService;
use macro_user_id::email::Email;
use macro_user_id::user_id::MacroUserIdStr;
@@ -170,6 +176,12 @@ pub async fn handler(
EventType::InvoicePaymentFailed
| EventType::InvoicePaymentSucceeded
| EventType::InvoicePaid => handle_payment_event(&ctx, event.data.object, event_type).await,
+ // A credit pack paid with a delayed method (bank debit, etc.) completes
+ // its session unpaid and reports the money later; both events book
+ // through the same idempotent path.
+ EventType::CheckoutSessionCompleted | EventType::CheckoutSessionAsyncPaymentSucceeded => {
+ handle_checkout_session_completed(&ctx, event.data.object).await
+ }
_ => {
tracing::error!(event_type=?event_type, "unexpected event type");
Ok(())
@@ -206,6 +218,26 @@ async fn handle_payment_event(
.as_ref()
.map(|subscription| subscription.id().as_str())
else {
+ // Our own one-off invoices: AI overage chunks. Their outcome drives
+ // whether the payer keeps overage; they never touch plan roles.
+ let is_overage_invoice = invoice
+ .metadata
+ .as_ref()
+ .and_then(|m| m.get(PURPOSE_METADATA_KEY))
+ .is_some_and(|purpose| purpose == PURPOSE_AI_OVERAGE);
+ if is_overage_invoice && let Some(invoice_id) = invoice.id.as_ref() {
+ tracing::info!(
+ event_type = ?event_type,
+ invoice_id = %invoice_id,
+ paid = !outcome.is_revoke(),
+ "processing ai overage invoice event"
+ );
+ ctx.ai_billing_service
+ .mark_overage_invoice(invoice_id.as_str(), !outcome.is_revoke())
+ .await
+ .context("failed to record ai overage invoice outcome")?;
+ return Ok(());
+ }
tracing::info!(
event_type = ?event_type,
invoice_id = ?invoice.id.as_ref().map(|id| id.as_str()),
@@ -273,14 +305,35 @@ async fn handle_payment_event(
"processing stripe invoice payment event"
);
+ let plan = subscription
+ .items
+ .data
+ .iter()
+ .filter_map(|item| item.price.as_ref())
+ .find_map(|price| ctx.stripe_prices.plan_for_price(price.id.as_str()));
+ // This subscription was fetched with the `stripe` client, which pins its
+ // own (older) API version where the current period still lives on the
+ // subscription. Webhook payloads arrive on the endpoint's newer version,
+ // where it moved onto the items; `handle_customer_subscription_event`
+ // reads it from there.
+ let period = period_from_timestamps(
+ subscription.current_period_start,
+ subscription.current_period_end,
+ );
+
if let Some(team_id) = subscription.metadata.get("team_id") {
let team_id = macro_uuid::string_to_uuid(team_id)?;
+ let owner = subscription
+ .metadata
+ .get("owner_id")
+ .and_then(|id| MacroUserIdStr::try_from(id.clone()).ok());
return handle_team_subscription_event(
ctx,
subscription_id,
subscription_status,
&team_id,
&email,
+ TeamPlanSync { owner, period },
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
@@ -325,15 +378,123 @@ async fn handle_payment_event(
ctx.user_roles_and_permissions_service
.update_user_roles_and_permissions_for_subscription(
- email,
+ email.clone(),
outcome.personal_subscription_status(),
- ProductTier::Opus,
+ plan.map(PaidPlan::product_tier)
+ .unwrap_or(ProductTier::Opus),
)
.await?;
+ sync_personal_billing_period(ctx, &email, period).await?;
Ok(())
}
+/// The period a subscription is currently in, from Stripe's unix timestamps.
+fn period_from_timestamps(start: i64, end: i64) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
+ DateTime::from_timestamp(start, 0).zip(DateTime::from_timestamp(end, 0))
+}
+
+/// Anchor a personal subscriber's AI allowance to their Stripe period.
+///
+/// A storage failure fails the webhook so Stripe redelivers it: until the
+/// anchor lands the allowance is metered against the calendar month, which
+/// is the wrong window for anyone who did not subscribe on the 1st. Every
+/// step of the handler before this is idempotent, so the retry is safe. An
+/// email that cannot become a user id is not transient and is only logged.
+async fn sync_personal_billing_period(
+ ctx: &ApiContext,
+ email: &Email<Lowercase<'_>>,
+ period: Option<(DateTime<Utc>, DateTime<Utc>)>,
+) -> anyhow::Result<()> {
+ let Some((start, end)) = period else {
+ return Ok(());
+ };
+ let Ok(user_id) = MacroUserIdStr::try_from_email(email.as_ref()) else {
+ tracing::warn!("could not derive a macro user id for billing period sync");
+ return Ok(());
+ };
+ ctx.ai_billing_service
+ .sync_period(&user_id, start, end)
+ .await
+ .context("failed to sync ai billing period")
+}
+
+/// What a team subscription event tells us about the team's billing period.
+///
+/// Seat plans are per member (recorded on the membership and re-stamped as
+/// roles by the teams service), so the subscription's prices say nothing the
+/// team does not already know; only the period anchor is taken from Stripe.
+#[derive(Debug, Clone)]
+struct TeamPlanSync {
+ /// The team owner (the payer), from subscription metadata.
+ owner: Option<MacroUserIdStr<'static>>,
+ /// The subscription's current period.
+ period: Option<(DateTime<Utc>, DateTime<Utc>)>,
+}
+
+/// Anchor the team's per-seat AI allowances to the subscription's period. As
+/// with [`sync_personal_billing_period`], a storage failure fails the webhook
+/// so Stripe redelivers it; a subscription with no `owner_id` metadata is
+/// not transient and is only logged.
+async fn sync_team_billing_period(ctx: &ApiContext, sync: &TeamPlanSync) -> anyhow::Result<()> {
+ let Some(owner) = sync.owner.as_ref() else {
+ tracing::warn!("team subscription without owner_id metadata; skipping period sync");
+ return Ok(());
+ };
+ let Some((start, end)) = sync.period else {
+ return Ok(());
+ };
+ ctx.ai_billing_service
+ .sync_period(owner, start, end)
+ .await
+ .context("failed to sync team billing period")
+}
+
+/// Book a paid credit-pack purchase, from `checkout.session.completed` or,
+/// for delayed payment methods, `checkout.session.async_payment_succeeded`.
+/// Subscription checkouts also arrive here and are ignored; the subscription
+/// events carry those. Idempotent on the session id.
+#[tracing::instrument(skip(ctx, event_object), err, ret)]
+async fn handle_checkout_session_completed(
+ ctx: &ApiContext,
+ event_object: EventObject,
+) -> anyhow::Result<()> {
+ let session = match event_object {
+ EventObject::CheckoutSessionCompleted(session)
+ | EventObject::CheckoutSessionAsyncPaymentSucceeded(session) => session,
+ _ => anyhow::bail!("expected checkout session"),
+ };
+ let metadata = session.metadata.clone().unwrap_or_default();
+ if metadata.get(PURPOSE_METADATA_KEY).map(String::as_str) != Some(PURPOSE_AI_CREDITS) {
+ tracing::info!(session_id = %session.id, "checkout session is not a credit purchase");
+ return Ok(());
+ }
+ if session.payment_status.as_str() != "paid" {
+ tracing::info!(
+ session_id = %session.id,
+ payment_status = ?session.payment_status,
+ "credit purchase not paid yet; waiting for checkout.session.async_payment_succeeded"
+ );
+ return Ok(());
+ }
+ let payer = metadata
+ .get(PAYER_METADATA_KEY)
+ .cloned()
+ .context("credit checkout session is missing the payer")?;
+ let payer = MacroUserIdStr::try_from(payer).context("invalid payer id on checkout session")?;
+ let amount_cents = session
+ .amount_total
+ .or_else(|| metadata.get("amount_cents").and_then(|a| a.parse().ok()))
+ .context("credit checkout session has no amount")?;
+
+ ctx.ai_billing_service
+ .apply_credit_purchase(&payer, amount_cents, session.id.as_str())
+ .await
+ .context("failed to book credit purchase")?;
+ tracing::info!(payer = %payer, amount_cents, "booked ai credit purchase");
+ Ok(())
+}
+
#[tracing::instrument(skip(ctx, event_object, previous_attributes), err, ret)]
async fn handle_customer_subscription_event(
ctx: &ApiContext,
@@ -463,10 +624,27 @@ async fn handle_customer_subscription_event(
mark_gtm_invite_converted(ctx, &email, subscription_id).await;
}
+ // For a personal subscription the seat price says which plan this is (a
+ // team subscription may carry one item per plan; its members' plans are
+ // recorded on the team). The first item carries the current period on
+ // this API version.
+ let plan = subscription
+ .items
+ .data
+ .iter()
+ .find_map(|item| ctx.stripe_prices.plan_for_price(item.price.id.as_str()));
+ let period = subscription.items.data.first().and_then(|item| {
+ period_from_timestamps(item.current_period_start, item.current_period_end)
+ });
+
// Get subscription metadata, if this is a team subscription then we need to handle it
// separately.
if let Some(team_id) = subscription.metadata.get("team_id") {
let team_id = macro_uuid::string_to_uuid(team_id)?;
+ let owner = subscription
+ .metadata
+ .get("owner_id")
+ .and_then(|id| MacroUserIdStr::try_from(id.clone()).ok());
// We need to handle team subscriptions differently than regular subscriptions.
return handle_team_subscription_event(
ctx,
@@ -474,6 +652,7 @@ async fn handle_customer_subscription_event(
subscription_status,
&team_id,
&email,
+ TeamPlanSync { owner, period },
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
@@ -571,15 +750,11 @@ async fn handle_customer_subscription_event(
tracing::error!(error=?e, "failed to process referral on subscription created");
}
- // Extract the price ID(s) from the subscription items
- let _price_id = subscription
- .items
- .data
- .first() // SAFETY: we only need the first item because we know the user is not in a team
- .map(|item| item.price.id.as_str().to_string())
- .context("no price id attached to subscription")?;
-
- let product_tier = ProductTier::Opus;
+ // Unknown prices (legacy or manually created subscriptions) keep the
+ // Premium entitlements.
+ let product_tier = plan
+ .map(PaidPlan::product_tier)
+ .unwrap_or(ProductTier::Opus);
ctx.user_roles_and_permissions_service
.update_user_roles_and_permissions_for_subscription(
@@ -588,6 +763,7 @@ async fn handle_customer_subscription_event(
product_tier,
)
.await?;
+ sync_personal_billing_period(ctx, &email, period).await?;
// Track conversion events to GA and Meta (fire-and-forget)
let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
@@ -678,6 +854,7 @@ async fn handle_team_subscription_event<'a>(
subscription_status: &str,
team_id: &uuid::Uuid,
email: &Email<Lowercase<'a>>,
+ plan_sync: TeamPlanSync,
tracking_data: SubscriptionTrackingData,
) -> anyhow::Result<()> {
tracing::trace!("handling team subscription");
@@ -694,9 +871,12 @@ async fn handle_team_subscription_event<'a>(
match subscription_status {
"active" | "trialing" => {
+ // 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)
.await?;
+ sync_team_billing_period(ctx, &plan_sync).await?;
ctx.teams_service
.patch_team_payment_status(team_id, true)
@@ -713,6 +893,7 @@ async fn handle_team_subscription_event<'a>(
ctx.teams_service
.revoke_permissions_for_team_members(team_id)
.await?;
+ sync_team_billing_period(ctx, &plan_sync).await?;
ctx.teams_service
.patch_team_payment_status(team_id, false)
.await?;
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index 31863d73af..3346319893 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -70,6 +70,10 @@ maybe_env_vars! {
pub struct GtmInvitePromoCode;
/// Hours a GTM invite link stays openable after creation. Defaults to 48.
pub struct GtmInviteLinkTtlHours;
+ /// Stripe price id for the Max plan seat. Optional so the service can
+ /// deploy before the price exists in Stripe; until it is set, Max checkout
+ /// and plan changes answer 400 and every subscription maps to Premium.
+ pub struct StripeMaxPriceId;
}
/// The configuration parameters for the application.
@@ -165,8 +169,11 @@ pub struct Config {
pub gtm_invite_promo_code: GtmInvitePromoCode,
/// Hours a GTM invite link can be opened and redeemed (optional, defaults to 48).
pub gtm_invite_link_ttl_hours: GtmInviteLinkTtlHours,
- /// The stripe price id
+ /// The stripe price id for the Premium plan seat
pub stripe_price_id: StripePriceId,
+ /// The stripe price id for the Max plan seat (optional, see
+ /// [`StripeMaxPriceId`])
+ pub stripe_max_price_id: StripeMaxPriceId,
/// The internal api key
pub internal_api_key: InternalApiKey,
/// Comma-separated Kafka bootstrap servers for the macro event broker.
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 872fbd2f61..7b4e514c09 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -348,11 +348,21 @@ async fn main() -> anyhow::Result<()> {
user_roles_and_permissions_macro_db,
);
+ let stripe_prices = api::StripePrices {
+ premium: config.stripe_price_id.to_string(),
+ max: config
+ .stripe_max_price_id
+ .value()
+ .filter(|id| !id.trim().is_empty())
+ .map(str::to_owned),
+ };
+ if stripe_prices.max.is_none() {
+ tracing::warn!("STRIPE_MAX_PRICE_ID is not set; the Max plan cannot be sold");
+ }
+
let teams_repo_impl = TeamRepositoryImpl::new(db.clone());
- let customer_repo_impl = CustomerRepositoryImpl::new(
- stripe_client.clone(),
- config.stripe_price_id.to_string().clone(),
- );
+ let customer_repo_impl =
+ CustomerRepositoryImpl::new(stripe_client.clone(), stripe_prices.seat_prices());
let favorites_service = favorites::domain::service::FavoritesServiceImpl::new(
favorites::outbound::pg_favorites_repo::PgFavoritesRepo::new(db.clone()),
);
@@ -433,7 +443,7 @@ async fn main() -> anyhow::Result<()> {
);
let teams_service_impl = TeamServiceImpl::new_with_analytics(
- teams_repo_impl,
+ teams_repo_impl.clone(),
customer_repo_impl,
channel_service.clone(),
user_roles_and_permissions_service.clone(),
@@ -497,6 +507,16 @@ async fn main() -> anyhow::Result<()> {
None
};
+ let stripe_client = Arc::new(stripe_client);
+ let ai_billing_service = Arc::new(ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ user_roles_and_permissions_service.clone(),
+ teams_repo_impl.clone(),
+ ),
+ ai_billing::outbound::PgUsageReader::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),
+ ));
let document_storage_service_client = Arc::new(document_storage_service_client);
let user_deletion = Arc::new(
authentication_service::outbound::user_deletion::UserDeletionAdapter::new(
@@ -518,7 +538,7 @@ async fn main() -> anyhow::Result<()> {
cursor_api_key_cipher,
codex_connection,
macro_cache_client: Arc::new(macro_cache_client),
- stripe_client: Arc::new(stripe_client),
+ stripe_client,
document_storage_service_client,
user_deletion,
email_service_client: Arc::new(email_service_client),
@@ -567,7 +587,8 @@ async fn main() -> anyhow::Result<()> {
}),
loops_client: Arc::new(loops_client),
analytics_client,
- stripe_price_id: config.stripe_price_id.to_string(),
+ stripe_prices,
+ ai_billing_service,
},
config.port,
)
diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.toml
index 8508baa8dd..365c9a5edf 100644
--- a/services/document_cognition_service/Cargo.toml
+++ b/services/document_cognition_service/Cargo.toml
@@ -26,7 +26,9 @@ local_queue = []
[dependencies]
agent = { path = "../../crates/agent", features = ["debug-messages"] }
ai_projections = { path = "../../crates/ai_projections", features = ["agent"] }
+ai_billing = { path = "../../crates/ai_billing" }
ai_usage = { path = "../../crates/ai_usage" }
+authentication_service_client = { path = "../../crates/authentication_service_client" }
aho-corasick = "1.1.3"
attachment = { path = "../../crates/attachment", features = ["provider"] }
non_empty = { path = "../../crates/non_empty" }
@@ -111,6 +113,10 @@ redis = { workspace = true, features = [
regex = { workspace = true }
reqwest.workspace = true
reminders = { path = "../../crates/reminders", default-features = false, features = ["ports"] }
+teams = { path = "../../crates/teams", default-features = false, features = [
+ "outbound",
+ "ports",
+] }
roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = [
"outbound",
] }
diff --git a/services/document_cognition_service/src/api/context.rs b/services/document_cognition_service/src/api/context.rs
index 4f6e5d93fa..1354ab8a09 100644
--- a/services/document_cognition_service/src/api/context.rs
+++ b/services/document_cognition_service/src/api/context.rs
@@ -44,6 +44,19 @@ pub type DcsUserPermissionsService =
roles_and_permissions::outbound::pgpool::MacroDB,
>;
+/// The AI billing gate: reads plan allowances, credits, and overage state.
+/// DCS never charges anyone (the payment gateway is a no-op); settlement is
+/// requested from the authentication service.
+pub type DcsAiBillingService = ai_billing::domain::BillingServiceImpl<
+ ai_billing::outbound::RolesTeamsEntitlementSource<
+ DcsUserPermissionsService,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+ ai_billing::outbound::PgUsageReader,
+ ai_billing::outbound::PgBillingRepo,
+ ai_billing::outbound::NoOpPaymentGateway,
+>;
+
/// Type alias for the chat model entitlement extractor wired to DCS services.
pub type DcsChatModelAccess = chat::inbound::http::extractors::ChatModelAccess<
DcsAuthorizationService,
@@ -132,6 +145,8 @@ pub struct ApiContext {
pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
pub authorization_state: MacroAuthorizationState<DcsAuthorizationService>,
pub user_permissions_service: Arc<DcsUserPermissionsService>,
+ /// Plan allowance gate for AI requests.
+ pub ai_billing: Arc<DcsAiBillingService>,
pub config: Arc<Config>,
pub internal_api_key: InternalApiKey,
pub notification_ingress_service: Arc<NotificationIngressType>,
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 8c01ee0001..07e90d72dd 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -519,6 +519,15 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
search_service_client,
email_service_client_external,
authorization_state: authorization_state.clone(),
+ ai_billing: Arc::new(ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ (*user_permissions_service).clone(),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
+ ),
+ ai_billing::outbound::PgUsageReader::new(pool.clone()),
+ ai_billing::outbound::PgBillingRepo::new(pool.clone()),
+ ai_billing::outbound::NoOpPaymentGateway,
+ )),
user_permissions_service,
config: Arc::new(Config::new_empty_for_test()),
internal_api_key: InternalApiKey::Comptime("testing"),
diff --git a/services/document_cognition_service/src/api/stream/chat_message.rs b/services/document_cognition_service/src/api/stream/chat_message.rs
index 0e08f51218..0793983f56 100644
--- a/services/document_cognition_service/src/api/stream/chat_message.rs
+++ b/services/document_cognition_service/src/api/stream/chat_message.rs
@@ -15,6 +15,7 @@ use crate::service::get_chat::get_chat;
use crate::service::notification::notify;
use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent};
use agent::{AgentLoop, StreamAccumulator};
+use ai_billing::BillingService;
use async_stream::stream;
use attachment::FormattedParts;
use axum::Json;
@@ -105,6 +106,9 @@ pub struct ChatMessageError {
pub stream_id: Option<String>,
#[serde(skip)]
pub status: Option<StatusCode>,
+ /// Stable machine-readable code for payment-required errors.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub code: Option<String>,
}
impl fmt::Display for ChatMessageError {
@@ -132,8 +136,8 @@ impl IntoResponse for ChatMessageError {
(status = 200, description = "Stream initiated successfully", body = SendChatMessageResponse),
(status = 400, description = "Bad request", body = ChatMessageError),
(status = 401, description = "Unauthorized"),
- (status = 402, description = "Payment required — user lacks access to the requested model"),
- (status = 403, description = "Forbidden"),
+ (status = 402, description = "Payment required — the user's AI allowance is used up", body = ChatMessageError),
+ (status = 403, description = "Forbidden — user lacks access to the requested model", body = ChatMessageError),
)
)]
#[tracing::instrument(skip(state, model_access, user, bearer, request), fields(chat_id=?request.chat_id, user_id = %user.authorization.user.macro_user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.entity_id.as_ref()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]
@@ -154,6 +158,23 @@ pub async fn send_chat_message(
.await
}
+/// Why the billing gate refuses this user right now, if it does. A gate
+/// failure (not a refusal) is logged and lets the request through: an outage
+/// in billing must not take AI down with it.
+async fn billing_denial(
+ ctx: &ApiContext,
+ user_id: &MacroUserIdStr<'_>,
+) -> Option<ai_billing::DenyReason> {
+ match ctx.ai_billing.check_allowance(user_id).await {
+ Ok(ai_billing::AllowanceDecision::Allow) => None,
+ Ok(ai_billing::AllowanceDecision::Deny(reason)) => Some(reason),
+ Err(e) => {
+ tracing::error!(error = ?e, user_id = %user_id, "ai billing gate failed; allowing request");
+ None
+ }
+ }
+}
+
async fn send_chat_message_inner(
state: ApiContext,
model_access: DcsChatModelAccess,
@@ -181,6 +202,18 @@ async fn send_chat_message_inner(
error: format!("No access to model {}", request.model),
stream_id: Some(stream_id.clone()),
status: Some(StatusCode::FORBIDDEN),
+ code: None,
+ });
+ }
+ // Paid users draw on a monthly AI allowance (then credits, then overage).
+ if model_access.professional()
+ && let Some(reason) = billing_denial(&ctx, &user_id).await
+ {
+ return Err(ChatMessageError {
+ error: reason.message().to_string(),
+ stream_id: Some(stream_id.clone()),
+ status: Some(StatusCode::PAYMENT_REQUIRED),
+ code: Some(reason.code().to_string()),
});
}
let model = request.model.clone();
@@ -207,6 +240,7 @@ async fn send_chat_message_inner(
error: format!("Permission check failed: {:?}", e),
stream_id: Some(stream_id),
status: None,
+ code: None,
});
}
Ok(access) => match access {
@@ -215,6 +249,7 @@ async fn send_chat_message_inner(
error: "Insufficient permissions to send messages".to_string(),
stream_id: Some(stream_id),
status: None,
+ code: None,
});
}
_ => (),
@@ -258,6 +293,7 @@ async fn send_chat_message_inner(
error: "Failed to store message".to_string(),
stream_id: Some(stream_id.clone()),
status: None,
+ code: None,
}
})?;
let user_message_id = resolved.message_id;
@@ -300,6 +336,7 @@ async fn send_chat_message_inner(
error: "Failed to build request".to_string(),
stream_id: Some(stream_id.clone()),
status: None,
+ code: None,
}
})?;
@@ -376,6 +413,7 @@ async fn create_new_chat(
error: "Failed to create chat".to_string(),
stream_id: Some(stream_id.to_string()),
status: None,
+ code: None,
}
})?;
let share_permission = SharePermissionV2::new_chat_share_permission(team_default);
@@ -397,6 +435,7 @@ async fn create_new_chat(
error: "Failed to create chat".to_string(),
stream_id: Some(stream_id.to_string()),
status: None,
+ code: None,
}
})?;
@@ -425,6 +464,7 @@ async fn create_new_chat(
error: "Failed to get chat".to_string(),
stream_id: Some(stream_id.to_string()),
status: None,
+ code: None,
}
})?;
diff --git a/services/document_cognition_service/src/api/structured_completion.rs b/services/document_cognition_service/src/api/structured_completion.rs
index aaeb2d781e..772a8fdd50 100644
--- a/services/document_cognition_service/src/api/structured_completion.rs
+++ b/services/document_cognition_service/src/api/structured_completion.rs
@@ -3,6 +3,7 @@ use crate::model::stream::ToolSet;
use agent::structured_output::DynamicSchema;
use agent::types::{ChatMessage, ChatMessageContent, Role};
use agent::{AgentLoop, StreamAccumulator};
+use ai_billing::BillingService;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
@@ -35,6 +36,9 @@ pub struct StructuredCompletionError {
pub error: String,
#[serde(skip)]
pub status: StatusCode,
+ /// Stable machine-readable code for payment-required errors.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub code: Option<String>,
}
impl fmt::Display for StructuredCompletionError {
@@ -73,6 +77,24 @@ pub async fn structured_completion(
let user_id = user.authorization.user.macro_user_id.clone();
+ // Paid users draw on a monthly AI allowance (then credits, then overage).
+ // A gate failure is logged and lets the request through.
+ if model_access.professional() {
+ match ctx.ai_billing.check_allowance(&user_id).await {
+ Ok(ai_billing::AllowanceDecision::Allow) => {}
+ Ok(ai_billing::AllowanceDecision::Deny(reason)) => {
+ return Err(StructuredCompletionError {
+ error: reason.message().to_string(),
+ status: StatusCode::PAYMENT_REQUIRED,
+ code: Some(reason.code().to_string()),
+ });
+ }
+ Err(e) => {
+ tracing::error!(error = ?e, user_id = %user_id, "ai billing gate failed; allowing request");
+ }
+ }
+ }
+
let tools_prompt: &(dyn std::fmt::Display + Sync) = match request.toolset {
ToolSet::All => &ctx.all_tools_prompt,
ToolSet::None => &prompt::BASE_PROMPT,
@@ -116,6 +138,7 @@ pub async fn structured_completion(
.map_err(|e| StructuredCompletionError {
error: format!("Agent loop failed: {e}"),
status: StatusCode::INTERNAL_SERVER_ERROR,
+ code: None,
})?;
let mut accumulator = StreamAccumulator::new();
@@ -128,6 +151,7 @@ pub async fn structured_completion(
return Err(StructuredCompletionError {
error: format!("Agent loop error: {e}"),
status: StatusCode::INTERNAL_SERVER_ERROR,
+ code: None,
});
}
}
@@ -169,6 +193,7 @@ pub async fn structured_completion(
.map_err(|e| StructuredCompletionError {
error: format!("Structured completion failed: {e}"),
status: StatusCode::INTERNAL_SERVER_ERROR,
+ code: None,
})?;
Ok(Json(StructuredCompletionResponse { result }))
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 7a381a8ebb..d302f157e5 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -34,8 +34,8 @@ use macro_authorization::{
};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::{
- CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, EmailServiceUrl,
- LexicalServiceUrl, StaticFileServiceUrl, SyncServiceUrl,
+ AuthServiceUrl, CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl,
+ EmailServiceUrl, LexicalServiceUrl, StaticFileServiceUrl, SyncServiceUrl,
};
use notification::domain::service::{
NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,
@@ -453,7 +453,37 @@ async fn main() -> anyhow::Result<()> {
lexical_client.clone(),
&side_effect_clients,
);
- let recorder = ai_usage::pg_recorder(db.clone());
+ let user_permissions_service = Arc::new(
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
+ ),
+ );
+
+ // The AI billing gate reads allowances, credits, and overage state here;
+ // collection (Stripe) lives in the authentication service, which the
+ // recorder below asks to settle once a payer runs past their allowance.
+ let ai_billing = Arc::new(ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ (*user_permissions_service).clone(),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(db.clone()),
+ ),
+ ai_billing::outbound::PgUsageReader::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::NoOpPaymentGateway,
+ ));
+ let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(
+ internal_api_key.clone(),
+ AuthServiceUrl::new()?.to_string(),
+ ));
+ let recorder: Arc<dyn ai_usage::UsageRecorder> =
+ Arc::new(ai_billing::outbound::SettlingUsageRecorder::new(
+ Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
+ ai_usage::outbound::PgUsageRepo::new(db.clone()),
+ )),
+ ai_billing.clone(),
+ ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client),
+ ));
// The import pipeline: staged/imported external items, gather jobs over
// the user's connectors, and the Haiku import job. Built before the tool
@@ -780,13 +810,6 @@ async fn main() -> anyhow::Result<()> {
)
.with_auth_completed_hook(pipedream_auth_hook);
- let user_permissions_service = Arc::new(
- roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
- roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
- roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
- ),
- );
-
let api_result = api::setup_and_serve(ApiContext {
db: db.clone(),
email_service_client_external,
@@ -795,6 +818,7 @@ async fn main() -> anyhow::Result<()> {
search_service_client,
authorization_state,
user_permissions_service,
+ ai_billing,
internal_api_key: config.internal_api_key.clone(),
config: Arc::new(config),
notification_ingress_service,