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.

feat(onboarding): earn $10 AI credit for invites and referrals (#8878)

Jacob Beckermanb5cfe242760c
diff --git a/.sqlx/query-0ef2ba65257ea353835a2519d0b7a4880dc58299be0a40d4f880b188fd738739.json b/.sqlx/query-0ef2ba65257ea353835a2519d0b7a4880dc58299be0a40d4f880b188fd738739.json
new file mode 100644
index 0000000000..01a266e2ee
--- /dev/null
+++ b/.sqlx/query-0ef2ba65257ea353835a2519d0b7a4880dc58299be0a40d4f880b188fd738739.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_invite_link (team_id, token, created_by)\n VALUES ($1, $2, $3)\n ON CONFLICT (team_id) DO UPDATE\n SET token = EXCLUDED.token,\n created_by = EXCLUDED.created_by,\n created_at = now()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0ef2ba65257ea353835a2519d0b7a4880dc58299be0a40d4f880b188fd738739"
+}
diff --git a/.sqlx/query-0f651f5ef335b7847909f83e887a76603dd1c99ea9706c84b44ca3ec23666408.json b/.sqlx/query-0f651f5ef335b7847909f83e887a76603dd1c99ea9706c84b44ca3ec23666408.json
deleted file mode 100644
index d236c7a3cf..0000000000
--- a/.sqlx/query-0f651f5ef335b7847909f83e887a76603dd1c99ea9706c84b44ca3ec23666408.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO team_invite_link (team_id, token)\n VALUES ($1, $2)\n ON CONFLICT (team_id) DO UPDATE\n SET token = EXCLUDED.token,\n created_at = now()\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "0f651f5ef335b7847909f83e887a76603dd1c99ea9706c84b44ca3ec23666408"
-}
diff --git a/.sqlx/query-595fd1716ea138f6d3e995dda5e2ad7dbb646a72ba2161d2afb2d83c5b326ab0.json b/.sqlx/query-595fd1716ea138f6d3e995dda5e2ad7dbb646a72ba2161d2afb2d83c5b326ab0.json
new file mode 100644
index 0000000000..e703abf3a2
--- /dev/null
+++ b/.sqlx/query-595fd1716ea138f6d3e995dda5e2ad7dbb646a72ba2161d2afb2d83c5b326ab0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(SUM(cost_cents), 0)::bigint AS \"bonus!\"\n FROM ai_free_allowance_bonus\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "bonus!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "595fd1716ea138f6d3e995dda5e2ad7dbb646a72ba2161d2afb2d83c5b326ab0"
+}
diff --git a/.sqlx/query-80b23d305a99cef820a42a920a288065af18ee4a52f00a8b97f90bc8de58aeaa.json b/.sqlx/query-80b23d305a99cef820a42a920a288065af18ee4a52f00a8b97f90bc8de58aeaa.json
new file mode 100644
index 0000000000..268d6124a3
--- /dev/null
+++ b/.sqlx/query-80b23d305a99cef820a42a920a288065af18ee4a52f00a8b97f90bc8de58aeaa.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO referral_tracking (id, referrer_id, referred_id, status, created_at)\n VALUES ($1, $2, $3, 'incomplete', NOW())\n ON CONFLICT (referred_id) DO NOTHING\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "80b23d305a99cef820a42a920a288065af18ee4a52f00a8b97f90bc8de58aeaa"
+}
diff --git a/.sqlx/query-9d74d7b51b75a6494c541984e7091f9c9da21ad7effb95702a980a27be73750d.json b/.sqlx/query-9d74d7b51b75a6494c541984e7091f9c9da21ad7effb95702a980a27be73750d.json
new file mode 100644
index 0000000000..115323e7cc
--- /dev/null
+++ b/.sqlx/query-9d74d7b51b75a6494c541984e7091f9c9da21ad7effb95702a980a27be73750d.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT created_by\n FROM team_invite_link\n WHERE token = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_by",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "9d74d7b51b75a6494c541984e7091f9c9da21ad7effb95702a980a27be73750d"
+}
diff --git a/.sqlx/query-9fc2c0a2cd3b00891b5a6b3b62d9d2ae1278d57ed591316997b2dae27a990db0.json b/.sqlx/query-9fc2c0a2cd3b00891b5a6b3b62d9d2ae1278d57ed591316997b2dae27a990db0.json
new file mode 100644
index 0000000000..159ce6f608
--- /dev/null
+++ b/.sqlx/query-9fc2c0a2cd3b00891b5a6b3b62d9d2ae1278d57ed591316997b2dae27a990db0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT u.id\n FROM \"User\" u\n JOIN macro_user m ON m.id = u.macro_user_id\n WHERE m.id = $1\n ORDER BY lower(u.email) = lower(m.email) DESC, u.id\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9fc2c0a2cd3b00891b5a6b3b62d9d2ae1278d57ed591316997b2dae27a990db0"
+}
diff --git a/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json b/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json
deleted file mode 100644
index 8a9fd5ece9..0000000000
--- a/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT stripe_customer_id FROM macro_user\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "stripe_customer_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7"
-}
diff --git a/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json b/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json
deleted file mode 100644
index 34d7bb06c4..0000000000
--- a/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT referrer_id FROM referral_tracking WHERE referred_id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "referrer_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613"
-}
diff --git a/.sqlx/query-e0e13a10cb2e3099116c732de33fa89b7244d171f8740195df0b1831e9072332.json b/.sqlx/query-e0e13a10cb2e3099116c732de33fa89b7244d171f8740195df0b1831e9072332.json
new file mode 100644
index 0000000000..1ae2e2ec23
--- /dev/null
+++ b/.sqlx/query-e0e13a10cb2e3099116c732de33fa89b7244d171f8740195df0b1831e9072332.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_free_allowance_bonus (id, user_id, cost_cents, note)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e0e13a10cb2e3099116c732de33fa89b7244d171f8740195df0b1831e9072332"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 1bbd65e609..0cac25d950 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16549,7 +16549,6 @@ name = "referral"
version = "0.1.0"
dependencies = [
"anyhow",
- "async-stripe",
"axum",
"axum-extra",
"chrono",
diff --git a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
index 48103295a4..01a2c00afe 100644
--- a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
+++ b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
@@ -55,6 +55,12 @@ test('a new user signs up, connects everything, and starts the trial', async ({
);
await page.getByRole('button', { name: 'Create team & invite 2' }).click();
+ await expect(page.getByText("You're on Acme")).toBeVisible();
+ await page.getByRole('button', { name: 'Copy invite link' }).click();
+ await expect
+ .poll(async () => (await fakeEvents(page)).map((e) => e.data))
+ .toContainEqual({ action: 'invite_link_copied' });
+ await page.getByRole('button', { name: 'Continue' }).click();
await expect(heading(page, 'Free Claude & GPT for 30 days.')).toBeVisible();
await expect(page.getByRole('textbox')).toHaveCount(0);
@@ -86,6 +92,7 @@ test('a deep link survives the inbox OAuth round-trip', async ({ page }) => {
await page.getByRole('button', { name: 'Continue' }).click();
// A work domain must create its team; there is no Skip on this step.
await page.getByRole('button', { name: 'Create team & invite 2' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
await page.getByRole('button', { name: 'Continue with Free' }).last().click();
await expectLanded(page, 'Entered Macro at /channel/launch');
@@ -298,6 +305,35 @@ test('an existing team member just confirms and moves on', async ({ page }) => {
await expect(heading(page, 'Free Claude & GPT for 30 days.')).toBeVisible();
});
+test('a personal address refers friends instead of creating a team', async ({
+ page,
+}) => {
+ await openFixture(page, '/?view=flow', {
+ record: { status: 'active', suggestedTeamDomain: undefined },
+ });
+ await page.evaluate(() => {
+ localStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'team' })
+ );
+ });
+ await page.reload();
+ await expect(heading(page, 'Invite friends.')).toBeVisible();
+ await expect(page.getByText('Workspace name')).toHaveCount(0);
+ await page.getByRole('button', { name: 'Copy referral link' }).click();
+ await page.getByLabel('Friend 1 email').fill('[email protected]');
+ await page.getByRole('button', { name: 'Send 1 invite' }).click();
+ await expect(heading(page, 'Free Claude & GPT for 30 days.')).toBeVisible();
+ const world = await fakeWorld(page);
+ expect(world.teams).toEqual([]);
+ expect((await fakeEvents(page)).map((e) => e.data)).toEqual(
+ expect.arrayContaining([
+ { action: 'referral_link_copied' },
+ { action: 'referrals_sent', invites_sent: 1 },
+ ])
+ );
+});
+
test('staff can bypass onboarding from any step', async ({ page }) => {
await openFixture(page, '/?view=flow', {
viewer: {
diff --git a/apps/web/src/features/onboarding/components/controls.tsx b/apps/web/src/features/onboarding/components/controls.tsx
index f889195a6f..8b6f410f70 100644
--- a/apps/web/src/features/onboarding/components/controls.tsx
+++ b/apps/web/src/features/onboarding/components/controls.tsx
@@ -1,5 +1,5 @@
import ArrowRightIcon from '@icon/system/regular/arrow-right.svg';
-import { onCleanup, onMount } from 'solid-js';
+import { type JSX, onCleanup, onMount } from 'solid-js';
export function FormInput(props: {
id: string;
@@ -66,10 +66,19 @@ export function ContinueButton(props: {
label?: string;
disabled?: boolean;
onClick: () => void;
+ /** A secondary action beside Continue; both stack full width on phones. */
+ secondary?: JSX.Element;
}) {
return (
<div class="mt-6 flex shrink-0 justify-center pb-3">
- <div class="flex justify-center">
+ <div
+ class={
+ props.secondary
+ ? 'flex w-full flex-col-reverse items-stretch gap-3 sm:w-auto sm:flex-row sm:items-center sm:justify-center'
+ : 'flex justify-center'
+ }
+ >
+ {props.secondary}
<button
type="button"
aria-label={props.label ?? 'Continue'}
@@ -85,3 +94,23 @@ export function ContinueButton(props: {
</div>
);
}
+
+/** An outlined action that sits beside Continue (see its `secondary` slot). */
+export function SecondaryButton(props: {
+ label: string;
+ icon?: JSX.Element;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ disabled={props.disabled}
+ onClick={props.onClick}
+ class="flex min-h-14 items-center justify-center gap-2.5 rounded-full border border-edge bg-surface px-7 py-3.5 text-base font-medium text-ink transition-colors hover:bg-ink/5 focus-visible:outline-2 focus-visible:outline-offset-8 focus-visible:outline-ink disabled:opacity-40"
+ >
+ {props.icon}
+ <span>{props.label}</span>
+ </button>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/team-panels.tsx b/apps/web/src/features/onboarding/components/team-panels.tsx
index 65462bff2b..3807af4b6b 100644
--- a/apps/web/src/features/onboarding/components/team-panels.tsx
+++ b/apps/web/src/features/onboarding/components/team-panels.tsx
@@ -1,13 +1,16 @@
import CheckIcon from '@icon/system/regular/check.svg';
+import LinkIcon from '@icon/system/regular/link.svg';
import { Button } from '@ui';
import { For } from 'solid-js';
import type { TeamInvite } from '../context/onboarding-context';
-import { ContinueButton, SkipButton } from './controls';
+import { ContinueButton, SecondaryButton, SkipButton } from './controls';
/** Already on a team — auto-joined by domain, or just created/joined here. */
export function OnTeamPanel(props: {
name: string;
finishing: boolean;
+ copyingLink: boolean;
+ onCopyLink: () => void;
onContinue: () => void;
}) {
return (
@@ -28,6 +31,14 @@ export function OnTeamPanel(props: {
label={props.finishing ? 'Opening your workspace…' : 'Continue'}
disabled={props.finishing}
onClick={props.onContinue}
+ secondary={
+ <SecondaryButton
+ label="Copy invite link"
+ icon={<LinkIcon class="size-5 shrink-0" aria-hidden="true" />}
+ disabled={props.copyingLink || props.finishing}
+ onClick={props.onCopyLink}
+ />
+ }
/>
</div>
);
diff --git a/apps/web/src/features/onboarding/components/team-setup.tsx b/apps/web/src/features/onboarding/components/team-setup.tsx
index 8d59ecb90c..c70e25cf9d 100644
--- a/apps/web/src/features/onboarding/components/team-setup.tsx
+++ b/apps/web/src/features/onboarding/components/team-setup.tsx
@@ -5,7 +5,11 @@ import { isPlausibleEmail, PREFILL_CAP } from '../core/team';
import { FormInput } from './controls';
/** Shared presentation for the public preview and authenticated team setup. */
-export function TeamSetup(props: { children: JSX.Element }) {
+export function TeamSetup(props: {
+ title?: string;
+ subtitle?: string;
+ children: JSX.Element;
+}) {
return (
<section class="mx-auto flex w-full max-w-lg flex-col items-center py-2 sm:py-4">
<header class="flex w-full flex-col items-center text-center">
@@ -13,11 +17,11 @@ export function TeamSetup(props: { children: JSX.Element }) {
tabindex="-1"
class="whitespace-nowrap font-[Roboto_Slab_Variable] text-[clamp(1.75rem,8vw,3rem)] font-[315] leading-[1.12] tracking-tight outline-none"
>
- Built for teams.
+ {props.title ?? 'Built for teams.'}
</h1>
<h2 class="mt-6 max-w-[440px] text-sm font-normal leading-6 text-ink-muted text-balance sm:text-[15px]">
- Bring your team into one workspace. Choose Free or upgrade for more AI
- and storage.
+ {props.subtitle ??
+ 'Bring your team into one workspace. Choose Free or upgrade for more AI and storage.'}
</h2>
</header>
<div class="mt-9 w-full">{props.children}</div>
@@ -30,14 +34,14 @@ export function TeamSetupFields(props: {
name: string;
emails: string[];
disabled?: boolean;
- suggested?: boolean;
+ /** One line above the invite list, e.g. the reward for inviting. */
+ hint?: string;
onNameChange: (value: string) => void;
onEmailChange: (index: number, value: string) => void;
onRemoveEmail: (index: number) => void;
onAddEmail: () => void;
children?: JSX.Element;
}) {
- let inviteList!: HTMLDivElement;
return (
<fieldset
disabled={props.disabled}
@@ -52,63 +56,93 @@ export function TeamSetupFields(props: {
onInput={props.onNameChange}
/>
</label>
- <div class="flex flex-col gap-6 border-t border-edge-muted pt-6">
- <Show when={props.suggested}>
- <p class="-mt-2 text-sm leading-6 text-ink-muted">
- We found a few people at your company. Review the addresses and
- remove anyone you don’t want to invite.
- </p>
- </Show>
- <div ref={inviteList} class="flex flex-col gap-3">
- <Index each={props.emails}>
- {(email, index) => (
- <div class="relative [&_.obf-input]:pr-12">
- <FormInput
- id={`${props.id}-teammate-${index}`}
- label={`Teammate ${index + 1} email`}
- type="email"
- placeholder="[email protected]"
- value={email()}
- invalid={!!email().trim() && !isPlausibleEmail(email())}
- onInput={(value) => props.onEmailChange(index, value)}
- />
- <Show when={email().trim()}>
- <button
- type="button"
- aria-label={`Don't invite ${email().trim()}`}
- class="absolute top-1/2 right-2 flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-ink-extra-muted hover:bg-ink/5 hover:text-ink focus-visible:outline-2 focus-visible:outline-ink"
- onClick={() => props.onRemoveEmail(index)}
- >
- <XIcon class="size-4" aria-hidden="true" />
- </button>
- </Show>
- </div>
- )}
- </Index>
- </div>
- <button
- type="button"
- class="-mt-3 flex self-center items-center gap-2 rounded-full px-3 py-2 text-sm text-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-ink disabled:opacity-40"
- disabled={props.emails.length >= PREFILL_CAP + 1}
- onClick={() => {
- props.onAddEmail();
- inviteList.lastElementChild
- ?.querySelector('input')
- ?.focus({ preventScroll: true });
- inviteList.lastElementChild?.scrollIntoView({
- block: 'nearest',
- behavior: window.matchMedia('(prefers-reduced-motion: reduce)')
- .matches
- ? 'instant'
- : 'smooth',
- });
- }}
- >
- <PlusIcon class="size-4" aria-hidden="true" />
- Add another teammate
- </button>
+ <div class="border-t border-edge-muted pt-6">
+ <InviteEmailList
+ id={props.id}
+ emails={props.emails}
+ hint={props.hint}
+ person="Teammate"
+ placeholder="[email protected]"
+ onEmailChange={props.onEmailChange}
+ onRemoveEmail={props.onRemoveEmail}
+ onAddEmail={props.onAddEmail}
+ />
</div>
{props.children}
</fieldset>
);
}
+
+/** Invite rows with remove buttons and "Add another", for teammates or friends. */
+export function InviteEmailList(props: {
+ id: string;
+ emails: string[];
+ /** One line above the list, e.g. the reward for inviting. */
+ hint?: string;
+ /** Who each row invites: "Teammate" labels rows "Teammate 1 email". */
+ person: string;
+ placeholder: string;
+ onEmailChange: (index: number, value: string) => void;
+ onRemoveEmail: (index: number) => void;
+ onAddEmail: () => void;
+}) {
+ let inviteList!: HTMLDivElement;
+ const rowId = () => props.person.toLowerCase();
+ return (
+ <div class="flex flex-col gap-6">
+ <Show when={props.hint}>
+ {(hint) => (
+ <p class="-mt-2 text-sm leading-6 text-ink-muted">{hint()}</p>
+ )}
+ </Show>
+ <div ref={inviteList} class="flex flex-col gap-3">
+ <Index each={props.emails}>
+ {(email, index) => (
+ <div class="relative [&_.obf-input]:pr-12">
+ <FormInput
+ id={`${props.id}-${rowId()}-${index}`}
+ label={`${props.person} ${index + 1} email`}
+ type="email"
+ placeholder={props.placeholder}
+ value={email()}
+ invalid={!!email().trim() && !isPlausibleEmail(email())}
+ onInput={(value) => props.onEmailChange(index, value)}
+ />
+ <Show when={email().trim()}>
+ <button
+ type="button"
+ aria-label={`Don't invite ${email().trim()}`}
+ class="absolute top-1/2 right-2 flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-ink-extra-muted hover:bg-ink/5 hover:text-ink focus-visible:outline-2 focus-visible:outline-ink"
+ onClick={() => props.onRemoveEmail(index)}
+ >
+ <XIcon class="size-4" aria-hidden="true" />
+ </button>
+ </Show>
+ </div>
+ )}
+ </Index>
+ </div>
+ <button
+ type="button"
+ class="-mt-3 flex self-center items-center gap-2 rounded-full px-3 py-2 text-sm text-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-ink disabled:opacity-40"
+ disabled={props.emails.length >= PREFILL_CAP + 1}
+ onClick={() => {
+ props.onAddEmail();
+ inviteList.lastElementChild
+ ?.querySelector('input')
+ ?.focus({ preventScroll: true });
+ inviteList.lastElementChild?.scrollIntoView({
+ block: 'nearest',
+ behavior: window.matchMedia('(prefers-reduced-motion: reduce)')
+ .matches
+ ? 'instant'
+ : 'smooth',
+ });
+ }}
+ >
+ <PlusIcon class="size-4" aria-hidden="true" />
+ Add another {props.person.toLowerCase()}
+ </button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/context/onboarding-context.tsx b/apps/web/src/features/onboarding/context/onboarding-context.tsx
index 3462b92e4b..96ae26186c 100644
--- a/apps/web/src/features/onboarding/context/onboarding-context.tsx
+++ b/apps/web/src/features/onboarding/context/onboarding-context.tsx
@@ -124,6 +124,19 @@ export type OnboardingContext = {
}): Promise<void>;
/** Rejects on failure; the capability reports its own errors. */
joinTeam(inviteId: string): Promise<void>;
+ /**
+ * Copies the viewer's team invite link, creating the link when the team has
+ * none. Rejects on failure; the capability reports its own result.
+ */
+ copyTeamInviteLink(): Promise<void>;
+ /**
+ * Sends a referral invite to each address; no team is involved. Rejects
+ * when none was sent; the capability reports its own result.
+ */
+ sendReferralInvites(emails: string[]): Promise<void>;
+ /** Copies the viewer's referral sign-up link. Rejects on failure; the
+ * capability reports its own result. */
+ copyReferralLink(): Promise<void>;
/** The invite promotion the account holds; null when it has none. */
createInviteOffer(): Accessor<Loadable<InviteOffer | null>>;
createTrialEligibility(): {
diff --git a/apps/web/src/features/onboarding/create-app-onboarding-context.ts b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
index 19f2f7493b..f0492ab975 100644
--- a/apps/web/src/features/onboarding/create-app-onboarding-context.ts
+++ b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
@@ -1,11 +1,15 @@
import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
+import { teamInviteLinkUrl } from '@app/features/settings/TeamInviteLinkSection';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { toast } from '@core/component/Toast/Toast';
import { SERVER_HOSTS } from '@core/constant/servers';
import { deriveIsAuthenticated } from '@core/context/user';
import { useAddInboxFlow } from '@core/email-link';
import { idToDisplayName, idToEmail } from '@core/user/util';
+import { writeClipboardData } from '@core/util/dataTransfer';
import { fireAndForget } from '@core/util/fireAndForget';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { Telemetry } from '@macro-inc/observability';
import {
useAiBillingPlansQuery,
useCreateBillingPortalMutation,
@@ -15,6 +19,7 @@ import {
} from '@queries/auth';
import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
import { type UserInfoData, useUserInfoQuery } from '@queries/auth/user-info';
+import { queryClient } from '@queries/client';
import { useContactsQuery } from '@queries/contacts/contacts';
import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';
import { queryReadyGate } from '@queries/gate';
@@ -30,8 +35,14 @@ import {
useJoinTeamMutation,
useUserInvitesQuery,
} from '@queries/team/invitations';
+import {
+ fetchTeamInviteLinkToken,
+ useCreateTeamInviteLinkMutation,
+} from '@queries/team/invite-link';
+import { useSendReferralInvitesMutation } from '@queries/team/referrals';
import {
useCreateTeamWithInvitesMutation,
+ userTeamsQueryOptions,
useUserTeamsQuery,
} from '@queries/team/teams';
import { applyWorkspaceAccent } from './apply-workspace-accent';
@@ -59,6 +70,58 @@ type UserInfoResult = {
data: UserInfoData | undefined;
};
+/** Copies `text`, confirming either way; rejects when nothing was copied. */
+async function copyLink(text: string, copied: string, failed: string) {
+ if (await writeClipboardData({ 'text/plain': text })) {
+ toast.success(copied);
+ return;
+ }
+ toast.failure(failed);
+ throw new Error(failed);
+}
+
+async function linkUrl(token: Promise<string>) {
+ return teamInviteLinkUrl(await token);
+}
+
+async function textBlob(text: Promise<string>) {
+ return new Blob([await text], { type: 'text/plain' });
+}
+
+/**
+ * Copies text that is still loading. The clipboard write starts before the
+ * text resolves so it keeps the click's user activation.
+ */
+async function copyPendingText(text: Promise<string>): Promise<boolean> {
+ const clipboard = navigator.clipboard;
+ if (!clipboard) return false;
+ if (typeof ClipboardItem !== 'undefined' && clipboard.write) {
+ const write = clipboard.write([
+ new ClipboardItem({ 'text/plain': textBlob(text) }),
+ ]);
+ try {
+ await write;
+ return true;
+ } catch {
+ // Fall through to writeText once the text is known.
+ }
+ }
+ try {
+ return await writeClipboardData({ 'text/plain': await text });
+ } catch {
+ return false;
+ }
+}
+
+/** The created team's id, or undefined when creation failed. */
+async function createdTeamId(creation: Promise<{ id: string }>) {
+ try {
+ return (await creation).id;
+ } catch {
+ return undefined;
+ }
+}
+
function toViewerState(result: UserInfoResult): ViewerState {
// Guarded: an unguarded `data` read suspends while the query is pending.
const data = queryReadyGate(result) ? result.data : undefined;
@@ -95,6 +158,27 @@ export function createAppOnboardingContext(): OnboardingContext {
const completeOnboarding = useCompleteOnboardingMutation();
const completeTutorial = useCompleteTutorialMutation();
const connectTool = createOnboardingToolConnect();
+ const createInviteLink = useCreateTeamInviteLinkMutation();
+ const sendReferrals = useSendReferralInvitesMutation();
+ // A team created on this step: its optimistic placeholder is in the teams
+ // cache until creation settles, so the invite link waits for the real id.
+ let createdTeam: Promise<string | undefined> | undefined;
+
+ const currentTeamId = async () =>
+ (await createdTeam) ??
+ (await queryClient.fetchQuery(userTeamsQueryOptions()))[0]?.id;
+
+ /** The team's link token, creating the link when the team has none. Only
+ * admins and owners may create one; the mutation reports that failure. */
+ const teamInviteLinkToken = () =>
+ Telemetry.span('onboarding.team_invite_link', async (span) => {
+ const teamId = await currentTeamId();
+ if (!teamId) throw new Error('Not on a team');
+ span.setAttr('team.id', teamId);
+ const existing = await fetchTeamInviteLinkToken(teamId);
+ span.setAttr('invite_link.created', existing === null);
+ return existing ?? (await createInviteLink.mutateAsync({ teamId }));
+ });
const viewer = () => toViewerState(userInfo);
const needsOnboarding = () => {
@@ -218,15 +302,53 @@ export function createAppOnboardingContext(): OnboardingContext {
};
},
createTeam: async ({ name, invites, allowDomainJoin }) => {
- await createTeam.mutateAsync({
+ const creation = createTeam.mutateAsync({
name,
invites: invites.map((email) => ({ email })),
allowDomainJoin,
});
+ createdTeam = createdTeamId(creation);
+ await creation;
},
joinTeam: async (inviteId) => {
await joinTeam.mutateAsync({ teamInviteId: inviteId });
},
+ copyTeamInviteLink: async () => {
+ const url = linkUrl(teamInviteLinkToken());
+ // Start the write inside the click; Safari drops it after an await.
+ const copied = copyPendingText(url);
+ try {
+ await url;
+ } catch (error) {
+ if (!createInviteLink.isError)
+ toast.failure("Couldn't get your team's invite link");
+ throw error;
+ }
+ if (await copied) {
+ toast.success('Invite link copied');
+ return;
+ }
+ toast.failure('Could not copy invite link');
+ throw new Error('Could not copy invite link');
+ },
+ sendReferralInvites: async (emails) => {
+ const { sent } = await sendReferrals.mutateAsync(emails);
+ if (sent.length === 0) throw new Error('No referral invites were sent');
+ },
+ copyReferralLink: async () => {
+ const code = queryReadyGate(userInfo)
+ ? userInfo.data.referralCode
+ : undefined;
+ if (!code) {
+ toast.failure("Your referral link isn't ready yet");
+ throw new Error('No referral code');
+ }
+ await copyLink(
+ `${getWebOrigin()}/app/signup?referral_code=${code}`,
+ 'Referral link copied',
+ 'Failed to copy link'
+ );
+ },
createInviteOffer: () => {
const query = useGtmInviteOfferQuery({ enabled: needsOnboarding });
diff --git a/apps/web/src/features/onboarding/primitives/team-step.ts b/apps/web/src/features/onboarding/primitives/team-step.ts
index ecbd7fa9a3..8cf696a2d9 100644
--- a/apps/web/src/features/onboarding/primitives/team-step.ts
+++ b/apps/web/src/features/onboarding/primitives/team-step.ts
@@ -69,7 +69,12 @@ export function createTeamStep(
}
/** The create form's prefill, once contacts and the domain suggestion settle. */
-export type TeamFormSeed = { domain: string | undefined; prefilled: string[] };
+export type TeamFormSeed = {
+ domain: string | undefined;
+ /** The record loaded without a work domain: show referrals, not a team form. */
+ personal: boolean;
+ prefilled: string[];
+};
export function teamFormSeed(input: {
record: Loadable<OnboardingRecord>;
@@ -84,6 +89,7 @@ export function teamFormSeed(input: {
: undefined;
return {
domain,
+ personal: input.record.t === 'ready' && !domain,
prefilled: prefillableTeammates({
contacts: input.contacts.t === 'ready' ? input.contacts.value : [],
domain,
@@ -92,6 +98,21 @@ export function teamFormSeed(input: {
};
}
+/** Invite rows a user edits; at least one row always remains. */
+function createInviteSlots(initial: string[]) {
+ const [slots, setSlots] = createSignal<string[]>(initial);
+ return {
+ slots,
+ setSlot: (index: number, value: string) =>
+ setSlots((current) =>
+ current.map((slot, i) => (i === index ? value : slot))
+ ),
+ removeSlot: (index: number) =>
+ setSlots((current) => removeInviteSlot(current, index)),
+ addSlot: () => setSlots((current) => [...current, '']),
+ };
+}
+
/**
* The create-team form, initialized once from its seed so the name and invite
* rows stay user-owned. Same-domain teammates are pre-added rather than
@@ -100,12 +121,12 @@ export function teamFormSeed(input: {
export function createTeamForm(
context: Pick<OnboardingContext, 'createTeam' | 'track'>,
seed: TeamFormSeed,
- options: { ownEmail: string | undefined; onCreated: () => void }
+ options: { ownEmail: string | undefined }
) {
const [name, setName] = createSignal(
seed.domain ? deriveTeamName(seed.domain) : ''
);
- const [slots, setSlots] = createSignal<string[]>(
+ const rows = createInviteSlots(
seed.prefilled.length > 0 ? [...seed.prefilled, ''] : ['', '']
);
const [pending, setPending] = createSignal(false);
@@ -113,7 +134,7 @@ export function createTeamForm(
const [allowDomainJoin, setAllowDomainJoin] = createSignal(true);
const domainJoin = () => seed.domain !== undefined && allowDomainJoin();
- const invites = () => validInviteEmails(slots(), options.ownEmail);
+ const invites = () => validInviteEmails(rows.slots(), options.ownEmail);
const canCreate = () => name().trim().length > 0 && !pending();
const create = async () => {
@@ -142,20 +163,12 @@ export function createTeamForm(
used_domain_suggestion: seed.domain !== undefined,
allow_domain_join: domainJoin(),
});
- options.onCreated();
};
return {
name,
setName,
- slots,
- setSlot: (index: number, value: string) =>
- setSlots((current) =>
- current.map((slot, i) => (i === index ? value : slot))
- ),
- removeSlot: (index: number) =>
- setSlots((current) => removeInviteSlot(current, index)),
- addSlot: () => setSlots((current) => [...current, '']),
+ ...rows,
invites,
pending,
canCreate,
@@ -163,7 +176,77 @@ export function createTeamForm(
domain: seed.domain,
allowDomainJoin,
setAllowDomainJoin,
- suggested: seed.prefilled.length > 0,
create,
};
}
+
+/**
+ * Referral invites for a personal address: no team is created; each person
+ * who signs up earns the inviter AI credit.
+ */
+export function createReferralForm(
+ context: Pick<
+ OnboardingContext,
+ 'sendReferralInvites' | 'copyReferralLink' | 'track'
+ >,
+ options: { ownEmail: string | undefined; onSent: () => void }
+) {
+ const rows = createInviteSlots(['', '']);
+ const [sending, setSending] = createSignal(false);
+ const [copying, setCopying] = createSignal(false);
+ const invites = () => validInviteEmails(rows.slots(), options.ownEmail);
+
+ const send = async () => {
+ const sent = invites();
+ if (sending() || sent.length === 0) return;
+ setSending(true);
+ try {
+ await context.sendReferralInvites(sent);
+ } catch {
+ // The capability reports its own failure; keep the addresses.
+ return;
+ } finally {
+ setSending(false);
+ }
+ context.track('onboarding_v4_team', {
+ action: 'referrals_sent',
+ invites_sent: sent.length,
+ });
+ options.onSent();
+ };
+
+ const copyLink = async () => {
+ if (copying()) return;
+ setCopying(true);
+ try {
+ await context.copyReferralLink();
+ context.track('onboarding_v4_team', { action: 'referral_link_copied' });
+ } catch {
+ // The capability reports its own failure.
+ } finally {
+ setCopying(false);
+ }
+ };
+
+ return { ...rows, invites, sending, send, copying, copyLink };
+}
+
+/** Copies the team's invite link from the on-team confirmation. */
+export function createTeamInviteLinkCopy(
+ context: Pick<OnboardingContext, 'copyTeamInviteLink' | 'track'>
+) {
+ const [copying, setCopying] = createSignal(false);
+ const copy = async () => {
+ if (copying()) return;
+ setCopying(true);
+ try {
+ await context.copyTeamInviteLink();
+ context.track('onboarding_v4_team', { action: 'invite_link_copied' });
+ } catch {
+ // The capability reports its own failure.
+ } finally {
+ setCopying(false);
+ }
+ };
+ return { copying, copy };
+}
diff --git a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
index b25107f4ec..6fd04fdb21 100644
--- a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
+++ b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
@@ -55,10 +55,14 @@ export type FakeOnboardingWorld = {
failures: Partial<
Record<
| 'emailAccounts'
+ | 'record'
| 'teams'
| 'catalog'
| 'createTeam'
| 'joinTeam'
+ | 'teamInviteLink'
+ | 'referralInvites'
+ | 'referralLink'
| 'planCatalog'
| 'trialEligibility'
| 'checkout'
@@ -206,8 +210,7 @@ export function createFakeOnboarding(
});
return viewerState();
},
- createOnboardingRecord: () => () =>
- settled() ? { t: 'ready', value: world.record } : { t: 'loading' },
+ createOnboardingRecord: () => () => loadable('record', () => world.record),
createEmailAccounts: () => ({
accounts: () => loadable('emailAccounts', () => world.emailAccounts),
refresh: async () => {},
@@ -323,6 +326,18 @@ export function createFakeOnboarding(
if (invite) draft.teams = [{ name: `${invite.invitedBy}'s team` }];
});
},
+ copyTeamInviteLink: async () => {
+ call('copyTeamInviteLink');
+ fail('teamInviteLink');
+ },
+ sendReferralInvites: async (emails) => {
+ call(`sendReferralInvites:${emails.join(',')}`);
+ fail('referralInvites');
+ },
+ copyReferralLink: async () => {
+ call('copyReferralLink');
+ fail('referralLink');
+ },
createInviteOffer: () => () => ({ t: 'ready', value: world.inviteOffer }),
createTrialEligibility: () => ({
eligibility: () =>
diff --git a/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
index 2a75e6f131..1811717a45 100644
--- a/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
+++ b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
@@ -95,11 +95,11 @@ describe('onboarding flow', () => {
expect(screen.getByDisplayValue('Acme')).toBeTruthy();
expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();
click('Create team & invite 2');
- await waitFor(() =>
- expect(fake.calls()).toContain(
- )
+ await screen.findByText("You're on Acme");
+ expect(fake.calls()).toContain(
);
+ click('Continue');
await heading('Free Claude & GPT for 30 days.');
fireEvent.click(
@@ -144,7 +144,7 @@ describe('onboarding flow', () => {
expect(screen.queryByRole('button', { name: 'Skip for now' })).toBeNull();
const domainJoin = screen.getByRole('switch', {
- name: 'Allow @acme.com emails to join',
+ name: /^Allow @acme.com emails to join/,
});
expect((domainJoin as HTMLInputElement).checked).toBe(true);
@@ -157,14 +157,150 @@ describe('onboarding flow', () => {
);
});
- it('lets personal-domain accounts skip the team without a domain switch', async () => {
- setup({
+ it('shows the created team with its invite link before continuing', async () => {
+ const { fake } = setup({ resume: 'team' });
+ await heading('Built for teams.');
+ click('Create team & invite 2');
+ await screen.findByText("You're on Acme");
+ expect(fake.world.teams).toEqual([{ name: 'Acme' }]);
+
+ click('Copy invite link');
+ await waitFor(() =>
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'invite_link_copied' },
+ })
+ );
+ expect(fake.calls()).toContain('copyTeamInviteLink');
+ expect(fake.events()).toContainEqual(
+ expect.objectContaining({
+ event: 'onboarding_v4_team',
+ data: expect.objectContaining({ action: 'created', invites_sent: 2 }),
+ })
+ );
+
+ click('Continue');
+ await heading('Free Claude & GPT for 30 days.');
+ });
+
+ it('keeps the on-team panel when copying the invite link fails', async () => {
+ const { fake } = setup({
+ resume: 'team',
+ world: {
+ teams: [{ name: 'Acme' }],
+ failures: { teamInviteLink: 'Not an admin' },
+ },
+ });
+ await screen.findByText("You're on Acme");
+ click('Copy invite link');
+ await waitFor(() => expect(fake.calls()).toContain('copyTeamInviteLink'));
+ expect(fake.events().map((e) => e.data)).not.toContainEqual({
+ action: 'invite_link_copied',
+ });
+ expect(
+ screen
+ .getByRole('button', { name: 'Copy invite link' })
+ .hasAttribute('disabled')
+ ).toBe(false);
+ });
+
+ it('offers personal addresses referrals instead of a team', async () => {
+ const { fake } = setup({
resume: 'team',
world: { record: { status: 'active', suggestedTeamDomain: undefined } },
});
- await heading('Built for teams.');
- await screen.findByRole('button', { name: 'Skip for now' });
+ await heading('Invite friends.');
+ expect(
+ screen.getByText('Get $10 of AI credit for each person who signs up.')
+ ).toBeTruthy();
+ expect(screen.queryByText('Workspace name')).toBeNull();
expect(screen.queryByRole('switch')).toBeNull();
+ const send = screen.getByRole('button', { name: 'Send invites' });
+ expect(send.hasAttribute('disabled')).toBe(true);
+
+ click('Copy referral link');
+ await waitFor(() =>
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'referral_link_copied' },
+ })
+ );
+ expect(fake.calls()).toContain('copyReferralLink');
+
+ fireEvent.input(screen.getByLabelText('Friend 1 email'), {
+ target: { value: '[email protected]' },
+ });
+ fireEvent.input(screen.getByLabelText('Friend 2 email'), {
+ target: { value: '[email protected]' },
+ });
+ click('Send 2 invites');
+
+ await heading('Free Claude & GPT for 30 days.');
+ expect(fake.calls()).toContain(
+ 'sendReferralInvites:[email protected],[email protected]'
+ );
+ expect(fake.calls().some((c) => c.startsWith('createTeam'))).toBe(false);
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'referrals_sent', invites_sent: 2 },
+ });
+ });
+
+ it('keeps the referral addresses when no invite could be sent', async () => {
+ const { fake } = setup({
+ resume: 'team',
+ world: {
+ record: { status: 'active', suggestedTeamDomain: undefined },
+ failures: { referralInvites: 'Send failed' },
+ },
+ });
+ await heading('Invite friends.');
+ fireEvent.input(screen.getByLabelText('Friend 1 email'), {
+ target: { value: '[email protected]' },
+ });
+ click('Send 1 invite');
+ await waitFor(() =>
+ expect(fake.calls()).toContain('sendReferralInvites:[email protected]')
+ );
+ await screen.findByRole('button', { name: 'Send 1 invite' });
+ expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();
+ expect(
+ screen.getByRole('heading', { level: 1, name: 'Invite friends.' })
+ ).toBeTruthy();
+ });
+
+ it('keeps the team form when the onboarding record fails to load', async () => {
+ setup({
+ resume: 'team',
+ world: {
+ record: { status: 'active', suggestedTeamDomain: undefined },
+ failures: { record: 'Read failed' },
+ },
+ });
+ await heading('Built for teams.');
+ expect(screen.queryByText('Invite friends.')).toBeNull();
+ expect(screen.getByText('Workspace name')).toBeTruthy();
+ });
+
+ it('lets personal addresses skip referrals', async () => {
+ const { fake } = setup({
+ resume: 'team',
+ world: { record: { status: 'active', suggestedTeamDomain: undefined } },
+ });
+ await heading('Invite friends.');
+ click('Skip for now');
+ await heading('Free Claude & GPT for 30 days.');
+ expect(fake.calls().some((c) => c.startsWith('sendReferralInvites'))).toBe(
+ false
+ );
+ expect(
+ fake
+ .events()
+ .filter((e) => e.event === 'onboarding_v4_step')
+ .map((e) => e.data)
+ ).toContainEqual(
+ expect.objectContaining({ step: 'team', state: 'skipped' })
+ );
});
it('opens a step link on that step and records it as the entry', async () => {
diff --git a/apps/web/src/features/onboarding/views/team-step.tsx b/apps/web/src/features/onboarding/views/team-step.tsx
index 308e789567..2e093374bd 100644
--- a/apps/web/src/features/onboarding/views/team-step.tsx
+++ b/apps/web/src/features/onboarding/views/team-step.tsx
@@ -1,25 +1,37 @@
import { fireAndForget } from '@core/util/fireAndForget';
+import LinkIcon from '@icon/system/regular/link.svg';
import { ToggleSwitch } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
-import { ContinueButton, SkipButton } from '../components/controls';
+import {
+ ContinueButton,
+ SecondaryButton,
+ SkipButton,
+} from '../components/controls';
import {
InvitesPanel,
OnTeamPanel,
TeamLoadError,
TeamStatus,
} from '../components/team-panels';
-import { TeamSetup, TeamSetupFields } from '../components/team-setup';
+import {
+ InviteEmailList,
+ TeamSetup,
+ TeamSetupFields,
+} from '../components/team-setup';
import { useOnboardingContext } from '../context/onboarding-context';
import {
+ createReferralForm,
createTeamForm,
+ createTeamInviteLinkCopy,
createTeamStep,
type TeamFormSeed,
teamFormSeed,
} from '../primitives/team-step';
-/** Set up your team: already a member → confirmation, pending invites →
- * join, otherwise create (with a domain-derived name and same-domain
- * teammates pre-added to the invite list). */
+/** Set up your team: already a member → confirmation with the team's invite
+ * link, pending invites → join, a work domain → create (with a domain-derived
+ * name and same-domain teammates pre-added to the invite list), and a
+ * personal address → refer friends instead of creating a team. */
export function TeamStep(props: {
finishing: boolean;
onContinue: () => void;
@@ -46,8 +58,22 @@ export function TeamStep(props: {
})
);
+ const inviteLink = createTeamInviteLinkCopy(context);
+ // A personal address has no team to create; it refers friends instead.
+ const referring = () => {
+ const ready = seed();
+ return team.state().t === 'create' && ready !== undefined && ready.personal;
+ };
+
return (
- <TeamSetup>
+ <TeamSetup
+ title={referring() ? 'Invite friends.' : undefined}
+ subtitle={
+ referring()
+ ? 'Get $10 of AI credit for each person who signs up.'
+ : undefined
+ }
+ >
<Switch>
<Match when={team.state().t === 'error'}>
<TeamLoadError onRetry={team.retry} />
@@ -60,6 +86,8 @@ export function TeamStep(props: {
<OnTeamPanel
name={name}
finishing={props.finishing}
+ copyingLink={inviteLink.copying()}
+ onCopyLink={() => fireAndForget(inviteLink.copy(), 'onboarding')}
onContinue={props.onContinue}
/>
)}
@@ -80,13 +108,23 @@ export function TeamStep(props: {
fallback={<TeamStatus message="Finding your teammates…" />}
>
{(ready) => (
- <TeamForm
- finishing={props.finishing}
- seed={ready()}
- ownEmail={ownEmail()}
- onContinue={props.onContinue}
- onSkip={props.onSkip}
- />
+ <Show
+ when={!ready().personal}
+ fallback={
+ <ReferralForm
+ finishing={props.finishing}
+ ownEmail={ownEmail()}
+ onContinue={props.onContinue}
+ onSkip={props.onSkip}
+ />
+ }
+ >
+ <TeamForm
+ finishing={props.finishing}
+ seed={ready()}
+ ownEmail={ownEmail()}
+ />
+ </Show>
)}
</Show>
</Match>
@@ -103,17 +141,16 @@ const pendingInvites = (
state: ReturnType<ReturnType<typeof createTeamStep>['state']>
) => (state.t === 'invites' ? state.invites : undefined);
+/** Creating the team switches the step to the on-team confirmation, where
+ * the creator can copy the team's invite link before continuing. */
function TeamForm(props: {
finishing: boolean;
seed: TeamFormSeed;
ownEmail: string | undefined;
- onContinue: () => void;
- onSkip: () => void;
}) {
const context = useOnboardingContext();
const form = createTeamForm(context, props.seed, {
ownEmail: props.ownEmail,
- onCreated: props.onContinue,
});
return (
<div class="flex flex-col gap-3">
@@ -122,7 +159,7 @@ function TeamForm(props: {
name={form.name()}
emails={form.slots()}
disabled={form.pending() || props.finishing}
- suggested={form.suggested}
+ hint="Invite teammates now for $10 AI credit each"
onNameChange={form.setName}
onEmailChange={form.setSlot}
onRemoveEmail={form.removeSlot}
@@ -132,13 +169,16 @@ function TeamForm(props: {
{(domain) => (
<ToggleSwitch
size="md"
- class="w-full gap-3 border-t border-edge-muted pt-6"
+ class="w-full flex-row-reverse justify-between gap-2 border-t border-edge-muted pt-6"
controlClass="shrink-0"
checked={form.allowDomainJoin()}
onChange={form.setAllowDomainJoin}
label={
- <span class="text-sm text-ink">
+ <span class="text-xs text-ink sm:text-sm">
Allow @{domain()} emails to join
+ <span class="ml-1 whitespace-nowrap rounded bg-ink/5 px-1 py-0.5 text-[10px] text-ink-muted sm:ml-2 sm:px-1.5 sm:text-xs">
+ recommended
+ </span>
</span>
}
/>
@@ -158,13 +198,63 @@ function TeamForm(props: {
disabled={!form.canCreate() || props.finishing}
onClick={() => fireAndForget(form.create(), 'onboarding')}
/>
- {/* A work domain always gets a team; only personal addresses may skip. */}
- <Show when={!form.domain}>
- <SkipButton
- disabled={form.pending() || props.finishing}
- onClick={props.onSkip}
+ </div>
+ );
+}
+
+function ReferralForm(props: {
+ finishing: boolean;
+ ownEmail: string | undefined;
+ onContinue: () => void;
+ onSkip: () => void;
+}) {
+ const context = useOnboardingContext();
+ const form = createReferralForm(context, {
+ ownEmail: props.ownEmail,
+ onSent: props.onContinue,
+ });
+ const count = () => form.invites().length;
+ return (
+ <div class="flex flex-col gap-3">
+ <fieldset
+ disabled={form.sending() || props.finishing}
+ class="flex min-w-0 flex-col gap-6 text-left"
+ >
+ <InviteEmailList
+ id="referral"
+ emails={form.slots()}
+ person="Friend"
+ placeholder="[email protected]"
+ onEmailChange={form.setSlot}
+ onRemoveEmail={form.removeSlot}
+ onAddEmail={form.addSlot}
/>
- </Show>
+ </fieldset>
+ <ContinueButton
+ label={
+ props.finishing
+ ? 'Opening your workspace…'
+ : form.sending()
+ ? 'Sending invites…'
+ : count() === 0
+ ? 'Send invites'
+ : `Send ${count()} ${count() === 1 ? 'invite' : 'invites'}`
+ }
+ disabled={count() === 0 || form.sending() || props.finishing}
+ onClick={() => fireAndForget(form.send(), 'onboarding')}
+ secondary={
+ <SecondaryButton
+ label="Copy referral link"
+ icon={<LinkIcon class="size-5 shrink-0" aria-hidden="true" />}
+ disabled={form.copying() || props.finishing}
+ onClick={() => fireAndForget(form.copyLink(), 'onboarding')}
+ />
+ }
+ />
+ <SkipButton
+ disabled={form.sending() || props.finishing}
+ onClick={props.onSkip}
+ />
</div>
);
}
diff --git a/apps/web/src/features/team-invitations/invite-modal.tsx b/apps/web/src/features/team-invitations/invite-modal.tsx
index b22745d9c2..1ee2cb045c 100644
--- a/apps/web/src/features/team-invitations/invite-modal.tsx
+++ b/apps/web/src/features/team-invitations/invite-modal.tsx
@@ -1,12 +1,10 @@
import { toast } from '@core/component/Toast/Toast';
import { useReferralCode } from '@core/context/user';
-import { fireAndForget } from '@core/util/fireAndForget';
import { getWebOrigin } from '@core/util/webOrigin';
import ClipboardIcon from '@icon/system/regular/clipboard.svg';
import CloseIcon from '@icon/system/regular/x.svg';
import { Telemetry } from '@macro-inc/observability';
-import { authServiceClient } from '@service-auth/client';
-import { contactsClient } from '@service-contacts/client';
+import { useSendReferralInvitesMutation } from '@queries/team/referrals';
import { Button, Dialog, Input, Panel } from '@ui';
import { createSignal, Show } from 'solid-js';
@@ -17,15 +15,6 @@ function parseEmails(raw: string): string[] {
.filter((s) => s.includes('@'));
}
-async function addInvitedContact(email: string) {
- const result = await contactsClient.addContact(
- `macro|${email.toLowerCase()}`
- );
- if (result.isErr()) {
- Telemetry.error(result.error, { surface: 'team-invitations' });
- }
-}
-
const [inviteModalOpen, setInviteModalOpen] = createSignal(false);
export { setInviteModalOpen };
@@ -33,7 +22,8 @@ export { setInviteModalOpen };
export const InviteModal = () => {
const [value, setValue] = createSignal('');
const [copied, setCopied] = createSignal(false);
- const [sending, setSending] = createSignal(false);
+ const sendInvites = useSendReferralInvitesMutation();
+ const sending = () => sendInvites.isPending;
const referralCode = useReferralCode();
const referralUrl = () => {
@@ -60,20 +50,8 @@ export const InviteModal = () => {
const handleSend = async () => {
const emails = parseEmails(value());
if (!emails.length) return;
- setSending(true);
- for (const email of emails) {
- const result = await authServiceClient.sendReferralInvite(email);
- if (result.isOk()) {
- fireAndForget(addInvitedContact(email), 'team-invitations');
- }
- }
+ await sendInvites.mutateAsync(emails);
setValue('');
- setSending(false);
- toast.success(
- emails.length === 1
- ? 'Invite sent successfully'
- : `${emails.length} invites sent successfully`
- );
setInviteModalOpen(false);
};
@@ -96,7 +74,7 @@ export const InviteModal = () => {
<Panel.Body scroll class="p-3 flex flex-col gap-3">
<p>
- Invite friends and teammates to Macro. You'll get $100 in credits
+ Invite friends and teammates to Macro. You'll get $10 of AI credit
for each person who signs up.
</p>
<div class="flex flex-col gap-2">
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index fc5e75a6cf..0161c9bec8 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -96,7 +96,13 @@ export type AppEvents = {
onboarding_v4_connector_connected: { connector: string };
/** What happened on the team step. */
onboarding_v4_team: {
- action: 'created' | 'joined_invite' | 'already_on_team';
+ action:
+ | 'created'
+ | 'joined_invite'
+ | 'already_on_team'
+ | 'invite_link_copied'
+ | 'referrals_sent'
+ | 'referral_link_copied';
invites_sent?: number;
/** Same-domain teammates the step pre-added to the invite list. */
invites_prefilled?: number;
diff --git a/apps/web/src/lib/queries/team/invite-link.ts b/apps/web/src/lib/queries/team/invite-link.ts
index 40bedb6150..725136236a 100644
--- a/apps/web/src/lib/queries/team/invite-link.ts
+++ b/apps/web/src/lib/queries/team/invite-link.ts
@@ -29,6 +29,14 @@ export function useTeamInviteLinkQuery(
return useQuery(() => teamInviteLinkQueryOptions(teamId(), enabled()));
}
+/** The team's invite link token, from the cache when fresh; null when none. */
+export async function fetchTeamInviteLinkToken(teamId: string) {
+ const link = await queryClient.fetchQuery(
+ teamInviteLinkQueryOptions(teamId, true)
+ );
+ return link.token ?? null;
+}
+
function setTeamInviteLink(teamId: string, token: string | null) {
queryClient.setQueryData<TeamInviteLinkResponse>(
teamKeys.inviteLink(teamId).queryKey,
diff --git a/apps/web/src/lib/queries/team/referrals.ts b/apps/web/src/lib/queries/team/referrals.ts
new file mode 100644
index 0000000000..0536496eb4
--- /dev/null
+++ b/apps/web/src/lib/queries/team/referrals.ts
@@ -0,0 +1,60 @@
+import { toast } from '@core/component/Toast/Toast';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import { authServiceClient } from '@service-auth/client';
+import { contactsClient } from '@service-contacts/client';
+import { useMutation } from '@tanstack/solid-query';
+
+async function addInvitedContact(email: string) {
+ const result = await contactsClient.addContact(
+ `macro|${email.toLowerCase()}`
+ );
+ if (result.isErr()) {
+ Telemetry.error(result.error, { surface: 'team-invitations' });
+ }
+}
+
+/** Which addresses got a referral invite and which could not be invited. */
+export type ReferralInvitesResult = { sent: string[]; failed: string[] };
+
+/**
+ * One request per address, so one failed address doesn't stop the rest. Each
+ * invited address is added to the sender's contacts.
+ */
+function sendReferralInvites(emails: string[]): Promise<ReferralInvitesResult> {
+ return Telemetry.span('referral.send_invites', async (span) => {
+ span.setAttr('referral.invite_count', emails.length);
+ const sent: string[] = [];
+ const failed: string[] = [];
+ for (const email of emails) {
+ const result = await authServiceClient.sendReferralInvite(email);
+ if (result.isOk()) {
+ sent.push(email);
+ fireAndForget(addInvitedContact(email), 'team-invitations');
+ } else {
+ failed.push(email);
+ }
+ }
+ span.setAttr('referral.failed_count', failed.length);
+ return { sent, failed };
+ });
+}
+
+/** Sends referral invites and reports the outcome with a toast. */
+export function useSendReferralInvitesMutation() {
+ return useMutation(() => ({
+ mutationFn: sendReferralInvites,
+ onSuccess: ({ sent, failed }: ReferralInvitesResult) => {
+ if (sent.length > 0) {
+ toast.success(
+ sent.length === 1
+ ? 'Invite sent successfully'
+ : `${sent.length} invites sent successfully`
+ );
+ }
+ if (failed.length > 0) {
+ toast.failure(`Couldn't invite ${failed.join(', ')}`);
+ }
+ },
+ }));
+}
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index 3e1454b53b..e6fc7821e0 100644
--- a/apps/web/src/lib/queries/team/teams.ts
+++ b/apps/web/src/lib/queries/team/teams.ts
@@ -17,7 +17,7 @@ import { TeamRole } from '@service-auth/generated/schemas/teamRole';
import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';
import type { ToggleAutoJoinDomainResponse } from '@service-auth/generated/schemas/toggleAutoJoinDomainResponse';
import type { ToggleNonAdminInvitesResponse } from '@service-auth/generated/schemas/toggleNonAdminInvitesResponse';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { authKeys } from '../auth';
import { queryClient } from '../client';
@@ -33,11 +33,14 @@ function fetchTeam() {
return throwOnErr(() => authServiceClient.getTeam());
}
-export function useUserTeamsQuery() {
- return useQuery(() => ({
+export const userTeamsQueryOptions = () =>
+ queryOptions({
queryKey: teamKeys.userTeams.queryKey,
queryFn: fetchUserTeams,
- }));
+ });
+
+export function useUserTeamsQuery() {
+ return useQuery(userTeamsQueryOptions);
}
export function useTeamQuery(teamId: Accessor<string>) {
diff --git a/crates/ai_billing/AGENTS.md b/crates/ai_billing/AGENTS.md
index 7811674aac..8a646dc9e4 100644
--- a/crates/ai_billing/AGENTS.md
+++ b/crates/ai_billing/AGENTS.md
@@ -18,6 +18,9 @@ provider cost (plus markup for overage).
- `src/domain/ledger.rs` + `src/domain/sweep.rs`: the credit/overage ledger
and the settlement sweep.
- `src/outbound/stripe_gateway.rs`: the only place Stripe is called.
+- `src/domain/invite_reward.rs`: the invite/referral reward — $10 prepaid
+ credit for a paid user's payer, or +$10 monthly free allowance (capped at
+ +$50, table `ai_free_allowance_bonus`) for a free user.
## Scope
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index 162b5cce7b..0fc553f41b 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -4,6 +4,7 @@
pub mod admission;
pub mod credit_grant;
pub mod financial;
+pub mod invite_reward;
pub mod ledger;
pub mod models;
pub mod period;
@@ -19,6 +20,10 @@ pub use admission::{
DisabledAiAdmissionService,
};
pub use credit_grant::{CreditGrant, CreditGrantRepo, CreditGrantService, GrantTarget};
+pub use invite_reward::{
+ FreeAllowanceBonusRepo, InviteReward, InviteRewardService, RewardOutcome,
+ capped_free_bonus_cents,
+};
pub use ledger::{
ReloadState, SettlementPlan, SettlementPolicy, SettlementState, plan_reload, plan_settlement,
};
diff --git a/crates/ai_billing/src/domain/invite_reward.rs b/crates/ai_billing/src/domain/invite_reward.rs
new file mode 100644
index 0000000000..afdd34010d
--- /dev/null
+++ b/crates/ai_billing/src/domain/invite_reward.rs
@@ -0,0 +1,143 @@
+//! The reward for bringing someone to Macro: an inviter or referrer earns AI
+//! for each person who joins their team or signs up through their link.
+//!
+//! A paid user's payer gets [`REWARD_CREDIT_CUSTOMER_CENTS`] of prepaid credit.
+//! A free user, who cannot spend credit, gets [`FREE_BONUS_COST_CENTS`] more
+//! monthly allowance, up to [`FREE_BONUS_CAP_COST_CENTS`] in total.
+//! Enterprise (unlimited) users need nothing. Each reward is keyed by the event
+//! that earned it, so a retried event never pays twice.
+
+use std::num::NonZeroU32;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::Result;
+use super::credit_grant::{CreditGrant, CreditGrantRepo};
+use super::ports::EntitlementSource;
+
+#[cfg(test)]
+mod test;
+
+/// $10 of prepaid credit for a paid user, in customer cents.
+pub const REWARD_CREDIT_CUSTOMER_CENTS: u32 = 1_000;
+/// $10 more monthly free allowance, in provider-cost cents.
+pub const FREE_BONUS_COST_CENTS: i64 = 1_000;
+/// The most bonus a free user's monthly allowance can gain, in cost cents.
+pub const FREE_BONUS_CAP_COST_CENTS: i64 = 5_000;
+
+const REWARD_ID_NAMESPACE: Uuid = Uuid::from_u128(0x6169_2d72_6577_6172_642d_6d61_6372_6f00);
+
+/// A reward earned by `beneficiary` because someone joined or signed up.
+#[derive(Debug, Clone)]
+pub struct InviteReward {
+ /// Who earns the reward: the inviter, link creator, or referrer.
+ pub beneficiary: MacroUserIdStr<'static>,
+ /// A stable key for the event that earned it, e.g. `team-invite:<id>`.
+ pub event_key: String,
+ /// Why it was granted; stored on the ledger entry.
+ pub note: String,
+}
+
+impl InviteReward {
+ /// The ledger id: the same event always books the same entry.
+ pub fn id(&self) -> Uuid {
+ Uuid::new_v5(&REWARD_ID_NAMESPACE, self.event_key.as_bytes())
+ }
+}
+
+/// What a reward turned into.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RewardOutcome {
+ /// Prepaid credit booked on the beneficiary's payer.
+ Credit,
+ /// Monthly free allowance raised.
+ FreeAllowance,
+ /// Already booked for this event, or the beneficiary is on an unlimited plan.
+ Nothing,
+}
+
+/// Persists free-allowance bonuses.
+pub trait FreeAllowanceBonusRepo: Send + Sync + 'static {
+ /// Book a bonus for `user`. Returns `false` when `id` was already booked.
+ fn record_free_allowance_bonus(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ id: Uuid,
+ cost_cents: i64,
+ note: &str,
+ ) -> impl Future<Output = Result<bool>> + Send;
+}
+
+/// Applies the cap to a user's booked bonus total.
+pub fn capped_free_bonus_cents(booked_cost_cents: i64) -> i64 {
+ booked_cost_cents.clamp(0, FREE_BONUS_CAP_COST_CENTS)
+}
+
+/// Grants [`InviteReward`]s.
+pub struct InviteRewardService<Entitlements, Grants, Bonuses> {
+ entitlements: Entitlements,
+ grants: Grants,
+ bonuses: Bonuses,
+}
+
+impl<Entitlements, Grants, Bonuses> InviteRewardService<Entitlements, Grants, Bonuses>
+where
+ Entitlements: EntitlementSource,
+ Grants: CreditGrantRepo,
+ Bonuses: FreeAllowanceBonusRepo,
+{
+ /// Build the service.
+ pub fn new(entitlements: Entitlements, grants: Grants, bonuses: Bonuses) -> Self {
+ Self {
+ entitlements,
+ grants,
+ bonuses,
+ }
+ }
+
+ /// Book `reward` in the form the beneficiary's plan can use.
+ #[tracing::instrument(
+ name = "ai_billing.invite_reward",
+ skip_all,
+ fields(beneficiary = %reward.beneficiary, reward_id = %reward.id(), outcome),
+ err
+ )]
+ pub async fn reward(&self, reward: &InviteReward) -> Result<RewardOutcome> {
+ let entitlement = self.entitlements.entitlement(&reward.beneficiary).await?;
+ let outcome = if entitlement.unlimited {
+ RewardOutcome::Nothing
+ } else if entitlement.tier.is_paid() {
+ let grant = CreditGrant {
+ id: reward.id(),
+ amount_cents: NonZeroU32::new(REWARD_CREDIT_CUSTOMER_CENTS)
+ .expect("the reward is positive"),
+ note: reward.note.clone(),
+ };
+ if self
+ .grants
+ .record_credit_grant(&entitlement.payer, &grant)
+ .await?
+ {
+ RewardOutcome::Credit
+ } else {
+ RewardOutcome::Nothing
+ }
+ } else if self
+ .bonuses
+ .record_free_allowance_bonus(
+ &reward.beneficiary,
+ reward.id(),
+ FREE_BONUS_COST_CENTS,
+ &reward.note,
+ )
+ .await?
+ {
+ RewardOutcome::FreeAllowance
+ } else {
+ RewardOutcome::Nothing
+ };
+ tracing::Span::current().record("outcome", tracing::field::debug(outcome));
+ Ok(outcome)
+ }
+}
diff --git a/crates/ai_billing/src/domain/invite_reward/test.rs b/crates/ai_billing/src/domain/invite_reward/test.rs
new file mode 100644
index 0000000000..a3b1688c6f
--- /dev/null
+++ b/crates/ai_billing/src/domain/invite_reward/test.rs
@@ -0,0 +1,147 @@
+use std::sync::Mutex;
+
+use super::*;
+use crate::domain::{BillingError, Entitlement, PlanTier};
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+struct FixedEntitlement(Entitlement);
+
+impl EntitlementSource for FixedEntitlement {
+ async fn entitlement(&self, _user: &MacroUserIdStr<'_>) -> Result<Entitlement> {
+ Ok(self.0.clone())
+ }
+
+ async fn stripe_customer_id(&self, _user: &MacroUserIdStr<'_>) -> Result<Option<String>> {
+ Ok(None)
+ }
+
+ async fn team_payer(&self, _team_id: Uuid) -> Result<Option<MacroUserIdStr<'static>>> {
+ Ok(None)
+ }
+}
+
+#[derive(Default)]
+struct Books {
+ grants: Mutex<Vec<(String, Uuid, u32)>>,
+ bonuses: Mutex<Vec<(String, Uuid, i64)>>,
+}
+
+impl CreditGrantRepo for &'static Books {
+ async fn record_credit_grant(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ grant: &CreditGrant,
+ ) -> Result<bool> {
+ let mut grants = self.grants.lock().unwrap();
+ if grants.iter().any(|(_, id, _)| *id == grant.id) {
+ return Ok(false);
+ }
+ grants.push((payer.to_string(), grant.id, grant.amount_cents.get()));
+ Ok(true)
+ }
+
+ async fn credit_grant_balance_cents(&self, _payer: &MacroUserIdStr<'_>) -> Result<i64> {
+ Err(BillingError::Storage(anyhow::anyhow!("unused")))
+ }
+}
+
+impl FreeAllowanceBonusRepo for &'static Books {
+ async fn record_free_allowance_bonus(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ id: Uuid,
+ cost_cents: i64,
+ _note: &str,
+ ) -> Result<bool> {
+ let mut bonuses = self.bonuses.lock().unwrap();
+ if bonuses.iter().any(|(_, existing, _)| *existing == id) {
+ return Ok(false);
+ }
+ bonuses.push((user.to_string(), id, cost_cents));
+ Ok(true)
+ }
+}
+
+fn books() -> &'static Books {
+ Box::leak(Box::default())
+}
+
+fn reward(beneficiary: &MacroUserIdStr<'static>, key: &str) -> InviteReward {
+ InviteReward {
+ beneficiary: beneficiary.clone(),
+ event_key: key.to_owned(),
+ note: "test".to_owned(),
+ }
+}
+
+#[tokio::test]
+async fn a_paid_inviter_gets_ten_dollars_of_credit_on_their_payer_once() {
+ let member = user("[email protected]");
+ let owner = user("[email protected]");
+ let mut entitlement = Entitlement::personal(owner.clone(), PlanTier::Premium);
+ entitlement.billed_users.push(member.clone());
+ let books = books();
+ let service = InviteRewardService::new(FixedEntitlement(entitlement), books, books);
+
+ let first = service
+ .reward(&reward(&member, "team-invite:1"))
+ .await
+ .unwrap();
+ let again = service
+ .reward(&reward(&member, "team-invite:1"))
+ .await
+ .unwrap();
+
+ assert_eq!(first, RewardOutcome::Credit);
+ assert_eq!(again, RewardOutcome::Nothing);
+ let grants = books.grants.lock().unwrap();
+ assert_eq!(grants.len(), 1);
+ assert_eq!(grants[0].0, owner.to_string());
+ assert_eq!(grants[0].2, REWARD_CREDIT_CUSTOMER_CENTS);
+ assert!(books.bonuses.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_free_inviter_gets_more_monthly_allowance() {
+ let free = user("[email protected]");
+ let books = books();
+ let service = InviteRewardService::new(
+ FixedEntitlement(Entitlement::personal(free.clone(), PlanTier::Free)),
+ books,
+ books,
+ );
+
+ let outcome = service.reward(&reward(&free, "referral:1")).await.unwrap();
+
+ assert_eq!(outcome, RewardOutcome::FreeAllowance);
+ let bonuses = books.bonuses.lock().unwrap();
+ assert_eq!(bonuses.len(), 1);
+ assert_eq!(bonuses[0].0, free.to_string());
+ assert_eq!(bonuses[0].2, FREE_BONUS_COST_CENTS);
+ assert!(books.grants.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn unlimited_plans_need_no_reward() {
+ let enterprise = user("[email protected]");
+ let mut entitlement = Entitlement::personal(enterprise.clone(), PlanTier::Premium);
+ entitlement.unlimited = true;
+ let books = books();
+ let service = InviteRewardService::new(FixedEntitlement(entitlement), books, books);
+
+ let outcome = service.reward(&reward(&enterprise, "x")).await.unwrap();
+
+ assert_eq!(outcome, RewardOutcome::Nothing);
+ assert!(books.grants.lock().unwrap().is_empty());
+ assert!(books.bonuses.lock().unwrap().is_empty());
+}
+
+#[test]
+fn the_bonus_cap_is_fifty_dollars() {
+ assert_eq!(capped_free_bonus_cents(-5), 0);
+ assert_eq!(capped_free_bonus_cents(3_000), 3_000);
+ assert_eq!(capped_free_bonus_cents(12_000), FREE_BONUS_CAP_COST_CENTS);
+}
diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rs
index 0e5db87469..bef8994fe8 100644
--- a/crates/ai_billing/src/domain/ledger.rs
+++ b/crates/ai_billing/src/domain/ledger.rs
@@ -153,7 +153,8 @@ pub fn plan_reload(state: ReloadState, thresholds: &AutoReloadThresholds) -> Opt
/// Assemble the API-facing snapshot from the resolved inputs. `used_cost_cents`
/// is this seat's usage at cost; `shared_chargeable_customer_cents` is the
/// payer's cumulative usage beyond all seat allowances, already marked up at
-/// `pricing`.
+/// `pricing`. `free_bonus_cost_cents` is a free seat's earned extra allowance,
+/// already capped; it is ignored for paid seats.
#[expect(
clippy::too_many_arguments,
reason = "snapshot assembly keeps its resolved billing inputs explicit"
@@ -167,9 +168,16 @@ pub fn build_snapshot(
shared_chargeable_customer_cents: i64,
ledger: PeriodLedger,
credit_balance_cents: i64,
+ free_bonus_cost_cents: i64,
pricing: AiPricing,
) -> UsageSnapshot {
- let included_cents = entitlement.included_ai_cents(pricing);
+ // Only a free seat's allowance grows; paid users earn prepaid credit instead.
+ let included_cents = entitlement.included_ai_cents(pricing)
+ + if entitlement.tier.is_paid() {
+ 0
+ } else {
+ free_bonus_cost_cents
+ };
let shared_covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;
let uncovered_cents = (shared_chargeable_customer_cents - shared_covered).max(0);
let seat_remaining = (included_cents - used_cost_cents).max(0);
diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rs
index 27ea9ab8fd..afc8ee2277 100644
--- a/crates/ai_billing/src/domain/ledger/test.rs
+++ b/crates/ai_billing/src/domain/ledger/test.rs
@@ -287,6 +287,7 @@ fn snapshot_for(
chargeable,
ledger,
balance,
+ 0,
AiPricing::testing(),
)
}
@@ -524,6 +525,7 @@ fn unlimited_is_never_blocked() {
AiPricing::testing().extra_customer_cents(97_999),
PeriodLedger::default(),
0,
+ 0,
AiPricing::testing(),
);
assert_eq!(decide(&s), AllowanceDecision::Allow);
@@ -553,6 +555,7 @@ fn credit_scope_follows_team_ownership_even_with_only_one_seat() {
0,
PeriodLedger::default(),
2_500,
+ 0,
AiPricing::testing(),
);
assert_eq!(snapshot.seats, 1);
@@ -584,6 +587,7 @@ fn team_member_is_not_the_payer() {
0,
PeriodLedger::default(),
0,
+ 0,
AiPricing::testing(),
);
assert!(!s.can_manage_billing);
diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rs
index e78f965073..c7c4e96570 100644
--- a/crates/ai_billing/src/domain/ports.rs
+++ b/crates/ai_billing/src/domain/ports.rs
@@ -239,6 +239,12 @@ pub trait BillingRepo: Send + Sync + 'static {
payer: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<()>> + Send;
+ /// Extra free allowance the user has earned, in cost cents, before the cap.
+ fn free_allowance_bonus_cents(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<i64>> + Send;
+
/// Current prepaid balance, customer cents.
fn credit_balance_cents(
&self,
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
index 166072d008..77b1be52a7 100644
--- a/crates/ai_billing/src/domain/service.rs
+++ b/crates/ai_billing/src/domain/service.rs
@@ -4,6 +4,7 @@
#[cfg(test)]
mod test;
+use super::invite_reward::capped_free_bonus_cents;
use super::ledger::{SettlementPolicy, build_snapshot, decide};
use super::models::{
AiUsageBilling, AllowanceDecision, AllowanceStore, AutoReloadMonthlyBudget,
@@ -415,6 +416,12 @@ where
let usage = self.usage.usage_cost_cents_by_user(&users, *period).await?;
(usage_for(user, &usage), 0, PeriodLedger::default(), 0)
};
+ // Invites and referrals raise a free user's monthly allowance.
+ let free_bonus_cost_cents = if entitlement.tier.is_paid() || entitlement.unlimited {
+ 0
+ } else {
+ capped_free_bonus_cents(self.repo.free_allowance_bonus_cents(user).await?)
+ };
Ok(build_snapshot(
user,
entitlement,
@@ -424,6 +431,7 @@ where
chargeable_customer_cents,
ledger,
credit_balance_cents,
+ free_bonus_cost_cents,
self.pricing,
))
}
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index 20b2a82c64..ca82bdb806 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -173,6 +173,7 @@ struct FakeReload {
struct RepoState {
settings: BillingSettings,
balance: i64,
+ free_bonus_cents: i64,
/// Credits consumed per period; charges are summed from `charges`.
consumed: HashMap<DateTime<Utc>, i64>,
purchases: Vec<String>,
@@ -352,6 +353,9 @@ impl BillingRepo for FakeRepo {
self.state.lock().unwrap().suspended = false;
Ok(())
}
+ async fn free_allowance_bonus_cents(&self, _user: &MacroUserIdStr<'_>) -> Result<i64> {
+ Ok(self.state.lock().unwrap().free_bonus_cents)
+ }
async fn credit_balance_cents(&self, _payer: &MacroUserIdStr<'_>) -> Result<i64> {
Ok(self.state.lock().unwrap().balance)
}
@@ -1398,6 +1402,32 @@ async fn free_users_are_hard_capped_at_the_free_allowance() {
));
}
+#[tokio::test]
+async fn earned_bonus_raises_the_free_allowance_up_to_the_cap() {
+ let (svc, repo, _, usage) = premium_service(500);
+ let free = user("[email protected]");
+ assert_eq!(
+ svc.check_allowance(&free).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::FreeAllowanceExhausted)
+ );
+
+ // Two rewards: $20 more allowance at provider cost.
+ repo.state.lock().unwrap().free_bonus_cents = 2_000;
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(snap.included_cents, 2_500);
+ assert_eq!(snap.remaining_cents, 2_000);
+ assert_eq!(
+ svc.check_allowance(&free).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+
+ // Past the cap, more rewards add nothing.
+ repo.state.lock().unwrap().free_bonus_cents = 9_000;
+ *usage.cents.lock().unwrap() = 0;
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(snap.included_cents, 500 + 5_000);
+}
+
#[tokio::test]
async fn free_users_are_not_gated_while_enforcement_is_off() {
let (svc, ..) = premium_service_with(AiUsageBilling::Enabled, 1_000_000);
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rs
index a7a2cd45fe..de2877d88f 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs
@@ -306,6 +306,20 @@ impl BillingRepo for PgBillingRepo {
Ok(())
}
+ async fn free_allowance_bonus_cents(&self, user: &MacroUserIdStr<'_>) -> Result<i64> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(SUM(cost_cents), 0)::bigint AS "bonus!"
+ FROM ai_free_allowance_bonus
+ WHERE user_id = $1
+ "#,
+ user.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)
+ }
+
async fn credit_balance_cents(&self, payer: &MacroUserIdStr<'_>) -> Result<i64> {
let balance = sqlx::query_scalar!(
r#"
diff --git a/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs b/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs
index 044a8c81f5..60ae867229 100644
--- a/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs
@@ -5,8 +5,10 @@ mod test;
use super::pg_funding_repo::lock_payer;
use crate::domain::credit_grant::{CreditGrant, CreditGrantRepo};
+use crate::domain::invite_reward::FreeAllowanceBonusRepo;
use crate::domain::{BillingError, Result};
use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
use sqlx::PgPool;
/// Postgres-backed [`CreditGrantRepo`].
@@ -68,3 +70,29 @@ impl CreditGrantRepo for PgCreditGrantRepo {
.map_err(storage)
}
}
+
+impl FreeAllowanceBonusRepo for PgCreditGrantRepo {
+ async fn record_free_allowance_bonus(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ id: Uuid,
+ cost_cents: i64,
+ note: &str,
+ ) -> Result<bool> {
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO ai_free_allowance_bonus (id, user_id, cost_cents, note)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ id,
+ user.as_ref(),
+ cost_cents,
+ note,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(result.rows_affected() == 1)
+ }
+}
diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rs
index 0025f2835c..48e950949a 100644
--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs
+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs
@@ -198,6 +198,7 @@ async fn record_with_policy(
chargeable_cents,
Default::default(),
0,
+ 0,
AiPricing::testing(),
),
});
diff --git a/crates/macro_db_client/migrations/20261029172024_ai_free_allowance_bonus.sql b/crates/macro_db_client/migrations/20261029172024_ai_free_allowance_bonus.sql
new file mode 100644
index 0000000000..299130395e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261029172024_ai_free_allowance_bonus.sql
@@ -0,0 +1,14 @@
+-- Extra monthly AI allowance a free user earns for invites and referrals.
+-- Each row raises the free monthly allowance by `cost_cents` (provider cost);
+-- the service caps the total it applies. Paid users get prepaid credit grants
+-- in ai_credit_ledger instead. `id` is derived from the event that earned it,
+-- so the same invite or referral never books twice.
+CREATE TABLE ai_free_allowance_bonus (
+ id UUID PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ cost_cents BIGINT NOT NULL CHECK (cost_cents > 0),
+ note TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX idx_ai_free_allowance_bonus_user ON ai_free_allowance_bonus (user_id);
diff --git a/crates/macro_db_client/migrations/20261029172025_team_invite_link_created_by.sql b/crates/macro_db_client/migrations/20261029172025_team_invite_link_created_by.sql
new file mode 100644
index 0000000000..9267c3b670
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261029172025_team_invite_link_created_by.sql
@@ -0,0 +1,3 @@
+-- Who created (or last reset) a team's invite link, so joins through it can
+-- reward them. NULL for links created before this column existed.
+ALTER TABLE team_invite_link ADD COLUMN created_by TEXT;
diff --git a/crates/referral/AGENTS.md b/crates/referral/AGENTS.md
index f437fcd2b7..b47a80bad8 100644
--- a/crates/referral/AGENTS.md
+++ b/crates/referral/AGENTS.md
@@ -2,24 +2,25 @@
## What it is
-Part of the billing feature (referrals). Generates/redeems referral codes,
-grants the Stripe discount, and notifies the referrer for the
-invite-to-Macro flow.
+Part of the billing feature (referrals). Generates referral codes, records a
+referral when a brand-new user signs up through one, and rewards the referrer
+($10 of AI credit, or more free allowance) through the `ReferralRewarder`
+port. Also sends invite-to-Macro emails.
## Start here
- `src/domain/service.rs`: `ReferralServiceImpl` — referral code generation,
- invite handling, and discount/notification orchestration.
-- `src/domain/ports.rs`: `ReferralRepo`, `DiscountClient`, `ReferralService`.
-- `src/outbound/pg_referral_repo.rs` + `src/outbound/stripe_discount_client.rs`:
- the Postgres and Stripe adapters.
+ referral tracking plus the referrer reward, and invite emails.
+- `src/domain/ports.rs`: `ReferralRepo`, `ReferralRewarder`, `ReferralService`.
+- `src/outbound/pg_referral_repo.rs`: the Postgres adapter. A user is referred
+ at most once (unique `referral_tracking.referred_id`).
## Scope
- Owns: referral code lifecycle and invite-to-Macro.
-- Not here: the discount's actual billing effect → Stripe (via
- `stripe_discount_client.rs`, a thin client only); sending the notification
- itself → `notification`.
+- Not here: the reward itself → `crates/ai_billing` (`InviteRewardService`,
+ wired in `services/authentication_service/src/outbound/invite_rewards.rs`);
+ sending the notification itself → `notification`.
## Boundaries
diff --git a/crates/referral/Cargo.toml b/crates/referral/Cargo.toml
index 80932c3a4d..23e03ee0ee 100644
--- a/crates/referral/Cargo.toml
+++ b/crates/referral/Cargo.toml
@@ -17,7 +17,7 @@ axum = [
]
default = ["axum", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
-outbound = ["dep:async-stripe", "dep:sqlx", "ports"]
+outbound = ["dep:sqlx", "ports"]
ports = []
[dependencies]
@@ -52,11 +52,7 @@ tower = { workspace = true, optional = true }
utoipa = { workspace = true, optional = true }
-async-stripe = { workspace = true, default-features = false, features = [
- "billing",
- "checkout",
- "runtime-tokio-hyper",
-], optional = true } # Outbound dependencies
+# Outbound dependencies
sqlx = { workspace = true, optional = true }
url = { workspace = true }
urlencoding = { workspace = true }
diff --git a/crates/referral/src/domain/models.rs b/crates/referral/src/domain/models.rs
index dead1315f7..aeb8086d55 100644
--- a/crates/referral/src/domain/models.rs
+++ b/crates/referral/src/domain/models.rs
@@ -2,9 +2,19 @@
pub use invite_email::{InviteToMacro, ReferralCode};
+use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::ShortUuidConverter;
use rate_limit::RateLimitExceeded;
+/// A referral recorded for the first time.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TrackedReferral {
+ /// The `referral_tracking` row.
+ pub tracking_id: uuid::Uuid,
+ /// Who referred the new user.
+ pub referrer: MacroUserIdStr<'static>,
+}
+
/// Errors that can occur during referral operations.
#[derive(Debug, thiserror::Error)]
pub enum ReferralError {
diff --git a/crates/referral/src/domain/ports.rs b/crates/referral/src/domain/ports.rs
index 2d810aaf8d..fd7591c403 100644
--- a/crates/referral/src/domain/ports.rs
+++ b/crates/referral/src/domain/ports.rs
@@ -9,7 +9,7 @@ use macro_user_id::{
};
use std::future::Future;
-use crate::domain::models::{ReferralCode, ReferralError};
+use crate::domain::models::{ReferralCode, ReferralError, TrackedReferral};
/// Repository for accessing referral data from the database.
///
@@ -27,12 +27,13 @@ pub trait ReferralRepo: Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'a>>,
) -> impl Future<Output = Result<ReferralCode, Self::Err>> + Send;
- /// Tracks a referral
+ /// Records that `referral_code` referred the user. Returns `None` when the
+ /// user was already referred, so a referral is only ever recorded once.
fn track_referral<'a>(
&self,
referred_user_id: &MacroUserId<Lowercase<'a>>,
referral_code: &ReferralCode,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<TrackedReferral>, Self::Err>> + Send;
/// Completes a referral
fn complete_referral<'a>(
@@ -41,18 +42,6 @@ pub trait ReferralRepo: Send + Sync + 'static {
referral_code: &ReferralCode,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Gets the referral code of the user who referred the given user, if any
- fn get_referred_by(
- &self,
- referred_user_id: &uuid::Uuid,
- ) -> impl Future<Output = Result<Option<ReferralCode>, Self::Err>> + Send;
-
- /// Gets the referrs customer id using their code
- fn get_referrers_customer_id(
- &self,
- referral_code: &ReferralCode,
- ) -> impl Future<Output = Result<String, Self::Err>> + Send;
-
/// Gets the sender's profile picture URL and display name in a single query.
/// Returns `(profile_picture_url, display_name)`, either of which may be `None`.
fn get_sender_info<'a>(
@@ -61,18 +50,17 @@ pub trait ReferralRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<(Option<String>, Option<String>), Self::Err>> + Send;
}
-/// Repository to handle applying discounts to the referrer when a referral is
-/// completed
-#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
-pub trait DiscountClient: Send + Sync + 'static {
- /// The error type returned by repository operations.
- type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
-
- /// Applies the discount to the referrer
- fn apply_discount(
+/// Rewards a referrer when someone signs up through their link.
+#[cfg_attr(test, mockall::automock)]
+pub trait ReferralRewarder: Send + Sync + 'static {
+ /// Rewards `referrer` for `referred`. `event_key` identifies the
+ /// referral, so a retry never pays twice.
+ fn reward_referrer(
&self,
- referrer_customer_id: &str,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ referrer: MacroUserIdStr<'static>,
+ referred: MacroUserIdStr<'static>,
+ event_key: String,
+ ) -> impl Future<Output = Result<(), anyhow::Error>> + Send;
}
/// Service interface for referral operations.
@@ -85,29 +73,14 @@ pub trait ReferralService: Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'a>>,
) -> impl Future<Output = Result<ReferralCode, ReferralError>> + Send;
- /// Starts tracking the referral
- /// The referral is completed when the user pays through stripe
+ /// Records that a new user signed up with `referral_code` and rewards the
+ /// referrer. A user can only be referred once.
fn track_referral<'a>(
&self,
referred_user_id: &MacroUserId<Lowercase<'a>>,
referral_code: &ReferralCode,
) -> impl Future<Output = Result<(), ReferralError>> + Send;
- /// Gets the referral code of the user who referred the given user, if any
- fn get_referred_by(
- &self,
- referred_user_id: &uuid::Uuid,
- ) -> impl Future<Output = Result<Option<ReferralCode>, ReferralError>> + Send;
-
- /// Processes a referral
- /// - tracks the referral
- /// - assigns the discount to the referrers' stripe
- fn process_referral<'a>(
- &self,
- referred_user_id: &MacroUserId<Lowercase<'a>>,
- referral_code: &ReferralCode,
- ) -> impl Future<Output = Result<(), ReferralError>> + Send;
-
/// Send a referral to an external user via email
fn send_referral_invite(
&self,
diff --git a/crates/referral/src/domain/service.rs b/crates/referral/src/domain/service.rs
index edc9e91dc4..1097710973 100644
--- a/crates/referral/src/domain/service.rs
+++ b/crates/referral/src/domain/service.rs
@@ -6,6 +6,7 @@ mod test;
use std::{collections::HashSet, ops::Deref};
use macro_user_id::{
+ cowlike::CowLike,
email::{EmailStr, ReadEmailParts},
lowercased::Lowercase,
user_id::{MacroUserId, MacroUserIdStr},
@@ -16,26 +17,26 @@ use rootcause::compat::boxed_error::IntoBoxedError;
use crate::domain::{
models::{InviteToMacro, ReferralCode, ReferralError},
- ports::{DiscountClient, ReferralRepo, ReferralService},
+ ports::{ReferralRepo, ReferralRewarder, ReferralService},
};
/// The concrete referral service implementation.
-pub struct ReferralServiceImpl<R, Dc, N> {
+pub struct ReferralServiceImpl<R, Rw, N> {
/// referral repo
pub repo: R,
- /// discount client
- pub discount_client: Dc,
+ /// rewards the referrer when someone signs up
+ pub rewarder: Rw,
/// the notification sender
pub notification_ingress: N,
}
impl<
R: ReferralRepo,
- Dc: DiscountClient,
+ Rw: ReferralRewarder,
// the constructor for this is Arc<NI> so we use a different bound here
N: Deref<Target = NI> + Send + Sync + 'static,
NI: NotificationIngress,
-> ReferralService for ReferralServiceImpl<R, Dc, N>
+> ReferralService for ReferralServiceImpl<R, Rw, N>
{
#[tracing::instrument(skip(self), err)]
async fn get_referral_code_for_user<'a>(
@@ -54,47 +55,40 @@ impl<
referred_user_id: &MacroUserId<Lowercase<'a>>,
referral_code: &ReferralCode,
) -> Result<(), ReferralError> {
- self.repo
+ let Some(tracked) = self
+ .repo
.track_referral(referred_user_id, referral_code)
.await
- .map_err(|e| ReferralError::Internal(e.into()))
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn get_referred_by(
- &self,
- referred_user_id: &uuid::Uuid,
- ) -> Result<Option<ReferralCode>, ReferralError> {
- self.repo
- .get_referred_by(referred_user_id)
+ .map_err(|e| ReferralError::Internal(e.into()))?
+ else {
+ return Ok(());
+ };
+ let referred = MacroUserIdStr::parse_from_str(referred_user_id.as_ref())
+ .map_err(|e| ReferralError::Internal(e.into()))?
+ .into_owned();
+ if referred == tracked.referrer {
+ return Ok(());
+ }
+ // The signup already happened; a failed reward is logged, not undone.
+ if let Err(error) = self
+ .rewarder
+ .reward_referrer(
+ tracked.referrer.clone(),
+ referred,
+ format!("referral:{}", tracked.tracking_id),
+ )
.await
- .map_err(|e| ReferralError::Internal(e.into()))
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn process_referral<'a>(
- &self,
- referred_user_id: &MacroUserId<Lowercase<'a>>,
- referral_code: &ReferralCode,
- ) -> Result<(), ReferralError> {
- // NOTE: This will error if the referral code is invalid and we cannot find a
- // user from the referral code
- let customer_id = self
+ {
+ tracing::error!(error = ?error, referrer = %tracked.referrer, "failed to reward the referrer");
+ return Ok(());
+ }
+ if let Err(error) = self
.repo
- .get_referrers_customer_id(referral_code)
- .await
- .map_err(|e| ReferralError::Internal(e.into()))?;
-
- self.repo
.complete_referral(referred_user_id, referral_code)
.await
- .map_err(|e| ReferralError::Internal(e.into()))?;
-
- self.discount_client
- .apply_discount(&customer_id)
- .await
- .map_err(|e| ReferralError::Internal(e.into()))?;
-
+ {
+ tracing::warn!(error = ?error.into(), "failed to mark the referral complete");
+ }
Ok(())
}
diff --git a/crates/referral/src/domain/service/test.rs b/crates/referral/src/domain/service/test.rs
index 8b51fd7788..c1f19fcb96 100644
--- a/crates/referral/src/domain/service/test.rs
+++ b/crates/referral/src/domain/service/test.rs
@@ -8,7 +8,8 @@ use rootcause::Report;
use crate::domain::{
models::ReferralError,
- ports::{MockDiscountClient, MockReferralRepo, ReferralService},
+ models::TrackedReferral,
+ ports::{MockReferralRepo, MockReferralRewarder, ReferralService},
service::ReferralServiceImpl,
};
@@ -52,19 +53,103 @@ fn mock_repo() -> MockReferralRepo {
repo
}
-fn mock_discount_client() -> MockDiscountClient {
- MockDiscountClient::new()
+fn build_service()
+-> ReferralServiceImpl<MockReferralRepo, MockReferralRewarder, MockNotificationIngress> {
+ with_parts(mock_repo(), MockReferralRewarder::new())
}
-fn build_service()
--> ReferralServiceImpl<MockReferralRepo, MockDiscountClient, MockNotificationIngress> {
+fn with_parts(
+ repo: MockReferralRepo,
+ rewarder: MockReferralRewarder,
+) -> ReferralServiceImpl<MockReferralRepo, MockReferralRewarder, MockNotificationIngress> {
ReferralServiceImpl {
- repo: mock_repo(),
- discount_client: mock_discount_client(),
+ repo,
+ rewarder,
notification_ingress: MockNotificationIngress(MockNotificationIngressInner),
}
}
+fn referred() -> macro_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'static>>
+{
+ macro_user_id::user_id::MacroUserId::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .lowercase()
+}
+
+#[tokio::test]
+async fn a_first_referral_rewards_the_referrer_and_completes() {
+ let tracking_id = uuid::Uuid::from_u128(7);
+ let mut repo = MockReferralRepo::new();
+ repo.expect_track_referral()
+ .times(1)
+ .returning(move |_, _| {
+ Box::pin(async move {
+ Ok(Some(TrackedReferral {
+ tracking_id,
+ referrer: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ }))
+ })
+ });
+ repo.expect_complete_referral()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let mut rewarder = MockReferralRewarder::new();
+ rewarder
+ .expect_reward_referrer()
+ .withf(move |referrer, referred, key| {
+ referrer.as_ref() == "macro|[email protected]"
+ && referred.as_ref() == "macro|[email protected]"
+ && key == &format!("referral:{tracking_id}")
+ })
+ .times(1)
+ .returning(|_, _, _| Box::pin(async { Ok(()) }));
+ let service = with_parts(repo, rewarder);
+
+ service
+ .track_referral(&referred(), &invite_email::ReferralCode("CODE".into()))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn an_already_referred_user_rewards_nobody() {
+ let mut repo = MockReferralRepo::new();
+ repo.expect_track_referral()
+ .returning(|_, _| Box::pin(async { Ok(None) }));
+ let mut rewarder = MockReferralRewarder::new();
+ rewarder.expect_reward_referrer().never();
+ let service = with_parts(repo, rewarder);
+
+ service
+ .track_referral(&referred(), &invite_email::ReferralCode("CODE".into()))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn a_failed_reward_leaves_the_referral_incomplete() {
+ let mut repo = MockReferralRepo::new();
+ repo.expect_track_referral().returning(|_, _| {
+ Box::pin(async {
+ Ok(Some(TrackedReferral {
+ tracking_id: uuid::Uuid::from_u128(8),
+ referrer: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ }))
+ })
+ });
+ repo.expect_complete_referral().never();
+ let mut rewarder = MockReferralRewarder::new();
+ rewarder
+ .expect_reward_referrer()
+ .returning(|_, _, _| Box::pin(async { Err(anyhow::anyhow!("billing down")) }));
+ let service = with_parts(repo, rewarder);
+
+ service
+ .track_referral(&referred(), &invite_email::ReferralCode("CODE".into()))
+ .await
+ .unwrap();
+}
+
fn test_user() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").unwrap()
}
diff --git a/crates/referral/src/inbound/axum_router/test.rs b/crates/referral/src/inbound/axum_router/test.rs
index 7c1626f853..bcd07783eb 100644
--- a/crates/referral/src/inbound/axum_router/test.rs
+++ b/crates/referral/src/inbound/axum_router/test.rs
@@ -86,23 +86,6 @@ impl ReferralService for MockReferralService {
Ok(())
}
- async fn get_referred_by(
- &self,
- _referred_user_id: &uuid::Uuid,
- ) -> Result<Option<ReferralCode>, ReferralError> {
- Ok(None)
- }
-
- async fn process_referral<'a>(
- &self,
- _referred_user_id: &macro_user_id::user_id::MacroUserId<
- macro_user_id::lowercased::Lowercase<'a>,
- >,
- _referral_code: &ReferralCode,
- ) -> Result<(), ReferralError> {
- Ok(())
- }
-
async fn send_referral_invite(
&self,
_sending_user: macro_user_id::user_id::MacroUserIdStr<'_>,
diff --git a/crates/referral/src/outbound.rs b/crates/referral/src/outbound.rs
index 126cfd9cc2..7a3847095c 100644
--- a/crates/referral/src/outbound.rs
+++ b/crates/referral/src/outbound.rs
@@ -1,4 +1,3 @@
//! Outbound handlers for referral crate
pub mod pg_referral_repo;
-pub mod stripe_discount_client;
diff --git a/crates/referral/src/outbound/pg_referral_repo.rs b/crates/referral/src/outbound/pg_referral_repo.rs
index 3770a8a62e..8941eb4d76 100644
--- a/crates/referral/src/outbound/pg_referral_repo.rs
+++ b/crates/referral/src/outbound/pg_referral_repo.rs
@@ -3,12 +3,16 @@
#[cfg(test)]
mod test;
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{
+ cowlike::CowLike,
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
use macro_uuid::ShortUuidConverter;
use sqlx::PgPool;
use crate::domain::{
- models::{ReferralCode, referral_code_to_uuid},
+ models::{ReferralCode, TrackedReferral, referral_code_to_uuid},
ports::ReferralRepo,
};
@@ -60,17 +64,29 @@ impl ReferralRepo for PgReferralRepo {
&self,
referred_user_id: &MacroUserId<Lowercase<'a>>,
referral_code: &ReferralCode,
- ) -> Result<(), Self::Err> {
+ ) -> Result<Option<TrackedReferral>, Self::Err> {
let referrer_id =
referral_code_to_uuid(referral_code).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
- // make sure this user exists
- sqlx::query!(
- "SELECT 1 as exists FROM macro_user WHERE id = $1",
+ // The referrer must exist; their Macro id is who earns the reward.
+ // One account can have several users (linked emails); the one on the
+ // account's primary email earns the reward.
+ let referrer = sqlx::query_scalar!(
+ r#"
+ SELECT u.id
+ FROM "User" u
+ JOIN macro_user m ON m.id = u.macro_user_id
+ WHERE m.id = $1
+ ORDER BY lower(u.email) = lower(m.email) DESC, u.id
+ LIMIT 1
+ "#,
&referrer_id
)
.fetch_one(&self.pool)
.await?;
+ let referrer = MacroUserIdStr::parse_from_str(&referrer)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned();
let referred_id = sqlx::query!(
r#"SELECT macro_user_id FROM "User" WHERE id = $1"#,
@@ -81,25 +97,26 @@ impl ReferralRepo for PgReferralRepo {
.await?;
let tracking_id = macro_uuid::generate_uuid_v7();
- sqlx::query!("INSERT INTO referral_tracking (id, referrer_id, referred_id, status, created_at) VALUES ($1, $2, $3, 'incomplete', NOW())", &tracking_id, &referrer_id, &referred_id).execute(&self.pool).await?;
-
- Ok(())
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn get_referred_by(
- &self,
- referred_user_id: &uuid::Uuid,
- ) -> Result<Option<ReferralCode>, Self::Err> {
- let referrer_id: Option<uuid::Uuid> = sqlx::query!(
- "SELECT referrer_id FROM referral_tracking WHERE referred_id = $1",
- referred_user_id
+ // A user is referred at most once (unique referred_id), so a repeated
+ // signup or login with a code records nothing.
+ let inserted = sqlx::query_scalar!(
+ r#"
+ INSERT INTO referral_tracking (id, referrer_id, referred_id, status, created_at)
+ VALUES ($1, $2, $3, 'incomplete', NOW())
+ ON CONFLICT (referred_id) DO NOTHING
+ RETURNING id
+ "#,
+ &tracking_id,
+ &referrer_id,
+ &referred_id
)
- .map(|r| r.referrer_id)
.fetch_optional(&self.pool)
.await?;
- Ok(referrer_id.map(|id| ReferralCode(self.short_uuid_converter.from_uuid(&id))))
+ Ok(inserted.map(|tracking_id| TrackedReferral {
+ tracking_id,
+ referrer,
+ }))
}
#[tracing::instrument(skip(self), err)]
@@ -145,26 +162,6 @@ impl ReferralRepo for PgReferralRepo {
Ok(())
}
- #[tracing::instrument(skip(self), err)]
- async fn get_referrers_customer_id(
- &self,
- referral_code: &ReferralCode,
- ) -> Result<String, Self::Err> {
- let fusion_user_id =
- referral_code_to_uuid(referral_code).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
-
- sqlx::query!(
- r#"
- SELECT stripe_customer_id FROM macro_user
- WHERE id = $1
- "#,
- fusion_user_id,
- )
- .map(|s| s.stripe_customer_id)
- .fetch_one(&self.pool)
- .await
- }
-
#[tracing::instrument(skip(self), err)]
async fn get_sender_info<'a>(
&self,
diff --git a/crates/referral/src/outbound/pg_referral_repo/test.rs b/crates/referral/src/outbound/pg_referral_repo/test.rs
index 853d0a2fae..fdc4a087d0 100644
--- a/crates/referral/src/outbound/pg_referral_repo/test.rs
+++ b/crates/referral/src/outbound/pg_referral_repo/test.rs
@@ -8,7 +8,7 @@ use crate::domain::ports::ReferralRepo;
use crate::outbound::pg_referral_repo::PgReferralRepo;
const REFERRER_UUID: &str = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
-const REFERRER_STRIPE_ID: &str = "cus_referrer";
+const REFERRER_ID: &str = "macro|[email protected]";
fn referrer_referral_code() -> ReferralCode {
let converter = ShortUuidConverter::default();
@@ -51,49 +51,6 @@ async fn test_get_referral_code_for_nonexistent_user(pool: Pool<Postgres>) {
assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
}
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("referral_users"))
-)]
-async fn test_get_referrers_customer_id(pool: Pool<Postgres>) {
- let repo = PgReferralRepo::new(pool);
-
- let code = referrer_referral_code();
- let customer_id = repo.get_referrers_customer_id(&code).await.unwrap();
-
- assert_eq!(customer_id, REFERRER_STRIPE_ID);
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("referral_users"))
-)]
-async fn test_get_referrers_customer_id_invalid_code(pool: Pool<Postgres>) {
- let repo = PgReferralRepo::new(pool);
-
- let code = ReferralCode("!!!invalid!!!".to_string());
- let result = repo.get_referrers_customer_id(&code).await;
-
- assert!(result.is_err());
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("referral_users"))
-)]
-async fn test_get_referrers_customer_id_nonexistent_user(pool: Pool<Postgres>) {
- let repo = PgReferralRepo::new(pool);
-
- // Valid short UUID format but no matching macro_user row
- let converter = ShortUuidConverter::default();
- let fake_uuid = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
- let code = ReferralCode(converter.from_uuid(&fake_uuid));
-
- let result = repo.get_referrers_customer_id(&code).await;
-
- assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
-}
-
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("referral_users"))
@@ -106,9 +63,20 @@ async fn test_track_referral(pool: Pool<Postgres>) {
.into_owned();
let code = referrer_referral_code();
- repo.track_referral(&referred_user_id.0, &code)
+ let tracked = repo
+ .track_referral(&referred_user_id.0, &code)
.await
- .unwrap();
+ .unwrap()
+ .expect("a first referral is recorded");
+ assert_eq!(tracked.referrer.as_ref(), REFERRER_ID);
+
+ // A second signup or login with a code records nothing.
+ assert_eq!(
+ repo.track_referral(&referred_user_id.0, &code)
+ .await
+ .unwrap(),
+ None
+ );
// Verify a row was inserted into referral_tracking
let row = sqlx::query!("SELECT referrer_id, referred_id FROM referral_tracking LIMIT 1")
@@ -306,46 +274,3 @@ async fn test_complete_referral_already_complete(pool: Pool<Postgres>) {
assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("referral_users"))
-)]
-async fn test_get_referred_by_found(pool: Pool<Postgres>) {
- let repo = PgReferralRepo::new(pool);
-
- // First track the referral so there's a row
- let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
- .unwrap()
- .into_owned();
- let code = referrer_referral_code();
- repo.track_referral(&referred_user_id.0, &code)
- .await
- .unwrap();
-
- // Now look up who referred this user
- let referred_uuid = uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
- let result = repo.get_referred_by(&referred_uuid).await.unwrap();
-
- assert!(result.is_some());
- let returned_code = result.unwrap();
-
- // The returned code should decode back to the referrer's UUID
- let converter = ShortUuidConverter::default();
- let decoded = converter.to_uuid(&returned_code.0).unwrap();
- assert_eq!(decoded.to_string(), REFERRER_UUID);
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("referral_users"))
-)]
-async fn test_get_referred_by_not_found(pool: Pool<Postgres>) {
- let repo = PgReferralRepo::new(pool);
-
- // Query with a UUID that has no referral_tracking row
- let unknown_uuid = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
- let result = repo.get_referred_by(&unknown_uuid).await.unwrap();
-
- assert!(result.is_none());
-}
diff --git a/crates/referral/src/outbound/stripe_discount_client.rs b/crates/referral/src/outbound/stripe_discount_client.rs
deleted file mode 100644
index 6952480671..0000000000
--- a/crates/referral/src/outbound/stripe_discount_client.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-//! Stripe adapter for applying discounts.
-
-use anyhow::{Context, bail};
-
-use crate::domain::ports::DiscountClient;
-
-/// Stripe implementation of the discount client
-#[derive(Clone)]
-pub struct StripeDiscountClient {
- /// inner stripe client
- stripe_client: stripe::Client,
- /// the amount a single discount is worth, in cents
- discount_amount_in_cents: i64,
-}
-
-impl StripeDiscountClient {
- /// Create a new stripe discount client
- pub fn new(stripe_client: stripe::Client, discount_amount: i64) -> Self {
- Self {
- stripe_client,
- discount_amount_in_cents: discount_amount,
- }
- }
-}
-
-impl DiscountClient for StripeDiscountClient {
- type Err = anyhow::Error;
-
- #[tracing::instrument(skip(self), err)]
- async fn apply_discount(&self, referrer_customer_id: &str) -> Result<(), Self::Err> {
- let customer_id: stripe::CustomerId = referrer_customer_id
- .parse()
- .context("invalid stripe customer id format")?;
-
- let customer = stripe::Customer::retrieve(&self.stripe_client, &customer_id, &[])
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to retrieve stripe customer"))
- .context("stripe customer not found or could not be retrieved")?;
-
- if customer.deleted {
- bail!("stripe customer '{referrer_customer_id}' has been deleted");
- }
-
- // Negative amount = credit applied to the customer's balance
- let params = stripe::CreateCustomerBalanceTransaction {
- amount: -self.discount_amount_in_cents,
- currency: stripe::Currency::USD,
- description: Some("Referral credit"),
- metadata: None,
- };
-
- stripe::Customer::create_balance_transaction(&self.stripe_client, &customer_id, params)
- .await
- .inspect_err(
- |e| tracing::error!(error=?e, "failed to create balance transaction for customer"),
- )
- .context("failed to apply referral credit to stripe customer balance")?;
-
- Ok(())
- }
-}
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
index 4f1206a318..265e1afc6d 100644
--- a/crates/teams/AGENTS.md
+++ b/crates/teams/AGENTS.md
@@ -24,6 +24,10 @@ event contract (schema, sanitization, delivery semantics).
invites, swept hourly in `authentication_service`. The repository claims
due invites and counts the reminder before sending, so replicas never
double-send and a failed send drops that reminder rather than retrying.
+- `src/domain/invite_rewards.rs`: the `InviteRewarder` port, called when an
+ invite is accepted or someone joins through an invite link (rewarding the
+ sender or `team_invite_link.created_by`). Billing implements it in
+ `authentication_service`; `teams` cannot depend on `ai_billing`.
- `src/domain/owned_entity_cleanup.rs` + `open_seat_release.rs`: account/team
deletion side effects (owned-entity transfer, seat release).
- `src/inbound/axum_router.rs` / `src/inbound/toolset.rs`: HTTP routes and AI
diff --git a/crates/teams/src/domain.rs b/crates/teams/src/domain.rs
index 3d7cb30e1e..5b8eb25df0 100644
--- a/crates/teams/src/domain.rs
+++ b/crates/teams/src/domain.rs
@@ -3,6 +3,7 @@ pub mod crm_enqueuer;
pub mod customer_repo;
pub mod domain_notice;
pub mod events;
+pub mod invite_rewards;
#[cfg(feature = "ports")]
pub mod join_announcement;
pub mod model;
diff --git a/crates/teams/src/domain/invite_rewards.rs b/crates/teams/src/domain/invite_rewards.rs
new file mode 100644
index 0000000000..8ede0bb0ba
--- /dev/null
+++ b/crates/teams/src/domain/invite_rewards.rs
@@ -0,0 +1,41 @@
+//! Rewards the person who brought a new member onto a team.
+//!
+//! Billing owns the reward itself; this crate only reports who earned one.
+//! `teams` cannot depend on billing, so the composition root supplies the
+//! [`InviteRewarder`].
+
+use std::{future::Future, pin::Pin};
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// Someone joined a team because of `inviter`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct InviteRewardEvent {
+ /// Who earned the reward: the invite's sender or the link's creator.
+ pub inviter: MacroUserIdStr<'static>,
+ /// Who joined.
+ pub joined: MacroUserIdStr<'static>,
+ /// A stable key for this join, so a retried join never pays twice.
+ pub event_key: String,
+}
+
+/// A boxed future, so the rewarder can be shared as a trait object.
+pub type InviteRewardFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + Send + 'a>>;
+
+/// Books the reward for an [`InviteRewardEvent`].
+pub trait InviteRewarder: std::fmt::Debug + Send + Sync + 'static {
+ /// Rewards the inviter. Failures are logged by the caller and never undo
+ /// the join.
+ fn reward_inviter(&self, event: InviteRewardEvent) -> InviteRewardFuture<'_>;
+}
+
+/// Rewards nobody. The default until a composition root wires billing in.
+#[derive(Debug)]
+pub struct NoOpInviteRewarder;
+
+impl InviteRewarder for NoOpInviteRewarder {
+ fn reward_inviter(&self, _event: InviteRewardEvent) -> InviteRewardFuture<'_> {
+ Box::pin(async { Ok(()) })
+ }
+}
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index 107b5f3acc..fd3b653b62 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -351,12 +351,20 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<Option<TeamInviteLinkToken>, TeamError>> + Send;
/// Sets the team's invite link to `token`, replacing any existing link.
+ /// `created_by` is rewarded when someone joins through it.
fn set_team_invite_link(
&self,
team_id: &uuid::Uuid,
token: &TeamInviteLinkToken,
+ created_by: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), TeamError>> + Send;
+ /// Who created the invite link with `token`, if it exists and is known.
+ fn get_team_invite_link_creator(
+ &self,
+ token: &TeamInviteLinkToken,
+ ) -> impl Future<Output = Result<Option<MacroUserIdStr<'static>>, TeamError>> + Send;
+
/// Removes the team's invite link. A no-op when the team has none.
fn delete_team_invite_link(
&self,
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index 053ed26e32..1deaf3929c 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -44,6 +44,7 @@ use crate::domain::{
TeamInviteRevokedMetadata, TeamJoinMethod, TeamMacroEvent, TeamMemberJoinedMetadata,
TeamMemberRemovedMetadata, TeamMemberRoleChangedMetadata, TeamUpdatedMetadata,
},
+ invite_rewards::{InviteRewardEvent, InviteRewarder, NoOpInviteRewarder},
model::{
CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError,
JoinTeamDirectlyError, JoinTeamError, PatchTeamCrmSettingsResponse, PatchTeamRequest,
@@ -149,6 +150,8 @@ pub struct TeamServiceImpl<
/// Outbound port that purges everything a team owns before the team is
/// deleted. The default refuses, so an unwired service cannot delete teams.
owned_entity_cleanup: OEC,
+ /// Rewards whoever brought a new member onto the team.
+ invite_rewarder: Arc<dyn InviteRewarder>,
}
fn channel_error_to_team_error(error: ChannelMutationErr) -> TeamError {
@@ -185,6 +188,7 @@ where
event_broker: self.event_broker.clone(),
open_seat_release: self.open_seat_release.clone(),
owned_entity_cleanup: self.owned_entity_cleanup.clone(),
+ invite_rewarder: self.invite_rewarder.clone(),
}
}
}
@@ -289,6 +293,7 @@ where
event_broker: NoopMacroEventBroker,
open_seat_release: NoOpOpenSeatRelease,
owned_entity_cleanup: UnwiredOwnedEntityCleanup,
+ invite_rewarder: Arc::new(NoOpInviteRewarder),
}
}
}
@@ -655,6 +660,7 @@ where
event_broker: self.event_broker,
open_seat_release: self.open_seat_release,
owned_entity_cleanup: self.owned_entity_cleanup,
+ invite_rewarder: self.invite_rewarder,
}
}
@@ -679,6 +685,7 @@ where
event_broker,
open_seat_release: self.open_seat_release,
owned_entity_cleanup: self.owned_entity_cleanup,
+ invite_rewarder: self.invite_rewarder,
}
}
@@ -703,6 +710,37 @@ where
event_broker: self.event_broker,
open_seat_release,
owned_entity_cleanup: self.owned_entity_cleanup,
+ invite_rewarder: self.invite_rewarder,
+ }
+ }
+
+ /// Replaces the rewarder for whoever brought a new member onto a team.
+ pub fn with_invite_rewarder(mut self, invite_rewarder: Arc<dyn InviteRewarder>) -> Self {
+ self.invite_rewarder = invite_rewarder;
+ self
+ }
+
+ /// Rewards `inviter` for `joined`, best-effort: the join already happened.
+ pub(crate) async fn reward_inviter(
+ &self,
+ inviter: &MacroUserIdStr<'_>,
+ joined: &MacroUserIdStr<'_>,
+ event_key: String,
+ ) {
+ if inviter == joined {
+ return;
+ }
+ let event = InviteRewardEvent {
+ inviter: inviter.clone().into_owned(),
+ joined: joined.clone().into_owned(),
+ event_key,
+ };
+ if let Err(error) = self.invite_rewarder.reward_inviter(event).await {
+ tracing::error!(
+ error = ?error,
+ inviter = %inviter,
+ "failed to reward the inviter for a team join"
+ );
}
}
@@ -728,6 +766,7 @@ where
event_broker: self.event_broker,
open_seat_release: self.open_seat_release,
owned_entity_cleanup,
+ invite_rewarder: self.invite_rewarder,
}
}
@@ -2031,6 +2070,13 @@ where
self.enqueue_joining_user_contacts(user_id, &teammate_ids)
.await;
+ self.reward_inviter(
+ &accepted_invite.invite.invited_by,
+ user_id,
+ format!("team-invite:{}", accepted_invite.invite.id),
+ )
+ .await;
+
self.track_team_analytics_event(TeamAnalyticsEvent::TeamJoined {
team_id: team_member.team_id,
team_invite_id: accepted_invite.invite.id,
diff --git a/crates/teams/src/domain/team_service/invite_link.rs b/crates/teams/src/domain/team_service/invite_link.rs
index 0b82b91630..71bb6c859f 100644
--- a/crates/teams/src/domain/team_service/invite_link.rs
+++ b/crates/teams/src/domain/team_service/invite_link.rs
@@ -50,6 +50,34 @@ where
OSR: OpenSeatRelease,
OEC: OwnedEntityCleanup,
{
+ /// Rewards whoever created the link `user_id` just joined through.
+ async fn reward_invite_link_creator(
+ &self,
+ token: &TeamInviteLinkToken,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ ) {
+ let creator = match self
+ .team_repository
+ .get_team_invite_link_creator(token)
+ .await
+ {
+ Ok(Some(creator)) => creator,
+ // Links made before creators were recorded reward nobody.
+ Ok(None) => return,
+ Err(error) => {
+ tracing::error!(error = ?error, %team_id, "failed to read the invite link creator");
+ return;
+ }
+ };
+ self.reward_inviter(
+ &creator,
+ user_id,
+ format!("team-invite-link:{team_id}:{user_id}"),
+ )
+ .await;
+ }
+
/// Checks the caller may invite people to the team, the same rule as
/// email invites, and returns whether they are a team admin or owner.
async fn caller_may_invite(
@@ -119,7 +147,7 @@ where
let token = TeamInviteLinkToken::generate();
self.team_repository
- .set_team_invite_link(&team_id, &token)
+ .set_team_invite_link(&team_id, &token, user_id)
.await?;
Ok(token)
}
@@ -166,7 +194,11 @@ where
.join_team_directly(&team.team_id, user_id, TeamJoinMethod::InviteLink)
.await?
{
- Some(member) => Ok(JoinTeamByInviteLinkOutcome::Joined(member)),
+ Some(member) => {
+ self.reward_invite_link_creator(token, &team.team_id, user_id)
+ .await;
+ Ok(JoinTeamByInviteLinkOutcome::Joined(member))
+ }
// The insert found an existing membership, which a concurrent
// join may have created on either this team or another one.
None => {
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index a575e0c814..97ed91350c 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -146,6 +146,7 @@ struct MockTeamRepository {
user_teams_after_add: Option<Vec<Team>>,
journal: Journal,
invite_link: Arc<Mutex<Option<TeamInviteLinkToken>>>,
+ invite_link_creator: Arc<Mutex<Option<MacroUserIdStr<'static>>>>,
invite_link_team: Option<TeamInviteLinkTeam>,
/// What `claim_due_invite_reminders` hands out, once.
due_invite_reminders: Arc<Mutex<Vec<DueInviteReminder>>>,
@@ -232,6 +233,7 @@ impl MockTeamRepository {
user_teams_after_add: None,
journal: Journal::default(),
invite_link: Arc::new(Mutex::new(None)),
+ invite_link_creator: Arc::new(Mutex::new(None)),
invite_link_team: None,
due_invite_reminders: Arc::new(Mutex::new(Vec::new())),
}
@@ -933,11 +935,23 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
token: &TeamInviteLinkToken,
+ created_by: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), TeamError>> + Send {
*self.invite_link.lock().unwrap() = Some(*token);
+ *self.invite_link_creator.lock().unwrap() = Some(created_by.clone().into_owned());
async { Ok(()) }
}
+ fn get_team_invite_link_creator(
+ &self,
+ token: &TeamInviteLinkToken,
+ ) -> impl Future<Output = Result<Option<MacroUserIdStr<'static>>, TeamError>> + Send {
+ let creator = (*self.invite_link.lock().unwrap() == Some(*token))
+ .then(|| self.invite_link_creator.lock().unwrap().clone())
+ .flatten();
+ async move { Ok(creator) }
+ }
+
fn delete_team_invite_link(
&self,
_: &uuid::Uuid,
@@ -957,6 +971,23 @@ impl TeamRepository for MockTeamRepository {
}
}
+// -- Recording InviteRewarder --
+
+#[derive(Debug, Default)]
+pub(super) struct RecordingInviteRewarder {
+ pub(super) events: Mutex<Vec<crate::domain::invite_rewards::InviteRewardEvent>>,
+}
+
+impl crate::domain::invite_rewards::InviteRewarder for RecordingInviteRewarder {
+ fn reward_inviter(
+ &self,
+ event: crate::domain::invite_rewards::InviteRewardEvent,
+ ) -> crate::domain::invite_rewards::InviteRewardFuture<'_> {
+ self.events.lock().unwrap().push(event);
+ Box::pin(async { Ok(()) })
+ }
+}
+
// -- Mock CustomerRepository --
#[derive(Clone)]
@@ -5577,6 +5608,33 @@ async fn team_event_invite_join_uses_accepted_invite_snapshot() {
);
}
+#[tokio::test]
+async fn accepting_an_invite_rewards_the_inviter_once_per_invite() {
+ let team_id = uuid::Uuid::from_u128(335);
+ let invite_id = uuid::Uuid::from_u128(336);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let team_repository = make_enterprise_join_team_repository(team_id, invite_id, &user_id);
+ let rewarder = Arc::new(RecordingInviteRewarder::default());
+ let service = TeamServiceImpl::new(
+ team_repository,
+ MockCustomerRepository::default(),
+ RecordingChannelService::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_invite_rewarder(rewarder.clone());
+
+ service.join_team(&invite_id, &user_id).await.unwrap();
+
+ let events = rewarder.events.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].inviter.as_ref(), "macro|[email protected]");
+ assert_eq!(events[0].joined, user_id);
+ assert_eq!(events[0].event_key, format!("team-invite:{invite_id}"));
+}
+
#[tokio::test]
async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {
let team_id = uuid::Uuid::from_u128(1);
diff --git a/crates/teams/src/domain/team_service/test/invite_link.rs b/crates/teams/src/domain/team_service/test/invite_link.rs
index eee0663cd1..516cfcb1f0 100644
--- a/crates/teams/src/domain/team_service/test/invite_link.rs
+++ b/crates/teams/src/domain/team_service/test/invite_link.rs
@@ -217,6 +217,38 @@ async fn joining_by_link_adds_the_user_and_publishes_the_join_method() {
);
}
+#[tokio::test]
+async fn joining_by_link_rewards_the_link_creator() {
+ let token = TeamInviteLinkToken::generate();
+ let team_repository = repository_with_link(token);
+ *team_repository.invite_link_creator.lock().unwrap() = Some(caller());
+ let rewarder = Arc::new(RecordingInviteRewarder::default());
+ let service = TeamServiceImpl::new(
+ team_repository,
+ MockCustomerRepository::default(),
+ RecordingChannelService::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_invite_rewarder(rewarder.clone());
+
+ service
+ .join_team_by_invite_link(&token, &joiner())
+ .await
+ .unwrap();
+
+ let events = rewarder.events.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].inviter, caller());
+ assert_eq!(events[0].joined, joiner());
+ assert_eq!(
+ events[0].event_key,
+ format!("team-invite-link:{TEAM_ID}:{JOINER}")
+ );
+}
+
#[tokio::test]
async fn joining_by_a_wrong_token_changes_nothing() {
let team_repository = repository_with_link(TeamInviteLinkToken::generate());
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index a7b510e34b..adea1c43fc 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -1645,8 +1645,17 @@ impl TeamRepository for TeamRepositoryImpl {
&self,
team_id: &uuid::Uuid,
token: &TeamInviteLinkToken,
+ created_by: &MacroUserIdStr<'_>,
) -> Result<(), TeamError> {
- invite_link::set_team_invite_link(&self.pool, team_id, token).await
+ invite_link::set_team_invite_link(&self.pool, team_id, token, created_by).await
+ }
+
+ #[tracing::instrument(skip(self, token), err)]
+ async fn get_team_invite_link_creator(
+ &self,
+ token: &TeamInviteLinkToken,
+ ) -> Result<Option<MacroUserIdStr<'static>>, TeamError> {
+ invite_link::get_team_invite_link_creator(&self.pool, token).await
}
#[tracing::instrument(skip(self), err)]
diff --git a/crates/teams/src/outbound/team_repo/invite_link.rs b/crates/teams/src/outbound/team_repo/invite_link.rs
index 8ca875c021..07e4eb2b82 100644
--- a/crates/teams/src/outbound/team_repo/invite_link.rs
+++ b/crates/teams/src/outbound/team_repo/invite_link.rs
@@ -1,5 +1,6 @@
//! Queries for a team's shareable invite link.
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::PgPool;
use crate::domain::model::{TeamError, TeamInviteLinkTeam, TeamInviteLinkToken};
@@ -26,17 +27,20 @@ pub(super) async fn set_team_invite_link(
pool: &PgPool,
team_id: &uuid::Uuid,
token: &TeamInviteLinkToken,
+ created_by: &MacroUserIdStr<'_>,
) -> Result<(), TeamError> {
sqlx::query!(
r#"
- INSERT INTO team_invite_link (team_id, token)
- VALUES ($1, $2)
+ INSERT INTO team_invite_link (team_id, token, created_by)
+ VALUES ($1, $2, $3)
ON CONFLICT (team_id) DO UPDATE
SET token = EXCLUDED.token,
+ created_by = EXCLUDED.created_by,
created_at = now()
"#,
team_id,
token.as_uuid(),
+ created_by.as_ref(),
)
.execute(pool)
.await?;
@@ -78,3 +82,27 @@ pub(super) async fn get_team_by_invite_link(
.fetch_optional(pool)
.await?)
}
+
+pub(super) async fn get_team_invite_link_creator(
+ pool: &PgPool,
+ token: &TeamInviteLinkToken,
+) -> Result<Option<MacroUserIdStr<'static>>, TeamError> {
+ let created_by = sqlx::query_scalar!(
+ r#"
+ SELECT created_by
+ FROM team_invite_link
+ WHERE token = $1
+ "#,
+ token.as_uuid(),
+ )
+ .fetch_optional(pool)
+ .await?
+ .flatten();
+ // A creator id that no longer parses is skipped, not an error: it only
+ // decides who gets a reward.
+ Ok(created_by.and_then(|id| {
+ MacroUserIdStr::parse_from_str(&id)
+ .ok()
+ .map(|id| id.into_owned())
+ }))
+}
diff --git a/crates/teams/src/outbound/team_repo/test/invite_link.rs b/crates/teams/src/outbound/team_repo/test/invite_link.rs
index 0482f6f129..4fbe01d8f7 100644
--- a/crates/teams/src/outbound/team_repo/test/invite_link.rs
+++ b/crates/teams/src/outbound/team_repo/test/invite_link.rs
@@ -6,6 +6,10 @@ use crate::domain::model::{TeamInviteLinkTeam, TeamInviteLinkToken};
const TEAM_1: Uuid = Uuid::from_u128(0x11111111_1111_1111_1111_111111111111);
const TEAM_2: Uuid = Uuid::from_u128(0x22222222_2222_2222_2222_222222222222);
+fn creator() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../fixtures", scripts("teams"))
@@ -18,8 +22,14 @@ async fn invite_links_are_set_reset_and_turned_off_per_team(
assert_eq!(team_repo.get_team_invite_link(&TEAM_1).await?, None);
let first = TeamInviteLinkToken::generate();
- team_repo.set_team_invite_link(&TEAM_1, &first).await?;
+ team_repo
+ .set_team_invite_link(&TEAM_1, &first, &creator())
+ .await?;
assert_eq!(team_repo.get_team_invite_link(&TEAM_1).await?, Some(first));
+ assert_eq!(
+ team_repo.get_team_invite_link_creator(&first).await?,
+ Some(creator())
+ );
assert_eq!(
team_repo.get_team_by_invite_link(&first).await?,
Some(TeamInviteLinkTeam {
@@ -30,13 +40,17 @@ async fn invite_links_are_set_reset_and_turned_off_per_team(
// Resetting replaces the token, so the old link stops resolving.
let reset = TeamInviteLinkToken::generate();
- team_repo.set_team_invite_link(&TEAM_1, &reset).await?;
+ team_repo
+ .set_team_invite_link(&TEAM_1, &reset, &creator())
+ .await?;
assert_eq!(team_repo.get_team_invite_link(&TEAM_1).await?, Some(reset));
assert_eq!(team_repo.get_team_by_invite_link(&first).await?, None);
// Another team's link is independent.
let other = TeamInviteLinkToken::generate();
- team_repo.set_team_invite_link(&TEAM_2, &other).await?;
+ team_repo
+ .set_team_invite_link(&TEAM_2, &other, &creator())
+ .await?;
team_repo.delete_team_invite_link(&TEAM_1).await?;
assert_eq!(team_repo.get_team_invite_link(&TEAM_1).await?, None);
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index e484ee2300..78949b3c48 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -258,9 +258,23 @@ Pending queries must show local loading states without suspending the flow.
When the server suggests a work domain, the create form has no Skip button and
shows an **Allow @domain emails to join** switch, on by default. Creating the
team with it on sets the team's auto-join domain and, after the invites, emails
-up to 25 of the creator's same-domain contacts who are not on Macro or invited
-yet (`POST /team/domain-notice`). Personal-domain accounts keep Skip and see no
-switch.
+up to 25 of the creator's same-domain contacts who are not on Macro, invited,
+or already sent a notice (`POST /team/domain-notice`). Creating the team does not leave the step: it
+switches to the **You're on <team>** confirmation, the same panel members who
+were already on a team (auto-joined or invite-accepted) see. That panel has
+**Copy invite link** beside **Continue**; it copies the team's
+`/app/team-invite?link=` URL, creating the link when the team has none. Members
+who may invite (admins and owners, or anyone when non-admin invites are on) can
+create the first link; when they can't, the button shows an error toast.
+
+Personal-domain accounts (no suggested work domain) never see the create-team
+form. The step shows an **Invite friends.** referral screen instead ("Get $10 of
+AI credit for each person who signs up."), with friend email rows, **Copy
+referral link** (`/app/signup?referral_code=`), **Send N invites** (one referral
+invite per address, then the plan step; no team is created), and **Skip for
+now**. Send stays disabled until an address is valid; if none of the invites
+can be sent, the addresses stay on screen. On phones, the paired buttons stack
+full width.
Members with an active or trialing license, including a license from their team,
finish directly from the team step without visiting the plan page. The Continue
diff --git a/docs/runbooks/ai-quota-enforcement.md b/docs/runbooks/ai-quota-enforcement.md
index a3c7ff6b13..312ff788e5 100644
--- a/docs/runbooks/ai-quota-enforcement.md
+++ b/docs/runbooks/ai-quota-enforcement.md
@@ -44,7 +44,8 @@ The classification is exhaustive and server-selected, not request-controlled.
Unlimited (enterprise) entitlements are never blocked by this quota policy.
Free-plan users are hard-capped at `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS` of
-counted usage per UTC calendar month: past it, admission answers
+counted usage per UTC calendar month, plus any bonus earned from team invites and
+referrals (`ai_free_allowance_bonus`, +$10 each, at most +$50): past it, admission answers
`ai_free_allowance_exhausted` and nothing is settled, since Free has no credits
or overage. Model-access and resource permissions remain independent. Counting
eligibility is not a claim that a particular user owes money; it does not
@@ -253,7 +254,7 @@ errors are not permission grants and must not disclose another user's quota.
| Result | HTTP status | Stable `code` | Retry semantics |
| --- | --- | --- | --- |
| Allowance exhausted | 402 | `ai_allowance_exhausted` | Policy/allowance must change; no automatic tight retry |
-| Free monthly cap reached | 402 | `ai_free_allowance_exhausted` | Only an upgrade (or the next calendar month) lifts it |
+| Free monthly cap reached | 402 | `ai_free_allowance_exhausted` | An upgrade, the next calendar month, or an earned invite/referral bonus lifts it |
| Spending cap reached | 402 | `ai_overage_limit_reached` | Policy/allowance must change |
| Overage payment failed | 402 | `ai_overage_payment_failed` | Billing problem must be resolved |
| Could not validate billing | 503 | `ai_billing_unavailable` | Retry later with bounded backoff; never execute on uncertainty |
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 168fb69b14..a0de461d1a 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -46,10 +46,7 @@ use notification::{
domain::service::SqsNotificationIngress, outbound::rate_limit::RedisRateLimitAdapter,
};
use rate_limit::domain::service::RateLimitServiceImpl;
-use referral::{
- domain::service::ReferralServiceImpl,
- outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},
-};
+use referral::{domain::service::ReferralServiceImpl, outbound::pg_referral_repo::PgReferralRepo};
use remote_env_var::LocalOrRemoteSecret;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
@@ -145,12 +142,18 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
pub(crate) type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;
-pub(crate) type ReferralServiceType = ReferralServiceImpl<
- PgReferralRepo,
- StripeDiscountClient,
- Arc<SqsNotificationIngress<SqsQueue>>,
+pub(crate) type InviteRewardsType = crate::outbound::invite_rewards::BillingInviteRewards<
+ ai_billing::outbound::RolesTeamsEntitlementSource<
+ UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+ ai_billing::outbound::PgCreditGrantRepo,
+ ai_billing::outbound::PgCreditGrantRepo,
>;
+pub(crate) type ReferralServiceType =
+ ReferralServiceImpl<PgReferralRepo, InviteRewardsType, Arc<SqsNotificationIngress<SqsQueue>>>;
+
pub(crate) type GtmInviteServiceType = GtmInviteServiceImpl<PgGtmInviteRepo>;
pub(crate) type UserLanguageServiceType = UserLanguageServiceImpl<PgUserLanguageRepo>;
diff --git a/services/authentication_service/src/api/oauth/oauth_redirect.rs b/services/authentication_service/src/api/oauth/oauth_redirect.rs
index bcd3f7a841..275262edd6 100644
--- a/services/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/services/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -144,32 +144,30 @@ pub async fn handler(
let decoded_user_id = decode_macro_access_token_allow_expired(&access_token, &ctx.jwt_args);
- if let Some(state) = state.as_ref()
+ let just_signed_up = match decoded_user_id.as_ref() {
+ Ok(user_id) => {
+ append_signed_up_param_if_new_user(
+ &ctx.macro_cache_client,
+ user_id.email_str(),
+ &mut redirect_url,
+ )
+ .await
+ }
+ Err(_) => false,
+ };
+
+ // Only a brand-new account counts as referred: an existing user who signs
+ // in through a referral link earns the referrer nothing.
+ if just_signed_up
+ && let Ok(user_id) = decoded_user_id.as_ref()
+ && let Some(state) = state.as_ref()
&& let Some(referral_code) = state.referral_code.as_ref()
{
- let user_id = decoded_user_id.as_ref().map_err(|e| {
- tracing::error!(
- auth_handoff_failure = "referral_jwt_decode_failed",
- error=?e,
- "unable to decode access token while tracking referral"
- );
- InnerErr::InvalidJwtError.into_response()
- })?;
-
let _ = ctx
.referral_service
.track_referral(user_id, &ReferralCode(referral_code.clone()))
.await
- .inspect_err(|e| tracing::error!(error=?e, "unable to complete referral for user"));
- }
-
- if let Ok(user_id) = decoded_user_id.as_ref() {
- append_signed_up_param_if_new_user(
- &ctx.macro_cache_client,
- user_id.email_str(),
- &mut redirect_url,
- )
- .await;
+ .inspect_err(|e| tracing::error!(error=?e, "unable to track referral for new user"));
}
// Set cookies
@@ -185,8 +183,6 @@ pub async fn handler(
enum InnerErr {
#[error("{0}")]
Serde(#[from] serde_json::Error),
- #[error("invalid jwt")]
- InvalidJwtError,
#[error("Macro Cache Err {0}")]
MacroCacheErr(anyhow::Error),
#[error("Failed to parse url {0}")]
@@ -198,13 +194,6 @@ enum InnerErr {
impl IntoResponse for InnerErr {
fn into_response(self) -> Response {
match self {
- InnerErr::InvalidJwtError => (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to deserialize jwt".into(),
- }),
- )
- .into_response(),
InnerErr::Serde(_error) => (
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
diff --git a/services/authentication_service/src/api/utils.rs b/services/authentication_service/src/api/utils.rs
index 9184ff6560..21d26bc247 100644
--- a/services/authentication_service/src/api/utils.rs
+++ b/services/authentication_service/src/api/utils.rs
@@ -139,16 +139,18 @@ pub async fn append_signed_up_param_if_new_user(
macro_cache_client: &macro_cache_client::MacroCache,
email: &str,
redirect_url: &mut Url,
-) {
+) -> bool {
match macro_cache_client.take_user_just_signed_up(email).await {
Ok(true) => {
redirect_url
.query_pairs_mut()
.append_pair("signed_up", "true");
+ true
}
- Ok(false) => {}
+ Ok(false) => false,
Err(e) => {
tracing::error!(error=?e, "unable to check just-signed-up marker");
+ false
}
}
}
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 4b3cc7dd35..851393c5fe 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -18,11 +18,10 @@ use axum::{
};
use gtm_invite::domain::ports::GtmInviteService;
use macro_user_id::email::Email;
+use macro_user_id::lowercased::Lowercase;
use macro_user_id::user_id::MacroUserIdStr;
-use macro_user_id::{cowlike::CowLike, lowercased::Lowercase};
use miniserde::json::Value as JsonValue;
use model::response::ErrorResponse;
-use referral::domain::ports::ReferralService;
use roles_and_permissions::domain::{
model::{ProductTier, SubscriptionStatus},
port::UserRolesAndPermissionsService,
@@ -693,13 +692,6 @@ async fn handle_customer_subscription_event(
);
}
- // Check if this user was referred and process the referral
- if subscription_status == "active"
- && let Err(e) = check_and_process_referral(ctx, &email).await
- {
- tracing::error!(error=?e, "failed to process referral on subscription created");
- }
-
// Unknown prices (legacy or manually created subscriptions) keep the
// Premium entitlements.
let product_tier = plan
@@ -772,38 +764,6 @@ async fn mark_gtm_invite_converted(
}
}
-/// Checks if the subscribing user was referred and, if so, processes the referral
-/// to credit the referrer.
-#[tracing::instrument(skip(ctx, email), err)]
-async fn check_and_process_referral(
- ctx: &ApiContext,
- email: &Email<macro_user_id::lowercased::Lowercase<'_>>,
-) -> anyhow::Result<()> {
- let (macro_user_id, user_id_str) =
- macro_db_client::user::get::get_user_macro_user_id_and_id_by_email(&ctx.db, email.as_ref())
- .await?;
-
- let Some(referral_code) = ctx
- .referral_service
- .get_referred_by(&macro_user_id)
- .await
- .map_err(|e| anyhow::anyhow!(e))?
- else {
- return Ok(());
- };
-
- let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(&user_id_str)
- .expect("user id from db should be valid")
- .into_owned();
-
- ctx.referral_service
- .process_referral(&user_id.0, &referral_code)
- .await
- .map_err(|e| anyhow::anyhow!(e))?;
-
- Ok(())
-}
-
/// Handles team subscription events.
/// NOTE: We use strs here because there is a mismatch between stripe crate and
/// stripe_webhook crate for these types. *sigh*
diff --git a/services/authentication_service/src/outbound.rs b/services/authentication_service/src/outbound.rs
index 2d5e5bedfc..1c2d5713b4 100644
--- a/services/authentication_service/src/outbound.rs
+++ b/services/authentication_service/src/outbound.rs
@@ -1,5 +1,6 @@
//! Adapters for authentication service use cases.
+pub mod invite_rewards;
pub mod microsoft;
pub mod subscription_checkout;
pub mod team_owned_entity_cleanup;
diff --git a/services/authentication_service/src/outbound/invite_rewards.rs b/services/authentication_service/src/outbound/invite_rewards.rs
new file mode 100644
index 0000000000..8ec8c338a9
--- /dev/null
+++ b/services/authentication_service/src/outbound/invite_rewards.rs
@@ -0,0 +1,95 @@
+//! Pays team-invite and referral rewards through AI billing.
+
+use std::sync::Arc;
+
+use ai_billing::domain::{
+ CreditGrantRepo, FreeAllowanceBonusRepo, InviteReward, InviteRewardService,
+ ports::EntitlementSource,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use teams::domain::invite_rewards::{InviteRewardEvent, InviteRewardFuture, InviteRewarder};
+
+/// Books invite and referral rewards with [`InviteRewardService`].
+pub(crate) struct BillingInviteRewards<E, G, B> {
+ service: Arc<InviteRewardService<E, G, B>>,
+}
+
+impl<E, G, B> BillingInviteRewards<E, G, B> {
+ pub(crate) fn new(service: InviteRewardService<E, G, B>) -> Self {
+ Self {
+ service: Arc::new(service),
+ }
+ }
+}
+
+impl<E, G, B> Clone for BillingInviteRewards<E, G, B> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+impl<E, G, B> std::fmt::Debug for BillingInviteRewards<E, G, B> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("BillingInviteRewards")
+ .finish_non_exhaustive()
+ }
+}
+
+impl<E, G, B> BillingInviteRewards<E, G, B>
+where
+ E: EntitlementSource,
+ G: CreditGrantRepo,
+ B: FreeAllowanceBonusRepo,
+{
+ async fn reward(
+ &self,
+ beneficiary: MacroUserIdStr<'static>,
+ joined: &MacroUserIdStr<'_>,
+ event_key: String,
+ why: &str,
+ ) -> anyhow::Result<()> {
+ let reward = InviteReward {
+ note: format!("{why}: {joined} ({event_key})"),
+ beneficiary,
+ event_key,
+ };
+ self.service
+ .reward(&reward)
+ .await
+ .map_err(|error| anyhow::anyhow!(error))?;
+ Ok(())
+ }
+}
+
+impl<E, G, B> InviteRewarder for BillingInviteRewards<E, G, B>
+where
+ E: EntitlementSource,
+ G: CreditGrantRepo,
+ B: FreeAllowanceBonusRepo,
+{
+ fn reward_inviter(&self, event: InviteRewardEvent) -> InviteRewardFuture<'_> {
+ Box::pin(async move {
+ self.reward(event.inviter, &event.joined, event.event_key, "team join")
+ .await
+ })
+ }
+}
+
+impl<E, G, B> referral::domain::ports::ReferralRewarder for BillingInviteRewards<E, G, B>
+where
+ E: EntitlementSource,
+ G: CreditGrantRepo,
+ B: FreeAllowanceBonusRepo,
+{
+ async fn reward_referrer(
+ &self,
+ referrer: MacroUserIdStr<'static>,
+ referred: MacroUserIdStr<'static>,
+ event_key: String,
+ ) -> anyhow::Result<()> {
+ self.reward(referrer, &referred, event_key, "referral signup")
+ .await
+ }
+}
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 2891e2f7ce..63cdcaa104 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -74,10 +74,7 @@ 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},
-};
+use referral::{domain::service::ReferralServiceImpl, outbound::pg_referral_repo::PgReferralRepo};
use system_status::{
domain::service::SystemStatusServiceImpl,
outbound::{
@@ -532,12 +529,21 @@ pub async fn run() -> anyhow::Result<()> {
db.clone(),
)));
+ // Invites that turn into teammates and referrals that sign up earn the
+ // inviter AI credit (or more free allowance).
+ let invite_rewards = crate::outbound::invite_rewards::BillingInviteRewards::new(
+ ai_billing::domain::InviteRewardService::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ user_roles_and_permissions_service.clone(),
+ teams_repo_impl.clone(),
+ ),
+ ai_billing::outbound::PgCreditGrantRepo::new(db.clone()),
+ ai_billing::outbound::PgCreditGrantRepo::new(db.clone()),
+ ),
+ );
let referral_service = ReferralServiceImpl {
repo: PgReferralRepo::new(db.clone()),
- discount_client: StripeDiscountClient::new(
- stripe_client.clone(),
- 10000, /*100$ credit, in cents*/
- ),
+ rewarder: invite_rewards.clone(),
notification_ingress: notification_ingress_service.clone(),
};
let gtm_invite_service = GtmInviteServiceImpl {
@@ -669,7 +675,8 @@ pub async fn run() -> anyhow::Result<()> {
.with_contacts_enqueuer(contacts_enqueuer)
.with_event_broker(macro_event_broker.clone())
.with_open_seat_release((*ai_billing_service).clone())
- .with_owned_entity_cleanup(team_owned_entity_cleanup);
+ .with_owned_entity_cleanup(team_owned_entity_cleanup)
+ .with_invite_rewarder(Arc::new(invite_rewards));
let teams_service = Arc::new(teams_service_impl);
let domain_notice_service =
Arc::new(teams::domain::domain_notice::DomainNoticeServiceImpl::new(