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.

Add GTM invite links: staff dashboard and signup integration (#6484)

Jacob Beckermanfbcb6c7c6c84
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index afacdab980..b88d777cd3 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1196,6 +1196,7 @@
"crates/genai_telemetry",
"crates/generic_email_domains",
"crates/github",
+ "crates/gtm_invite",
"crates/harness_id",
"crates/harness_token",
"crates/invite_email",
@@ -5141,6 +5142,26 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "gtm_invite": [
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/cowlike",
+ "crates/gtm_invite",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/ip_extractor",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/model-error-response",
+ "crates/model_user",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/workspace-hack"
+ ],
"harness_id": [
"crates/harness_id",
"crates/workspace-hack"
diff --git a/.sqlx/query-0127bf6502a430d2bc82fd954a3f251f89eedb5a776cfdc5ad5f46a1998b69e6.json b/.sqlx/query-0127bf6502a430d2bc82fd954a3f251f89eedb5a776cfdc5ad5f46a1998b69e6.json
new file mode 100644
index 0000000000..cd6a9312f8
--- /dev/null
+++ b/.sqlx/query-0127bf6502a430d2bc82fd954a3f251f89eedb5a776cfdc5ad5f46a1998b69e6.json
@@ -0,0 +1,113 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at, revoked_at, open_count,\n first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,\n stripe_subscription_id\n FROM gtm_invite_link\n WHERE ($1::TEXT IS NULL OR created_by_user_id = $1)\n ORDER BY created_at DESC, id DESC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "recipient_email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "note",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "promo_code",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 11,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "redeemed_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "redeemed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "converted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "stripe_subscription_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "0127bf6502a430d2bc82fd954a3f251f89eedb5a776cfdc5ad5f46a1998b69e6"
+}
diff --git a/.sqlx/query-03c88ad84b1339872aee98eb5f2ffbe4cc67b248b298dbc665872012bc28f8b6.json b/.sqlx/query-03c88ad84b1339872aee98eb5f2ffbe4cc67b248b298dbc665872012bc28f8b6.json
new file mode 100644
index 0000000000..4d1ec78bf8
--- /dev/null
+++ b/.sqlx/query-03c88ad84b1339872aee98eb5f2ffbe4cc67b248b298dbc665872012bc28f8b6.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE gtm_invite_link\n SET open_count = open_count + 1,\n first_opened_at = COALESCE(first_opened_at, $2)\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "03c88ad84b1339872aee98eb5f2ffbe4cc67b248b298dbc665872012bc28f8b6"
+}
diff --git a/.sqlx/query-4677c0c3664d2f32bb09e30009ae9e0f094035b992c8e3c5c045fd5982015f24.json b/.sqlx/query-4677c0c3664d2f32bb09e30009ae9e0f094035b992c8e3c5c045fd5982015f24.json
new file mode 100644
index 0000000000..d62449d5ce
--- /dev/null
+++ b/.sqlx/query-4677c0c3664d2f32bb09e30009ae9e0f094035b992c8e3c5c045fd5982015f24.json
@@ -0,0 +1,112 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at, revoked_at, open_count,\n first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,\n stripe_subscription_id\n FROM gtm_invite_link\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "recipient_email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "note",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "promo_code",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 11,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "redeemed_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "redeemed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "converted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "stripe_subscription_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "4677c0c3664d2f32bb09e30009ae9e0f094035b992c8e3c5c045fd5982015f24"
+}
diff --git a/.sqlx/query-5b4b7bdb25c7660ceebef4ea5683f93776eb88d61a20d64b9c4f47fc46a0223f.json b/.sqlx/query-5b4b7bdb25c7660ceebef4ea5683f93776eb88d61a20d64b9c4f47fc46a0223f.json
new file mode 100644
index 0000000000..6fc4ad15c2
--- /dev/null
+++ b/.sqlx/query-5b4b7bdb25c7660ceebef4ea5683f93776eb88d61a20d64b9c4f47fc46a0223f.json
@@ -0,0 +1,112 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at, revoked_at, open_count,\n first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,\n stripe_subscription_id\n FROM gtm_invite_link\n WHERE token = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "recipient_email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "note",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "promo_code",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 11,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "redeemed_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "redeemed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "converted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "stripe_subscription_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "5b4b7bdb25c7660ceebef4ea5683f93776eb88d61a20d64b9c4f47fc46a0223f"
+}
diff --git a/.sqlx/query-5e1c5170a61a76cb9b13645d3470bd2c7b1395d29f6da1c208b6070fc969cf92.json b/.sqlx/query-5e1c5170a61a76cb9b13645d3470bd2c7b1395d29f6da1c208b6070fc969cf92.json
new file mode 100644
index 0000000000..1daa50f652
--- /dev/null
+++ b/.sqlx/query-5e1c5170a61a76cb9b13645d3470bd2c7b1395d29f6da1c208b6070fc969cf92.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE gtm_invite_link\n SET converted_at = $3,\n stripe_subscription_id = $2\n WHERE redeemed_by_user_id = $1\n AND converted_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5e1c5170a61a76cb9b13645d3470bd2c7b1395d29f6da1c208b6070fc969cf92"
+}
diff --git a/.sqlx/query-677ac77de487d5a7b77c43ae50a91abbd6bfe5257b95f5528947fb7ae6eb991c.json b/.sqlx/query-677ac77de487d5a7b77c43ae50a91abbd6bfe5257b95f5528947fb7ae6eb991c.json
new file mode 100644
index 0000000000..62c94850ba
--- /dev/null
+++ b/.sqlx/query-677ac77de487d5a7b77c43ae50a91abbd6bfe5257b95f5528947fb7ae6eb991c.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO gtm_invite_link\n (id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "677ac77de487d5a7b77c43ae50a91abbd6bfe5257b95f5528947fb7ae6eb991c"
+}
diff --git a/.sqlx/query-744ce586820e9006dab5f05ce51b0622f46ca0e73db20da6a5e376578629845b.json b/.sqlx/query-744ce586820e9006dab5f05ce51b0622f46ca0e73db20da6a5e376578629845b.json
new file mode 100644
index 0000000000..2573cd858d
--- /dev/null
+++ b/.sqlx/query-744ce586820e9006dab5f05ce51b0622f46ca0e73db20da6a5e376578629845b.json
@@ -0,0 +1,112 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at, revoked_at, open_count,\n first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,\n stripe_subscription_id\n FROM gtm_invite_link\n WHERE redeemed_by_user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "recipient_email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "note",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "promo_code",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 11,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "redeemed_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "redeemed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "converted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "stripe_subscription_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "744ce586820e9006dab5f05ce51b0622f46ca0e73db20da6a5e376578629845b"
+}
diff --git a/.sqlx/query-856bef0f024f9c257f5f02597f78182a88f7cf505246f7a9e36ab93e1a3b4fe2.json b/.sqlx/query-856bef0f024f9c257f5f02597f78182a88f7cf505246f7a9e36ab93e1a3b4fe2.json
new file mode 100644
index 0000000000..8602395de5
--- /dev/null
+++ b/.sqlx/query-856bef0f024f9c257f5f02597f78182a88f7cf505246f7a9e36ab93e1a3b4fe2.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE gtm_invite_link\n SET revoked_at = $2\n WHERE id = $1\n AND revoked_at IS NULL\n AND redeemed_by_user_id IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "856bef0f024f9c257f5f02597f78182a88f7cf505246f7a9e36ab93e1a3b4fe2"
+}
diff --git a/.sqlx/query-b131304342eee942b45b7b784cb019c00c239d2b5508b09ab8cceea1fd3b92de.json b/.sqlx/query-b131304342eee942b45b7b784cb019c00c239d2b5508b09ab8cceea1fd3b92de.json
new file mode 100644
index 0000000000..454bc1074f
--- /dev/null
+++ b/.sqlx/query-b131304342eee942b45b7b784cb019c00c239d2b5508b09ab8cceea1fd3b92de.json
@@ -0,0 +1,114 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE gtm_invite_link\n SET redeemed_by_user_id = $2,\n redeemed_at = COALESCE(redeemed_at, $3)\n WHERE id = $1\n AND revoked_at IS NULL\n AND ((redeemed_by_user_id IS NULL AND expires_at > $3)\n OR redeemed_by_user_id = $2)\n RETURNING id, token, first_name, recipient_email, note, promo_code,\n created_by_user_id, created_at, expires_at, revoked_at, open_count,\n first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,\n stripe_subscription_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "recipient_email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "note",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "promo_code",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 11,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "redeemed_by_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "redeemed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "converted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "stripe_subscription_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "b131304342eee942b45b7b784cb019c00c239d2b5508b09ab8cceea1fd3b92de"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 32ef8b1412..27d5c0c8ac 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1630,6 +1630,7 @@ dependencies = [
"fusionauth",
"futures",
"github",
+ "gtm_invite",
"http-body-util",
"jsonwebtoken 10.3.0",
"last_online_tracker",
@@ -7598,6 +7599,38 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "gtm_invite"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "axum-extra",
+ "chrono",
+ "http-body-util",
+ "ip_extractor",
+ "macro_authorization",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "mockall",
+ "model-error-response",
+ "model_user",
+ "rand 0.9.4",
+ "rate_limit",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "tower 0.5.3",
+ "tracing",
+ "utoipa",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "guppy"
version = "0.17.26"
diff --git a/Cargo.toml b/Cargo.toml
index 9ff9ee4562..3459218b9c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -52,6 +52,7 @@ members = [
"crates/graphql_properties",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
+ "crates/gtm_invite",
"crates/harness_id",
"crates/harness_token",
"crates/harnesses",
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index ecc889e668..f05076ec65 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -101,6 +101,8 @@ const AUTH_URLS = [
`${ROUTER_BASE_CONCAT}welcome`,
`${ROUTER_BASE_CONCAT}mobile-email-signup`,
`${ROUTER_BASE_CONCAT}team-invite`,
+ `${ROUTER_BASE_CONCAT}invite`,
+ `${ROUTER_BASE_CONCAT}internal/invite-links`,
];
const [sidebarState, setSidebarState] = makePersisted(
diff --git a/apps/web/src/features/gtm-invite/InviteLinksPortal.tsx b/apps/web/src/features/gtm-invite/InviteLinksPortal.tsx
new file mode 100644
index 0000000000..0257630243
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/InviteLinksPortal.tsx
@@ -0,0 +1,484 @@
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { toast } from '@core/component/Toast/Toast';
+import { useEmail, useIsAuthenticated } from '@core/context/user';
+import { idToDisplayName } from '@core/user/util';
+import LogoIcon from '@icon/macro-logo.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import LinkIcon from '@phosphor/link.svg';
+import XIcon from '@phosphor/x.svg';
+import {
+ type GtmInviteLink,
+ useCreateGtmInviteLinkMutation,
+ useGtmInviteLinksQuery,
+ useRevokeGtmInviteLinkMutation,
+} from '@queries/gtm-invite/links';
+import { useNavigate } from '@solidjs/router';
+import { Button, cn } from '@ui';
+import {
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ Match,
+ onMount,
+ Show,
+ Switch,
+} from 'solid-js';
+import {
+ buildInviteLinkUrl,
+ describeInviteStatus,
+ formatFreeMonths,
+ formatTimeLeft,
+ INVITE_PORTAL_ROUTE,
+ type InviteStatusTone,
+} from './core/invite-link';
+
+const STAFF_EMAIL_DOMAIN = '@macro.com';
+
+/**
+ * Internal portal for the GTM team: mint personal 48-hour invite links and
+ * watch them get opened, signed up through, and converted. Reachable at
+ * `/internal/invite-links`; the auth service only serves staff accounts, this
+ * gate just keeps everyone else from seeing an empty shell.
+ */
+export function InviteLinksPortal() {
+ const isAuthenticated = useIsAuthenticated();
+ const email = useEmail();
+ const navigate = useNavigate();
+ const analytics = useAnalytics();
+
+ const isStaff = () =>
+ email()?.toLowerCase().endsWith(STAFF_EMAIL_DOMAIN) ?? false;
+
+ onMount(() => {
+ analytics.pageView('gtm_invite_portal');
+ });
+
+ return (
+ <div class="size-full overflow-y-auto bg-surface font-sans text-ink">
+ <div class="mx-auto flex w-full max-w-5xl flex-col gap-8 px-6 py-10">
+ <header class="flex items-center gap-3">
+ <LogoIcon class="size-8 text-accent" />
+ <div class="flex flex-col">
+ <h1 class="text-xl font-semibold tracking-tight">Invite links</h1>
+ <p class="text-sm text-ink-muted">
+ Personal signup links for prospects. Each one is good for 48 hours
+ and gives the recipient their first month of Premium free.
+ </p>
+ </div>
+ </header>
+
+ <Switch>
+ <Match when={isAuthenticated() === false}>
+ <Gate
+ title="Log in to continue"
+ body="This page is for Macro staff."
+ action={
+ <Button
+ variant="cta"
+ size="lg"
+ onClick={() =>
+ navigate(
+ `/login?redirect=${encodeURIComponent(INVITE_PORTAL_ROUTE)}`
+ )
+ }
+ >
+ Log in
+ </Button>
+ }
+ />
+ </Match>
+ <Match when={isAuthenticated() === true && !isStaff()}>
+ <Gate
+ title="Macro staff only"
+ body="Invite links can only be created from a @macro.com account."
+ />
+ </Match>
+ <Match when={isAuthenticated() === true && isStaff()}>
+ <PortalBody />
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ );
+}
+
+function Gate(props: { title: string; body: string; action?: JSX.Element }) {
+ return (
+ <div class="flex flex-col items-start gap-4 rounded-xl border border-edge p-6">
+ <div class="flex flex-col gap-1">
+ <h2 class="text-base font-semibold">{props.title}</h2>
+ <p class="text-sm text-ink-muted">{props.body}</p>
+ </div>
+ {props.action}
+ </div>
+ );
+}
+
+function PortalBody() {
+ const [mine, setMine] = createSignal(false);
+ const [latest, setLatest] = createSignal<GtmInviteLink | undefined>();
+ const linksQuery = useGtmInviteLinksQuery(mine);
+ const links = () => (linksQuery.isSuccess ? linksQuery.data : []);
+
+ return (
+ <div class="flex flex-col gap-8">
+ <CreateLinkForm onCreated={setLatest} />
+
+ <Show when={latest()}>{(link) => <LatestLinkCard link={link()} />}</Show>
+
+ <section class="flex flex-col gap-3">
+ <div class="flex items-center justify-between gap-3">
+ <h2 class="text-base font-semibold">Links</h2>
+ <div class="flex gap-1 rounded-lg border border-edge p-0.5">
+ <FilterButton active={!mine()} onClick={() => setMine(false)}>
+ Everyone's
+ </FilterButton>
+ <FilterButton active={mine()} onClick={() => setMine(true)}>
+ Mine
+ </FilterButton>
+ </div>
+ </div>
+ <Switch>
+ <Match when={linksQuery.isPending}>
+ <p class="py-6 text-sm text-ink-muted">Loading…</p>
+ </Match>
+ <Match when={linksQuery.isError}>
+ <p class="py-6 text-sm text-failure">
+ Couldn't load invite links — refresh to try again.
+ </p>
+ </Match>
+ <Match when={links().length === 0}>
+ <p class="rounded-xl border border-dashed border-edge px-4 py-8 text-center text-sm text-ink-muted">
+ No links yet. Create one above and send it along.
+ </p>
+ </Match>
+ <Match when={links().length > 0}>
+ <LinksTable links={links()} />
+ </Match>
+ </Switch>
+ </section>
+ </div>
+ );
+}
+
+function FilterButton(props: {
+ active: boolean;
+ onClick: () => void;
+ children: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={props.onClick}
+ class={cn(
+ 'rounded-md px-3 py-1 text-xs font-medium transition-colors',
+ props.active
+ ? 'bg-ink text-surface'
+ : 'text-ink-muted hover:bg-hover hover:text-ink'
+ )}
+ >
+ {props.children}
+ </button>
+ );
+}
+
+function Field(props: {
+ id: string;
+ label: string;
+ hint?: string;
+ type?: string;
+ placeholder?: string;
+ value: string;
+ required?: boolean;
+ onInput: (value: string) => void;
+}) {
+ return (
+ <label class="flex flex-col gap-1.5" for={props.id}>
+ <span class="text-xs font-medium text-ink-muted">
+ {props.label}
+ <Show when={!props.required}>
+ <span class="font-normal"> (optional)</span>
+ </Show>
+ </span>
+ <input
+ id={props.id}
+ name={props.id}
+ type={props.type ?? 'text'}
+ placeholder={props.placeholder}
+ value={props.value}
+ required={props.required}
+ onInput={(e) => props.onInput(e.currentTarget.value)}
+ class="w-full rounded-lg border border-edge bg-surface px-3 py-2 text-sm text-ink placeholder:text-ink-placeholder transition-colors focus:border-accent focus:outline-none"
+ />
+ <Show when={props.hint}>
+ <span class="text-xs text-ink-muted">{props.hint}</span>
+ </Show>
+ </label>
+ );
+}
+
+function CreateLinkForm(props: { onCreated: (link: GtmInviteLink) => void }) {
+ const analytics = useAnalytics();
+ const [firstName, setFirstName] = createSignal('');
+ const [recipientEmail, setRecipientEmail] = createSignal('');
+ const [note, setNote] = createSignal('');
+
+ const create = useCreateGtmInviteLinkMutation({
+ onSuccess: (link) => {
+ props.onCreated(link);
+ analytics.track('gtm_invite_link_created', { link_id: link.id });
+ setFirstName('');
+ setRecipientEmail('');
+ setNote('');
+ void copyLink(link, { silent: true });
+ toast.success(`Link for ${link.firstName} created and copied`);
+ },
+ });
+
+ const canSubmit = () => firstName().trim().length > 0 && !create.isPending;
+
+ return (
+ <form
+ class="flex flex-col gap-4 rounded-xl border border-edge p-5"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!canSubmit()) return;
+ create.mutate({
+ firstName: firstName().trim(),
+ recipientEmail: recipientEmail().trim() || null,
+ note: note().trim() || null,
+ });
+ }}
+ >
+ <div class="flex flex-col gap-1">
+ <h2 class="text-base font-semibold">New invite link</h2>
+ <p class="text-sm text-ink-muted">
+ The recipient sees "Welcome, {firstName().trim() || 'their name'}" and
+ a Continue button that takes them into signup.
+ </p>
+ </div>
+ <div class="grid gap-4 sm:grid-cols-3">
+ <Field
+ id="firstName"
+ label="First name"
+ placeholder="Ada"
+ value={firstName()}
+ required
+ onInput={setFirstName}
+ />
+ <Field
+ id="recipientEmail"
+ label="Email"
+ type="email"
+ placeholder="[email protected]"
+ hint="For your own tracking; the link isn't tied to it."
+ value={recipientEmail()}
+ onInput={setRecipientEmail}
+ />
+ <Field
+ id="note"
+ label="Note"
+ placeholder="Met at the Series A dinner"
+ value={note()}
+ onInput={setNote}
+ />
+ </div>
+ <div class="flex items-center justify-end gap-3">
+ <Button variant="cta" size="lg" type="submit" disabled={!canSubmit()}>
+ <LinkIcon class="size-4" />
+ {create.isPending ? 'Creating…' : 'Create link'}
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+async function copyLink(link: GtmInviteLink, options?: { silent?: boolean }) {
+ const url = buildInviteLinkUrl(link.token);
+ try {
+ await navigator.clipboard.writeText(url);
+ if (!options?.silent) toast.success('Link copied');
+ } catch {
+ toast.failure("Couldn't copy — select the link and copy it manually");
+ }
+}
+
+function LatestLinkCard(props: { link: GtmInviteLink }) {
+ const url = () => buildInviteLinkUrl(props.link.token);
+ return (
+ <div class="flex flex-col gap-3 rounded-xl border border-accent/40 bg-accent/5 p-5">
+ <div class="flex items-center justify-between gap-3">
+ <span class="text-sm font-semibold">
+ Link for {props.link.firstName} ·{' '}
+ {formatFreeMonths(props.link.freeMonths)} · expires in{' '}
+ {formatTimeLeft(props.link.expiresAt).replace(' left', '')}
+ </span>
+ <Button variant="strong" size="sm" onClick={() => copyLink(props.link)}>
+ <CopyIcon class="size-4" />
+ Copy link
+ </Button>
+ </div>
+ <code class="break-all rounded-lg border border-edge bg-surface px-3 py-2 text-xs text-ink select-all">
+ {url()}
+ </code>
+ </div>
+ );
+}
+
+const dateTime = new Intl.DateTimeFormat(undefined, {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+});
+
+function formatDate(value: string | null | undefined): string {
+ return value ? dateTime.format(new Date(value)) : '—';
+}
+
+function StatusPill(props: { status: GtmInviteLink['status'] }) {
+ const presentation = createMemo(() => describeInviteStatus(props.status));
+ const toneClass = (tone: InviteStatusTone) =>
+ ({
+ accent: 'bg-accent/15 text-accent',
+ muted: 'bg-ink/10 text-ink-muted',
+ success: 'bg-success-bg text-success',
+ failure: 'bg-failure-bg text-failure',
+ })[tone];
+ return (
+ <span
+ class={cn(
+ 'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
+ toneClass(presentation().tone)
+ )}
+ >
+ {presentation().label}
+ </span>
+ );
+}
+
+function LinksTable(props: { links: GtmInviteLink[] }) {
+ const revoke = useRevokeGtmInviteLinkMutation();
+
+ return (
+ <div class="overflow-x-auto rounded-xl border border-edge">
+ <table class="w-full min-w-200 text-left text-sm">
+ <thead class="bg-ink/[0.03] text-xs uppercase tracking-wide text-ink-muted">
+ <tr>
+ <th class="px-4 py-2.5 font-medium">Recipient</th>
+ <th class="px-4 py-2.5 font-medium">Status</th>
+ <th class="px-4 py-2.5 font-medium">Sent by</th>
+ <th class="px-4 py-2.5 font-medium">Created</th>
+ <th class="px-4 py-2.5 font-medium">Opens</th>
+ <th class="px-4 py-2.5 font-medium">Signed up</th>
+ <th class="px-4 py-2.5 font-medium">Subscribed</th>
+ <th class="px-4 py-2.5 font-medium" />
+ </tr>
+ </thead>
+ <tbody>
+ <For each={props.links}>
+ {(link) => (
+ <tr class="border-t border-edge-muted align-top">
+ <td class="px-4 py-3">
+ <div class="flex flex-col">
+ <span class="font-medium text-ink">{link.firstName}</span>
+ <Show when={link.recipientEmail}>
+ <span class="text-xs text-ink-muted">
+ {link.recipientEmail}
+ </span>
+ </Show>
+ <Show when={link.note}>
+ <span class="text-xs text-ink-muted italic">
+ {link.note}
+ </span>
+ </Show>
+ </div>
+ </td>
+ <td class="px-4 py-3">
+ <div class="flex flex-col gap-1">
+ <StatusPill status={link.status} />
+ <Show when={link.status === 'active'}>
+ <span class="text-xs text-ink-muted">
+ {formatTimeLeft(link.expiresAt)}
+ </span>
+ </Show>
+ </div>
+ </td>
+ <td class="px-4 py-3 text-ink">
+ {idToDisplayName(link.createdBy)}
+ </td>
+ <td class="px-4 py-3 text-ink-muted">
+ {formatDate(link.createdAt)}
+ </td>
+ <td class="px-4 py-3 text-ink-muted">
+ <div class="flex flex-col">
+ <span class="text-ink">{link.openCount}</span>
+ <Show when={link.firstOpenedAt}>
+ <span class="text-xs">
+ first {formatDate(link.firstOpenedAt)}
+ </span>
+ </Show>
+ </div>
+ </td>
+ <td class="px-4 py-3 text-ink-muted">
+ <Show when={link.redeemedBy} fallback="—">
+ {(redeemedBy) => (
+ <div class="flex flex-col">
+ <span class="text-ink">
+ {idToDisplayName(redeemedBy())}
+ </span>
+ <span class="text-xs">
+ {formatDate(link.redeemedAt)}
+ </span>
+ </div>
+ )}
+ </Show>
+ </td>
+ <td class="px-4 py-3 text-ink-muted">
+ <Show when={link.convertedAt} fallback="—">
+ {(convertedAt) => (
+ <div class="flex flex-col">
+ <span class="text-ink">
+ {formatDate(convertedAt())}
+ </span>
+ <Show when={link.stripeSubscriptionId}>
+ <span class="text-xs">
+ {link.stripeSubscriptionId}
+ </span>
+ </Show>
+ </div>
+ )}
+ </Show>
+ </td>
+ <td class="px-4 py-3">
+ <div class="flex justify-end gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => copyLink(link)}
+ title="Copy link"
+ >
+ <CopyIcon class="size-4" />
+ </Button>
+ <Show when={link.status === 'active'}>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={revoke.isPending}
+ onClick={() => revoke.mutate({ id: link.id })}
+ title="Revoke link"
+ >
+ <XIcon class="size-4" />
+ </Button>
+ </Show>
+ </div>
+ </td>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx
new file mode 100644
index 0000000000..825fb92607
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx
@@ -0,0 +1,98 @@
+import { PLAN_FEATURES, PLANS } from '@app/features/paywall/plans';
+import { SkipButton } from '@app/features/setup/flow/shared';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import ArrowRight from '@phosphor/arrow-right.svg';
+import Check from '@phosphor/check.svg';
+import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
+import { Button } from '@ui';
+import { Index, onMount } from 'solid-js';
+import { formatFreeMonths } from './core/invite-link';
+
+const PREMIUM = PLANS[1];
+
+/**
+ * Replaces the free/paid plan picker for an account that signed up through a
+ * GTM invite link: Premium's first month is free, checkout still collects a
+ * card, and the promotion is applied server-side when the session is created.
+ */
+export function InviteOfferPanel(props: {
+ offer: GtmInviteOffer;
+ finishing: boolean;
+ onStartCheckout: () => void;
+ onContinueFree: () => void;
+}) {
+ const analytics = useAnalytics();
+
+ onMount(() => {
+ analytics.track('gtm_invite_offer_viewed', {
+ link_id: props.offer.linkId,
+ promo_code: props.offer.promoCode,
+ });
+ });
+
+ const freeMonths = () => props.offer.freeMonths;
+ const freePeriod = () =>
+ freeMonths() === 1 ? 'first month' : `first ${freeMonths()} months`;
+
+ return (
+ <div class="flex flex-col gap-6">
+ <div class="flex flex-col gap-4 rounded-xl border border-accent/40 bg-accent/5 p-5">
+ <div class="flex items-center justify-between gap-3">
+ <span class="text-sm font-semibold text-ink">{PREMIUM.name}</span>
+ <span class="rounded-full bg-accent px-2.5 py-0.5 text-xs font-semibold text-accent-contrast">
+ {formatFreeMonths(freeMonths())}
+ </span>
+ </div>
+ <div class="flex flex-col gap-1">
+ <div class="flex items-baseline gap-2">
+ <span class="text-3xl font-semibold tracking-tight text-ink">
+ $0
+ </span>
+ <span class="text-sm text-ink-muted">for your {freePeriod()}</span>
+ </div>
+ <span class="text-xs text-ink-muted">
+ then ${PREMIUM.price} per user / month
+ </span>
+ </div>
+ <ul class="flex flex-col gap-2">
+ <Index each={PLAN_FEATURES}>
+ {(feature) => (
+ <li class="flex items-center justify-between gap-2 text-xs">
+ <span class="flex items-center gap-1.5 text-ink-muted">
+ <Check class="size-3 text-accent" />
+ {feature().label}
+ </span>
+ <span class="font-medium text-ink">
+ {feature().values.premium}
+ </span>
+ </li>
+ )}
+ </Index>
+ </ul>
+ </div>
+
+ <p class="text-xs leading-relaxed text-ink-muted">
+ You'll add a card at checkout so Premium keeps going after your{' '}
+ {freePeriod()}. Nothing is charged until then, and you can cancel
+ anytime before.
+ </p>
+
+ <div class="flex flex-col gap-3">
+ <Button
+ variant="cta"
+ size="xl"
+ disabled={props.finishing}
+ onClick={() => props.onStartCheckout()}
+ >
+ {props.finishing ? 'Heading to checkout…' : 'Claim your free month'}
+ <ArrowRight class="size-5" />
+ </Button>
+ <SkipButton
+ label="Continue with Free instead"
+ disabled={props.finishing}
+ onClick={() => props.onContinueFree()}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/gtm-invite/InviteWelcome.tsx b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
new file mode 100644
index 0000000000..0f1b23fef9
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
@@ -0,0 +1,248 @@
+import { NoiseBackground } from '@app/features/setup/flow/shared';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { useIsAuthenticated } from '@core/context/user';
+import LogoIcon from '@icon/macro-logo.svg';
+import ArrowRight from '@phosphor/arrow-right.svg';
+import {
+ usePublicGtmInviteLinkQuery,
+ useRedeemGtmInviteLinkMutation,
+} from '@queries/gtm-invite/links';
+import type { GtmInviteLinkStatus } from '@service-auth/generated/schemas/gtmInviteLinkStatus';
+import { A, useNavigate, useSearchParams } from '@solidjs/router';
+import { Button } from '@ui';
+import { createEffect, createMemo, Match, on, onMount, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ clearPendingInviteToken,
+ INVITE_TOKEN_PARAM,
+ isPlausibleInviteToken,
+ SIGNUP_INVITE_PARAM,
+ savePendingInviteToken,
+} from './core/invite-link';
+
+type WelcomeView =
+ | { kind: 'missing' }
+ | { kind: 'loading' }
+ | { kind: 'invalid' }
+ | { kind: 'expired' }
+ | { kind: 'revoked' }
+ | { kind: 'used' }
+ | { kind: 'welcome'; firstName: string; freeMonths: number };
+
+/**
+ * The public landing page for a GTM invite link (`/invite?token=…`): a
+ * personal welcome for the prospect a staff member sent it to. Continue parks
+ * the token for the signup that follows; a signed-in visitor (back from SSO,
+ * or an existing account) redeems on the spot instead.
+ */
+export function InviteWelcome() {
+ const [searchParams] = useSearchParams();
+ const navigate = useNavigate();
+ const analytics = useAnalytics();
+ const isAuthenticated = useIsAuthenticated();
+
+ const token = createMemo(() => {
+ const raw = searchParams[INVITE_TOKEN_PARAM];
+ const value = Array.isArray(raw) ? raw[0] : raw;
+ return isPlausibleInviteToken(value) ? value : undefined;
+ });
+
+ const linkQuery = usePublicGtmInviteLinkQuery(token);
+ // Guarded reads: a pending query must not suspend the page into the root
+ // fallback, and the fetch itself is what the dashboard counts as an open.
+ const link = () => (linkQuery.isSuccess ? linkQuery.data : undefined);
+
+ const view = createMemo((): WelcomeView => {
+ if (!token()) return { kind: 'missing' };
+ if (linkQuery.isError) return { kind: 'invalid' };
+ const resolved = link();
+ if (!resolved) return { kind: 'loading' };
+ // A signed-in visitor may be the recipient coming back from SSO on a link
+ // they already redeemed; redemption is idempotent for them.
+ if (isAuthenticated() === true && resolved.status === 'redeemed') {
+ return {
+ kind: 'welcome',
+ firstName: resolved.firstName,
+ freeMonths: resolved.freeMonths,
+ };
+ }
+ return match<GtmInviteLinkStatus, WelcomeView>(resolved.status)
+ .with('active', () => ({
+ kind: 'welcome',
+ firstName: resolved.firstName,
+ freeMonths: resolved.freeMonths,
+ }))
+ .with('expired', () => ({ kind: 'expired' }))
+ .with('revoked', () => ({ kind: 'revoked' }))
+ .with('redeemed', 'converted', () => ({ kind: 'used' }))
+ .exhaustive();
+ });
+ const welcomeDetails = () => {
+ const current = view();
+ return current.kind === 'welcome' ? current : undefined;
+ };
+
+ onMount(() => {
+ analytics.pageView('gtm_invite_welcome');
+ });
+
+ // Analytics on an external system, once the link resolves.
+ createEffect(
+ on(link, (resolved) => {
+ if (!resolved) return;
+ analytics.track('gtm_invite_opened', { status: resolved.status });
+ })
+ );
+
+ const redeem = useRedeemGtmInviteLinkMutation({
+ onSuccess: () => {
+ clearPendingInviteToken();
+ },
+ onSettled: () => {
+ // Attributed (or not — a failed attempt leaves the parked token for the
+ // next authenticated load to retry).
+ navigate('/', { replace: true });
+ },
+ });
+
+ const onContinue = () => {
+ const value = token();
+ if (!value) return;
+ savePendingInviteToken(value);
+ analytics.track('gtm_invite_continue', {
+ authenticated: isAuthenticated() === true,
+ });
+ if (isAuthenticated() === true) {
+ redeem.mutate({ token: value });
+ return;
+ }
+ navigate(`/signup?${SIGNUP_INVITE_PARAM}=${encodeURIComponent(value)}`);
+ };
+
+ return (
+ <div class="relative flex size-full items-center justify-center overflow-hidden bg-surface font-sans text-ink">
+ <style>{
+ /*css*/ `
+ @keyframes gtm-card-in {
+ from { opacity: 0; transform: translateY(14px) scale(0.985); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+ }
+ .gtm-card { animation: gtm-card-in 520ms cubic-bezier(0.22, 1, 0.36, 1) both; }
+ `
+ }</style>
+
+ <NoiseBackground />
+
+ <div class="gtm-card relative z-10 w-full max-w-sm px-4 sm:max-w-lg sm:px-8">
+ <div class="flex flex-col gap-8">
+ <LogoIcon class="size-12 text-accent" />
+
+ <Switch>
+ <Match when={view().kind === 'loading'}>
+ <div class="flex flex-col gap-3">
+ <div class="h-8 w-56 animate-pulse rounded-md bg-ink/10" />
+ <div class="h-4 w-80 max-w-full animate-pulse rounded-md bg-ink/10" />
+ </div>
+ </Match>
+
+ <Match when={welcomeDetails()}>
+ {(details) => (
+ <div class="flex flex-col gap-8">
+ <div class="flex flex-col gap-2">
+ <h1 class="text-3xl font-semibold tracking-tight text-ink">
+ Welcome, {details().firstName}
+ </h1>
+ <p class="max-w-md text-sm leading-relaxed text-ink-muted">
+ Your Macro workspace is ready to set up. Bring your email,
+ docs, and team together in one place — and your{' '}
+ {details().freeMonths === 1
+ ? 'first month'
+ : `first ${details().freeMonths} months`}{' '}
+ of Premium {details().freeMonths === 1 ? 'is' : 'are'} on
+ us.
+ </p>
+ </div>
+ <div class="flex flex-col gap-3">
+ <Button
+ variant="cta"
+ size="xl"
+ disabled={redeem.isPending}
+ onClick={onContinue}
+ >
+ {redeem.isPending ? 'One moment…' : 'Continue'}
+ <ArrowRight class="size-5" />
+ </Button>
+ <p class="text-center text-xs text-ink/50">
+ Already have an account?{' '}
+ <A
+ href="/login"
+ class="text-link underline underline-offset-2 hover:text-link-hover"
+ onClick={() => {
+ const value = token();
+ if (value) savePendingInviteToken(value);
+ }}
+ >
+ Log in
+ </A>
+ </p>
+ </div>
+ </div>
+ )}
+ </Match>
+
+ <Match when={view().kind === 'expired'}>
+ <UnavailableInvite
+ title="This invite link has expired"
+ body="Invite links stay open for 48 hours. Ask your Macro contact for a fresh one and we'll pick up right where this one left off."
+ />
+ </Match>
+
+ <Match when={view().kind === 'used'}>
+ <UnavailableInvite
+ title="This invite link has already been used"
+ body="If that was you, log in to pick up where you left off. Otherwise, ask your Macro contact for a link of your own."
+ />
+ </Match>
+
+ <Match when={view().kind === 'revoked'}>
+ <UnavailableInvite
+ title="This invite link is no longer active"
+ body="Ask your Macro contact for a new link."
+ />
+ </Match>
+
+ <Match
+ when={view().kind === 'invalid' || view().kind === 'missing'}
+ >
+ <UnavailableInvite
+ title="This invite link isn't valid"
+ body="Double-check the link you were sent, or ask your Macro contact for a new one."
+ />
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function UnavailableInvite(props: { title: string; body: string }) {
+ const navigate = useNavigate();
+ return (
+ <div class="flex flex-col gap-8">
+ <div class="flex flex-col gap-2">
+ <h1 class="text-2xl font-semibold tracking-tight text-ink">
+ {props.title}
+ </h1>
+ <p class="max-w-md text-sm leading-relaxed text-ink-muted">
+ {props.body}
+ </p>
+ </div>
+ <div class="flex gap-3">
+ <Button variant="outline" size="lg" onClick={() => navigate('/login')}>
+ Log in
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/gtm-invite/core/invite-link.test.ts b/apps/web/src/features/gtm-invite/core/invite-link.test.ts
new file mode 100644
index 0000000000..703e939c3a
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/core/invite-link.test.ts
@@ -0,0 +1,104 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@core/util/platform', () => ({ isTauri: () => false }));
+
+import {
+ buildInviteLinkUrl,
+ clearPendingInviteToken,
+ describeInviteStatus,
+ formatFreeMonths,
+ formatTimeLeft,
+ getPendingInviteToken,
+ isPlausibleInviteToken,
+ PENDING_INVITE_TOKEN_STORAGE_KEY,
+ savePendingInviteToken,
+} from './invite-link';
+
+const TOKEN = 'AbCdEfGhIjKlMnOpQrStUvWxYz012345';
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+describe('isPlausibleInviteToken', () => {
+ it('accepts generated tokens and rejects anything else', () => {
+ expect(isPlausibleInviteToken(TOKEN)).toBe(true);
+ expect(isPlausibleInviteToken('short')).toBe(false);
+ expect(isPlausibleInviteToken('has spaces in it and is long')).toBe(false);
+ expect(isPlausibleInviteToken(undefined)).toBe(false);
+ expect(isPlausibleInviteToken(['a'])).toBe(false);
+ });
+});
+
+describe('buildInviteLinkUrl', () => {
+ it('points at the web app welcome page with the token encoded', () => {
+ expect(buildInviteLinkUrl('a b', 'https://macro.com')).toBe(
+ 'https://macro.com/app/invite?token=a%20b'
+ );
+ });
+
+ it('uses the local dev server origin when running on localhost', () => {
+ // jsdom's default origin is http://localhost:3000.
+ expect(buildInviteLinkUrl(TOKEN)).toBe(
+ `${window.location.origin}/app/invite?token=${TOKEN}`
+ );
+ });
+});
+
+describe('pending token storage', () => {
+ it('round-trips a token and clears it', () => {
+ savePendingInviteToken(TOKEN);
+ expect(localStorage.getItem(PENDING_INVITE_TOKEN_STORAGE_KEY)).toBe(TOKEN);
+ expect(getPendingInviteToken()).toBe(TOKEN);
+
+ clearPendingInviteToken();
+ expect(getPendingInviteToken()).toBeUndefined();
+ });
+
+ it('ignores a corrupted stored value', () => {
+ localStorage.setItem(PENDING_INVITE_TOKEN_STORAGE_KEY, 'nope');
+ expect(getPendingInviteToken()).toBeUndefined();
+ });
+});
+
+describe('describeInviteStatus', () => {
+ it('labels every status', () => {
+ expect(describeInviteStatus('active')).toEqual({
+ label: 'Active',
+ tone: 'accent',
+ });
+ expect(describeInviteStatus('expired').label).toBe('Expired');
+ expect(describeInviteStatus('revoked').tone).toBe('failure');
+ expect(describeInviteStatus('redeemed').label).toBe('Signed up');
+ expect(describeInviteStatus('converted')).toEqual({
+ label: 'Subscribed',
+ tone: 'success',
+ });
+ });
+});
+
+describe('formatTimeLeft', () => {
+ const now = Date.parse('2026-09-15T12:00:00Z');
+
+ it('formats hours and minutes remaining', () => {
+ expect(formatTimeLeft('2026-09-17T11:12:00Z', now)).toBe('47h 12m left');
+ expect(formatTimeLeft('2026-09-15T14:00:00Z', now)).toBe('2h left');
+ expect(formatTimeLeft('2026-09-15T12:08:30Z', now)).toBe('8m left');
+ expect(formatTimeLeft('2026-09-15T12:00:10Z', now)).toBe('1m left');
+ });
+
+ it('reports expiry', () => {
+ expect(formatTimeLeft('2026-09-15T11:00:00Z', now)).toBe('Expired');
+ });
+});
+
+describe('formatFreeMonths', () => {
+ it('pluralizes', () => {
+ expect(formatFreeMonths(1)).toBe('1 month free');
+ expect(formatFreeMonths(3)).toBe('3 months free');
+ });
+});
diff --git a/apps/web/src/features/gtm-invite/core/invite-link.ts b/apps/web/src/features/gtm-invite/core/invite-link.ts
new file mode 100644
index 0000000000..ab44c9e7b2
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/core/invite-link.ts
@@ -0,0 +1,122 @@
+/**
+ * Pure helpers for GTM invite links: the personal, time-limited signup links
+ * Macro staff hand to prospects. The welcome page (`/invite?token=…`) parks
+ * the token in localStorage until the visitor has an account; the first
+ * authenticated load redeems it and the plan step shows the offer.
+ */
+import { isTauri } from '@core/util/platform';
+import type { GtmInviteLinkStatus } from '@service-auth/generated/schemas/gtmInviteLinkStatus';
+import { match } from 'ts-pattern';
+
+/** Where the welcome page parks the token until the visitor has an account. */
+export const PENDING_INVITE_TOKEN_STORAGE_KEY = 'gtm_invite_pending_token';
+/** Query parameter carrying the token on the welcome page. */
+export const INVITE_TOKEN_PARAM = 'token';
+/** Query parameter carrying the token onto the signup page (analytics only). */
+export const SIGNUP_INVITE_PARAM = 'gtm_invite';
+/** Base-relative route of the public welcome page. */
+export const INVITE_ROUTE = '/invite';
+/** Base-relative route of the staff dashboard. */
+export const INVITE_PORTAL_ROUTE = '/internal/invite-links';
+
+/** Mirrors the backend's token shape: 16–64 URL-safe characters. */
+const TOKEN_PATTERN = /^[A-Za-z0-9_-]{16,64}$/;
+
+export function isPlausibleInviteToken(value: unknown): value is string {
+ return typeof value === 'string' && TOKEN_PATTERN.test(value);
+}
+
+/**
+ * The origin recipients should open links on. Staff may create links from
+ * the desktop app, whose own origin (`tauri://…`) means nothing to a
+ * prospect, so links always point at the web app.
+ */
+export function inviteLinkOrigin(): string {
+ if (
+ typeof window !== 'undefined' &&
+ !isTauri() &&
+ window.location.hostname === 'localhost'
+ ) {
+ return window.location.origin;
+ }
+ return import.meta.env.MODE === 'development'
+ ? 'https://dev.macro.com'
+ : 'https://macro.com';
+}
+
+export function buildInviteLinkUrl(
+ token: string,
+ origin: string = inviteLinkOrigin()
+): string {
+ return `${origin}/app${INVITE_ROUTE}?${INVITE_TOKEN_PARAM}=${encodeURIComponent(token)}`;
+}
+
+export function savePendingInviteToken(token: string): void {
+ try {
+ localStorage.setItem(PENDING_INVITE_TOKEN_STORAGE_KEY, token);
+ } catch {
+ // Private mode / blocked storage: the signup still works, unattributed.
+ }
+}
+
+export function getPendingInviteToken(): string | undefined {
+ try {
+ const value = localStorage.getItem(PENDING_INVITE_TOKEN_STORAGE_KEY);
+ return isPlausibleInviteToken(value) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function clearPendingInviteToken(): void {
+ try {
+ localStorage.removeItem(PENDING_INVITE_TOKEN_STORAGE_KEY);
+ } catch {
+ // Nothing to clear.
+ }
+}
+
+export type InviteStatusTone = 'accent' | 'muted' | 'success' | 'failure';
+
+export interface InviteStatusPresentation {
+ label: string;
+ tone: InviteStatusTone;
+}
+
+/** Dashboard wording and color for a link's lifecycle status. */
+export function describeInviteStatus(
+ status: GtmInviteLinkStatus
+): InviteStatusPresentation {
+ return match(status)
+ .with('active', () => ({ label: 'Active', tone: 'accent' as const }))
+ .with('expired', () => ({ label: 'Expired', tone: 'muted' as const }))
+ .with('revoked', () => ({ label: 'Revoked', tone: 'failure' as const }))
+ .with('redeemed', () => ({ label: 'Signed up', tone: 'success' as const }))
+ .with('converted', () => ({
+ label: 'Subscribed',
+ tone: 'success' as const,
+ }))
+ .exhaustive();
+}
+
+const MINUTE_MS = 60_000;
+const HOUR_MS = 60 * MINUTE_MS;
+
+/** "47h 12m left", "8m left", or "Expired" for an active link's window. */
+export function formatTimeLeft(
+ expiresAt: string,
+ now: number = Date.now()
+): string {
+ const remaining = new Date(expiresAt).getTime() - now;
+ if (!Number.isFinite(remaining)) return '';
+ if (remaining <= 0) return 'Expired';
+ const hours = Math.floor(remaining / HOUR_MS);
+ const minutes = Math.floor((remaining % HOUR_MS) / MINUTE_MS);
+ if (hours === 0) return `${Math.max(minutes, 1)}m left`;
+ return minutes === 0 ? `${hours}h left` : `${hours}h ${minutes}m left`;
+}
+
+/** "1 month free" / "3 months free" for offer badges. */
+export function formatFreeMonths(freeMonths: number): string {
+ return `${freeMonths} ${freeMonths === 1 ? 'month' : 'months'} free`;
+}
diff --git a/apps/web/src/features/gtm-invite/usePendingInviteRedemption.ts b/apps/web/src/features/gtm-invite/usePendingInviteRedemption.ts
new file mode 100644
index 0000000000..d34fb7063b
--- /dev/null
+++ b/apps/web/src/features/gtm-invite/usePendingInviteRedemption.ts
@@ -0,0 +1,49 @@
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { useIsAuthenticated } from '@core/context/user';
+import { thrownResultErrorHasCode } from '@core/util/result';
+import { useRedeemGtmInviteLinkMutation } from '@queries/gtm-invite/links';
+import { createEffect, on } from 'solid-js';
+import {
+ clearPendingInviteToken,
+ getPendingInviteToken,
+} from './core/invite-link';
+
+/**
+ * Finishes the invite handoff once the visitor has an account. The welcome
+ * page parks the token in localStorage before sending them to sign up; the
+ * first authenticated load redeems it, which attributes the account to the
+ * staff member who sent the link and unlocks the free-month offer.
+ *
+ * Redemption is idempotent server-side, so an extra attempt is harmless.
+ * Anything but an auth failure is terminal (unknown, expired, already used
+ * by someone else) and drops the token rather than retrying forever.
+ */
+export function usePendingInviteRedemption() {
+ const isAuthenticated = useIsAuthenticated();
+ const analytics = useAnalytics();
+ const redeem = useRedeemGtmInviteLinkMutation({
+ onSuccess: (offer) => {
+ clearPendingInviteToken();
+ analytics.track('gtm_invite_redeemed', {
+ link_id: offer.linkId,
+ promo_code: offer.promoCode,
+ });
+ },
+ onError: (error) => {
+ if (thrownResultErrorHasCode(error, 'UNAUTHORIZED')) return;
+ clearPendingInviteToken();
+ console.error('Failed to redeem GTM invite link', error);
+ },
+ });
+
+ let attempted = false;
+ createEffect(
+ on(isAuthenticated, (authenticated) => {
+ if (authenticated !== true || attempted) return;
+ const token = getPendingInviteToken();
+ if (!token) return;
+ attempted = true;
+ redeem.mutate({ token });
+ })
+ );
+}
diff --git a/apps/web/src/features/setup/flow/OnboardingFlow.tsx b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
index 1c98d4a4f5..79b5a1a84f 100644
--- a/apps/web/src/features/setup/flow/OnboardingFlow.tsx
+++ b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
@@ -7,10 +7,12 @@ import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
import { useUserInfoQuery } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
import { useEmailLinksQuery } from '@queries/email/link';
+import { useGtmInviteOfferQuery } from '@queries/gtm-invite/links';
import { useImportQuery } from '@queries/import';
import { useMcpServersQuery } from '@queries/mcp-servers';
import { useOnboardingQuery } from '@queries/onboarding';
import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
+import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
import { useNavigate } from '@solidjs/router';
import { cn } from '@ui';
import { Stepper } from '@ui/components/Stepper';
@@ -92,6 +94,8 @@ interface StepControls {
startPremiumCheckout: (tier: 'premium') => void;
/** Finish after checkout confirmed payment (or an existing license). */
finishPremium: () => void;
+ /** The free-month promotion an invite-link signup holds, once known. */
+ inviteOffer: () => GtmInviteOffer | null;
}
interface ConnectorStepCopy {
@@ -222,6 +226,7 @@ function buildSteps(
render: (controls) => (
<PlanStep
finishing={controls.finishing()}
+ inviteOffer={controls.inviteOffer()}
onFree={controls.finishFree}
onStartCheckout={controls.startPremiumCheckout}
onPremiumPaid={controls.finishPremium}
@@ -270,6 +275,12 @@ function FlowContent() {
// Analytics inputs; read only from handlers/effects so they never
// suspend this boundary.
const linksQuery = useEmailLinksQuery();
+ // An account that signed up through a GTM invite link holds a free-month
+ // promotion; the plan step shows it in place of the picker. Guarded read so
+ // a pending fetch never suspends the flow.
+ const inviteOfferQuery = useGtmInviteOfferQuery({ enabled: needsOnboarding });
+ const inviteOffer = () =>
+ inviteOfferQuery.isSuccess ? inviteOfferQuery.data : null;
const serversQuery = useMcpServersQuery({ neverSuspend: true });
const pipedreamQuery = usePipedreamConnectionsQuery({ neverSuspend: true });
const analytics = useAnalytics();
@@ -346,6 +357,16 @@ function FlowContent() {
);
const currentStep = createMemo(() => steps()[stepIndex()]);
const currentStepKey = createMemo(() => currentStep().key);
+ // The plan step's header follows the offer without rebuilding the steps
+ // (which would remount the step mid-flow).
+ const stepTitle = () =>
+ currentStep().key === 'plan' && inviteOffer()
+ ? 'Your first month is on us'
+ : currentStep().title;
+ const stepSubtitle = () =>
+ currentStep().key === 'plan' && inviteOffer()
+ ? 'Your invite comes with Macro Premium free for the first month. You can change plans anytime.'
+ : currentStep().subtitle;
const userId = () => userInfoQuery.data?.userId;
// The current step's hero-module state: the email module lights once any
@@ -440,6 +461,7 @@ function FlowContent() {
finishFree: (planSkipped) => void finish.finishFree(planSkipped),
startPremiumCheckout: (tier) => void finish.startPremiumCheckout(tier),
finishPremium: () => void finish.finishPremium(),
+ inviteOffer,
};
// Heal a half-landed finish: NewOnboardingRedirect keys off
@@ -548,11 +570,11 @@ function FlowContent() {
}}
>
<h1 class="text-2xl font-semibold tracking-tight text-ink">
- {currentStep().title}
+ {stepTitle()}
</h1>
- <Show when={currentStep().subtitle}>
+ <Show when={stepSubtitle()}>
<p class="max-w-md text-sm leading-relaxed text-ink-muted">
- {currentStep().subtitle}
+ {stepSubtitle()}
</p>
</Show>
</div>
diff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsx
index 24d60b3aa5..50f0db90b0 100644
--- a/apps/web/src/features/setup/flow/PlanStep.tsx
+++ b/apps/web/src/features/setup/flow/PlanStep.tsx
@@ -1,3 +1,4 @@
+import { InviteOfferPanel } from '@app/features/gtm-invite/InviteOfferPanel';
import {
PLAN_FEATURES,
PLANS,
@@ -7,6 +8,7 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';
import ArrowRight from '@phosphor/arrow-right.svg';
import Check from '@phosphor/check.svg';
import { useUserInfoQuery } from '@queries/auth/user-info';
+import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
import { useSearchParams } from '@solidjs/router';
import { Button, cn } from '@ui';
import { createSignal, Index, onCleanup, onMount, Show } from 'solid-js';
@@ -19,9 +21,13 @@ const LICENSE_POLL_INTERVAL_MS = 1_000;
/** Free vs paid. The last step: free/skip finishes immediately; premium
* round-trips through Stripe checkout (the flow stays incomplete, so both
- * checkout legs land back here) and finishes once payment is confirmed. */
+ * checkout legs land back here) and finishes once payment is confirmed.
+ * An account that signed up through a GTM invite link sees its free-month
+ * offer in place of the picker; checkout applies the promotion server-side. */
export function PlanStep(props: {
finishing: boolean;
+ /** The promotion an invite-link signup holds, once known. */
+ inviteOffer?: GtmInviteOffer | null;
onFree: (planSkipped: boolean) => void;
onStartCheckout: (tier: Exclude<PlanTier, 'free'>) => void;
onPremiumPaid: () => void;
@@ -99,83 +105,117 @@ export function PlanStep(props: {
</div>
}
>
- <div class="flex flex-col gap-6">
- <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <Index each={PLANS}>
- {(plan) => (
- <button
- type="button"
- onClick={() => setSelected(plan().tier)}
- class={cn(
- 'flex flex-col gap-4 rounded-xl border p-5 text-left transition-colors cursor-default',
- selected() === plan().tier
- ? 'border-ink/40 ring-1 ring-ink/20'
- : 'border-edge hover:border-edge-muted'
- )}
- >
- <div class="flex items-center justify-between">
- <span class="text-sm font-semibold text-ink">
- {plan().name}
- </span>
- <span
- class={cn(
- 'flex items-center justify-center size-4 rounded-full border',
- selected() === plan().tier
- ? 'border-ink bg-ink text-surface'
- : 'border-edge'
- )}
- >
- <Show when={selected() === plan().tier}>
- <Check class="size-3" />
- </Show>
- </span>
- </div>
- <div class="flex items-baseline gap-1">
- <span class="text-2xl font-semibold tracking-tight text-ink">
- ${plan().price}
- </span>
- <span class="text-xs text-ink-muted">
- {plan().price === 0 ? 'forever' : 'per user / month'}
- </span>
- </div>
- <ul class="flex flex-col gap-2">
- <Index each={PLAN_FEATURES}>
- {(feature) => (
- <li class="flex items-center justify-between gap-2 text-xs">
- <span class="text-ink-muted">{feature().label}</span>
- <span class="text-ink font-medium">
- {feature().values[plan().tier]}
- </span>
- </li>
- )}
- </Index>
- </ul>
- </button>
- )}
- </Index>
- </div>
-
- <div class="flex flex-col gap-3">
- <Button
- variant="cta"
- size="xl"
- disabled={props.finishing}
- onClick={finish}
- >
- {props.finishing
- ? selected() === 'free'
- ? 'Setting up your workspace…'
- : 'Heading to checkout…'
- : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}
- <ArrowRight class="size-5" />
- </Button>
- <SkipButton
- label="Decide later"
- disabled={props.finishing}
- onClick={() => props.onFree(true)}
+ <Show
+ when={props.inviteOffer}
+ fallback={
+ <PlanPicker
+ finishing={props.finishing}
+ selected={selected()}
+ onSelect={setSelected}
+ onFinish={finish}
+ onDecideLater={() => props.onFree(true)}
/>
- </div>
- </div>
+ }
+ >
+ {(offer) => (
+ <InviteOfferPanel
+ offer={offer()}
+ finishing={props.finishing}
+ onStartCheckout={() => props.onStartCheckout('premium')}
+ onContinueFree={() => props.onFree(false)}
+ />
+ )}
+ </Show>
</Show>
);
}
+
+/** The regular free/premium picker. */
+function PlanPicker(props: {
+ finishing: boolean;
+ selected: PlanTier;
+ onSelect: (tier: PlanTier) => void;
+ onFinish: () => void;
+ onDecideLater: () => void;
+}) {
+ const selected = () => props.selected;
+ return (
+ <div class="flex flex-col gap-6">
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <Index each={PLANS}>
+ {(plan) => (
+ <button
+ type="button"
+ onClick={() => props.onSelect(plan().tier)}
+ class={cn(
+ 'flex flex-col gap-4 rounded-xl border p-5 text-left transition-colors cursor-default',
+ selected() === plan().tier
+ ? 'border-ink/40 ring-1 ring-ink/20'
+ : 'border-edge hover:border-edge-muted'
+ )}
+ >
+ <div class="flex items-center justify-between">
+ <span class="text-sm font-semibold text-ink">
+ {plan().name}
+ </span>
+ <span
+ class={cn(
+ 'flex items-center justify-center size-4 rounded-full border',
+ selected() === plan().tier
+ ? 'border-ink bg-ink text-surface'
+ : 'border-edge'
+ )}
+ >
+ <Show when={selected() === plan().tier}>
+ <Check class="size-3" />
+ </Show>
+ </span>
+ </div>
+ <div class="flex items-baseline gap-1">
+ <span class="text-2xl font-semibold tracking-tight text-ink">
+ ${plan().price}
+ </span>
+ <span class="text-xs text-ink-muted">
+ {plan().price === 0 ? 'forever' : 'per user / month'}
+ </span>
+ </div>
+ <ul class="flex flex-col gap-2">
+ <Index each={PLAN_FEATURES}>
+ {(feature) => (
+ <li class="flex items-center justify-between gap-2 text-xs">
+ <span class="text-ink-muted">{feature().label}</span>
+ <span class="text-ink font-medium">
+ {feature().values[plan().tier]}
+ </span>
+ </li>
+ )}
+ </Index>
+ </ul>
+ </button>
+ )}
+ </Index>
+ </div>
+
+ <div class="flex flex-col gap-3">
+ <Button
+ variant="cta"
+ size="xl"
+ disabled={props.finishing}
+ onClick={() => props.onFinish()}
+ >
+ {props.finishing
+ ? selected() === 'free'
+ ? 'Setting up your workspace…'
+ : 'Heading to checkout…'
+ : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}
+ <ArrowRight class="size-5" />
+ </Button>
+ <SkipButton
+ label="Decide later"
+ disabled={props.finishing}
+ onClick={() => props.onDecideLater()}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index 68b07116c9..756bcb27ff 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -68,6 +68,16 @@ export type AppEvents = {
* linked, an email-code signup with none. `entry_step` is where the
* user landed ('email' unless a persisted step was restored).
*/
+ /** A GTM invite welcome page resolved its link (`/invite?token=`). */
+ gtm_invite_opened: { status: string };
+ /** The recipient pressed Continue on the welcome page. */
+ gtm_invite_continue: { authenticated: boolean };
+ /** An account was attributed to an invite link and granted its offer. */
+ gtm_invite_redeemed: { link_id: string; promo_code: string };
+ /** The plan step showed the free-month offer instead of the picker. */
+ gtm_invite_offer_viewed: { link_id: string; promo_code: string };
+ /** Staff created an invite link in the internal portal. */
+ gtm_invite_link_created: { link_id: string };
onboarding_v4_started: {
signup_method: 'google' | 'email_code';
entry_step: string;
diff --git a/apps/web/src/lib/queries/gtm-invite/keys.ts b/apps/web/src/lib/queries/gtm-invite/keys.ts
new file mode 100644
index 0000000000..71388192d5
--- /dev/null
+++ b/apps/web/src/lib/queries/gtm-invite/keys.ts
@@ -0,0 +1,7 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const gtmInviteKeys = createQueryKeys('gtmInvite', {
+ links: (mine: boolean) => [mine],
+ publicLink: (token: string) => [token],
+ offer: null,
+});
diff --git a/apps/web/src/lib/queries/gtm-invite/links.ts b/apps/web/src/lib/queries/gtm-invite/links.ts
new file mode 100644
index 0000000000..ce051a9e7a
--- /dev/null
+++ b/apps/web/src/lib/queries/gtm-invite/links.ts
@@ -0,0 +1,150 @@
+/**
+ * Queries and mutations for GTM invite links: the staff dashboard (create,
+ * list, revoke), the public welcome page (resolve), and the signup handoff
+ * (redeem, then the offer the plan step shows).
+ */
+import { toast } from '@core/component/Toast/Toast';
+import { throwOnErr } from '@core/util/result';
+import { authServiceClient } from '@service-auth/client';
+import type { CreateGtmInviteLinkRequest } from '@service-auth/generated/schemas/createGtmInviteLinkRequest';
+import type { GtmInviteLink } from '@service-auth/generated/schemas/gtmInviteLink';
+import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+import { queryClient } from '../client';
+import { type MutationCallbacks, withCallbacks } from '../utils';
+
+import { gtmInviteKeys } from './keys';
+
+export type { GtmInviteLink, GtmInviteOffer };
+
+const LINKS_REFETCH_INTERVAL_MS = 30_000;
+const OFFER_STALE_TIME_MS = 60_000;
+
+/** Staff dashboard: every staff member's links, or just the caller's. */
+export function useGtmInviteLinksQuery(mine: Accessor<boolean>) {
+ return useQuery(() => ({
+ queryKey: gtmInviteKeys.links(mine()).queryKey,
+ queryFn: async () =>
+ await throwOnErr(() =>
+ authServiceClient.listGtmInviteLinks({ mine: mine() })
+ ),
+ // Opens and signups land server-side; keep the dashboard live.
+ refetchInterval: LINKS_REFETCH_INTERVAL_MS,
+ }));
+}
+
+export function invalidateGtmInviteLinks() {
+ return queryClient.invalidateQueries({ queryKey: gtmInviteKeys.links._def });
+}
+
+type CreateLinkCallbacks = MutationCallbacks<
+ GtmInviteLink,
+ Error,
+ CreateGtmInviteLinkRequest
+>;
+
+export function useCreateGtmInviteLinkMutation(
+ callbacks?: CreateLinkCallbacks
+) {
+ return useMutation(() => ({
+ mutationFn: async (args: CreateGtmInviteLinkRequest) =>
+ await throwOnErr(() => authServiceClient.createGtmInviteLink(args)),
+ ...withCallbacks<GtmInviteLink, Error, CreateGtmInviteLinkRequest>(
+ {
+ onSuccess: () => {
+ invalidateGtmInviteLinks();
+ },
+ onError: (error) => {
+ toast.failure(error.message || "Couldn't create the invite link");
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+type RevokeLinkArgs = { id: string };
+type RevokeLinkCallbacks = MutationCallbacks<
+ GtmInviteLink,
+ Error,
+ RevokeLinkArgs
+>;
+
+export function useRevokeGtmInviteLinkMutation(
+ callbacks?: RevokeLinkCallbacks
+) {
+ return useMutation(() => ({
+ mutationFn: async ({ id }: RevokeLinkArgs) =>
+ await throwOnErr(() => authServiceClient.revokeGtmInviteLink(id)),
+ ...withCallbacks<GtmInviteLink, Error, RevokeLinkArgs>(
+ {
+ onSuccess: () => {
+ invalidateGtmInviteLinks();
+ toast.success('Invite link revoked');
+ },
+ onError: (error) => {
+ toast.failure(error.message || "Couldn't revoke the invite link");
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+/**
+ * The public welcome page's view of a link. Every fetch counts as an "open"
+ * on the dashboard, so the result is pinned for the page's lifetime.
+ */
+export function usePublicGtmInviteLinkQuery(
+ token: Accessor<string | undefined>
+) {
+ return useQuery(() => ({
+ queryKey: gtmInviteKeys.publicLink(token() ?? '').queryKey,
+ queryFn: async () =>
+ await throwOnErr(() =>
+ authServiceClient.resolveGtmInviteLink(token() ?? '')
+ ),
+ enabled: !!token(),
+ retry: false,
+ staleTime: Number.POSITIVE_INFINITY,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ }));
+}
+
+/** The promotion the signed-in account holds from an invite link, or null. */
+export function useGtmInviteOfferQuery(options?: { enabled?: () => boolean }) {
+ return useQuery(() => ({
+ queryKey: gtmInviteKeys.offer.queryKey,
+ queryFn: async () =>
+ await throwOnErr(() => authServiceClient.getGtmInviteOffer()),
+ enabled: options?.enabled ? options.enabled() : true,
+ staleTime: OFFER_STALE_TIME_MS,
+ }));
+}
+
+export function invalidateGtmInviteOffer() {
+ return queryClient.invalidateQueries({
+ queryKey: gtmInviteKeys.offer.queryKey,
+ });
+}
+
+type RedeemArgs = { token: string };
+type RedeemCallbacks = MutationCallbacks<GtmInviteOffer, Error, RedeemArgs>;
+
+export function useRedeemGtmInviteLinkMutation(callbacks?: RedeemCallbacks) {
+ return useMutation(() => ({
+ mutationFn: async ({ token }: RedeemArgs) =>
+ await throwOnErr(() => authServiceClient.redeemGtmInviteLink(token)),
+ ...withCallbacks<GtmInviteOffer, Error, RedeemArgs>(
+ {
+ onSuccess: () => {
+ invalidateGtmInviteOffer();
+ },
+ },
+ callbacks
+ ),
+ }));
+}
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 fb5c8f09ac..933232aa7d 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -28,12 +28,17 @@ import type {
UserQuota,
} from './generated/schemas';
import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';
+import type { CreateGtmInviteLinkRequest } from './generated/schemas/createGtmInviteLinkRequest';
import type { CreateTeamRequest } from './generated/schemas/createTeamRequest';
import type { EmptyResponse } from './generated/schemas/emptyResponse';
import type { GenericSuccessResponse } from './generated/schemas/genericSuccessResponse';
import type { GetLegacyUserPermissionsResponse } from './generated/schemas/getLegacyUserPermissionsResponse';
import type { GetProfilePicturesRequestBody } from './generated/schemas/getProfilePicturesRequestBody';
import type { GetUserInfo } from './generated/schemas/getUserInfo';
+import type { GtmInviteLink } from './generated/schemas/gtmInviteLink';
+import type { GtmInviteLinkList } from './generated/schemas/gtmInviteLinkList';
+import type { GtmInviteOffer } from './generated/schemas/gtmInviteOffer';
+import type { GtmInviteOfferStatus } from './generated/schemas/gtmInviteOfferStatus';
import type { InviteToTeamRequest } from './generated/schemas/inviteToTeamRequest';
import type { MacroApiTokenResponse } from './generated/schemas/macroApiTokenResponse';
import type { PasswordRequest } from './generated/schemas/passwordRequest';
@@ -42,6 +47,7 @@ import type { PatchUserGroupRequest } from './generated/schemas/patchUserGroupRe
import type { PatchUserOnboardingRequest } from './generated/schemas/patchUserOnboardingRequest';
import type { PostGetNamesRequestBody } from './generated/schemas/postGetNamesRequestBody';
import type { ProfilePictures } from './generated/schemas/profilePictures';
+import type { PublicGtmInviteLink } from './generated/schemas/publicGtmInviteLink';
import type { PutProfilePictureParams } from './generated/schemas/putProfilePictureParams';
import type { PutUserNameQueryParams } from './generated/schemas/putUserNameQueryParams';
import type { Team } from './generated/schemas/team';
@@ -525,6 +531,65 @@ export const authServiceClient = {
).map(() => undefined);
},
+ // GTM invite links: personal, time-limited signup links Macro staff hand
+ // to prospects. Staff endpoints are gated server-side on a @macro.com account.
+ async createGtmInviteLink(args: CreateGtmInviteLinkRequest) {
+ return (
+ await fetchWithAuth<GtmInviteLink>(`${authHost}/gtm-invite/links`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ })
+ ).map((link) => link);
+ },
+
+ async listGtmInviteLinks(args: { mine: boolean }) {
+ return (
+ await fetchWithAuth<GtmInviteLinkList>(
+ `${authHost}/gtm-invite/links?mine=${args.mine ? 'true' : 'false'}`,
+ { method: 'GET' }
+ )
+ ).map((result) => result.links);
+ },
+
+ async revokeGtmInviteLink(id: string) {
+ return (
+ await fetchWithAuth<GtmInviteLink>(
+ `${authHost}/gtm-invite/links/${encodeURIComponent(id)}`,
+ { method: 'DELETE' }
+ )
+ ).map((link) => link);
+ },
+
+ /** Public: the recipient has no account yet, so nothing is sent for auth. */
+ async resolveGtmInviteLink(token: string) {
+ return (
+ await authApiFetch<PublicGtmInviteLink>(
+ `/gtm-invite/public/${encodeURIComponent(token)}`,
+ { method: 'GET', trace: { expectedStatusCodes: [404] } }
+ )
+ ).map((link) => link);
+ },
+
+ /** Attributes the signed-in account to the link and grants its offer. */
+ async redeemGtmInviteLink(token: string) {
+ return (
+ await fetchWithAuth<GtmInviteOffer>(`${authHost}/gtm-invite/redeem`, {
+ method: 'POST',
+ body: JSON.stringify({ token }),
+ })
+ ).map((offer) => offer);
+ },
+
+ /** The promotion this account holds from an invite link, or null. */
+ async getGtmInviteOffer() {
+ return (
+ await fetchWithAuth<GtmInviteOfferStatus>(
+ `${authHost}/gtm-invite/offer`,
+ { method: 'GET' }
+ )
+ ).map((result) => result.offer ?? null);
+ },
+
// Stripe HTTP methods (replacing RPC calls)
async createCheckoutSessionV2(args: {
successUrl: string;
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 d25cc65550..91ed201406 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
@@ -13,6 +13,7 @@ import type {
CodexLoginStart,
CreateAccountMergeRequest,
CreateCheckoutSessionV2Request,
+ CreateGtmInviteLinkRequest,
CreateInProgressLinkResponse,
CreatePortalSessionRequest,
CreateTeamRequest,
@@ -32,6 +33,10 @@ import type {
GetUserLinkExistsParams,
GithubLinkStatusResponse,
GmailLinkStatusResponse,
+ GtmInviteLink,
+ GtmInviteLinkList,
+ GtmInviteOffer,
+ GtmInviteOfferStatus,
InitGithubLinkParams,
InitGithubLinkResponse,
InitGmailLinkParams,
@@ -39,6 +44,7 @@ import type {
InitOutlookLinkParams,
InitOutlookLinkResponse,
InviteToTeamRequest,
+ ListGtmInviteLinksParams,
MacroApiTokenParams,
MacroApiTokenResponse,
PasswordlessCallbackParams,
@@ -54,10 +60,12 @@ import type {
Permission,
PostGetNamesRequestBody,
ProfilePictures,
+ PublicGtmInviteLink,
PutCursorApiKeyRequest,
PutCursorDefaultModelRequest,
PutProfilePictureParams,
PutUserNameParams,
+ RedeemGtmInviteLinkRequest,
ResendFusionauthVerifyUserEmailRequest,
SendInviteBody,
SendMobileWelcomeEmailRequest,
@@ -925,6 +933,440 @@ export const enrichGithubPullRequests = async (
} as enrichGithubPullRequestsResponse;
};
+/**
+ * @summary Lists invite links, newest first. Macro staff only.
+ */
+export type listGtmInviteLinksResponse200 = {
+ data: GtmInviteLinkList;
+ status: 200;
+};
+
+export type listGtmInviteLinksResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type listGtmInviteLinksResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type listGtmInviteLinksResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type listGtmInviteLinksResponseSuccess =
+ listGtmInviteLinksResponse200 & {
+ headers: Headers;
+ };
+export type listGtmInviteLinksResponseError = (
+ | listGtmInviteLinksResponse401
+ | listGtmInviteLinksResponse403
+ | listGtmInviteLinksResponse500
+) & {
+ headers: Headers;
+};
+
+export type listGtmInviteLinksResponse =
+ | listGtmInviteLinksResponseSuccess
+ | listGtmInviteLinksResponseError;
+
+export const getListGtmInviteLinksUrl = (params?: ListGtmInviteLinksParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/gtm-invite/links?${stringifiedParams}`
+ : `/gtm-invite/links`;
+};
+
+export const listGtmInviteLinks = async (
+ params?: ListGtmInviteLinksParams,
+ options?: RequestInit
+): Promise<listGtmInviteLinksResponse> => {
+ const res = await fetch(getListGtmInviteLinksUrl(params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listGtmInviteLinksResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listGtmInviteLinksResponse;
+};
+
+/**
+ * @summary Creates an invite link. Macro staff only.
+ */
+export type createGtmInviteLinkResponse200 = {
+ data: GtmInviteLink;
+ status: 200;
+};
+
+export type createGtmInviteLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type createGtmInviteLinkResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type createGtmInviteLinkResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type createGtmInviteLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type createGtmInviteLinkResponseSuccess =
+ createGtmInviteLinkResponse200 & {
+ headers: Headers;
+ };
+export type createGtmInviteLinkResponseError = (
+ | createGtmInviteLinkResponse400
+ | createGtmInviteLinkResponse401
+ | createGtmInviteLinkResponse403
+ | createGtmInviteLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type createGtmInviteLinkResponse =
+ | createGtmInviteLinkResponseSuccess
+ | createGtmInviteLinkResponseError;
+
+export const getCreateGtmInviteLinkUrl = () => {
+ return `/gtm-invite/links`;
+};
+
+export const createGtmInviteLink = async (
+ createGtmInviteLinkRequest: CreateGtmInviteLinkRequest,
+ options?: RequestInit
+): Promise<createGtmInviteLinkResponse> => {
+ const res = await fetch(getCreateGtmInviteLinkUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createGtmInviteLinkRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createGtmInviteLinkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createGtmInviteLinkResponse;
+};
+
+/**
+ * @summary Revokes an invite link nobody has signed up through. Macro staff only.
+ */
+export type revokeGtmInviteLinkResponse200 = {
+ data: GtmInviteLink;
+ status: 200;
+};
+
+export type revokeGtmInviteLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type revokeGtmInviteLinkResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type revokeGtmInviteLinkResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type revokeGtmInviteLinkResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type revokeGtmInviteLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type revokeGtmInviteLinkResponseSuccess =
+ revokeGtmInviteLinkResponse200 & {
+ headers: Headers;
+ };
+export type revokeGtmInviteLinkResponseError = (
+ | revokeGtmInviteLinkResponse400
+ | revokeGtmInviteLinkResponse401
+ | revokeGtmInviteLinkResponse403
+ | revokeGtmInviteLinkResponse404
+ | revokeGtmInviteLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type revokeGtmInviteLinkResponse =
+ | revokeGtmInviteLinkResponseSuccess
+ | revokeGtmInviteLinkResponseError;
+
+export const getRevokeGtmInviteLinkUrl = (id: string) => {
+ return `/gtm-invite/links/${id}`;
+};
+
+export const revokeGtmInviteLink = async (
+ id: string,
+ options?: RequestInit
+): Promise<revokeGtmInviteLinkResponse> => {
+ const res = await fetch(getRevokeGtmInviteLinkUrl(id), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: revokeGtmInviteLinkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as revokeGtmInviteLinkResponse;
+};
+
+/**
+ * @summary The promotion the signed-in user's account holds from an invite link, if
+they redeemed one and have not started a paid subscription yet.
+ */
+export type getGtmInviteOfferResponse200 = {
+ data: GtmInviteOfferStatus;
+ status: 200;
+};
+
+export type getGtmInviteOfferResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getGtmInviteOfferResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getGtmInviteOfferResponseSuccess = getGtmInviteOfferResponse200 & {
+ headers: Headers;
+};
+export type getGtmInviteOfferResponseError = (
+ | getGtmInviteOfferResponse401
+ | getGtmInviteOfferResponse500
+) & {
+ headers: Headers;
+};
+
+export type getGtmInviteOfferResponse =
+ | getGtmInviteOfferResponseSuccess
+ | getGtmInviteOfferResponseError;
+
+export const getGetGtmInviteOfferUrl = () => {
+ return `/gtm-invite/offer`;
+};
+
+export const getGtmInviteOffer = async (
+ options?: RequestInit
+): Promise<getGtmInviteOfferResponse> => {
+ const res = await fetch(getGetGtmInviteOfferUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getGtmInviteOfferResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getGtmInviteOfferResponse;
+};
+
+/**
+ * Unauthenticated: the recipient has no account yet. Only the first name and
+whether the link is still usable are exposed.
+ * @summary Resolves an invite link for the public welcome page and counts the open.
+ */
+export type resolveGtmInviteLinkResponse200 = {
+ data: PublicGtmInviteLink;
+ status: 200;
+};
+
+export type resolveGtmInviteLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type resolveGtmInviteLinkResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type resolveGtmInviteLinkResponse429 = {
+ data: void;
+ status: 429;
+};
+
+export type resolveGtmInviteLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type resolveGtmInviteLinkResponseSuccess =
+ resolveGtmInviteLinkResponse200 & {
+ headers: Headers;
+ };
+export type resolveGtmInviteLinkResponseError = (
+ | resolveGtmInviteLinkResponse400
+ | resolveGtmInviteLinkResponse404
+ | resolveGtmInviteLinkResponse429
+ | resolveGtmInviteLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type resolveGtmInviteLinkResponse =
+ | resolveGtmInviteLinkResponseSuccess
+ | resolveGtmInviteLinkResponseError;
+
+export const getResolveGtmInviteLinkUrl = (token: string) => {
+ return `/gtm-invite/public/${token}`;
+};
+
+export const resolveGtmInviteLink = async (
+ token: string,
+ options?: RequestInit
+): Promise<resolveGtmInviteLinkResponse> => {
+ const res = await fetch(getResolveGtmInviteLinkUrl(token), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: resolveGtmInviteLinkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as resolveGtmInviteLinkResponse;
+};
+
+/**
+ * @summary Attributes the signed-in user's account to the invite link they opened and
+grants them its offer. Idempotent for the same account.
+ */
+export type redeemGtmInviteLinkResponse200 = {
+ data: GtmInviteOffer;
+ status: 200;
+};
+
+export type redeemGtmInviteLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type redeemGtmInviteLinkResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type redeemGtmInviteLinkResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type redeemGtmInviteLinkResponse409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type redeemGtmInviteLinkResponse410 = {
+ data: ErrorResponse;
+ status: 410;
+};
+
+export type redeemGtmInviteLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type redeemGtmInviteLinkResponseSuccess =
+ redeemGtmInviteLinkResponse200 & {
+ headers: Headers;
+ };
+export type redeemGtmInviteLinkResponseError = (
+ | redeemGtmInviteLinkResponse400
+ | redeemGtmInviteLinkResponse401
+ | redeemGtmInviteLinkResponse404
+ | redeemGtmInviteLinkResponse409
+ | redeemGtmInviteLinkResponse410
+ | redeemGtmInviteLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type redeemGtmInviteLinkResponse =
+ | redeemGtmInviteLinkResponseSuccess
+ | redeemGtmInviteLinkResponseError;
+
+export const getRedeemGtmInviteLinkUrl = () => {
+ return `/gtm-invite/redeem`;
+};
+
+export const redeemGtmInviteLink = async (
+ redeemGtmInviteLinkRequest: RedeemGtmInviteLinkRequest,
+ options?: RequestInit
+): Promise<redeemGtmInviteLinkResponse> => {
+ const res = await fetch(getRedeemGtmInviteLinkUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(redeemGtmInviteLinkRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: redeemGtmInviteLinkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as redeemGtmInviteLinkResponse;
+};
+
/**
* @summary Health check
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequest.ts
new file mode 100644
index 0000000000..e57644ce66
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequest.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateGtmInviteLinkRequestNote } from './createGtmInviteLinkRequestNote';
+import type { CreateGtmInviteLinkRequestRecipientEmail } from './createGtmInviteLinkRequestRecipientEmail';
+
+/**
+ * Request body to create a link.
+ */
+export interface CreateGtmInviteLinkRequest {
+ /** The recipient's first name, shown on the welcome page. */
+ firstName: string;
+ /** Free-form internal note for the dashboard. */
+ note?: CreateGtmInviteLinkRequestNote;
+ /** The recipient's email, when the sender knows it. */
+ recipientEmail?: CreateGtmInviteLinkRequestRecipientEmail;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestNote.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestNote.ts
new file mode 100644
index 0000000000..df26a5195a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestNote.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Free-form internal note for the dashboard.
+ */
+export type CreateGtmInviteLinkRequestNote = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestRecipientEmail.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestRecipientEmail.ts
new file mode 100644
index 0000000000..23d29116cc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createGtmInviteLinkRequestRecipientEmail.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The recipient's email, when the sender knows it.
+ */
+export type CreateGtmInviteLinkRequestRecipientEmail = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLink.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLink.ts
new file mode 100644
index 0000000000..5ae2d4ad68
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLink.ts
@@ -0,0 +1,60 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GtmInviteLinkConvertedAt } from './gtmInviteLinkConvertedAt';
+import type { GtmInviteLinkFirstOpenedAt } from './gtmInviteLinkFirstOpenedAt';
+import type { GtmInviteLinkNote } from './gtmInviteLinkNote';
+import type { GtmInviteLinkRecipientEmail } from './gtmInviteLinkRecipientEmail';
+import type { GtmInviteLinkRedeemedAt } from './gtmInviteLinkRedeemedAt';
+import type { GtmInviteLinkRedeemedBy } from './gtmInviteLinkRedeemedBy';
+import type { GtmInviteLinkRevokedAt } from './gtmInviteLinkRevokedAt';
+import type { GtmInviteLinkStatus } from './gtmInviteLinkStatus';
+import type { GtmInviteLinkStripeSubscriptionId } from './gtmInviteLinkStripeSubscriptionId';
+
+/**
+ * A link as shown on the staff dashboard.
+ */
+export interface GtmInviteLink {
+ /** When the account started a paid subscription. */
+ convertedAt?: GtmInviteLinkConvertedAt;
+ /** When the link was created. */
+ createdAt: string;
+ /** The Macro user id of the staff member who created the link. */
+ createdBy: string;
+ /** When the link stops being openable. */
+ expiresAt: string;
+ /** The recipient's first name. */
+ firstName: string;
+ /** When the welcome page first loaded. */
+ firstOpenedAt?: GtmInviteLinkFirstOpenedAt;
+ /**
+ * Free months the promotion grants.
+ * @minimum 0
+ */
+ freeMonths: number;
+ /** Primary key. */
+ id: string;
+ /** Internal note. */
+ note?: GtmInviteLinkNote;
+ /** How many times the welcome page loaded. */
+ openCount: number;
+ /** The Stripe promotion code applied at checkout. */
+ promoCode: string;
+ /** The recipient's email, when known. */
+ recipientEmail?: GtmInviteLinkRecipientEmail;
+ /** When that account redeemed the link. */
+ redeemedAt?: GtmInviteLinkRedeemedAt;
+ /** The Macro user id of the account that signed up through the link. */
+ redeemedBy?: GtmInviteLinkRedeemedBy;
+ /** When staff revoked the link. */
+ revokedAt?: GtmInviteLinkRevokedAt;
+ /** Lifecycle status. */
+ status: GtmInviteLinkStatus;
+ /** The Stripe subscription id of that subscription. */
+ stripeSubscriptionId?: GtmInviteLinkStripeSubscriptionId;
+ /** The secret to embed in the link URL. */
+ token: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkConvertedAt.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkConvertedAt.ts
new file mode 100644
index 0000000000..aa9e4345d3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkConvertedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the account started a paid subscription.
+ */
+export type GtmInviteLinkConvertedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkFirstOpenedAt.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkFirstOpenedAt.ts
new file mode 100644
index 0000000000..2a72f02dbf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkFirstOpenedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the welcome page first loaded.
+ */
+export type GtmInviteLinkFirstOpenedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkList.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkList.ts
new file mode 100644
index 0000000000..d19447679a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkList.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 { GtmInviteLink } from './gtmInviteLink';
+
+/**
+ * Links for the dashboard.
+ */
+export interface GtmInviteLinkList {
+ /** Newest first. */
+ links: GtmInviteLink[];
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkNote.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkNote.ts
new file mode 100644
index 0000000000..7d4c921fbd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkNote.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Internal note.
+ */
+export type GtmInviteLinkNote = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRecipientEmail.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRecipientEmail.ts
new file mode 100644
index 0000000000..d7bb76ec6a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRecipientEmail.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The recipient's email, when known.
+ */
+export type GtmInviteLinkRecipientEmail = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedAt.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedAt.ts
new file mode 100644
index 0000000000..7602777dd9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When that account redeemed the link.
+ */
+export type GtmInviteLinkRedeemedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedBy.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedBy.ts
new file mode 100644
index 0000000000..b0c03e1835
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRedeemedBy.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The Macro user id of the account that signed up through the link.
+ */
+export type GtmInviteLinkRedeemedBy = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRevokedAt.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRevokedAt.ts
new file mode 100644
index 0000000000..1050e7a7fd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkRevokedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When staff revoked the link.
+ */
+export type GtmInviteLinkRevokedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStatus.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStatus.ts
new file mode 100644
index 0000000000..2fbdf9cc88
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStatus.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Where a link is in its lifecycle.
+ */
+export type GtmInviteLinkStatus =
+ (typeof GtmInviteLinkStatus)[keyof typeof GtmInviteLinkStatus];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GtmInviteLinkStatus = {
+ active: 'active',
+ expired: 'expired',
+ revoked: 'revoked',
+ redeemed: 'redeemed',
+ converted: 'converted',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStripeSubscriptionId.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStripeSubscriptionId.ts
new file mode 100644
index 0000000000..95448a729e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteLinkStripeSubscriptionId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The Stripe subscription id of that subscription.
+ */
+export type GtmInviteLinkStripeSubscriptionId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOffer.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOffer.ts
new file mode 100644
index 0000000000..fa83da7973
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOffer.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The promotion a signed-in user's account holds.
+ */
+export interface GtmInviteOffer {
+ /** The first name the link was made out to. */
+ firstName: string;
+ /**
+ * Free months the promotion grants.
+ * @minimum 0
+ */
+ freeMonths: number;
+ /** The redeemed link. */
+ linkId: string;
+ /** The Stripe promotion code checkout applies. */
+ promoCode: string;
+ /** When the account redeemed the link. */
+ redeemedAt: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatus.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatus.ts
new file mode 100644
index 0000000000..e84ab2c1d5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatus.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GtmInviteOfferStatusOffer } from './gtmInviteOfferStatusOffer';
+
+/**
+ * Whether the signed-in user holds an unused offer.
+ */
+export interface GtmInviteOfferStatus {
+ offer?: GtmInviteOfferStatusOffer;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatusOffer.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatusOffer.ts
new file mode 100644
index 0000000000..8b7fc51d2a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/gtmInviteOfferStatusOffer.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 { GtmInviteOffer } from './gtmInviteOffer';
+
+export type GtmInviteOfferStatusOffer = null | GtmInviteOffer;
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 dfcc1cf7c8..85fa9bcd87 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
@@ -25,6 +25,9 @@ export * from './codexLoginState';
export * from './createAccountMergeRequest';
export * from './createCheckoutSessionV2Request';
export * from './createCheckoutSessionV2RequestDiscount';
+export * from './createGtmInviteLinkRequest';
+export * from './createGtmInviteLinkRequestNote';
+export * from './createGtmInviteLinkRequestRecipientEmail';
export * from './createInProgressLinkResponse';
export * from './createPortalSessionRequest';
export * from './createTeamRequest';
@@ -81,6 +84,20 @@ export * from './githubPullRequestCommentUrl';
export * from './githubPullRequestRef';
export * from './githubPullRequestStatus';
export * from './gmailLinkStatusResponse';
+export * from './gtmInviteLink';
+export * from './gtmInviteLinkConvertedAt';
+export * from './gtmInviteLinkFirstOpenedAt';
+export * from './gtmInviteLinkList';
+export * from './gtmInviteLinkNote';
+export * from './gtmInviteLinkRecipientEmail';
+export * from './gtmInviteLinkRedeemedAt';
+export * from './gtmInviteLinkRedeemedBy';
+export * from './gtmInviteLinkRevokedAt';
+export * from './gtmInviteLinkStatus';
+export * from './gtmInviteLinkStripeSubscriptionId';
+export * from './gtmInviteOffer';
+export * from './gtmInviteOfferStatus';
+export * from './gtmInviteOfferStatusOffer';
export * from './initGithubLinkParams';
export * from './initGithubLinkResponse';
export * from './initGmailLinkParams';
@@ -90,6 +107,7 @@ export * from './initOutlookLinkResponse';
export * from './inviteEntry';
export * from './inviteToTeamRequest';
export * from './linkShare';
+export * from './listGtmInviteLinksParams';
export * from './macroApiTokenParams';
export * from './macroApiTokenResponse';
export * from './passwordlessCallbackParams';
@@ -113,6 +131,7 @@ export * from './permission';
export * from './postGetNamesRequestBody';
export * from './profilePictureQueryParams';
export * from './profilePictures';
+export * from './publicGtmInviteLink';
export * from './putCursorApiKeyRequest';
export * from './putCursorDefaultModelRequest';
export * from './putCursorDefaultModelRequestModelId';
@@ -121,6 +140,7 @@ export * from './putUserNameParams';
export * from './putUserNameQueryParams';
export * from './putUserNameQueryParamsFirstName';
export * from './putUserNameQueryParamsLastName';
+export * from './redeemGtmInviteLinkRequest';
export * from './resendFusionauthVerifyUserEmailRequest';
export * from './sendInviteBody';
export * from './sendMobileWelcomeEmailRequest';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/listGtmInviteLinksParams.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/listGtmInviteLinksParams.ts
new file mode 100644
index 0000000000..58f3ef7bc5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/listGtmInviteLinksParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ListGtmInviteLinksParams = {
+ /**
+ * Only the caller's own links (default: every staff member's).
+ */
+ mine?: boolean;
+};
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/publicGtmInviteLink.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/publicGtmInviteLink.ts
new file mode 100644
index 0000000000..efe2106875
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/publicGtmInviteLink.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GtmInviteLinkStatus } from './gtmInviteLinkStatus';
+
+/**
+ * What the public welcome page learns about a link.
+ */
+export interface PublicGtmInviteLink {
+ /** The recipient's first name. */
+ firstName: string;
+ /**
+ * Free months the promotion grants.
+ * @minimum 0
+ */
+ freeMonths: number;
+ /** Whether the link can still be used. */
+ status: GtmInviteLinkStatus;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/redeemGtmInviteLinkRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/redeemGtmInviteLinkRequest.ts
new file mode 100644
index 0000000000..04f6eade49
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/redeemGtmInviteLinkRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body to redeem a link.
+ */
+export interface RedeemGtmInviteLinkRequest {
+ /** The token from the link URL. */
+ token: string;
+}
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 97a7d9e24f..b5d54c074b 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -646,6 +646,406 @@
}
}
},
+ "/gtm-invite/links": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "Lists invite links, newest first. Macro staff only.",
+ "operationId": "list_gtm_invite_links",
+ "parameters": [
+ {
+ "name": "mine",
+ "in": "query",
+ "description": "Only the caller's own links (default: every staff member's).",
+ "required": false,
+ "schema": {
+ "type": "boolean"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLinkList"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["gtm_invite"],
+ "summary": "Creates an invite link. Macro staff only.",
+ "operationId": "create_gtm_invite_link",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateGtmInviteLinkRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/links/{id}": {
+ "delete": {
+ "tags": ["gtm_invite"],
+ "summary": "Revokes an invite link nobody has signed up through. Macro staff only.",
+ "operationId": "revoke_gtm_invite_link",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The invite link id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/offer": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "The promotion the signed-in user's account holds from an invite link, if\nthey redeemed one and have not started a paid subscription yet.",
+ "operationId": "get_gtm_invite_offer",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteOfferStatus"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/public/{token}": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "Resolves an invite link for the public welcome page and counts the open.",
+ "description": "Unauthenticated: the recipient has no account yet. Only the first name and\nwhether the link is still usable are exposed.",
+ "operationId": "resolve_gtm_invite_link",
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "description": "The token from the invite link URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PublicGtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": ""
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/redeem": {
+ "post": {
+ "tags": ["gtm_invite"],
+ "summary": "Attributes the signed-in user's account to the invite link they opened and\ngrants them its offer. Idempotent for the same account.",
+ "operationId": "redeem_gtm_invite_link",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RedeemGtmInviteLinkRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteOffer"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "410": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["health"],
@@ -4137,6 +4537,25 @@
}
}
},
+ "CreateGtmInviteLinkRequest": {
+ "type": "object",
+ "description": "Request body to create a link.",
+ "required": ["firstName"],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name, shown on the welcome page."
+ },
+ "note": {
+ "type": ["string", "null"],
+ "description": "Free-form internal note for the dashboard."
+ },
+ "recipientEmail": {
+ "type": ["string", "null"],
+ "description": "The recipient's email, when the sender knows it."
+ }
+ }
+ },
"CreateInProgressLinkResponse": {
"type": "object",
"required": ["link_id"],
@@ -4708,6 +5127,179 @@
}
}
},
+ "GtmInviteLink": {
+ "type": "object",
+ "description": "A link as shown on the staff dashboard.",
+ "required": [
+ "id",
+ "token",
+ "firstName",
+ "promoCode",
+ "freeMonths",
+ "status",
+ "createdBy",
+ "createdAt",
+ "expiresAt",
+ "openCount"
+ ],
+ "properties": {
+ "convertedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the account started a paid subscription."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the link was created."
+ },
+ "createdBy": {
+ "type": "string",
+ "description": "The Macro user id of the staff member who created the link."
+ },
+ "expiresAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the link stops being openable."
+ },
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name."
+ },
+ "firstOpenedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the welcome page first loaded."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Primary key."
+ },
+ "note": {
+ "type": ["string", "null"],
+ "description": "Internal note."
+ },
+ "openCount": {
+ "type": "integer",
+ "format": "int32",
+ "description": "How many times the welcome page loaded."
+ },
+ "promoCode": {
+ "type": "string",
+ "description": "The Stripe promotion code applied at checkout."
+ },
+ "recipientEmail": {
+ "type": ["string", "null"],
+ "description": "The recipient's email, when known."
+ },
+ "redeemedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When that account redeemed the link."
+ },
+ "redeemedBy": {
+ "type": ["string", "null"],
+ "description": "The Macro user id of the account that signed up through the link."
+ },
+ "revokedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When staff revoked the link."
+ },
+ "status": {
+ "$ref": "#/components/schemas/GtmInviteLinkStatus",
+ "description": "Lifecycle status."
+ },
+ "stripeSubscriptionId": {
+ "type": ["string", "null"],
+ "description": "The Stripe subscription id of that subscription."
+ },
+ "token": {
+ "type": "string",
+ "description": "The secret to embed in the link URL."
+ }
+ }
+ },
+ "GtmInviteLinkList": {
+ "type": "object",
+ "description": "Links for the dashboard.",
+ "required": ["links"],
+ "properties": {
+ "links": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ },
+ "description": "Newest first."
+ }
+ }
+ },
+ "GtmInviteLinkStatus": {
+ "type": "string",
+ "description": "Where a link is in its lifecycle.",
+ "enum": ["active", "expired", "revoked", "redeemed", "converted"]
+ },
+ "GtmInviteOffer": {
+ "type": "object",
+ "description": "The promotion a signed-in user's account holds.",
+ "required": [
+ "linkId",
+ "firstName",
+ "promoCode",
+ "freeMonths",
+ "redeemedAt"
+ ],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The first name the link was made out to."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The redeemed link."
+ },
+ "promoCode": {
+ "type": "string",
+ "description": "The Stripe promotion code checkout applies."
+ },
+ "redeemedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the account redeemed the link."
+ }
+ }
+ },
+ "GtmInviteOfferStatus": {
+ "type": "object",
+ "description": "Whether the signed-in user holds an unused offer.",
+ "properties": {
+ "offer": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GtmInviteOffer",
+ "description": "The offer, when the account redeemed a link and has not subscribed yet."
+ }
+ ]
+ }
+ }
+ },
"InitGithubLinkResponse": {
"type": "object",
"required": ["authorization_url", "link_id"],
@@ -5016,6 +5608,27 @@
}
}
},
+ "PublicGtmInviteLink": {
+ "type": "object",
+ "description": "What the public welcome page learns about a link.",
+ "required": ["firstName", "status", "freeMonths"],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "status": {
+ "$ref": "#/components/schemas/GtmInviteLinkStatus",
+ "description": "Whether the link can still be used."
+ }
+ }
+ },
"PutCursorApiKeyRequest": {
"type": "object",
"description": "The key the user pasted.",
@@ -5050,6 +5663,17 @@
}
}
},
+ "RedeemGtmInviteLinkRequest": {
+ "type": "object",
+ "description": "Request body to redeem a link.",
+ "required": ["token"],
+ "properties": {
+ "token": {
+ "type": "string",
+ "description": "The token from the link URL."
+ }
+ }
+ },
"ResendFusionauthVerifyUserEmailRequest": {
"type": "object",
"required": ["email"],
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 291b776c0a..4bdd7a0d28 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -6,6 +6,9 @@ import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAu
import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnboarding';
import { setCookie } from '@app/features/auth/Shared';
import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
+import { InviteLinksPortal } from '@app/features/gtm-invite/InviteLinksPortal';
+import { InviteWelcome } from '@app/features/gtm-invite/InviteWelcome';
+import { usePendingInviteRedemption } from '@app/features/gtm-invite/usePendingInviteRedemption';
import { GlobalShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';
@@ -355,6 +358,16 @@ const ROUTES: RouteDefinition[] = [
path: '/setup',
component: SetupRoute,
},
+ {
+ // A personal GTM invite link (`?token=`): welcome page, then signup.
+ path: '/invite',
+ component: InviteWelcome,
+ },
+ {
+ // Macro staff only: create and track GTM invite links.
+ path: '/internal/invite-links',
+ component: InviteLinksPortal,
+ },
{
path: '/team-invite',
component: TeamInviteAcceptance,
@@ -421,6 +434,10 @@ function UserInfoSideEffects() {
useSyncLoginCookie();
+ // A signup that started from a GTM invite link finishes its attribution on
+ // the first authenticated load (the welcome page parked the token).
+ usePendingInviteRedemption();
+
// Set user info for observability and analytics
const userInfo = useUserInfo();
diff --git a/crates/gtm_invite/Cargo.toml b/crates/gtm_invite/Cargo.toml
new file mode 100644
index 0000000000..73ed0f54c6
--- /dev/null
+++ b/crates/gtm_invite/Cargo.toml
@@ -0,0 +1,61 @@
+[package]
+edition = "2024"
+name = "gtm_invite"
+publish = false
+version = "0.1.0"
+
+[features]
+axum = [
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:ip_extractor",
+ "dep:macro_authorization",
+ "dep:model-error-response",
+ "dep:tower",
+ "dep:utoipa",
+]
+default = ["axum", "inbound", "outbound", "ports"]
+inbound = ["axum", "ports"]
+outbound = ["dep:sqlx", "ports"]
+ports = []
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+chrono = { workspace = true }
+rand = { workspace = true }
+serde = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+# Domain models
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
+ "axum",
+] }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+rate_limit = { path = "../rate_limit", features = ["axum"] }
+
+# Axum dependencies (for inbound)
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
+ip_extractor = { path = "../ip_extractor", optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
+tower = { workspace = true, optional = true }
+utoipa = { workspace = true, optional = true }
+
+# Outbound dependencies
+sqlx = { workspace = true, optional = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+http-body-util = { workspace = true }
+macro_db_migrator = { path = "../macro_db_migrator" }
+mockall = { workspace = true }
+model_user = { path = "../model_user" }
+rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }
+rootcause = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
diff --git a/crates/gtm_invite/justfile b/crates/gtm_invite/justfile
new file mode 100644
index 0000000000..21b4243533
--- /dev/null
+++ b/crates/gtm_invite/justfile
@@ -0,0 +1,9 @@
+import '../../tooling/just/database.just'
+
+mod sqlx '../../tooling/just/sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
+
+check:
+ cargo check --all-features
diff --git a/crates/gtm_invite/src/domain.rs b/crates/gtm_invite/src/domain.rs
new file mode 100644
index 0000000000..a947d9653b
--- /dev/null
+++ b/crates/gtm_invite/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports (trait interfaces), and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/crates/gtm_invite/src/domain/models.rs b/crates/gtm_invite/src/domain/models.rs
new file mode 100644
index 0000000000..26c76c02aa
--- /dev/null
+++ b/crates/gtm_invite/src/domain/models.rs
@@ -0,0 +1,292 @@
+//! Domain models for GTM invite links.
+
+use std::{fmt, str::FromStr};
+
+use chrono::{DateTime, Duration, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use rand::{Rng, distr::Alphanumeric};
+use rate_limit::RateLimitExceeded;
+use uuid::Uuid;
+
+/// Number of characters in a generated invite token.
+pub const INVITE_TOKEN_LENGTH: usize = 32;
+const MIN_INVITE_TOKEN_LENGTH: usize = 16;
+const MAX_INVITE_TOKEN_LENGTH: usize = 64;
+const MAX_PROMO_CODE_LENGTH: usize = 64;
+/// Longest accepted first name on a link.
+pub const MAX_FIRST_NAME_LENGTH: usize = 80;
+/// Longest accepted internal note on a link.
+pub const MAX_NOTE_LENGTH: usize = 500;
+
+/// Errors that can occur during invite link operations.
+#[derive(Debug, thiserror::Error)]
+pub enum GtmInviteError {
+ /// A rate limit was exceeded.
+ #[error("rate limit exceeded")]
+ RateLimitExceeded(#[from] RateLimitExceeded),
+ /// No link exists for the given token or id.
+ #[error("invite link not found")]
+ NotFound,
+ /// The caller is not Macro staff.
+ #[error("only Macro staff can manage invite links")]
+ Forbidden,
+ /// The link's 48-hour window has passed.
+ #[error("this invite link has expired")]
+ Expired,
+ /// The link was revoked by staff.
+ #[error("this invite link has been revoked")]
+ Revoked,
+ /// Another account already signed up through this link.
+ #[error("this invite link was already used by another account")]
+ AlreadyRedeemed,
+ /// The token does not have the shape of a generated token.
+ #[error("invalid invite token")]
+ InvalidToken,
+ /// The request was malformed.
+ #[error("bad request: {0}")]
+ BadRequest(String),
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+/// The opaque secret carried in an invite link URL.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub struct InviteToken(String);
+
+impl InviteToken {
+ /// Generate a fresh, cryptographically random token.
+ pub fn generate() -> Self {
+ let token: String = rand::rng()
+ .sample_iter(Alphanumeric)
+ .take(INVITE_TOKEN_LENGTH)
+ .map(char::from)
+ .collect();
+ Self(token)
+ }
+
+ /// The token as a string slice.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl FromStr for InviteToken {
+ type Err = GtmInviteError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let valid_length = (MIN_INVITE_TOKEN_LENGTH..=MAX_INVITE_TOKEN_LENGTH).contains(&s.len());
+ let valid_chars = s
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
+ if valid_length && valid_chars {
+ Ok(Self(s.to_owned()))
+ } else {
+ Err(GtmInviteError::InvalidToken)
+ }
+ }
+}
+
+impl fmt::Display for InviteToken {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// A promo code is not a valid Stripe promotion code.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+#[error("promo code must be 1-64 characters of letters, digits, '-' or '_'")]
+pub struct InvalidPromoCode;
+
+/// A Stripe promotion code such as `1MF`, as customers type it at checkout.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub struct PromoCode(String);
+
+impl PromoCode {
+ /// The code as a string slice.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl FromStr for PromoCode {
+ type Err = InvalidPromoCode;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let trimmed = s.trim();
+ let valid_length = (1..=MAX_PROMO_CODE_LENGTH).contains(&trimmed.len());
+ let valid_chars = trimmed
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
+ if valid_length && valid_chars {
+ Ok(Self(trimmed.to_owned()))
+ } else {
+ Err(InvalidPromoCode)
+ }
+ }
+}
+
+impl fmt::Display for PromoCode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// Static configuration for the offer every link carries.
+#[derive(Clone, Debug)]
+pub struct GtmInviteConfig {
+ /// The Stripe promotion code applied at checkout for redeemed links.
+ pub promo_code: PromoCode,
+ /// How long a link can be opened and redeemed after it is created.
+ pub link_ttl: Duration,
+ /// Number of free months the promotion grants, for user-facing copy.
+ pub free_months: u8,
+}
+
+/// What Macro staff supply to create a link.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CreateInviteLink {
+ /// The recipient's first name, shown on the welcome page.
+ pub first_name: String,
+ /// The recipient's email, when the sender knows it.
+ pub recipient_email: Option<String>,
+ /// Free-form internal note (company, context) for the dashboard.
+ pub note: Option<String>,
+}
+
+/// Filter for listing links on the dashboard.
+#[derive(Clone, Debug)]
+pub struct ListInviteLinks {
+ /// Restrict to links created by this user.
+ pub created_by: Option<MacroUserIdStr<'static>>,
+ /// Maximum number of links to return, newest first.
+ pub limit: i64,
+}
+
+/// The Stripe subscription that a redeemed link converted into.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct InviteConversion {
+ /// When the subscription became active.
+ pub converted_at: DateTime<Utc>,
+ /// The Stripe subscription id, when known.
+ pub stripe_subscription_id: Option<String>,
+}
+
+/// The account that signed up through a link.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct InviteRedemption {
+ /// The user who redeemed the link.
+ pub user_id: MacroUserIdStr<'static>,
+ /// When the link was redeemed.
+ pub redeemed_at: DateTime<Utc>,
+ /// The paid subscription the redemption turned into, once it did.
+ pub conversion: Option<InviteConversion>,
+}
+
+/// A stored invite link.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct InviteLink {
+ /// Primary key.
+ pub id: Uuid,
+ /// The secret embedded in the link URL.
+ pub token: InviteToken,
+ /// The recipient's first name.
+ pub first_name: String,
+ /// The recipient's email, when known.
+ pub recipient_email: Option<String>,
+ /// Internal note for the dashboard.
+ pub note: Option<String>,
+ /// The promotion applied when the recipient checks out.
+ pub promo_code: PromoCode,
+ /// The staff member who created the link.
+ pub created_by: MacroUserIdStr<'static>,
+ /// When the link was created.
+ pub created_at: DateTime<Utc>,
+ /// When the link stops being openable and redeemable.
+ pub expires_at: DateTime<Utc>,
+ /// When staff revoked the link, if they did.
+ pub revoked_at: Option<DateTime<Utc>>,
+ /// How many times the welcome page resolved this link.
+ pub open_count: i32,
+ /// When the welcome page first resolved this link.
+ pub first_opened_at: Option<DateTime<Utc>>,
+ /// The signup attributed to this link, once there is one.
+ pub redemption: Option<InviteRedemption>,
+}
+
+/// Where a link is in its lifecycle, derived at read time.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum InviteLinkStatus {
+ /// Openable and redeemable.
+ Active,
+ /// The window passed without a signup.
+ Expired,
+ /// Staff revoked it before anyone signed up.
+ Revoked,
+ /// Someone signed up through it; no paid subscription yet.
+ Redeemed,
+ /// The signup turned into a paid subscription.
+ Converted,
+}
+
+impl InviteLinkStatus {
+ /// The status in its wire spelling.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Active => "active",
+ Self::Expired => "expired",
+ Self::Revoked => "revoked",
+ Self::Redeemed => "redeemed",
+ Self::Converted => "converted",
+ }
+ }
+}
+
+impl fmt::Display for InviteLinkStatus {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+/// A string is not an [`InviteLinkStatus`].
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+#[error("unknown invite link status: {0}")]
+pub struct UnknownInviteLinkStatus(pub String);
+
+impl FromStr for InviteLinkStatus {
+ type Err = UnknownInviteLinkStatus;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "active" => Ok(Self::Active),
+ "expired" => Ok(Self::Expired),
+ "revoked" => Ok(Self::Revoked),
+ "redeemed" => Ok(Self::Redeemed),
+ "converted" => Ok(Self::Converted),
+ other => Err(UnknownInviteLinkStatus(other.to_owned())),
+ }
+ }
+}
+
+impl InviteLink {
+ /// The link's lifecycle status as of `now`.
+ ///
+ /// A redemption outranks expiry and revocation: a recipient who signed
+ /// up keeps their attribution even after the window closes.
+ pub fn status(&self, now: DateTime<Utc>) -> InviteLinkStatus {
+ match &self.redemption {
+ Some(redemption) if redemption.conversion.is_some() => InviteLinkStatus::Converted,
+ Some(_) => InviteLinkStatus::Redeemed,
+ None if self.revoked_at.is_some() => InviteLinkStatus::Revoked,
+ None if now >= self.expires_at => InviteLinkStatus::Expired,
+ None => InviteLinkStatus::Active,
+ }
+ }
+
+ /// Whether this link was redeemed by `user`.
+ pub fn is_redeemed_by(&self, user: &MacroUserIdStr<'_>) -> bool {
+ self.redemption
+ .as_ref()
+ .is_some_and(|redemption| redemption.user_id.as_ref() == user.as_ref())
+ }
+}
diff --git a/crates/gtm_invite/src/domain/ports.rs b/crates/gtm_invite/src/domain/ports.rs
new file mode 100644
index 0000000000..1ac20f9b10
--- /dev/null
+++ b/crates/gtm_invite/src/domain/ports.rs
@@ -0,0 +1,141 @@
+//! Port definitions for the GTM invite domain.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use std::future::Future;
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use crate::domain::models::{
+ CreateInviteLink, GtmInviteConfig, GtmInviteError, InviteLink, InviteToken, ListInviteLinks,
+};
+
+/// Repository for invite links.
+///
+/// All methods perform database operations — SQL queries are written
+/// directly in the outbound adapter implementation.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait GtmInviteRepo: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Stores a freshly created link.
+ fn insert_link(&self, link: &InviteLink) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Looks a link up by the token in its URL.
+ fn get_link_by_token(
+ &self,
+ token: &InviteToken,
+ ) -> impl Future<Output = Result<Option<InviteLink>, Self::Err>> + Send;
+
+ /// Looks a link up by primary key.
+ fn get_link_by_id(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<Option<InviteLink>, Self::Err>> + Send;
+
+ /// Lists links newest first, optionally scoped to one creator.
+ fn list_links(
+ &self,
+ filter: &ListInviteLinks,
+ ) -> impl Future<Output = Result<Vec<InviteLink>, Self::Err>> + Send;
+
+ /// Counts a welcome-page open of the link.
+ fn record_open(
+ &self,
+ id: Uuid,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Revokes an unredeemed, unrevoked link. Returns whether a row changed.
+ fn revoke_link(
+ &self,
+ id: Uuid,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Atomically attributes the link to `user_id` if it is still open to be
+ /// redeemed (or was already redeemed by the same user). Returns the
+ /// updated link, or `None` when another account holds it or its window
+ /// closed.
+ fn redeem_link<'a>(
+ &self,
+ id: Uuid,
+ user_id: &MacroUserIdStr<'a>,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Option<InviteLink>, Self::Err>> + Send;
+
+ /// The link `user_id` signed up through, if any.
+ fn get_redeemed_link_for_user<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<Option<InviteLink>, Self::Err>> + Send;
+
+ /// Records that the user's redeemed link turned into a paid subscription.
+ /// Returns whether a row changed.
+ fn mark_converted<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ stripe_subscription_id: &str,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+}
+
+/// Service interface for invite link operations.
+///
+/// Orchestrates business logic using the repository.
+pub trait GtmInviteService: Send + Sync + 'static {
+ /// The offer configuration links are created with.
+ fn config(&self) -> &GtmInviteConfig;
+
+ /// Creates a link. Only Macro staff may create links.
+ fn create_link(
+ &self,
+ creator: &MacroUserIdStr<'_>,
+ request: CreateInviteLink,
+ ) -> impl Future<Output = Result<InviteLink, GtmInviteError>> + Send;
+
+ /// Lists links for the dashboard. Only Macro staff may list links.
+ fn list_links(
+ &self,
+ caller: &MacroUserIdStr<'_>,
+ only_mine: bool,
+ ) -> impl Future<Output = Result<Vec<InviteLink>, GtmInviteError>> + Send;
+
+ /// Revokes a link nobody has signed up through. Only Macro staff may revoke.
+ fn revoke_link(
+ &self,
+ caller: &MacroUserIdStr<'_>,
+ id: Uuid,
+ ) -> impl Future<Output = Result<InviteLink, GtmInviteError>> + Send;
+
+ /// Resolves a link for the public welcome page and counts the open.
+ fn resolve_link(
+ &self,
+ token: &InviteToken,
+ ) -> impl Future<Output = Result<InviteLink, GtmInviteError>> + Send;
+
+ /// Attributes the signed-in user's account to the link and grants them
+ /// its offer. Idempotent for the same user.
+ fn redeem_link(
+ &self,
+ token: &InviteToken,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<InviteLink, GtmInviteError>> + Send;
+
+ /// The redeemed link whose offer the user has not yet used at checkout.
+ fn active_offer_for_user(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<InviteLink>, GtmInviteError>> + Send;
+
+ /// Records the user's redeemed link as converted into a paid
+ /// subscription. Returns whether the user held a redeemed link.
+ fn mark_converted(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ stripe_subscription_id: &str,
+ ) -> impl Future<Output = Result<bool, GtmInviteError>> + Send;
+}
diff --git a/crates/gtm_invite/src/domain/service.rs b/crates/gtm_invite/src/domain/service.rs
new file mode 100644
index 0000000000..105336c516
--- /dev/null
+++ b/crates/gtm_invite/src/domain/service.rs
@@ -0,0 +1,276 @@
+//! GTM invite service implementation.
+
+#[cfg(test)]
+mod test;
+
+use chrono::Utc;
+use macro_user_id::{cowlike::CowLike, email::Email, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{
+ CreateInviteLink, GtmInviteConfig, GtmInviteError, InviteLink, InviteLinkStatus,
+ InviteToken, ListInviteLinks, MAX_FIRST_NAME_LENGTH, MAX_NOTE_LENGTH,
+ },
+ ports::{GtmInviteRepo, GtmInviteService},
+};
+
+/// Most links the dashboard lists in one call.
+const DASHBOARD_LIST_LIMIT: i64 = 500;
+
+/// The concrete invite link service implementation.
+pub struct GtmInviteServiceImpl<R> {
+ /// Invite link repository.
+ pub repo: R,
+ /// The offer every new link carries.
+ pub config: GtmInviteConfig,
+}
+
+impl<R: GtmInviteRepo> GtmInviteService for GtmInviteServiceImpl<R> {
+ fn config(&self) -> &GtmInviteConfig {
+ &self.config
+ }
+
+ #[tracing::instrument(skip_all, fields(creator = %creator.as_ref()), err)]
+ async fn create_link(
+ &self,
+ creator: &MacroUserIdStr<'_>,
+ request: CreateInviteLink,
+ ) -> Result<InviteLink, GtmInviteError> {
+ require_staff(creator)?;
+ let request = normalize_create_request(request)?;
+
+ let now = Utc::now();
+ let link = InviteLink {
+ id: macro_uuid::generate_uuid_v7(),
+ token: InviteToken::generate(),
+ first_name: request.first_name,
+ recipient_email: request.recipient_email,
+ note: request.note,
+ promo_code: self.config.promo_code.clone(),
+ created_by: creator.clone().into_owned(),
+ created_at: now,
+ expires_at: now + self.config.link_ttl,
+ revoked_at: None,
+ open_count: 0,
+ first_opened_at: None,
+ redemption: None,
+ };
+
+ self.repo.insert_link(&link).await.map_err(internal)?;
+ Ok(link)
+ }
+
+ #[tracing::instrument(skip_all, fields(caller = %caller.as_ref(), only_mine), err)]
+ async fn list_links(
+ &self,
+ caller: &MacroUserIdStr<'_>,
+ only_mine: bool,
+ ) -> Result<Vec<InviteLink>, GtmInviteError> {
+ require_staff(caller)?;
+ let filter = ListInviteLinks {
+ created_by: only_mine.then(|| caller.clone().into_owned()),
+ limit: DASHBOARD_LIST_LIMIT,
+ };
+ self.repo.list_links(&filter).await.map_err(internal)
+ }
+
+ #[tracing::instrument(skip_all, fields(caller = %caller.as_ref(), link_id = %id), err)]
+ async fn revoke_link(
+ &self,
+ caller: &MacroUserIdStr<'_>,
+ id: Uuid,
+ ) -> Result<InviteLink, GtmInviteError> {
+ require_staff(caller)?;
+ let link = self
+ .repo
+ .get_link_by_id(id)
+ .await
+ .map_err(internal)?
+ .ok_or(GtmInviteError::NotFound)?;
+
+ if link.redemption.is_some() {
+ return Err(already_used());
+ }
+
+ if link.revoked_at.is_none() {
+ // The update is conditional on the row still being unredeemed, so a
+ // signup racing this revoke wins and keeps its attribution.
+ let revoked = self
+ .repo
+ .revoke_link(id, Utc::now())
+ .await
+ .map_err(internal)?;
+ if !revoked {
+ return Err(already_used());
+ }
+ }
+
+ self.repo
+ .get_link_by_id(id)
+ .await
+ .map_err(internal)?
+ .ok_or(GtmInviteError::NotFound)
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn resolve_link(&self, token: &InviteToken) -> Result<InviteLink, GtmInviteError> {
+ let link = self
+ .repo
+ .get_link_by_token(token)
+ .await
+ .map_err(internal)?
+ .ok_or(GtmInviteError::NotFound)?;
+
+ // Tracking only — never fail the welcome page over it.
+ let _ = self
+ .repo
+ .record_open(link.id, Utc::now())
+ .await
+ .inspect_err(|e| tracing::warn!(error=?e, "failed to record invite link open"));
+
+ Ok(link)
+ }
+
+ #[tracing::instrument(skip_all, fields(user = %user.as_ref()), err)]
+ async fn redeem_link(
+ &self,
+ token: &InviteToken,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<InviteLink, GtmInviteError> {
+ let link = self
+ .repo
+ .get_link_by_token(token)
+ .await
+ .map_err(internal)?
+ .ok_or(GtmInviteError::NotFound)?;
+
+ if link.is_redeemed_by(user) {
+ return Ok(link);
+ }
+
+ // A user holds one offer: whichever link they redeemed first stays.
+ if let Some(existing) = self
+ .repo
+ .get_redeemed_link_for_user(user)
+ .await
+ .map_err(internal)?
+ {
+ tracing::info!(
+ existing_link_id = %existing.id,
+ link_id = %link.id,
+ "user already redeemed another invite link; keeping the first"
+ );
+ return Ok(existing);
+ }
+
+ let now = Utc::now();
+ match link.status(now) {
+ InviteLinkStatus::Active => {}
+ InviteLinkStatus::Expired => return Err(GtmInviteError::Expired),
+ InviteLinkStatus::Revoked => return Err(GtmInviteError::Revoked),
+ InviteLinkStatus::Redeemed | InviteLinkStatus::Converted => {
+ return Err(GtmInviteError::AlreadyRedeemed);
+ }
+ }
+
+ // The repository re-checks the guards atomically; `None` means a
+ // concurrent signup, revoke, or the expiry beat us.
+ self.repo
+ .redeem_link(link.id, user, now)
+ .await
+ .map_err(internal)?
+ .ok_or(GtmInviteError::AlreadyRedeemed)
+ }
+
+ #[tracing::instrument(skip_all, fields(user = %user.as_ref()), err)]
+ async fn active_offer_for_user(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<InviteLink>, GtmInviteError> {
+ let link = self
+ .repo
+ .get_redeemed_link_for_user(user)
+ .await
+ .map_err(internal)?;
+ Ok(link.filter(|link| {
+ link.redemption
+ .as_ref()
+ .is_some_and(|redemption| redemption.conversion.is_none())
+ }))
+ }
+
+ #[tracing::instrument(skip_all, fields(user = %user.as_ref(), stripe_subscription_id), err)]
+ async fn mark_converted(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ stripe_subscription_id: &str,
+ ) -> Result<bool, GtmInviteError> {
+ self.repo
+ .mark_converted(user, stripe_subscription_id, Utc::now())
+ .await
+ .map_err(internal)
+ }
+}
+
+fn require_staff(user: &MacroUserIdStr<'_>) -> Result<(), GtmInviteError> {
+ if user.is_macro_staff() {
+ Ok(())
+ } else {
+ Err(GtmInviteError::Forbidden)
+ }
+}
+
+fn internal<E: Into<anyhow::Error>>(error: E) -> GtmInviteError {
+ GtmInviteError::Internal(error.into())
+}
+
+fn already_used() -> GtmInviteError {
+ GtmInviteError::BadRequest("a link someone already signed up through cannot be revoked".into())
+}
+
+/// Trims and validates staff input for a new link.
+pub(crate) fn normalize_create_request(
+ request: CreateInviteLink,
+) -> Result<CreateInviteLink, GtmInviteError> {
+ let first_name = request.first_name.trim();
+ if first_name.is_empty() {
+ return Err(GtmInviteError::BadRequest("first name is required".into()));
+ }
+ if first_name.chars().count() > MAX_FIRST_NAME_LENGTH {
+ return Err(GtmInviteError::BadRequest(format!(
+ "first name must be at most {MAX_FIRST_NAME_LENGTH} characters"
+ )));
+ }
+
+ let recipient_email = match nonblank(request.recipient_email.as_deref()) {
+ None => None,
+ Some(email) => {
+ let lowercased = email.to_lowercase();
+ Email::parse_from_str(&lowercased).map_err(|_| {
+ GtmInviteError::BadRequest("recipient email is not a valid email address".into())
+ })?;
+ Some(lowercased)
+ }
+ };
+
+ let note = nonblank(request.note.as_deref()).map(str::to_owned);
+ if note
+ .as_ref()
+ .is_some_and(|note| note.chars().count() > MAX_NOTE_LENGTH)
+ {
+ return Err(GtmInviteError::BadRequest(format!(
+ "note must be at most {MAX_NOTE_LENGTH} characters"
+ )));
+ }
+
+ Ok(CreateInviteLink {
+ first_name: first_name.to_owned(),
+ recipient_email,
+ note,
+ })
+}
+
+fn nonblank(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|value| !value.is_empty())
+}
diff --git a/crates/gtm_invite/src/domain/service/test.rs b/crates/gtm_invite/src/domain/service/test.rs
new file mode 100644
index 0000000000..b31c2c4aa4
--- /dev/null
+++ b/crates/gtm_invite/src/domain/service/test.rs
@@ -0,0 +1,546 @@
+use chrono::{Duration, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{
+ CreateInviteLink, GtmInviteConfig, GtmInviteError, INVITE_TOKEN_LENGTH, InviteConversion,
+ InviteLink, InviteLinkStatus, InviteRedemption, InviteToken, PromoCode,
+ },
+ ports::{GtmInviteService, MockGtmInviteRepo},
+ service::{GtmInviteServiceImpl, normalize_create_request},
+};
+
+const TTL_HOURS: i64 = 48;
+
+fn config() -> GtmInviteConfig {
+ GtmInviteConfig {
+ promo_code: "1MF".parse().unwrap(),
+ link_ttl: Duration::hours(TTL_HOURS),
+ free_months: 1,
+ }
+}
+
+fn service(repo: MockGtmInviteRepo) -> GtmInviteServiceImpl<MockGtmInviteRepo> {
+ GtmInviteServiceImpl {
+ repo,
+ config: config(),
+ }
+}
+
+fn staff() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn outsider() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn prospect() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn other_prospect() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn create_request() -> CreateInviteLink {
+ CreateInviteLink {
+ first_name: "Ada".into(),
+ recipient_email: Some("[email protected]".into()),
+ note: Some("Met at the conference".into()),
+ }
+}
+
+fn active_link() -> InviteLink {
+ let now = Utc::now();
+ InviteLink {
+ id: Uuid::now_v7(),
+ token: InviteToken::generate(),
+ first_name: "Ada".into(),
+ recipient_email: None,
+ note: None,
+ promo_code: "1MF".parse().unwrap(),
+ created_by: staff(),
+ created_at: now - Duration::hours(1),
+ expires_at: now + Duration::hours(TTL_HOURS - 1),
+ revoked_at: None,
+ open_count: 0,
+ first_opened_at: None,
+ redemption: None,
+ }
+}
+
+fn redeemed_by(link: InviteLink, user: MacroUserIdStr<'static>) -> InviteLink {
+ InviteLink {
+ redemption: Some(InviteRedemption {
+ user_id: user,
+ redeemed_at: Utc::now(),
+ conversion: None,
+ }),
+ ..link
+ }
+}
+
+fn converted(link: InviteLink) -> InviteLink {
+ let redemption = link.redemption.map(|redemption| InviteRedemption {
+ conversion: Some(InviteConversion {
+ converted_at: Utc::now(),
+ stripe_subscription_id: Some("sub_123".into()),
+ }),
+ ..redemption
+ });
+ InviteLink { redemption, ..link }
+}
+
+// -- create_link --
+
+#[tokio::test]
+async fn create_link_rejects_non_staff_without_touching_the_repo() {
+ let svc = service(MockGtmInviteRepo::new());
+
+ let result = svc.create_link(&outsider(), create_request()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::Forbidden)));
+}
+
+#[tokio::test]
+async fn create_link_generates_a_token_and_stamps_the_offer() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_insert_link()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ let svc = service(repo);
+
+ let link = svc.create_link(&staff(), create_request()).await.unwrap();
+
+ assert_eq!(link.token.as_str().len(), INVITE_TOKEN_LENGTH);
+ assert_eq!(
+ link.expires_at - link.created_at,
+ Duration::hours(TTL_HOURS)
+ );
+ assert_eq!(link.promo_code.as_str(), "1MF");
+ assert_eq!(link.created_by.as_ref(), staff().as_ref());
+ assert_eq!(link.first_name, "Ada");
+ assert_eq!(link.recipient_email.as_deref(), Some("[email protected]"));
+ assert_eq!(link.status(Utc::now()), InviteLinkStatus::Active);
+}
+
+#[tokio::test]
+async fn create_link_generates_distinct_tokens() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_insert_link()
+ .times(2)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ let svc = service(repo);
+
+ let first = svc.create_link(&staff(), create_request()).await.unwrap();
+ let second = svc.create_link(&staff(), create_request()).await.unwrap();
+
+ assert_ne!(first.token, second.token);
+ assert_ne!(first.id, second.id);
+}
+
+#[test]
+fn normalize_rejects_blank_first_name() {
+ let result = normalize_create_request(CreateInviteLink {
+ first_name: " ".into(),
+ recipient_email: None,
+ note: None,
+ });
+
+ assert!(matches!(result, Err(GtmInviteError::BadRequest(_))));
+}
+
+#[test]
+fn normalize_rejects_invalid_recipient_email() {
+ let result = normalize_create_request(CreateInviteLink {
+ first_name: "Ada".into(),
+ recipient_email: Some("not-an-email".into()),
+ note: None,
+ });
+
+ assert!(matches!(result, Err(GtmInviteError::BadRequest(_))));
+}
+
+#[test]
+fn normalize_trims_and_lowercases_input() {
+ let normalized = normalize_create_request(CreateInviteLink {
+ first_name: " Ada ".into(),
+ recipient_email: Some(" [email protected] ".into()),
+ note: Some(" ".into()),
+ })
+ .unwrap();
+
+ assert_eq!(normalized.first_name, "Ada");
+ assert_eq!(
+ normalized.recipient_email.as_deref(),
+ );
+ assert_eq!(normalized.note, None);
+}
+
+// -- list_links --
+
+#[tokio::test]
+async fn list_links_only_mine_scopes_to_the_caller() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_list_links()
+ .withf(|filter| {
+ filter
+ .created_by
+ .as_ref()
+ .is_some_and(|creator| creator.as_ref() == staff().as_ref())
+ })
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(vec![]) }));
+ let svc = service(repo);
+
+ svc.list_links(&staff(), true).await.unwrap();
+}
+
+#[tokio::test]
+async fn list_links_for_everyone_has_no_creator_filter() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_list_links()
+ .withf(|filter| filter.created_by.is_none())
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(vec![]) }));
+ let svc = service(repo);
+
+ svc.list_links(&staff(), false).await.unwrap();
+}
+
+#[tokio::test]
+async fn list_links_rejects_non_staff() {
+ let svc = service(MockGtmInviteRepo::new());
+
+ let result = svc.list_links(&outsider(), false).await;
+
+ assert!(matches!(result, Err(GtmInviteError::Forbidden)));
+}
+
+// -- revoke_link --
+
+#[tokio::test]
+async fn revoke_link_refuses_a_redeemed_link() {
+ let link = redeemed_by(active_link(), prospect());
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_id().returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ let svc = service(repo);
+
+ let result = svc.revoke_link(&staff(), Uuid::now_v7()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::BadRequest(_))));
+}
+
+#[tokio::test]
+async fn revoke_link_marks_an_active_link_revoked() {
+ let link = active_link();
+ let id = link.id;
+ let mut repo = MockGtmInviteRepo::new();
+ let mut lookups = 0;
+ let after = InviteLink {
+ revoked_at: Some(Utc::now()),
+ ..link.clone()
+ };
+ repo.expect_get_link_by_id().times(2).returning(move |_| {
+ lookups += 1;
+ let link = if lookups == 1 {
+ link.clone()
+ } else {
+ after.clone()
+ };
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ repo.expect_revoke_link()
+ .withf(move |revoke_id, _| *revoke_id == id)
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(true) }));
+ let svc = service(repo);
+
+ let revoked = svc.revoke_link(&staff(), id).await.unwrap();
+
+ assert_eq!(revoked.status(Utc::now()), InviteLinkStatus::Revoked);
+}
+
+#[tokio::test]
+async fn revoke_link_reports_missing_links() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_id()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let svc = service(repo);
+
+ let result = svc.revoke_link(&staff(), Uuid::now_v7()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::NotFound)));
+}
+
+// -- resolve_link --
+
+#[tokio::test]
+async fn resolve_link_counts_the_open_and_returns_the_link() {
+ let link = active_link();
+ let id = link.id;
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_token().returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ repo.expect_record_open()
+ .withf(move |open_id, _| *open_id == id)
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let svc = service(repo);
+
+ let resolved = svc.resolve_link(&InviteToken::generate()).await.unwrap();
+
+ assert_eq!(resolved.id, id);
+}
+
+#[tokio::test]
+async fn resolve_link_survives_a_failed_open_count() {
+ let link = active_link();
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_token().returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ repo.expect_record_open()
+ .returning(|_, _| Box::pin(async { Err(anyhow::anyhow!("db down")) }));
+ let svc = service(repo);
+
+ assert!(svc.resolve_link(&InviteToken::generate()).await.is_ok());
+}
+
+#[tokio::test]
+async fn resolve_link_reports_unknown_tokens() {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_token()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let svc = service(repo);
+
+ let result = svc.resolve_link(&InviteToken::generate()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::NotFound)));
+}
+
+// -- redeem_link --
+
+fn repo_with_link(link: InviteLink) -> MockGtmInviteRepo {
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_link_by_token().returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ repo
+}
+
+#[tokio::test]
+async fn redeem_link_attributes_an_active_link() {
+ let link = active_link();
+ let id = link.id;
+ let redeemed = redeemed_by(link.clone(), prospect());
+ let mut repo = repo_with_link(link);
+ repo.expect_get_redeemed_link_for_user()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ repo.expect_redeem_link()
+ .withf(move |redeem_id, user, _| *redeem_id == id && user.as_ref() == prospect().as_ref())
+ .times(1)
+ .returning(move |_, _, _| {
+ let redeemed = redeemed.clone();
+ Box::pin(async move { Ok(Some(redeemed)) })
+ });
+ let svc = service(repo);
+
+ let result = svc
+ .redeem_link(&InviteToken::generate(), &prospect())
+ .await
+ .unwrap();
+
+ assert!(result.is_redeemed_by(&prospect()));
+ assert_eq!(result.status(Utc::now()), InviteLinkStatus::Redeemed);
+}
+
+#[tokio::test]
+async fn redeem_link_is_idempotent_for_the_same_user() {
+ let link = redeemed_by(active_link(), prospect());
+ let svc = service(repo_with_link(link));
+
+ let result = svc
+ .redeem_link(&InviteToken::generate(), &prospect())
+ .await
+ .unwrap();
+
+ assert!(result.is_redeemed_by(&prospect()));
+}
+
+#[tokio::test]
+async fn redeem_link_rejects_a_link_another_account_used() {
+ let link = redeemed_by(active_link(), other_prospect());
+ let mut repo = repo_with_link(link);
+ repo.expect_get_redeemed_link_for_user()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let svc = service(repo);
+
+ let result = svc.redeem_link(&InviteToken::generate(), &prospect()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::AlreadyRedeemed)));
+}
+
+#[tokio::test]
+async fn redeem_link_rejects_expired_and_revoked_links() {
+ let expired = InviteLink {
+ expires_at: Utc::now() - Duration::minutes(1),
+ ..active_link()
+ };
+ let mut repo = repo_with_link(expired);
+ repo.expect_get_redeemed_link_for_user()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let result = service(repo)
+ .redeem_link(&InviteToken::generate(), &prospect())
+ .await;
+ assert!(matches!(result, Err(GtmInviteError::Expired)));
+
+ let revoked = InviteLink {
+ revoked_at: Some(Utc::now()),
+ ..active_link()
+ };
+ let mut repo = repo_with_link(revoked);
+ repo.expect_get_redeemed_link_for_user()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let result = service(repo)
+ .redeem_link(&InviteToken::generate(), &prospect())
+ .await;
+ assert!(matches!(result, Err(GtmInviteError::Revoked)));
+}
+
+#[tokio::test]
+async fn redeem_link_keeps_the_users_first_link() {
+ let first = redeemed_by(active_link(), prospect());
+ let first_id = first.id;
+ let second = active_link();
+ let mut repo = repo_with_link(second);
+ repo.expect_get_redeemed_link_for_user()
+ .returning(move |_| {
+ let first = first.clone();
+ Box::pin(async move { Ok(Some(first)) })
+ });
+ let svc = service(repo);
+
+ let result = svc
+ .redeem_link(&InviteToken::generate(), &prospect())
+ .await
+ .unwrap();
+
+ assert_eq!(result.id, first_id);
+}
+
+#[tokio::test]
+async fn redeem_link_treats_a_lost_race_as_already_redeemed() {
+ let mut repo = repo_with_link(active_link());
+ repo.expect_get_redeemed_link_for_user()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ repo.expect_redeem_link()
+ .returning(|_, _, _| Box::pin(async { Ok(None) }));
+ let svc = service(repo);
+
+ let result = svc.redeem_link(&InviteToken::generate(), &prospect()).await;
+
+ assert!(matches!(result, Err(GtmInviteError::AlreadyRedeemed)));
+}
+
+// -- active_offer_for_user --
+
+#[tokio::test]
+async fn active_offer_is_the_unconverted_redeemed_link() {
+ let link = redeemed_by(active_link(), prospect());
+ let id = link.id;
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_redeemed_link_for_user()
+ .returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ let svc = service(repo);
+
+ let offer = svc.active_offer_for_user(&prospect()).await.unwrap();
+
+ assert_eq!(offer.map(|link| link.id), Some(id));
+}
+
+#[tokio::test]
+async fn active_offer_is_gone_once_converted() {
+ let link = converted(redeemed_by(active_link(), prospect()));
+ let mut repo = MockGtmInviteRepo::new();
+ repo.expect_get_redeemed_link_for_user()
+ .returning(move |_| {
+ let link = link.clone();
+ Box::pin(async move { Ok(Some(link)) })
+ });
+ let svc = service(repo);
+
+ let offer = svc.active_offer_for_user(&prospect()).await.unwrap();
+
+ assert!(offer.is_none());
+}
+
+// -- models --
+
+#[test]
+fn status_prefers_redemption_over_expiry_and_revocation() {
+ let stale = InviteLink {
+ expires_at: Utc::now() - Duration::days(30),
+ revoked_at: Some(Utc::now()),
+ ..active_link()
+ };
+ assert_eq!(stale.status(Utc::now()), InviteLinkStatus::Revoked);
+
+ let redeemed = redeemed_by(stale.clone(), prospect());
+ assert_eq!(redeemed.status(Utc::now()), InviteLinkStatus::Redeemed);
+ assert_eq!(
+ converted(redeemed).status(Utc::now()),
+ InviteLinkStatus::Converted
+ );
+}
+
+#[test]
+fn tokens_must_look_generated() {
+ assert!(
+ InviteToken::generate()
+ .as_str()
+ .parse::<InviteToken>()
+ .is_ok()
+ );
+ assert!("short".parse::<InviteToken>().is_err());
+ assert!(
+ "has spaces in it and is long enough"
+ .parse::<InviteToken>()
+ .is_err()
+ );
+ assert!("a".repeat(65).parse::<InviteToken>().is_err());
+}
+
+#[test]
+fn promo_codes_are_trimmed_and_validated() {
+ assert_eq!(" 1MF ".parse::<PromoCode>().unwrap().as_str(), "1MF");
+ assert!("".parse::<PromoCode>().is_err());
+ assert!("bad code".parse::<PromoCode>().is_err());
+}
+
+#[test]
+fn statuses_round_trip_through_strings() {
+ for status in [
+ InviteLinkStatus::Active,
+ InviteLinkStatus::Expired,
+ InviteLinkStatus::Revoked,
+ InviteLinkStatus::Redeemed,
+ InviteLinkStatus::Converted,
+ ] {
+ assert_eq!(status.to_string().parse::<InviteLinkStatus>(), Ok(status));
+ }
+ assert!("bogus".parse::<InviteLinkStatus>().is_err());
+}
diff --git a/crates/gtm_invite/src/inbound.rs b/crates/gtm_invite/src/inbound.rs
new file mode 100644
index 0000000000..4cb9a54659
--- /dev/null
+++ b/crates/gtm_invite/src/inbound.rs
@@ -0,0 +1,4 @@
+//! Inbound adapters for the GTM invite crate.
+
+#[cfg(feature = "axum")]
+pub mod axum_router;
diff --git a/crates/gtm_invite/src/inbound/axum_router.rs b/crates/gtm_invite/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..7eba1e47f0
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router.rs
@@ -0,0 +1,125 @@
+//! Axum router for GTM invite link endpoints.
+//!
+//! Nested under `/gtm-invite` by the authentication service:
+//! - `POST /links` — staff: create a link
+//! - `GET /links?mine=true` — staff: list links (all, or just the caller's)
+//! - `DELETE /links/{id}` — staff: revoke a link nobody used yet
+//! - `GET /public/{token}` — anyone: resolve a link for the welcome page
+//! - `POST /redeem` — signed-in user: attribute their account to a link
+//! - `GET /offer` — signed-in user: the promotion their account holds
+
+/// Create a link.
+pub mod create_link;
+/// Wire types shared by the handlers.
+pub mod dto;
+/// The signed-in user's offer.
+pub mod get_offer;
+/// Extractor that admits only Macro staff.
+pub mod gtm_macro_staff;
+/// List links for the dashboard.
+pub mod list_links;
+/// Attribute the signed-in user to a link.
+pub mod redeem_link;
+/// Resolve a link for the public welcome page.
+pub mod resolve_link;
+/// Revoke a link.
+pub mod revoke_link;
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::FromRef,
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, post},
+};
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use model_error_response::ErrorResponse;
+use rate_limit::{RateLimitService, inbound::rate_limit_middleware};
+
+use crate::domain::{models::GtmInviteError, ports::GtmInviteService};
+pub use resolve_link::PerIpResolveRateLimit;
+
+impl IntoResponse for GtmInviteError {
+ fn into_response(self) -> axum::response::Response {
+ let status_code = match &self {
+ GtmInviteError::RateLimitExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
+ GtmInviteError::NotFound => StatusCode::NOT_FOUND,
+ GtmInviteError::Forbidden => StatusCode::FORBIDDEN,
+ GtmInviteError::Expired | GtmInviteError::Revoked => StatusCode::GONE,
+ GtmInviteError::AlreadyRedeemed => StatusCode::CONFLICT,
+ GtmInviteError::InvalidToken | GtmInviteError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ GtmInviteError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ let mut message = self.to_string();
+ if status_code.is_server_error() {
+ tracing::error!(error=?self, "internal server error");
+ // override internal server error to hide errors
+ message = "internal server error".to_string();
+ }
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+/// Router state containing the invite service.
+pub struct GtmInviteRouterState<T, R, Auth> {
+ /// The invite link service implementation.
+ pub service: Arc<T>,
+ /// The rate limiter guarding the public resolve endpoint.
+ pub rate_limiter: R,
+ /// State for request authorization.
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<T, R: Clone, Auth> Clone for GtmInviteRouterState<T, R, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ rate_limiter: self.rate_limiter.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<T, R, Auth> FromRef<GtmInviteRouterState<T, R, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &GtmInviteRouterState<T, R, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Build the invite link router with all endpoints.
+pub fn gtm_invite_router<T, R, Auth, S>(state: GtmInviteRouterState<T, R, Auth>) -> Router<S>
+where
+ T: GtmInviteService,
+ R: RateLimitService + Clone,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ // The public route is the only unauthenticated one; tokens are
+ // unguessable, the per-IP limit just keeps scanners cheap to ignore.
+ .route("/public/{token}", get(resolve_link::handler::<T, R, Auth>))
+ .layer(axum::middleware::from_fn_with_state(
+ state.rate_limiter.clone(),
+ rate_limit_middleware::<R, PerIpResolveRateLimit, R>,
+ ))
+ .route(
+ "/links",
+ post(create_link::handler::<T, R, Auth>).get(list_links::handler::<T, R, Auth>),
+ )
+ .route("/links/{id}", delete(revoke_link::handler::<T, R, Auth>))
+ .route("/redeem", post(redeem_link::handler::<T, R, Auth>))
+ .route("/offer", get(get_offer::handler::<T, R, Auth>))
+ .with_state(state)
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/create_link.rs b/crates/gtm_invite/src/inbound/axum_router/create_link.rs
new file mode 100644
index 0000000000..e710c17ffe
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/create_link.rs
@@ -0,0 +1,43 @@
+//! Handler for `POST /gtm-invite/links`.
+
+use axum::{Json, extract::State};
+use chrono::Utc;
+use macro_authorization::MacroAuthorizationService;
+
+use super::GtmInviteRouterState;
+use super::dto::{CreateGtmInviteLinkRequest, GtmInviteLink};
+use super::gtm_macro_staff::GtmMacroStaffExtractor;
+use crate::domain::models::GtmInviteError;
+use crate::domain::ports::GtmInviteService;
+
+/// Creates an invite link. Macro staff only.
+#[utoipa::path(
+ tag = "gtm_invite",
+ post,
+ path = "/gtm-invite/links",
+ operation_id = "create_gtm_invite_link",
+ request_body = CreateGtmInviteLinkRequest,
+ responses(
+ (status = 200, body = GtmInviteLink),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 403, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ staff: GtmMacroStaffExtractor<Auth>,
+ Json(request): Json<CreateGtmInviteLinkRequest>,
+) -> Result<Json<GtmInviteLink>, GtmInviteError> {
+ let creator = &staff.macro_user_id;
+ let link = state.service.create_link(creator, request.into()).await?;
+ let free_months = state.service.config().free_months;
+
+ Ok(Json(GtmInviteLink::from_link(
+ link,
+ free_months,
+ Utc::now(),
+ )))
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/dto.rs b/crates/gtm_invite/src/inbound/axum_router/dto.rs
new file mode 100644
index 0000000000..b3ff3d5109
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/dto.rs
@@ -0,0 +1,223 @@
+//! Wire types for the invite link endpoints.
+
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use utoipa::{IntoParams, ToSchema};
+use uuid::Uuid;
+
+use crate::domain::models::{CreateInviteLink, InviteLink, InviteLinkStatus};
+
+/// Where a link is in its lifecycle.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum GtmInviteLinkStatus {
+ /// Openable and redeemable.
+ Active,
+ /// The window passed without a signup.
+ Expired,
+ /// Staff revoked it before anyone signed up.
+ Revoked,
+ /// Someone signed up through it; no paid subscription yet.
+ Redeemed,
+ /// The signup turned into a paid subscription.
+ Converted,
+}
+
+impl From<InviteLinkStatus> for GtmInviteLinkStatus {
+ fn from(status: InviteLinkStatus) -> Self {
+ match status {
+ InviteLinkStatus::Active => Self::Active,
+ InviteLinkStatus::Expired => Self::Expired,
+ InviteLinkStatus::Revoked => Self::Revoked,
+ InviteLinkStatus::Redeemed => Self::Redeemed,
+ InviteLinkStatus::Converted => Self::Converted,
+ }
+ }
+}
+
+/// A link as shown on the staff dashboard.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GtmInviteLink {
+ /// Primary key.
+ pub id: Uuid,
+ /// The secret to embed in the link URL.
+ pub token: String,
+ /// The recipient's first name.
+ pub first_name: String,
+ /// The recipient's email, when known.
+ pub recipient_email: Option<String>,
+ /// Internal note.
+ pub note: Option<String>,
+ /// The Stripe promotion code applied at checkout.
+ pub promo_code: String,
+ /// Free months the promotion grants.
+ pub free_months: u8,
+ /// Lifecycle status.
+ pub status: GtmInviteLinkStatus,
+ /// The Macro user id of the staff member who created the link.
+ pub created_by: String,
+ /// When the link was created.
+ pub created_at: DateTime<Utc>,
+ /// When the link stops being openable.
+ pub expires_at: DateTime<Utc>,
+ /// When staff revoked the link.
+ pub revoked_at: Option<DateTime<Utc>>,
+ /// How many times the welcome page loaded.
+ pub open_count: i32,
+ /// When the welcome page first loaded.
+ pub first_opened_at: Option<DateTime<Utc>>,
+ /// The Macro user id of the account that signed up through the link.
+ pub redeemed_by: Option<String>,
+ /// When that account redeemed the link.
+ pub redeemed_at: Option<DateTime<Utc>>,
+ /// When the account started a paid subscription.
+ pub converted_at: Option<DateTime<Utc>>,
+ /// The Stripe subscription id of that subscription.
+ pub stripe_subscription_id: Option<String>,
+}
+
+impl GtmInviteLink {
+ /// Flattens a domain link for the dashboard.
+ pub fn from_link(link: InviteLink, free_months: u8, now: DateTime<Utc>) -> Self {
+ let status = link.status(now).into();
+ let (redeemed_by, redeemed_at, converted_at, stripe_subscription_id) = match link.redemption
+ {
+ Some(redemption) => {
+ let (converted_at, stripe_subscription_id) = match redemption.conversion {
+ Some(conversion) => (
+ Some(conversion.converted_at),
+ conversion.stripe_subscription_id,
+ ),
+ None => (None, None),
+ };
+ (
+ Some(redemption.user_id.as_ref().to_owned()),
+ Some(redemption.redeemed_at),
+ converted_at,
+ stripe_subscription_id,
+ )
+ }
+ None => (None, None, None, None),
+ };
+ Self {
+ id: link.id,
+ token: link.token.to_string(),
+ first_name: link.first_name,
+ recipient_email: link.recipient_email,
+ note: link.note,
+ promo_code: link.promo_code.to_string(),
+ free_months,
+ status,
+ created_by: link.created_by.as_ref().to_owned(),
+ created_at: link.created_at,
+ expires_at: link.expires_at,
+ revoked_at: link.revoked_at,
+ open_count: link.open_count,
+ first_opened_at: link.first_opened_at,
+ redeemed_by,
+ redeemed_at,
+ converted_at,
+ stripe_subscription_id,
+ }
+ }
+}
+
+/// Request body to create a link.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateGtmInviteLinkRequest {
+ /// The recipient's first name, shown on the welcome page.
+ pub first_name: String,
+ /// The recipient's email, when the sender knows it.
+ #[serde(default)]
+ pub recipient_email: Option<String>,
+ /// Free-form internal note for the dashboard.
+ #[serde(default)]
+ pub note: Option<String>,
+}
+
+impl From<CreateGtmInviteLinkRequest> for CreateInviteLink {
+ fn from(request: CreateGtmInviteLinkRequest) -> Self {
+ Self {
+ first_name: request.first_name,
+ recipient_email: request.recipient_email,
+ note: request.note,
+ }
+ }
+}
+
+/// Query parameters for listing links.
+#[derive(Debug, Default, Deserialize, IntoParams)]
+#[serde(rename_all = "camelCase")]
+pub struct ListGtmInviteLinksQuery {
+ /// Only the caller's own links (default: every staff member's).
+ #[serde(default)]
+ pub mine: bool,
+}
+
+/// Links for the dashboard.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GtmInviteLinkList {
+ /// Newest first.
+ pub links: Vec<GtmInviteLink>,
+}
+
+/// What the public welcome page learns about a link.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PublicGtmInviteLink {
+ /// The recipient's first name.
+ pub first_name: String,
+ /// Whether the link can still be used.
+ pub status: GtmInviteLinkStatus,
+ /// Free months the promotion grants.
+ pub free_months: u8,
+}
+
+/// Request body to redeem a link.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RedeemGtmInviteLinkRequest {
+ /// The token from the link URL.
+ pub token: String,
+}
+
+/// The promotion a signed-in user's account holds.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GtmInviteOffer {
+ /// The redeemed link.
+ pub link_id: Uuid,
+ /// The first name the link was made out to.
+ pub first_name: String,
+ /// The Stripe promotion code checkout applies.
+ pub promo_code: String,
+ /// Free months the promotion grants.
+ pub free_months: u8,
+ /// When the account redeemed the link.
+ pub redeemed_at: DateTime<Utc>,
+}
+
+impl GtmInviteOffer {
+ /// The offer carried by a redeemed link, or `None` for an unredeemed one.
+ pub fn from_link(link: InviteLink, free_months: u8) -> Option<Self> {
+ let redemption = link.redemption?;
+ Some(Self {
+ link_id: link.id,
+ first_name: link.first_name,
+ promo_code: link.promo_code.to_string(),
+ free_months,
+ redeemed_at: redemption.redeemed_at,
+ })
+ }
+}
+
+/// Whether the signed-in user holds an unused offer.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GtmInviteOfferStatus {
+ /// The offer, when the account redeemed a link and has not subscribed yet.
+ pub offer: Option<GtmInviteOffer>,
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/get_offer.rs b/crates/gtm_invite/src/inbound/axum_router/get_offer.rs
new file mode 100644
index 0000000000..814baaf2e7
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/get_offer.rs
@@ -0,0 +1,36 @@
+//! Handler for `GET /gtm-invite/offer`.
+
+use axum::{Json, extract::State};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
+
+use super::GtmInviteRouterState;
+use super::dto::{GtmInviteOffer, GtmInviteOfferStatus};
+use crate::domain::models::GtmInviteError;
+use crate::domain::ports::GtmInviteService;
+
+/// The promotion the signed-in user's account holds from an invite link, if
+/// they redeemed one and have not started a paid subscription yet.
+#[utoipa::path(
+ tag = "gtm_invite",
+ get,
+ path = "/gtm-invite/offer",
+ operation_id = "get_gtm_invite_offer",
+ responses(
+ (status = 200, body = GtmInviteOfferStatus),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+) -> Result<Json<GtmInviteOfferStatus>, GtmInviteError> {
+ let user = &authorization.authorization.user.macro_user_id;
+ let link = state.service.active_offer_for_user(user).await?;
+ let free_months = state.service.config().free_months;
+
+ Ok(Json(GtmInviteOfferStatus {
+ offer: link.and_then(|link| GtmInviteOffer::from_link(link, free_months)),
+ }))
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/gtm_macro_staff.rs b/crates/gtm_invite/src/inbound/axum_router/gtm_macro_staff.rs
new file mode 100644
index 0000000000..6bd63cb03a
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/gtm_macro_staff.rs
@@ -0,0 +1,68 @@
+//! Extractor that admits only authenticated Macro staff.
+
+use std::marker::PhantomData;
+
+use axum::{
+ extract::{FromRef, FromRequestParts},
+ http::request::Parts,
+ response::{IntoResponse, Response},
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
+ MacroAuthorizationState, UserOrInternal,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::models::GtmInviteError;
+
+/// Authenticated Macro staff principal for GTM invite staff endpoints.
+pub struct GtmMacroStaffExtractor<Auth> {
+ /// The authenticated staff user's id.
+ pub macro_user_id: MacroUserIdStr<'static>,
+ _auth: PhantomData<fn() -> Auth>,
+}
+
+/// Rejection returned when the Macro staff check fails.
+#[derive(Debug, thiserror::Error)]
+pub enum GtmMacroStaffRejection {
+ /// The request could not be authorized.
+ #[error("authorization failed")]
+ Authorization(#[from] MacroAuthorizationRejection),
+ /// The authenticated user is not Macro staff.
+ #[error("only Macro staff can manage invite links")]
+ NotStaff,
+}
+
+impl IntoResponse for GtmMacroStaffRejection {
+ fn into_response(self) -> Response {
+ match self {
+ Self::Authorization(rejection) => rejection.into_response(),
+ Self::NotStaff => GtmInviteError::Forbidden.into_response(),
+ }
+ }
+}
+
+impl<S, Auth> FromRequestParts<S> for GtmMacroStaffExtractor<Auth>
+where
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = GtmMacroStaffRejection;
+
+ #[tracing::instrument(err, skip(parts, state))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let authorization =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
+ .await?;
+ let macro_user_id = authorization.authorization.user.macro_user_id;
+ if !macro_user_id.is_macro_staff() {
+ return Err(GtmMacroStaffRejection::NotStaff);
+ }
+
+ Ok(Self {
+ macro_user_id,
+ _auth: PhantomData,
+ })
+ }
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/list_links.rs b/crates/gtm_invite/src/inbound/axum_router/list_links.rs
new file mode 100644
index 0000000000..3a8ca7cc19
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/list_links.rs
@@ -0,0 +1,47 @@
+//! Handler for `GET /gtm-invite/links`.
+
+use axum::{
+ Json,
+ extract::{Query, State},
+};
+use chrono::Utc;
+use macro_authorization::MacroAuthorizationService;
+
+use super::GtmInviteRouterState;
+use super::dto::{GtmInviteLink, GtmInviteLinkList, ListGtmInviteLinksQuery};
+use super::gtm_macro_staff::GtmMacroStaffExtractor;
+use crate::domain::models::GtmInviteError;
+use crate::domain::ports::GtmInviteService;
+
+/// Lists invite links, newest first. Macro staff only.
+#[utoipa::path(
+ tag = "gtm_invite",
+ get,
+ path = "/gtm-invite/links",
+ operation_id = "list_gtm_invite_links",
+ params(ListGtmInviteLinksQuery),
+ responses(
+ (status = 200, body = GtmInviteLinkList),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 403, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, fields(mine = query.mine), err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ staff: GtmMacroStaffExtractor<Auth>,
+ Query(query): Query<ListGtmInviteLinksQuery>,
+) -> Result<Json<GtmInviteLinkList>, GtmInviteError> {
+ let caller = &staff.macro_user_id;
+ let links = state.service.list_links(caller, query.mine).await?;
+ let free_months = state.service.config().free_months;
+ let now = Utc::now();
+
+ Ok(Json(GtmInviteLinkList {
+ links: links
+ .into_iter()
+ .map(|link| GtmInviteLink::from_link(link, free_months, now))
+ .collect(),
+ }))
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/redeem_link.rs b/crates/gtm_invite/src/inbound/axum_router/redeem_link.rs
new file mode 100644
index 0000000000..8b98c30061
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/redeem_link.rs
@@ -0,0 +1,43 @@
+//! Handler for `POST /gtm-invite/redeem`.
+
+use axum::{Json, extract::State};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
+
+use super::GtmInviteRouterState;
+use super::dto::{GtmInviteOffer, RedeemGtmInviteLinkRequest};
+use crate::domain::models::{GtmInviteError, InviteToken};
+use crate::domain::ports::GtmInviteService;
+
+/// Attributes the signed-in user's account to the invite link they opened and
+/// grants them its offer. Idempotent for the same account.
+#[utoipa::path(
+ tag = "gtm_invite",
+ post,
+ path = "/gtm-invite/redeem",
+ operation_id = "redeem_gtm_invite_link",
+ request_body = RedeemGtmInviteLinkRequest,
+ responses(
+ (status = 200, body = GtmInviteOffer),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 404, body = model_error_response::ErrorResponse),
+ (status = 409, body = model_error_response::ErrorResponse),
+ (status = 410, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Json(request): Json<RedeemGtmInviteLinkRequest>,
+) -> Result<Json<GtmInviteOffer>, GtmInviteError> {
+ let token: InviteToken = request.token.parse()?;
+ let user = &authorization.authorization.user.macro_user_id;
+ let link = state.service.redeem_link(&token, user).await?;
+ let free_months = state.service.config().free_months;
+
+ GtmInviteOffer::from_link(link, free_months)
+ .map(Json)
+ .ok_or_else(|| GtmInviteError::Internal(anyhow::anyhow!("redeemed link has no redemption")))
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/resolve_link.rs b/crates/gtm_invite/src/inbound/axum_router/resolve_link.rs
new file mode 100644
index 0000000000..328dc0a875
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/resolve_link.rs
@@ -0,0 +1,87 @@
+//! Handler for `GET /gtm-invite/public/{token}`.
+
+use std::time::Duration;
+
+use axum::{
+ Json, RequestPartsExt,
+ extract::{FromRequestParts, Path, State},
+};
+use chrono::Utc;
+use ip_extractor::ClientIp;
+use macro_authorization::MacroAuthorizationService;
+use rate_limit::{RateLimitConfig, RateLimitKey, inbound::RateLimitExtractable};
+
+use super::GtmInviteRouterState;
+use super::dto::PublicGtmInviteLink;
+use crate::domain::models::{GtmInviteError, InviteToken};
+use crate::domain::ports::GtmInviteService;
+
+/// Resolves an invite link for the public welcome page and counts the open.
+///
+/// Unauthenticated: the recipient has no account yet. Only the first name and
+/// whether the link is still usable are exposed.
+#[utoipa::path(
+ tag = "gtm_invite",
+ get,
+ path = "/gtm-invite/public/{token}",
+ operation_id = "resolve_gtm_invite_link",
+ params(("token" = String, Path, description = "The token from the invite link URL")),
+ responses(
+ (status = 200, body = PublicGtmInviteLink),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 404, body = model_error_response::ErrorResponse),
+ (status = 429),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ Path(token): Path<String>,
+) -> Result<Json<PublicGtmInviteLink>, GtmInviteError> {
+ let token: InviteToken = token.parse()?;
+ let link = state.service.resolve_link(&token).await?;
+
+ Ok(Json(PublicGtmInviteLink {
+ first_name: link.first_name.clone(),
+ status: link.status(Utc::now()).into(),
+ free_months: state.service.config().free_months,
+ }))
+}
+
+/// Per-IP rate limit on resolving links: generous for a person reloading a
+/// welcome page, tight enough that scanning tokens is pointless.
+pub struct PerIpResolveRateLimit(ClientIp);
+
+impl<S> RateLimitExtractable<S> for PerIpResolveRateLimit
+where
+ S: Send + Sync,
+{
+ fn config() -> RateLimitConfig {
+ RateLimitConfig {
+ max_count: 120,
+ window: Duration::from_mins(60),
+ }
+ }
+
+ fn key(&self) -> RateLimitKey {
+ RateLimitKey::builder(&"per-ip-gtm-invite-resolve")
+ .append(&self.0.origin_ip())
+ .finish()
+ }
+}
+
+impl<S> FromRequestParts<S> for PerIpResolveRateLimit
+where
+ S: Send + Sync,
+{
+ type Rejection = <ClientIp as FromRequestParts<S>>::Rejection;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ let ip: ClientIp = parts.extract_with_state(state).await?;
+ Ok(Self(ip))
+ }
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/revoke_link.rs b/crates/gtm_invite/src/inbound/axum_router/revoke_link.rs
new file mode 100644
index 0000000000..2d60b82909
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/revoke_link.rs
@@ -0,0 +1,48 @@
+//! Handler for `DELETE /gtm-invite/links/{id}`.
+
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use chrono::Utc;
+use macro_authorization::MacroAuthorizationService;
+use uuid::Uuid;
+
+use super::GtmInviteRouterState;
+use super::dto::GtmInviteLink;
+use super::gtm_macro_staff::GtmMacroStaffExtractor;
+use crate::domain::models::GtmInviteError;
+use crate::domain::ports::GtmInviteService;
+
+/// Revokes an invite link nobody has signed up through. Macro staff only.
+#[utoipa::path(
+ tag = "gtm_invite",
+ delete,
+ path = "/gtm-invite/links/{id}",
+ operation_id = "revoke_gtm_invite_link",
+ params(("id" = Uuid, Path, description = "The invite link id")),
+ responses(
+ (status = 200, body = GtmInviteLink),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 403, body = model_error_response::ErrorResponse),
+ (status = 404, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, fields(link_id = %id), err)]
+pub async fn handler<T: GtmInviteService, R, Auth: MacroAuthorizationService>(
+ State(state): State<GtmInviteRouterState<T, R, Auth>>,
+ staff: GtmMacroStaffExtractor<Auth>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<GtmInviteLink>, GtmInviteError> {
+ let caller = &staff.macro_user_id;
+ let link = state.service.revoke_link(caller, id).await?;
+ let free_months = state.service.config().free_months;
+
+ Ok(Json(GtmInviteLink::from_link(
+ link,
+ free_months,
+ Utc::now(),
+ )))
+}
diff --git a/crates/gtm_invite/src/inbound/axum_router/test.rs b/crates/gtm_invite/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..64ff068e10
--- /dev/null
+++ b/crates/gtm_invite/src/inbound/axum_router/test.rs
@@ -0,0 +1,532 @@
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use axum::{
+ Extension,
+ body::Body,
+ extract::ConnectInfo,
+ http::{Request, StatusCode, header},
+};
+use chrono::{Duration, Utc};
+use http_body_util::BodyExt;
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
+use rate_limit::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+ domain::models::RateLimitOk,
+};
+use rootcause::Report;
+use tower::ServiceExt;
+use uuid::Uuid;
+
+use crate::domain::models::{
+ CreateInviteLink, GtmInviteConfig, GtmInviteError, InviteLink, InviteRedemption, InviteToken,
+};
+use crate::domain::ports::GtmInviteService;
+use crate::inbound::axum_router::dto::{
+ GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus,
+ PublicGtmInviteLink,
+};
+use crate::inbound::axum_router::{GtmInviteRouterState, gtm_invite_router};
+
+const STAFF_JWT: &str = "staff";
+const OUTSIDER_JWT: &str = "outsider";
+const STAFF_USER_ID: &str = "macro|[email protected]";
+const OUTSIDER_USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone)]
+struct FakeAuthorizationService;
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ match jwt {
+ STAFF_JWT => Ok(test_user_context(STAFF_USER_ID)),
+ OUTSIDER_JWT => Ok(test_user_context(OUTSIDER_USER_ID)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+fn test_user_context(user_id: &str) -> UserContext {
+ UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),
+ permissions: None,
+ organization_id: None,
+ }
+}
+
+fn config() -> GtmInviteConfig {
+ GtmInviteConfig {
+ promo_code: "1MF".parse().unwrap(),
+ link_ttl: Duration::hours(48),
+ free_months: 1,
+ }
+}
+
+fn sample_link() -> InviteLink {
+ let now = Utc::now();
+ InviteLink {
+ id: Uuid::now_v7(),
+ token: InviteToken::generate(),
+ first_name: "Ada".into(),
+ recipient_email: Some("[email protected]".into()),
+ note: None,
+ promo_code: "1MF".parse().unwrap(),
+ created_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ created_at: now,
+ expires_at: now + Duration::hours(48),
+ revoked_at: None,
+ open_count: 3,
+ first_opened_at: Some(now),
+ redemption: None,
+ }
+}
+
+fn redeemed_link() -> InviteLink {
+ InviteLink {
+ redemption: Some(InviteRedemption {
+ user_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ redeemed_at: Utc::now(),
+ conversion: None,
+ }),
+ ..sample_link()
+ }
+}
+
+struct FakeGtmInviteService {
+ config: GtmInviteConfig,
+ resolve: Result<InviteLink, GtmInviteError>,
+ offer: Option<InviteLink>,
+}
+
+impl FakeGtmInviteService {
+ fn new() -> Self {
+ Self {
+ config: config(),
+ resolve: Ok(sample_link()),
+ offer: None,
+ }
+ }
+
+ fn clone_result(
+ result: &Result<InviteLink, GtmInviteError>,
+ ) -> Result<InviteLink, GtmInviteError> {
+ match result {
+ Ok(link) => Ok(link.clone()),
+ Err(GtmInviteError::NotFound) => Err(GtmInviteError::NotFound),
+ Err(GtmInviteError::Expired) => Err(GtmInviteError::Expired),
+ Err(GtmInviteError::AlreadyRedeemed) => Err(GtmInviteError::AlreadyRedeemed),
+ Err(_) => Err(GtmInviteError::Internal(anyhow::anyhow!("fake failure"))),
+ }
+ }
+}
+
+impl GtmInviteService for FakeGtmInviteService {
+ fn config(&self) -> &GtmInviteConfig {
+ &self.config
+ }
+
+ async fn create_link(
+ &self,
+ _creator: &MacroUserIdStr<'_>,
+ request: CreateInviteLink,
+ ) -> Result<InviteLink, GtmInviteError> {
+ Ok(InviteLink {
+ first_name: request.first_name,
+ ..sample_link()
+ })
+ }
+
+ async fn list_links(
+ &self,
+ _caller: &MacroUserIdStr<'_>,
+ _only_mine: bool,
+ ) -> Result<Vec<InviteLink>, GtmInviteError> {
+ Ok(vec![sample_link(), redeemed_link()])
+ }
+
+ async fn revoke_link(
+ &self,
+ _caller: &MacroUserIdStr<'_>,
+ _id: Uuid,
+ ) -> Result<InviteLink, GtmInviteError> {
+ Ok(InviteLink {
+ revoked_at: Some(Utc::now()),
+ ..sample_link()
+ })
+ }
+
+ async fn resolve_link(&self, _token: &InviteToken) -> Result<InviteLink, GtmInviteError> {
+ Self::clone_result(&self.resolve)
+ }
+
+ async fn redeem_link(
+ &self,
+ _token: &InviteToken,
+ _user: &MacroUserIdStr<'_>,
+ ) -> Result<InviteLink, GtmInviteError> {
+ Self::clone_result(&self.resolve).map(|_| redeemed_link())
+ }
+
+ async fn active_offer_for_user(
+ &self,
+ _user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<InviteLink>, GtmInviteError> {
+ Ok(self.offer.clone())
+ }
+
+ async fn mark_converted(
+ &self,
+ _user: &MacroUserIdStr<'_>,
+ _stripe_subscription_id: &str,
+ ) -> Result<bool, GtmInviteError> {
+ Ok(true)
+ }
+}
+
+#[derive(Clone)]
+struct MockRateLimitPort {
+ should_exceed: bool,
+}
+
+impl rate_limit::RateLimitPort for MockRateLimitPort {
+ async fn check(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ if self.should_exceed {
+ Ok(Err(RateLimitExceeded {
+ current_count: config.max_count.saturating_add(1),
+ max_count: config.max_count,
+ retry_after: config.window,
+ }))
+ } else {
+ Ok(Ok(RateLimitOk::new_testing_value(0, key, config)))
+ }
+ }
+
+ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+fn rate_limiter(should_exceed: bool) -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort { should_exceed },
+ }
+}
+
+fn build_router(service: FakeGtmInviteService, rate_limit_exceeded: bool) -> axum::Router {
+ let state = GtmInviteRouterState {
+ service: Arc::new(service),
+ rate_limiter: rate_limiter(rate_limit_exceeded),
+ authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),
+ };
+ gtm_invite_router(state).layer(Extension(ConnectInfo(SocketAddr::from((
+ [127, 0, 0, 1],
+ 0,
+ )))))
+}
+
+fn authed(request: axum::http::request::Builder, jwt: &str) -> axum::http::request::Builder {
+ request.header(header::AUTHORIZATION, format!("Bearer {jwt}"))
+}
+
+fn json_body(value: serde_json::Value) -> Body {
+ Body::from(value.to_string())
+}
+
+async fn read_json<T: serde::de::DeserializeOwned>(response: axum::response::Response) -> T {
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ serde_json::from_slice(&body).unwrap()
+}
+
+#[tokio::test]
+async fn staff_can_create_links() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(Request::post("/links"), STAFF_JWT)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(serde_json::json!({ "firstName": "Grace" })))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let link: GtmInviteLink = read_json(response).await;
+ assert_eq!(link.first_name, "Grace");
+ assert_eq!(link.status, GtmInviteLinkStatus::Active);
+ assert_eq!(link.promo_code, "1MF");
+ assert_eq!(link.free_months, 1);
+ assert_eq!(link.created_by, STAFF_USER_ID);
+}
+
+#[tokio::test]
+async fn outsiders_cannot_create_links() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(Request::post("/links"), OUTSIDER_JWT)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(serde_json::json!({ "firstName": "Grace" })))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+}
+
+#[tokio::test]
+async fn anonymous_callers_cannot_create_links() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = Request::post("/links")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(serde_json::json!({ "firstName": "Grace" })))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn staff_can_list_links_with_redemption_details() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(Request::get("/links?mine=true"), STAFF_JWT)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let list: GtmInviteLinkList = read_json(response).await;
+ assert_eq!(list.links.len(), 2);
+ assert_eq!(list.links[1].status, GtmInviteLinkStatus::Redeemed);
+ assert_eq!(list.links[1].redeemed_by.as_deref(), Some(OUTSIDER_USER_ID));
+}
+
+#[tokio::test]
+async fn outsiders_cannot_list_or_revoke_links() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let list = authed(Request::get("/links"), OUTSIDER_JWT)
+ .body(Body::empty())
+ .unwrap();
+ assert_eq!(
+ app.clone().oneshot(list).await.unwrap().status(),
+ StatusCode::FORBIDDEN
+ );
+
+ let revoke = authed(
+ Request::delete(format!("/links/{}", Uuid::now_v7())),
+ OUTSIDER_JWT,
+ )
+ .body(Body::empty())
+ .unwrap();
+ assert_eq!(
+ app.oneshot(revoke).await.unwrap().status(),
+ StatusCode::FORBIDDEN
+ );
+}
+
+#[tokio::test]
+async fn staff_can_revoke_links() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(
+ Request::delete(format!("/links/{}", Uuid::now_v7())),
+ STAFF_JWT,
+ )
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let link: GtmInviteLink = read_json(response).await;
+ assert_eq!(link.status, GtmInviteLinkStatus::Revoked);
+}
+
+#[tokio::test]
+async fn anyone_can_resolve_a_link_and_only_sees_public_fields() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = Request::get(format!("/public/{}", InviteToken::generate()))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ let raw: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(raw.get("createdBy").is_none());
+ assert!(raw.get("token").is_none());
+ let public: PublicGtmInviteLink = serde_json::from_value(raw).unwrap();
+ assert_eq!(public.first_name, "Ada");
+ assert_eq!(public.status, GtmInviteLinkStatus::Active);
+ assert_eq!(public.free_months, 1);
+}
+
+#[tokio::test]
+async fn resolving_a_malformed_token_is_a_bad_request() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = Request::get("/public/short").body(Body::empty()).unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+}
+
+#[tokio::test]
+async fn resolving_an_unknown_token_is_not_found() {
+ let service = FakeGtmInviteService {
+ resolve: Err(GtmInviteError::NotFound),
+ ..FakeGtmInviteService::new()
+ };
+ let app = build_router(service, false);
+ let request = Request::get(format!("/public/{}", InviteToken::generate()))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn resolving_is_rate_limited_per_ip() {
+ let app = build_router(FakeGtmInviteService::new(), true);
+ let request = Request::get(format!("/public/{}", InviteToken::generate()))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
+}
+
+#[tokio::test]
+async fn the_rate_limit_does_not_cover_authenticated_routes() {
+ let app = build_router(FakeGtmInviteService::new(), true);
+ let request = authed(Request::get("/offer"), OUTSIDER_JWT)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+}
+
+#[tokio::test]
+async fn signed_in_users_redeem_links_and_receive_the_offer() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(Request::post("/redeem"), OUTSIDER_JWT)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(
+ serde_json::json!({ "token": InviteToken::generate().as_str() }),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let offer: GtmInviteOffer = read_json(response).await;
+ assert_eq!(offer.promo_code, "1MF");
+ assert_eq!(offer.first_name, "Ada");
+}
+
+#[tokio::test]
+async fn redeeming_requires_authentication() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = Request::post("/redeem")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(
+ serde_json::json!({ "token": InviteToken::generate().as_str() }),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn redeeming_an_expired_link_is_gone() {
+ let service = FakeGtmInviteService {
+ resolve: Err(GtmInviteError::Expired),
+ ..FakeGtmInviteService::new()
+ };
+ let app = build_router(service, false);
+ let request = authed(Request::post("/redeem"), OUTSIDER_JWT)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(
+ serde_json::json!({ "token": InviteToken::generate().as_str() }),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::GONE);
+}
+
+#[tokio::test]
+async fn redeeming_a_link_someone_else_used_is_a_conflict() {
+ let service = FakeGtmInviteService {
+ resolve: Err(GtmInviteError::AlreadyRedeemed),
+ ..FakeGtmInviteService::new()
+ };
+ let app = build_router(service, false);
+ let request = authed(Request::post("/redeem"), OUTSIDER_JWT)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(json_body(
+ serde_json::json!({ "token": InviteToken::generate().as_str() }),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CONFLICT);
+}
+
+#[tokio::test]
+async fn offer_is_null_without_a_redeemed_link() {
+ let app = build_router(FakeGtmInviteService::new(), false);
+ let request = authed(Request::get("/offer"), OUTSIDER_JWT)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let status: GtmInviteOfferStatus = read_json(response).await;
+ assert!(status.offer.is_none());
+}
+
+#[tokio::test]
+async fn offer_is_returned_for_a_redeemed_link() {
+ let service = FakeGtmInviteService {
+ offer: Some(redeemed_link()),
+ ..FakeGtmInviteService::new()
+ };
+ let app = build_router(service, false);
+ let request = authed(Request::get("/offer"), OUTSIDER_JWT)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let status: GtmInviteOfferStatus = read_json(response).await;
+ let offer = status.offer.expect("offer present");
+ assert_eq!(offer.promo_code, "1MF");
+ assert_eq!(offer.free_months, 1);
+}
diff --git a/crates/gtm_invite/src/lib.rs b/crates/gtm_invite/src/lib.rs
new file mode 100644
index 0000000000..e5366df926
--- /dev/null
+++ b/crates/gtm_invite/src/lib.rs
@@ -0,0 +1,22 @@
+//! GTM invite links.
+//!
+//! Macro staff create personal, time-limited signup links for prospects. Opening
+//! a link shows a personal welcome, signing up through it attributes the new
+//! account to the staff member who created the link, and the redeemed link
+//! carries a promotional first month of Premium that checkout applies.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/crates/gtm_invite/src/outbound.rs b/crates/gtm_invite/src/outbound.rs
new file mode 100644
index 0000000000..0f80818698
--- /dev/null
+++ b/crates/gtm_invite/src/outbound.rs
@@ -0,0 +1,3 @@
+//! Outbound adapters for the GTM invite crate.
+
+pub mod pg_gtm_invite_repo;
diff --git a/crates/gtm_invite/src/outbound/pg_gtm_invite_repo.rs b/crates/gtm_invite/src/outbound/pg_gtm_invite_repo.rs
new file mode 100644
index 0000000000..909a5e54f1
--- /dev/null
+++ b/crates/gtm_invite/src/outbound/pg_gtm_invite_repo.rs
@@ -0,0 +1,319 @@
+//! PostgreSQL implementation of the [`GtmInviteRepo`] port.
+
+#[cfg(test)]
+mod test;
+
+use chrono::{DateTime, Utc};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{InviteConversion, InviteLink, InviteRedemption, InviteToken, ListInviteLinks},
+ ports::GtmInviteRepo,
+};
+
+/// PostgreSQL-backed invite link repository.
+#[derive(Clone)]
+pub struct PgGtmInviteRepo {
+ /// The postgres pool
+ pool: PgPool,
+}
+
+impl PgGtmInviteRepo {
+ /// Create a new repository backed by the given connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// One `gtm_invite_link` row, as stored.
+struct InviteLinkRow {
+ id: Uuid,
+ token: String,
+ first_name: String,
+ recipient_email: Option<String>,
+ note: Option<String>,
+ promo_code: String,
+ created_by_user_id: String,
+ created_at: DateTime<Utc>,
+ expires_at: DateTime<Utc>,
+ revoked_at: Option<DateTime<Utc>>,
+ open_count: i32,
+ first_opened_at: Option<DateTime<Utc>>,
+ redeemed_by_user_id: Option<String>,
+ redeemed_at: Option<DateTime<Utc>>,
+ converted_at: Option<DateTime<Utc>>,
+ stripe_subscription_id: Option<String>,
+}
+
+fn decode_error(message: impl std::fmt::Display) -> sqlx::Error {
+ sqlx::Error::Decode(message.to_string().into())
+}
+
+fn parse_user_id(raw: &str) -> Result<MacroUserIdStr<'static>, sqlx::Error> {
+ MacroUserIdStr::parse_from_str(raw)
+ .map(CowLike::into_owned)
+ .map_err(|e| decode_error(format!("stored macro user id is invalid: {e:?}")))
+}
+
+impl TryFrom<InviteLinkRow> for InviteLink {
+ type Error = sqlx::Error;
+
+ fn try_from(row: InviteLinkRow) -> Result<Self, Self::Error> {
+ let redemption = match (row.redeemed_by_user_id, row.redeemed_at) {
+ (Some(user_id), Some(redeemed_at)) => Some(InviteRedemption {
+ user_id: parse_user_id(&user_id)?,
+ redeemed_at,
+ conversion: row.converted_at.map(|converted_at| InviteConversion {
+ converted_at,
+ stripe_subscription_id: row.stripe_subscription_id,
+ }),
+ }),
+ (None, None) => None,
+ _ => return Err(decode_error("redemption columns are inconsistent")),
+ };
+
+ Ok(InviteLink {
+ id: row.id,
+ token: row
+ .token
+ .parse::<InviteToken>()
+ .map_err(|e| decode_error(format!("stored invite token is invalid: {e}")))?,
+ first_name: row.first_name,
+ recipient_email: row.recipient_email,
+ note: row.note,
+ promo_code: row
+ .promo_code
+ .parse()
+ .map_err(|e| decode_error(format!("stored promo code is invalid: {e}")))?,
+ created_by: parse_user_id(&row.created_by_user_id)?,
+ created_at: row.created_at,
+ expires_at: row.expires_at,
+ revoked_at: row.revoked_at,
+ open_count: row.open_count,
+ first_opened_at: row.first_opened_at,
+ redemption,
+ })
+ }
+}
+
+impl GtmInviteRepo for PgGtmInviteRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(skip(self, link), fields(link_id = %link.id), err)]
+ async fn insert_link(&self, link: &InviteLink) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO gtm_invite_link
+ (id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
+ "#,
+ link.id,
+ link.token.as_str(),
+ link.first_name,
+ link.recipient_email.as_deref(),
+ link.note.as_deref(),
+ link.promo_code.as_str(),
+ link.created_by.as_ref(),
+ link.created_at,
+ link.expires_at,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self, token), err)]
+ async fn get_link_by_token(
+ &self,
+ token: &InviteToken,
+ ) -> Result<Option<InviteLink>, Self::Err> {
+ sqlx::query_as!(
+ InviteLinkRow,
+ r#"
+ SELECT id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at, revoked_at, open_count,
+ first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,
+ stripe_subscription_id
+ FROM gtm_invite_link
+ WHERE token = $1
+ "#,
+ token.as_str(),
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .map(InviteLink::try_from)
+ .transpose()
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_link_by_id(&self, id: Uuid) -> Result<Option<InviteLink>, Self::Err> {
+ sqlx::query_as!(
+ InviteLinkRow,
+ r#"
+ SELECT id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at, revoked_at, open_count,
+ first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,
+ stripe_subscription_id
+ FROM gtm_invite_link
+ WHERE id = $1
+ "#,
+ id,
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .map(InviteLink::try_from)
+ .transpose()
+ }
+
+ #[tracing::instrument(skip(self, filter), fields(limit = filter.limit), err)]
+ async fn list_links(&self, filter: &ListInviteLinks) -> Result<Vec<InviteLink>, Self::Err> {
+ let created_by = filter
+ .created_by
+ .as_ref()
+ .map(|creator| -> &str { creator.as_ref() });
+ sqlx::query_as!(
+ InviteLinkRow,
+ r#"
+ SELECT id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at, revoked_at, open_count,
+ first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,
+ stripe_subscription_id
+ FROM gtm_invite_link
+ WHERE ($1::TEXT IS NULL OR created_by_user_id = $1)
+ ORDER BY created_at DESC, id DESC
+ LIMIT $2
+ "#,
+ created_by,
+ filter.limit,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(InviteLink::try_from)
+ .collect()
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn record_open(&self, id: Uuid, now: DateTime<Utc>) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ UPDATE gtm_invite_link
+ SET open_count = open_count + 1,
+ first_opened_at = COALESCE(first_opened_at, $2)
+ WHERE id = $1
+ "#,
+ id,
+ now,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn revoke_link(&self, id: Uuid, now: DateTime<Utc>) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE gtm_invite_link
+ SET revoked_at = $2
+ WHERE id = $1
+ AND revoked_at IS NULL
+ AND redeemed_by_user_id IS NULL
+ "#,
+ id,
+ now,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+ }
+
+ #[tracing::instrument(skip(self, user_id), fields(user_id = %user_id.as_ref()), err)]
+ async fn redeem_link<'a>(
+ &self,
+ id: Uuid,
+ user_id: &MacroUserIdStr<'a>,
+ now: DateTime<Utc>,
+ ) -> Result<Option<InviteLink>, Self::Err> {
+ // Single statement so two accounts racing for one link, or a signup
+ // racing a revoke, resolve in the database: only an open link (or the
+ // same user's own redemption) matches.
+ sqlx::query_as!(
+ InviteLinkRow,
+ r#"
+ UPDATE gtm_invite_link
+ SET redeemed_by_user_id = $2,
+ redeemed_at = COALESCE(redeemed_at, $3)
+ WHERE id = $1
+ AND revoked_at IS NULL
+ AND ((redeemed_by_user_id IS NULL AND expires_at > $3)
+ OR redeemed_by_user_id = $2)
+ RETURNING id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at, revoked_at, open_count,
+ first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,
+ stripe_subscription_id
+ "#,
+ id,
+ user_id.as_ref(),
+ now,
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .map(InviteLink::try_from)
+ .transpose()
+ }
+
+ #[tracing::instrument(skip(self, user_id), fields(user_id = %user_id.as_ref()), err)]
+ async fn get_redeemed_link_for_user<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ ) -> Result<Option<InviteLink>, Self::Err> {
+ sqlx::query_as!(
+ InviteLinkRow,
+ r#"
+ SELECT id, token, first_name, recipient_email, note, promo_code,
+ created_by_user_id, created_at, expires_at, revoked_at, open_count,
+ first_opened_at, redeemed_by_user_id, redeemed_at, converted_at,
+ stripe_subscription_id
+ FROM gtm_invite_link
+ WHERE redeemed_by_user_id = $1
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .map(InviteLink::try_from)
+ .transpose()
+ }
+
+ #[tracing::instrument(skip(self, user_id), fields(user_id = %user_id.as_ref()), err)]
+ async fn mark_converted<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ stripe_subscription_id: &str,
+ now: DateTime<Utc>,
+ ) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE gtm_invite_link
+ SET converted_at = $3,
+ stripe_subscription_id = $2
+ WHERE redeemed_by_user_id = $1
+ AND converted_at IS NULL
+ "#,
+ user_id.as_ref(),
+ stripe_subscription_id,
+ now,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+ }
+}
diff --git a/crates/gtm_invite/src/outbound/pg_gtm_invite_repo/test.rs b/crates/gtm_invite/src/outbound/pg_gtm_invite_repo/test.rs
new file mode 100644
index 0000000000..c899c91585
--- /dev/null
+++ b/crates/gtm_invite/src/outbound/pg_gtm_invite_repo/test.rs
@@ -0,0 +1,314 @@
+use chrono::{Duration, SubsecRound, Utc};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use crate::domain::models::{InviteLink, InviteLinkStatus, InviteToken, ListInviteLinks};
+use crate::domain::ports::GtmInviteRepo;
+use crate::outbound::pg_gtm_invite_repo::PgGtmInviteRepo;
+
+fn staff(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+fn prospect() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn other_prospect() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn link(created_by: &str, first_name: &str) -> InviteLink {
+ // Postgres keeps microseconds; chrono has nanoseconds.
+ let now = Utc::now().trunc_subsecs(6);
+ InviteLink {
+ id: Uuid::now_v7(),
+ token: InviteToken::generate(),
+ first_name: first_name.into(),
+ recipient_email: Some(format!("{}@startup.io", first_name.to_lowercase())),
+ note: Some("from the demo".into()),
+ promo_code: "1MF".parse().unwrap(),
+ created_by: staff(created_by),
+ created_at: now,
+ expires_at: now + Duration::hours(48),
+ revoked_at: None,
+ open_count: 0,
+ first_opened_at: None,
+ redemption: None,
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn insert_and_read_back_by_token_and_id(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let created = link("[email protected]", "Ada");
+
+ repo.insert_link(&created).await.unwrap();
+
+ let by_token = repo
+ .get_link_by_token(&created.token)
+ .await
+ .unwrap()
+ .expect("link by token");
+ let by_id = repo
+ .get_link_by_id(created.id)
+ .await
+ .unwrap()
+ .expect("link by id");
+
+ assert_eq!(by_token, created);
+ assert_eq!(by_id, created);
+ assert_eq!(by_token.status(Utc::now()), InviteLinkStatus::Active);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unknown_tokens_and_ids_are_none(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+
+ assert!(
+ repo.get_link_by_token(&InviteToken::generate())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(repo.get_link_by_id(Uuid::now_v7()).await.unwrap().is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn tokens_are_unique(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let first = link("[email protected]", "Ada");
+ let duplicate = InviteLink {
+ id: Uuid::now_v7(),
+ ..first.clone()
+ };
+
+ repo.insert_link(&first).await.unwrap();
+
+ assert!(repo.insert_link(&duplicate).await.is_err());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_is_newest_first_and_filters_by_creator(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let older = InviteLink {
+ created_at: Utc::now() - Duration::hours(2),
+ ..link("[email protected]", "Ada")
+ };
+ let newer = link("[email protected]", "Grace");
+ let someone_elses = link("[email protected]", "Linus");
+ for link in [&older, &newer, &someone_elses] {
+ repo.insert_link(link).await.unwrap();
+ }
+
+ let everyone = repo
+ .list_links(&ListInviteLinks {
+ created_by: None,
+ limit: 100,
+ })
+ .await
+ .unwrap();
+ let first_names: Vec<_> = everyone.iter().map(|l| l.first_name.as_str()).collect();
+ assert_eq!(first_names.len(), 3);
+ assert_eq!(first_names.last(), Some(&"Ada"));
+
+ let valentinas = repo
+ .list_links(&ListInviteLinks {
+ created_by: Some(staff("[email protected]")),
+ limit: 100,
+ })
+ .await
+ .unwrap();
+ let ids: Vec<_> = valentinas.iter().map(|l| l.id).collect();
+ assert_eq!(ids, vec![newer.id, older.id]);
+
+ let limited = repo
+ .list_links(&ListInviteLinks {
+ created_by: None,
+ limit: 1,
+ })
+ .await
+ .unwrap();
+ assert_eq!(limited.len(), 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn record_open_counts_and_keeps_the_first_open_time(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let created = link("[email protected]", "Ada");
+ repo.insert_link(&created).await.unwrap();
+ let first_open = Utc::now() - Duration::minutes(10);
+ let second_open = Utc::now();
+
+ repo.record_open(created.id, first_open).await.unwrap();
+ repo.record_open(created.id, second_open).await.unwrap();
+
+ let opened = repo.get_link_by_id(created.id).await.unwrap().unwrap();
+ assert_eq!(opened.open_count, 2);
+ assert_eq!(
+ opened.first_opened_at.map(|t| t.timestamp_millis()),
+ Some(first_open.timestamp_millis())
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn revoke_only_touches_open_links(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let created = link("[email protected]", "Ada");
+ repo.insert_link(&created).await.unwrap();
+
+ assert!(repo.revoke_link(created.id, Utc::now()).await.unwrap());
+ // Already revoked: nothing to do.
+ assert!(!repo.revoke_link(created.id, Utc::now()).await.unwrap());
+ let revoked = repo.get_link_by_id(created.id).await.unwrap().unwrap();
+ assert_eq!(revoked.status(Utc::now()), InviteLinkStatus::Revoked);
+
+ let redeemed = link("[email protected]", "Grace");
+ repo.insert_link(&redeemed).await.unwrap();
+ repo.redeem_link(redeemed.id, &prospect(), Utc::now())
+ .await
+ .unwrap()
+ .expect("redeemed");
+ assert!(!repo.revoke_link(redeemed.id, Utc::now()).await.unwrap());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn redeem_is_first_come_and_idempotent_for_the_winner(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let created = link("[email protected]", "Ada");
+ repo.insert_link(&created).await.unwrap();
+ let now = Utc::now();
+
+ let redeemed = repo
+ .redeem_link(created.id, &prospect(), now)
+ .await
+ .unwrap()
+ .expect("first redemption wins");
+ assert!(redeemed.is_redeemed_by(&prospect()));
+ assert_eq!(redeemed.status(now), InviteLinkStatus::Redeemed);
+
+ // Same user again keeps the original redemption time.
+ let again = repo
+ .redeem_link(created.id, &prospect(), now + Duration::hours(1))
+ .await
+ .unwrap()
+ .expect("idempotent for the same user");
+ assert_eq!(
+ again
+ .redemption
+ .as_ref()
+ .map(|r| r.redeemed_at.timestamp_millis()),
+ Some(now.timestamp_millis())
+ );
+
+ // Someone else is refused.
+ assert!(
+ repo.redeem_link(created.id, &other_prospect(), now)
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ let stored = repo
+ .get_redeemed_link_for_user(&prospect())
+ .await
+ .unwrap()
+ .expect("lookup by redeemer");
+ assert_eq!(stored.id, created.id);
+ assert!(
+ repo.get_redeemed_link_for_user(&other_prospect())
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn redeem_refuses_expired_and_revoked_links(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let expired = InviteLink {
+ expires_at: Utc::now() - Duration::minutes(1),
+ ..link("[email protected]", "Ada")
+ };
+ repo.insert_link(&expired).await.unwrap();
+ assert!(
+ repo.redeem_link(expired.id, &prospect(), Utc::now())
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ let revoked = link("[email protected]", "Grace");
+ repo.insert_link(&revoked).await.unwrap();
+ repo.revoke_link(revoked.id, Utc::now()).await.unwrap();
+ assert!(
+ repo.redeem_link(revoked.id, &prospect(), Utc::now())
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_user_can_only_hold_one_redeemed_link(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let first = link("[email protected]", "Ada");
+ let second = link("[email protected]", "Ada");
+ repo.insert_link(&first).await.unwrap();
+ repo.insert_link(&second).await.unwrap();
+
+ repo.redeem_link(first.id, &prospect(), Utc::now())
+ .await
+ .unwrap()
+ .expect("first link redeemed");
+
+ // The partial unique index on redeemed_by_user_id rejects a second link.
+ assert!(
+ repo.redeem_link(second.id, &prospect(), Utc::now())
+ .await
+ .is_err()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn mark_converted_records_the_subscription_once(pool: Pool<Postgres>) {
+ let repo = PgGtmInviteRepo::new(pool);
+ let created = link("[email protected]", "Ada");
+ repo.insert_link(&created).await.unwrap();
+
+ // Nobody redeemed it yet: nothing to convert.
+ assert!(
+ !repo
+ .mark_converted(&prospect(), "sub_1", Utc::now())
+ .await
+ .unwrap()
+ );
+
+ repo.redeem_link(created.id, &prospect(), Utc::now())
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert!(
+ repo.mark_converted(&prospect(), "sub_1", Utc::now())
+ .await
+ .unwrap()
+ );
+ // A second subscription event does not overwrite the first.
+ assert!(
+ !repo
+ .mark_converted(&prospect(), "sub_2", Utc::now())
+ .await
+ .unwrap()
+ );
+
+ let converted = repo.get_link_by_id(created.id).await.unwrap().unwrap();
+ assert_eq!(converted.status(Utc::now()), InviteLinkStatus::Converted);
+ let conversion = converted
+ .redemption
+ .and_then(|redemption| redemption.conversion)
+ .expect("conversion recorded");
+ assert_eq!(conversion.stripe_subscription_id.as_deref(), Some("sub_1"));
+}
diff --git a/crates/macro_db_client/migrations/20260917130509_gtm_invite_link.sql b/crates/macro_db_client/migrations/20260917130509_gtm_invite_link.sql
new file mode 100644
index 0000000000..6a640e46a9
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260917130509_gtm_invite_link.sql
@@ -0,0 +1,43 @@
+-- GTM invite links: personal, time-limited signup links created by Macro staff
+-- that grant the recipient a promotional first month of Premium.
+--
+-- User references are Macro user ids (`macro|email`), matching "User".id, so
+-- the auth service can attribute links straight from the request principal.
+CREATE TABLE public.gtm_invite_link
+(
+ id UUID NOT NULL,
+ token TEXT NOT NULL,
+ first_name TEXT NOT NULL,
+ recipient_email TEXT,
+ note TEXT,
+ promo_code TEXT NOT NULL,
+ created_by_user_id TEXT NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
+ revoked_at TIMESTAMP WITH TIME ZONE,
+ open_count INTEGER NOT NULL DEFAULT 0,
+ first_opened_at TIMESTAMP WITH TIME ZONE,
+ redeemed_by_user_id TEXT,
+ redeemed_at TIMESTAMP WITH TIME ZONE,
+ converted_at TIMESTAMP WITH TIME ZONE,
+ stripe_subscription_id TEXT,
+
+ CONSTRAINT gtm_invite_link_pkey PRIMARY KEY (id),
+ CONSTRAINT gtm_invite_link_token_key UNIQUE (token),
+ CONSTRAINT gtm_invite_link_redemption_consistent
+ CHECK ((redeemed_by_user_id IS NULL) = (redeemed_at IS NULL)),
+ CONSTRAINT gtm_invite_link_conversion_requires_redemption
+ CHECK (converted_at IS NULL OR redeemed_by_user_id IS NOT NULL)
+);
+
+-- Dashboard listings: newest first, optionally scoped to the creator.
+CREATE INDEX idx_gtm_invite_link_created_by_created_at
+ ON public.gtm_invite_link (created_by_user_id, created_at DESC);
+
+CREATE INDEX idx_gtm_invite_link_created_at
+ ON public.gtm_invite_link (created_at DESC);
+
+-- A user holds at most one redeemed link.
+CREATE UNIQUE INDEX idx_gtm_invite_link_redeemed_by_user_id
+ ON public.gtm_invite_link (redeemed_by_user_id)
+ WHERE redeemed_by_user_id IS NOT NULL;
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index e9d64743b9..11348d8a2a 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -6,6 +6,8 @@
| --- | --- |
| `/app` | Redirects to inbox |
| `/app/welcome` | Login page (when unauthenticated) |
+| `/app/invite?token=<token>` | GTM invite welcome page ("Welcome, <first name>", Continue → signup). Links come from the staff portal, last 48h, and grant the first month of Premium free once the account is created |
+| `/app/internal/invite-links` | Macro staff only (`@macro.com`): create GTM invite links and track opens, signups, and subscriptions |
| `/app/component/inbox` | Home (notifications + recent activity) |
| `/app/component/mail` | Email client |
| `/app/component/channels` | Channels list |
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index 47dd41dee1..6ebe84b547 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, 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, 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, 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, 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, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, 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, 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';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index 158cb4c5b1..3c3860716d 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, 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, 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, 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, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, 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, 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';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -224,6 +224,67 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Lists invite links, newest first. Macro staff only.
+ */
+ public listGtmInviteLinks<ThrowOnError extends boolean = false>(options?: Options<ListGtmInviteLinksData, ThrowOnError>): RequestResult<ListGtmInviteLinksResponses, ListGtmInviteLinksErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListGtmInviteLinksResponses, ListGtmInviteLinksErrors, ThrowOnError>({ url: '/gtm-invite/links', ...options });
+ }
+
+ /**
+ * Creates an invite link. Macro staff only.
+ */
+ public createGtmInviteLink<ThrowOnError extends boolean = false>(options: Options<CreateGtmInviteLinkData, ThrowOnError>): RequestResult<CreateGtmInviteLinkResponses, CreateGtmInviteLinkErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<CreateGtmInviteLinkResponses, CreateGtmInviteLinkErrors, ThrowOnError>({
+ url: '/gtm-invite/links',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Revokes an invite link nobody has signed up through. Macro staff only.
+ */
+ public revokeGtmInviteLink<ThrowOnError extends boolean = false>(options: Options<RevokeGtmInviteLinkData, ThrowOnError>): RequestResult<RevokeGtmInviteLinkResponses, RevokeGtmInviteLinkErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<RevokeGtmInviteLinkResponses, RevokeGtmInviteLinkErrors, ThrowOnError>({ url: '/gtm-invite/links/{id}', ...options });
+ }
+
+ /**
+ * The promotion the signed-in user's account holds from an invite link, if
+ * they redeemed one and have not started a paid subscription yet.
+ */
+ public getGtmInviteOffer<ThrowOnError extends boolean = false>(options?: Options<GetGtmInviteOfferData, ThrowOnError>): RequestResult<GetGtmInviteOfferResponses, GetGtmInviteOfferErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<GetGtmInviteOfferResponses, GetGtmInviteOfferErrors, ThrowOnError>({ url: '/gtm-invite/offer', ...options });
+ }
+
+ /**
+ * Resolves an invite link for the public welcome page and counts the open.
+ *
+ * Unauthenticated: the recipient has no account yet. Only the first name and
+ * whether the link is still usable are exposed.
+ */
+ public resolveGtmInviteLink<ThrowOnError extends boolean = false>(options: Options<ResolveGtmInviteLinkData, ThrowOnError>): RequestResult<ResolveGtmInviteLinkResponses, ResolveGtmInviteLinkErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<ResolveGtmInviteLinkResponses, ResolveGtmInviteLinkErrors, ThrowOnError>({ url: '/gtm-invite/public/{token}', ...options });
+ }
+
+ /**
+ * Attributes the signed-in user's account to the invite link they opened and
+ * grants them its offer. Idempotent for the same account.
+ */
+ public redeemGtmInviteLink<ThrowOnError extends boolean = false>(options: Options<RedeemGtmInviteLinkData, ThrowOnError>): RequestResult<RedeemGtmInviteLinkResponses, RedeemGtmInviteLinkErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<RedeemGtmInviteLinkResponses, RedeemGtmInviteLinkErrors, ThrowOnError>({
+ url: '/gtm-invite/redeem',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Health check
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 53b0631419..ce5eea31a6 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -167,6 +167,24 @@ export type CreateCheckoutSessionV2Request = {
successUrl: string;
};
+/**
+ * Request body to create a link.
+ */
+export type CreateGtmInviteLinkRequest = {
+ /**
+ * The recipient's first name, shown on the welcome page.
+ */
+ firstName: string;
+ /**
+ * Free-form internal note for the dashboard.
+ */
+ note?: string | null;
+ /**
+ * The recipient's email, when the sender knows it.
+ */
+ recipientEmail?: string | null;
+};
+
export type CreateInProgressLinkResponse = {
/**
* The link id
@@ -620,6 +638,132 @@ export type GmailLinkStatusResponse = {
reauthentication_required: boolean;
};
+/**
+ * A link as shown on the staff dashboard.
+ */
+export type GtmInviteLink = {
+ /**
+ * When the account started a paid subscription.
+ */
+ convertedAt?: string | null;
+ /**
+ * When the link was created.
+ */
+ createdAt: string;
+ /**
+ * The Macro user id of the staff member who created the link.
+ */
+ createdBy: string;
+ /**
+ * When the link stops being openable.
+ */
+ expiresAt: string;
+ /**
+ * The recipient's first name.
+ */
+ firstName: string;
+ /**
+ * When the welcome page first loaded.
+ */
+ firstOpenedAt?: string | null;
+ /**
+ * Free months the promotion grants.
+ */
+ freeMonths: number;
+ /**
+ * Primary key.
+ */
+ id: string;
+ /**
+ * Internal note.
+ */
+ note?: string | null;
+ /**
+ * How many times the welcome page loaded.
+ */
+ openCount: number;
+ /**
+ * The Stripe promotion code applied at checkout.
+ */
+ promoCode: string;
+ /**
+ * The recipient's email, when known.
+ */
+ recipientEmail?: string | null;
+ /**
+ * When that account redeemed the link.
+ */
+ redeemedAt?: string | null;
+ /**
+ * The Macro user id of the account that signed up through the link.
+ */
+ redeemedBy?: string | null;
+ /**
+ * When staff revoked the link.
+ */
+ revokedAt?: string | null;
+ /**
+ * Lifecycle status.
+ */
+ status: GtmInviteLinkStatus;
+ /**
+ * The Stripe subscription id of that subscription.
+ */
+ stripeSubscriptionId?: string | null;
+ /**
+ * The secret to embed in the link URL.
+ */
+ token: string;
+};
+
+/**
+ * Links for the dashboard.
+ */
+export type GtmInviteLinkList = {
+ /**
+ * Newest first.
+ */
+ links: Array<GtmInviteLink>;
+};
+
+/**
+ * Where a link is in its lifecycle.
+ */
+export type GtmInviteLinkStatus = 'active' | 'expired' | 'revoked' | 'redeemed' | 'converted';
+
+/**
+ * The promotion a signed-in user's account holds.
+ */
+export type GtmInviteOffer = {
+ /**
+ * The first name the link was made out to.
+ */
+ firstName: string;
+ /**
+ * Free months the promotion grants.
+ */
+ freeMonths: number;
+ /**
+ * The redeemed link.
+ */
+ linkId: string;
+ /**
+ * The Stripe promotion code checkout applies.
+ */
+ promoCode: string;
+ /**
+ * When the account redeemed the link.
+ */
+ redeemedAt: string;
+};
+
+/**
+ * Whether the signed-in user holds an unused offer.
+ */
+export type GtmInviteOfferStatus = {
+ offer?: null | GtmInviteOffer;
+};
+
export type InitGithubLinkResponse = {
/**
* The OAuth authorization URL to redirect the user to
@@ -851,6 +995,24 @@ export type ProfilePictures = {
pictures: Array<UserProfilePicture>;
};
+/**
+ * What the public welcome page learns about a link.
+ */
+export type PublicGtmInviteLink = {
+ /**
+ * The recipient's first name.
+ */
+ firstName: string;
+ /**
+ * Free months the promotion grants.
+ */
+ freeMonths: number;
+ /**
+ * Whether the link can still be used.
+ */
+ status: GtmInviteLinkStatus;
+};
+
/**
* The key the user pasted.
*/
@@ -883,6 +1045,16 @@ export type PutUserNameQueryParams = {
last_name?: string | null;
};
+/**
+ * Request body to redeem a link.
+ */
+export type RedeemGtmInviteLinkRequest = {
+ /**
+ * The token from the link URL.
+ */
+ token: string;
+};
+
export type ResendFusionauthVerifyUserEmailRequest = {
/**
* The email address to resend the verification email to
@@ -1446,6 +1618,153 @@ export type EnrichGithubPullRequestsResponses = {
export type EnrichGithubPullRequestsResponse2 = EnrichGithubPullRequestsResponses[keyof EnrichGithubPullRequestsResponses];
+export type ListGtmInviteLinksData = {
+ body?: never;
+ path?: never;
+ query?: {
+ /**
+ * Only the caller's own links (default: every staff member's).
+ */
+ mine?: boolean;
+ };
+ url: '/gtm-invite/links';
+};
+
+export type ListGtmInviteLinksErrors = {
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type ListGtmInviteLinksError = ListGtmInviteLinksErrors[keyof ListGtmInviteLinksErrors];
+
+export type ListGtmInviteLinksResponses = {
+ 200: GtmInviteLinkList;
+};
+
+export type ListGtmInviteLinksResponse = ListGtmInviteLinksResponses[keyof ListGtmInviteLinksResponses];
+
+export type CreateGtmInviteLinkData = {
+ body: CreateGtmInviteLinkRequest;
+ path?: never;
+ query?: never;
+ url: '/gtm-invite/links';
+};
+
+export type CreateGtmInviteLinkErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type CreateGtmInviteLinkError = CreateGtmInviteLinkErrors[keyof CreateGtmInviteLinkErrors];
+
+export type CreateGtmInviteLinkResponses = {
+ 200: GtmInviteLink;
+};
+
+export type CreateGtmInviteLinkResponse = CreateGtmInviteLinkResponses[keyof CreateGtmInviteLinkResponses];
+
+export type RevokeGtmInviteLinkData = {
+ body?: never;
+ path: {
+ /**
+ * The invite link id
+ */
+ id: string;
+ };
+ query?: never;
+ url: '/gtm-invite/links/{id}';
+};
+
+export type RevokeGtmInviteLinkErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 404: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type RevokeGtmInviteLinkError = RevokeGtmInviteLinkErrors[keyof RevokeGtmInviteLinkErrors];
+
+export type RevokeGtmInviteLinkResponses = {
+ 200: GtmInviteLink;
+};
+
+export type RevokeGtmInviteLinkResponse = RevokeGtmInviteLinkResponses[keyof RevokeGtmInviteLinkResponses];
+
+export type GetGtmInviteOfferData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/gtm-invite/offer';
+};
+
+export type GetGtmInviteOfferErrors = {
+ 401: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type GetGtmInviteOfferError = GetGtmInviteOfferErrors[keyof GetGtmInviteOfferErrors];
+
+export type GetGtmInviteOfferResponses = {
+ 200: GtmInviteOfferStatus;
+};
+
+export type GetGtmInviteOfferResponse = GetGtmInviteOfferResponses[keyof GetGtmInviteOfferResponses];
+
+export type ResolveGtmInviteLinkData = {
+ body?: never;
+ path: {
+ /**
+ * The token from the invite link URL
+ */
+ token: string;
+ };
+ query?: never;
+ url: '/gtm-invite/public/{token}';
+};
+
+export type ResolveGtmInviteLinkErrors = {
+ 400: ErrorResponse;
+ 404: ErrorResponse;
+ 429: unknown;
+ 500: ErrorResponse;
+};
+
+export type ResolveGtmInviteLinkError = ResolveGtmInviteLinkErrors[keyof ResolveGtmInviteLinkErrors];
+
+export type ResolveGtmInviteLinkResponses = {
+ 200: PublicGtmInviteLink;
+};
+
+export type ResolveGtmInviteLinkResponse = ResolveGtmInviteLinkResponses[keyof ResolveGtmInviteLinkResponses];
+
+export type RedeemGtmInviteLinkData = {
+ body: RedeemGtmInviteLinkRequest;
+ path?: never;
+ query?: never;
+ url: '/gtm-invite/redeem';
+};
+
+export type RedeemGtmInviteLinkErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ 404: ErrorResponse;
+ 409: ErrorResponse;
+ 410: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type RedeemGtmInviteLinkError = RedeemGtmInviteLinkErrors[keyof RedeemGtmInviteLinkErrors];
+
+export type RedeemGtmInviteLinkResponses = {
+ 200: GtmInviteOffer;
+};
+
+export type RedeemGtmInviteLinkResponse = RedeemGtmInviteLinkResponses[keyof RedeemGtmInviteLinkResponses];
+
export type HealthHandlerData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 97a7d9e24f..b5d54c074b 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -646,6 +646,406 @@
}
}
},
+ "/gtm-invite/links": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "Lists invite links, newest first. Macro staff only.",
+ "operationId": "list_gtm_invite_links",
+ "parameters": [
+ {
+ "name": "mine",
+ "in": "query",
+ "description": "Only the caller's own links (default: every staff member's).",
+ "required": false,
+ "schema": {
+ "type": "boolean"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLinkList"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["gtm_invite"],
+ "summary": "Creates an invite link. Macro staff only.",
+ "operationId": "create_gtm_invite_link",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateGtmInviteLinkRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/links/{id}": {
+ "delete": {
+ "tags": ["gtm_invite"],
+ "summary": "Revokes an invite link nobody has signed up through. Macro staff only.",
+ "operationId": "revoke_gtm_invite_link",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The invite link id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/offer": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "The promotion the signed-in user's account holds from an invite link, if\nthey redeemed one and have not started a paid subscription yet.",
+ "operationId": "get_gtm_invite_offer",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteOfferStatus"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/public/{token}": {
+ "get": {
+ "tags": ["gtm_invite"],
+ "summary": "Resolves an invite link for the public welcome page and counts the open.",
+ "description": "Unauthenticated: the recipient has no account yet. Only the first name and\nwhether the link is still usable are exposed.",
+ "operationId": "resolve_gtm_invite_link",
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "description": "The token from the invite link URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PublicGtmInviteLink"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": ""
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gtm-invite/redeem": {
+ "post": {
+ "tags": ["gtm_invite"],
+ "summary": "Attributes the signed-in user's account to the invite link they opened and\ngrants them its offer. Idempotent for the same account.",
+ "operationId": "redeem_gtm_invite_link",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RedeemGtmInviteLinkRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GtmInviteOffer"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "410": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["health"],
@@ -4137,6 +4537,25 @@
}
}
},
+ "CreateGtmInviteLinkRequest": {
+ "type": "object",
+ "description": "Request body to create a link.",
+ "required": ["firstName"],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name, shown on the welcome page."
+ },
+ "note": {
+ "type": ["string", "null"],
+ "description": "Free-form internal note for the dashboard."
+ },
+ "recipientEmail": {
+ "type": ["string", "null"],
+ "description": "The recipient's email, when the sender knows it."
+ }
+ }
+ },
"CreateInProgressLinkResponse": {
"type": "object",
"required": ["link_id"],
@@ -4708,6 +5127,179 @@
}
}
},
+ "GtmInviteLink": {
+ "type": "object",
+ "description": "A link as shown on the staff dashboard.",
+ "required": [
+ "id",
+ "token",
+ "firstName",
+ "promoCode",
+ "freeMonths",
+ "status",
+ "createdBy",
+ "createdAt",
+ "expiresAt",
+ "openCount"
+ ],
+ "properties": {
+ "convertedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the account started a paid subscription."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the link was created."
+ },
+ "createdBy": {
+ "type": "string",
+ "description": "The Macro user id of the staff member who created the link."
+ },
+ "expiresAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the link stops being openable."
+ },
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name."
+ },
+ "firstOpenedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the welcome page first loaded."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Primary key."
+ },
+ "note": {
+ "type": ["string", "null"],
+ "description": "Internal note."
+ },
+ "openCount": {
+ "type": "integer",
+ "format": "int32",
+ "description": "How many times the welcome page loaded."
+ },
+ "promoCode": {
+ "type": "string",
+ "description": "The Stripe promotion code applied at checkout."
+ },
+ "recipientEmail": {
+ "type": ["string", "null"],
+ "description": "The recipient's email, when known."
+ },
+ "redeemedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When that account redeemed the link."
+ },
+ "redeemedBy": {
+ "type": ["string", "null"],
+ "description": "The Macro user id of the account that signed up through the link."
+ },
+ "revokedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When staff revoked the link."
+ },
+ "status": {
+ "$ref": "#/components/schemas/GtmInviteLinkStatus",
+ "description": "Lifecycle status."
+ },
+ "stripeSubscriptionId": {
+ "type": ["string", "null"],
+ "description": "The Stripe subscription id of that subscription."
+ },
+ "token": {
+ "type": "string",
+ "description": "The secret to embed in the link URL."
+ }
+ }
+ },
+ "GtmInviteLinkList": {
+ "type": "object",
+ "description": "Links for the dashboard.",
+ "required": ["links"],
+ "properties": {
+ "links": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GtmInviteLink"
+ },
+ "description": "Newest first."
+ }
+ }
+ },
+ "GtmInviteLinkStatus": {
+ "type": "string",
+ "description": "Where a link is in its lifecycle.",
+ "enum": ["active", "expired", "revoked", "redeemed", "converted"]
+ },
+ "GtmInviteOffer": {
+ "type": "object",
+ "description": "The promotion a signed-in user's account holds.",
+ "required": [
+ "linkId",
+ "firstName",
+ "promoCode",
+ "freeMonths",
+ "redeemedAt"
+ ],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The first name the link was made out to."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The redeemed link."
+ },
+ "promoCode": {
+ "type": "string",
+ "description": "The Stripe promotion code checkout applies."
+ },
+ "redeemedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the account redeemed the link."
+ }
+ }
+ },
+ "GtmInviteOfferStatus": {
+ "type": "object",
+ "description": "Whether the signed-in user holds an unused offer.",
+ "properties": {
+ "offer": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GtmInviteOffer",
+ "description": "The offer, when the account redeemed a link and has not subscribed yet."
+ }
+ ]
+ }
+ }
+ },
"InitGithubLinkResponse": {
"type": "object",
"required": ["authorization_url", "link_id"],
@@ -5016,6 +5608,27 @@
}
}
},
+ "PublicGtmInviteLink": {
+ "type": "object",
+ "description": "What the public welcome page learns about a link.",
+ "required": ["firstName", "status", "freeMonths"],
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The recipient's first name."
+ },
+ "freeMonths": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Free months the promotion grants.",
+ "minimum": 0
+ },
+ "status": {
+ "$ref": "#/components/schemas/GtmInviteLinkStatus",
+ "description": "Whether the link can still be used."
+ }
+ }
+ },
"PutCursorApiKeyRequest": {
"type": "object",
"description": "The key the user pasted.",
@@ -5050,6 +5663,17 @@
}
}
},
+ "RedeemGtmInviteLinkRequest": {
+ "type": "object",
+ "description": "Request body to redeem a link.",
+ "required": ["token"],
+ "properties": {
+ "token": {
+ "type": "string",
+ "description": "The token from the link URL."
+ }
+ }
+ },
"ResendFusionauthVerifyUserEmailRequest": {
"type": "object",
"required": ["email"],
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index f6c46c95c8..f7499fe2f2 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -43,6 +43,7 @@ export const authExcluded = [
'checkGmailLinkStatus',
'configureCodex',
'createCheckoutSessionV2',
+ 'createGtmInviteLink',
'createInProgressLink',
'createMergeRequest',
'createPortalSession',
@@ -58,6 +59,7 @@ export const authExcluded = [
'generateEmailLink',
'getCodexConnection',
'getCursorApiKey',
+ 'getGtmInviteOffer',
'getLegacyUserPermissions',
'getPermissions',
'getReferralCode',
@@ -77,6 +79,7 @@ export const authExcluded = [
'joinTeam',
'listCodexEnvironments',
'listCursorModels',
+ 'listGtmInviteLinks',
'logout',
'oauth2Callback',
'oauthRedirect',
@@ -94,10 +97,13 @@ export const authExcluded = [
'putCursorDefaultModel',
'putProfilePicture',
'putUserName',
+ 'redeemGtmInviteLink',
'refresh',
'rejectInvitation',
'removeUserFromTeam',
'resendFusionauthVerifyUserEmail',
+ 'resolveGtmInviteLink',
+ 'revokeGtmInviteLink',
'sendMobileWelcomeEmail',
'sendReferralCode',
'sessionCreation',
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 2943abbabc..dfa48ac616 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -73,6 +73,7 @@ foreign_entity = { path = "../../crates/foreign_entity" }
favorites = { path = "../../crates/favorites", features = ["postgres"] }
fusionauth = { path = "../../crates/fusionauth" }
futures = { workspace = true }
+gtm_invite = { path = "../../crates/gtm_invite" }
github = { path = "../../crates/github", default-features = false, features = [
"axum",
"inbound",
diff --git a/services/authentication_service/README.md b/services/authentication_service/README.md
index 525f6eb6dd..da9d9e3aa6 100644
--- a/services/authentication_service/README.md
+++ b/services/authentication_service/README.md
@@ -64,6 +64,26 @@ Matching rules:
supported.
- Denial responses and policy errors must not disclose configured addresses.
+## GTM invite links
+
+Macro staff (any `@macro.com` account) mint personal, 48-hour signup links from
+`/app/internal/invite-links`. The recipient opens `/app/invite?token=…`, signs up,
+and the account is attributed to the staff member who created the link. At the
+plan step of onboarding the account sees a free-month offer instead of the plan
+picker, and checkout applies a Stripe promotion code server-side. The Stripe
+subscription webhook then marks the link converted.
+
+Both settings are optional plain Doppler values (project
+`authentication-service`); the service falls back to the defaults when unset.
+
+| Setting | Default | Meaning |
+| --- | --- | --- |
+| `GTM_INVITE_PROMO_CODE` | `1MF` | Customer-facing Stripe promotion code applied at checkout. Must exist and be active in Stripe (`1MF` is 100% off the first month). |
+| `GTM_INVITE_LINK_TTL_HOURS` | `48` | How long a link can be opened and redeemed after creation. |
+
+Links live in the `gtm_invite_link` MacroDB table (crate `gtm_invite`); the
+dashboard reads it through `GET /gtm-invite/links`.
+
## Shared mailboxes
Internal shared-mailbox grant relocation creates ordinary FusionAuth users for
diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rs
index 5d3b8c9717..2478d76f93 100644
--- a/services/authentication_service/src/api.rs
+++ b/services/authentication_service/src/api.rs
@@ -140,6 +140,16 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
},
),
)
+ .nest(
+ "/gtm-invite",
+ gtm_invite::inbound::axum_router::gtm_invite_router(
+ gtm_invite::inbound::axum_router::GtmInviteRouterState {
+ service: state.gtm_invite_service.clone(),
+ rate_limiter: state.rate_limit_service.clone(),
+ authorization_state: state.authorization_state.clone(),
+ },
+ ),
+ )
.nest("/jwt", jwt::router())
.nest("/session", session::router())
.merge(mobile_welcome_email::router(state.clone()))
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 55e330a0dc..39a4c2f9e8 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -24,6 +24,9 @@ use github::domain::service::GithubLinkServiceImpl;
use github::outbound::github_auth_client::GithubAuthImpl;
use github::outbound::github_oauth_client::GithubOauthImpl;
use github::outbound::pg_github_repo::PgGithubRepo;
+use gtm_invite::{
+ domain::service::GtmInviteServiceImpl, outbound::pg_gtm_invite_repo::PgGtmInviteRepo,
+};
use loops_client::LoopsClient;
use macro_auth::{InternalApiKey, middleware::decode_jwt::JwtValidationArgs};
use macro_authorization::{
@@ -95,6 +98,8 @@ pub(crate) type ReferralServiceType = ReferralServiceImpl<
Arc<SqsNotificationIngress<SqsQueue>>,
>;
+pub(crate) type GtmInviteServiceType = GtmInviteServiceImpl<PgGtmInviteRepo>;
+
pub(crate) type GithubLinkServiceType = GithubLinkServiceImpl<
PgGithubRepo,
GithubOauthImpl,
@@ -145,6 +150,7 @@ pub(crate) struct ApiContext {
pub analytics_client: Arc<AnalyticsClient>,
pub loops_client: Arc<LoopsClient>,
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,
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 05fd3b3388..4963e8c601 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -3,6 +3,10 @@ use github::domain::models::{
EnrichedGithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment,
GithubPullRequestRef, GithubPullRequestStatus,
};
+use gtm_invite::inbound::axum_router::dto::{
+ CreateGtmInviteLinkRequest, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus,
+ GtmInviteOffer, GtmInviteOfferStatus, PublicGtmInviteLink, RedeemGtmInviteLinkRequest,
+};
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamRequest, PatchTeamUserRole,
@@ -164,6 +168,14 @@ use model::user::{
referral::inbound::axum_router::get_referral_code_handler::<crate::api::context::ReferralServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
referral::inbound::axum_router::post_referral_invite_handler::<crate::api::context::ReferralServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ /// /gtm-invite
+ gtm_invite::inbound::axum_router::create_link::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ gtm_invite::inbound::axum_router::list_links::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ gtm_invite::inbound::axum_router::revoke_link::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ gtm_invite::inbound::axum_router::resolve_link::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ gtm_invite::inbound::axum_router::redeem_link::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+ gtm_invite::inbound::axum_router::get_offer::handler::<crate::api::context::GtmInviteServiceType, crate::api::context::RateLimiter, crate::api::context::AuthorizationService>,
+
/// /mobile-welcome-email
mobile_welcome_email::handler,
@@ -204,6 +216,16 @@ use model::user::{
CursorApiKeyStatus,
PutCursorApiKeyRequest,
+ // GTM invite links
+ GtmInviteLink,
+ GtmInviteLinkStatus,
+ GtmInviteLinkList,
+ CreateGtmInviteLinkRequest,
+ PublicGtmInviteLink,
+ RedeemGtmInviteLinkRequest,
+ GtmInviteOffer,
+ GtmInviteOfferStatus,
+
// GitHub pull requests
EnrichGithubPullRequestsProxyRequest,
EnrichGithubPullRequestsResponse,
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 1a995f46ad..93e2c9cb8a 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
@@ -2,7 +2,9 @@ use axum::{Json, extract::State};
use entity_access::domain::models::OwnerTeamRole;
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractorV2;
+use gtm_invite::domain::ports::GtmInviteService;
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
+use macro_user_id::user_id::MacroUserIdStr;
use serde::Deserialize;
use utoipa::ToSchema;
@@ -90,24 +92,40 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
return Err(StripeOperationError::AlreadySubscribed);
}
- // If a discount code is provided, look up the promotion code ID
- let promo_code_id = if let Some(ref discount) = req.discount {
- let mut list_params = stripe::ListPromotionCodes::new();
- list_params.code = Some(discount);
- list_params.active = Some(true);
- list_params.limit = Some(1);
-
- let promo_codes = stripe::PromotionCode::list(&ctx.stripe_client, &list_params).await?;
-
- let promo_code = promo_codes
- .data
- .into_iter()
- .next()
- .ok_or(StripeOperationError::PromoCodeNotFound)?;
-
- Some(promo_code.id)
- } else {
- None
+ // An explicit discount code is authoritative and must exist. Without one,
+ // an account that signed up through a GTM invite link gets the link's
+ // promotion applied for it — best-effort, so a code that went missing in
+ // Stripe degrades to a regular checkout instead of blocking it.
+ let promo_code_id = match req.discount.as_deref() {
+ Some(discount) => Some(
+ find_active_promotion_code(&ctx.stripe_client, discount)
+ .await?
+ .ok_or(StripeOperationError::PromoCodeNotFound)?,
+ ),
+ None => match gtm_invite_promo_code(&ctx, &user.authorization.user.macro_user_id).await {
+ Some(code) => match find_active_promotion_code(&ctx.stripe_client, &code).await {
+ Ok(Some(id)) => {
+ tracing::info!(promo_code = %code, "applying GTM invite promotion to checkout");
+ Some(id)
+ }
+ Ok(None) => {
+ tracing::error!(
+ promo_code = %code,
+ "GTM invite promotion code is not active in Stripe; checking out without it"
+ );
+ None
+ }
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ promo_code = %code,
+ "failed to look up GTM invite promotion code; checking out without it"
+ );
+ None
+ }
+ },
+ None => None,
+ },
};
// Build subscription metadata from optional tracking fields
@@ -177,3 +195,30 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
Ok(Json(StripeSessionResponse { url }))
}
+
+/// Finds the active Stripe promotion code customers redeem as `code`.
+async fn find_active_promotion_code(
+ stripe_client: &stripe::Client,
+ code: &str,
+) -> Result<Option<stripe::PromotionCodeId>, stripe::StripeError> {
+ let mut list_params = stripe::ListPromotionCodes::new();
+ list_params.code = Some(code);
+ list_params.active = Some(true);
+ list_params.limit = Some(1);
+
+ let promo_codes = stripe::PromotionCode::list(stripe_client, &list_params).await?;
+
+ Ok(promo_codes.data.into_iter().next().map(|promo| promo.id))
+}
+
+/// The promotion code an account holds from a redeemed GTM invite link, if any.
+async fn gtm_invite_promo_code(ctx: &ApiContext, user_id: &MacroUserIdStr<'_>) -> Option<String> {
+ match ctx.gtm_invite_service.active_offer_for_user(user_id).await {
+ Ok(Some(link)) => Some(link.promo_code.to_string()),
+ Ok(None) => None,
+ Err(e) => {
+ tracing::error!(error=?e, "failed to look up GTM invite offer for checkout");
+ None
+ }
+ }
+}
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 442d980668..0a115fd9fb 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -11,6 +11,7 @@ use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
+use gtm_invite::domain::ports::GtmInviteService;
use macro_user_id::email::Email;
use macro_user_id::user_id::MacroUserIdStr;
use macro_user_id::{cowlike::CowLike, lowercased::Lowercase};
@@ -455,6 +456,13 @@ async fn handle_customer_subscription_event(
let is_new_subscription = matches!(event_type, EventType::CustomerSubscriptionCreated)
|| is_transition_from_incomplete;
+ // An account that signed up through a GTM invite link converted the moment
+ // its subscription — personal or team — is live. Tracking only: never
+ // fails the webhook.
+ if matches!(subscription_status, "active" | "trialing") {
+ mark_gtm_invite_converted(ctx, &email, subscription_id).await;
+ }
+
// 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") {
@@ -601,6 +609,33 @@ async fn handle_customer_subscription_event(
Ok(())
}
+/// Records the subscriber's redeemed GTM invite link, if they hold one, as
+/// converted into this subscription.
+#[tracing::instrument(skip(ctx, email), fields(subscription_id))]
+async fn mark_gtm_invite_converted(
+ ctx: &ApiContext,
+ email: &Email<macro_user_id::lowercased::Lowercase<'_>>,
+ subscription_id: &str,
+) {
+ let user_id = match macro_user_id::user_id::MacroUserIdStr::try_from_email(email.as_ref()) {
+ Ok(user_id) => user_id,
+ Err(e) => {
+ tracing::error!(error=?e, "customer email is not a valid macro user id");
+ return;
+ }
+ };
+
+ match ctx
+ .gtm_invite_service
+ .mark_converted(&user_id, subscription_id)
+ .await
+ {
+ Ok(true) => tracing::info!("marked GTM invite link as converted"),
+ Ok(false) => {}
+ Err(e) => tracing::error!(error=?e, "failed to mark GTM invite link as converted"),
+ }
+}
+
/// Checks if the subscribing user was referred and, if so, processes the referral
/// to credit the referrer.
#[tracing::instrument(skip(ctx, email), err)]
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index ef5f48dac7..1ae47254a8 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -3,6 +3,7 @@ use std::sync::LazyLock;
use anyhow::Context;
use authentication_service::service::signup_policy::SignupPolicy;
use database_env_vars::{DatabaseUrl, RedisUri};
+use gtm_invite::domain::models::{GtmInviteConfig, PromoCode};
use macro_auth::InternalApiKey;
pub use macro_env::Environment;
use macro_env_var::{env_vars, maybe_env_vars};
@@ -65,6 +66,10 @@ maybe_env_vars! {
pub struct LoopsApiKey;
/// JSON array of exact email addresses allowed to sign up in Develop.
pub struct DevelopmentSignupAllowlistJson;
+ /// Stripe promotion code GTM invite links grant at checkout. Defaults to `1MF`.
+ pub struct GtmInvitePromoCode;
+ /// Hours a GTM invite link stays openable after creation. Defaults to 48.
+ pub struct GtmInviteLinkTtlHours;
}
/// The configuration parameters for the application.
@@ -151,6 +156,11 @@ pub struct Config {
///
/// All `@macro.com` email addresses are allowed by the Develop policy automatically.
pub development_signup_allowlist_json: DevelopmentSignupAllowlistJson,
+ /// Stripe promotion code applied at checkout for accounts that signed up
+ /// through a GTM invite link (optional, defaults to `1MF`).
+ 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
pub stripe_price_id: StripePriceId,
/// The internal api key
@@ -233,6 +243,11 @@ impl Config {
) -> anyhow::Result<SignupPolicy> {
resolve_signup_policy(environment, &self.development_signup_allowlist_json)
}
+
+ /// Resolves the offer GTM invite links carry.
+ pub(crate) fn gtm_invite_config(&self) -> anyhow::Result<GtmInviteConfig> {
+ resolve_gtm_invite_config(&self.gtm_invite_promo_code, &self.gtm_invite_link_ttl_hours)
+ }
}
fn resolve_microsoft_credentials(
@@ -280,6 +295,39 @@ fn resolve_signup_policy(
}
}
+/// The promotion code applied when `GTM_INVITE_PROMO_CODE` is unset: 100% off
+/// the first month, created in Stripe for exactly this program.
+const DEFAULT_GTM_INVITE_PROMO_CODE: &str = "1MF";
+/// How long an invite link stays usable when `GTM_INVITE_LINK_TTL_HOURS` is unset.
+const DEFAULT_GTM_INVITE_LINK_TTL_HOURS: i64 = 48;
+/// Free months the default promotion grants, for user-facing copy.
+const GTM_INVITE_FREE_MONTHS: u8 = 1;
+
+fn resolve_gtm_invite_config(
+ promo_code: &GtmInvitePromoCode,
+ link_ttl_hours: &GtmInviteLinkTtlHours,
+) -> anyhow::Result<GtmInviteConfig> {
+ let promo_code: PromoCode = nonblank_value(promo_code.value())
+ .unwrap_or(DEFAULT_GTM_INVITE_PROMO_CODE)
+ .parse()
+ .context("GTM_INVITE_PROMO_CODE is invalid")?;
+ let link_ttl_hours: i64 = match nonblank_value(link_ttl_hours.value()) {
+ Some(hours) => hours
+ .trim()
+ .parse()
+ .context("GTM_INVITE_LINK_TTL_HOURS must be a whole number of hours")?,
+ None => DEFAULT_GTM_INVITE_LINK_TTL_HOURS,
+ };
+ if link_ttl_hours <= 0 {
+ anyhow::bail!("GTM_INVITE_LINK_TTL_HOURS must be positive");
+ }
+ Ok(GtmInviteConfig {
+ promo_code,
+ link_ttl: chrono::Duration::hours(link_ttl_hours),
+ free_months: GTM_INVITE_FREE_MONTHS,
+ })
+}
+
fn nonblank_value(value: Option<&str>) -> Option<&str> {
value.filter(|value| !value.trim().is_empty())
}
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index b7b6f22bcc..c7194d1545 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -65,6 +65,9 @@ use teams::{
},
};
+use gtm_invite::{
+ domain::service::GtmInviteServiceImpl, outbound::pg_gtm_invite_repo::PgGtmInviteRepo,
+};
use referral::{
domain::service::ReferralServiceImpl,
outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},
@@ -106,6 +109,9 @@ async fn main() -> anyhow::Result<()> {
.signup_policy()
.context("invalid signup policy configuration")?,
);
+ let gtm_invite_config = config
+ .gtm_invite_config()
+ .context("invalid GTM invite link configuration")?;
let microsoft_credentials = config
.microsoft_credentials()
.context("invalid Microsoft OAuth configuration")?;
@@ -437,6 +443,10 @@ async fn main() -> anyhow::Result<()> {
),
notification_ingress: notification_ingress_service.clone(),
};
+ let gtm_invite_service = GtmInviteServiceImpl {
+ repo: PgGtmInviteRepo::new(db.clone()),
+ config: gtm_invite_config,
+ };
let codex_connection = if let Some(key_id) = config.codex_oauth_kms_key_id() {
let cipher = Arc::new(codex_connection::outbound::cipher::EnvelopeCipher::new(
@@ -494,6 +504,7 @@ async fn main() -> anyhow::Result<()> {
favorites_service: Arc::new(favorites_service),
entity_access_service: entity_access_service_impl,
referral_service: Arc::new(referral_service),
+ gtm_invite_service: Arc::new(gtm_invite_service),
native_app_service: Arc::new(NativeAppServiceImpl {
bundle_fetcher: DefaultBundleFetcher::new(
AppServiceUrl::new_for_environment(config.environment)