Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): instrument pricing checkout events (#799)

Gener4e2c04e60450
diff --git a/src/web/src/app/pricing/pricing-client.dom.test.tsx b/src/web/src/app/pricing/pricing-client.dom.test.tsx
index d1d247137..e6ab1ac91 100644
--- a/src/web/src/app/pricing/pricing-client.dom.test.tsx
+++ b/src/web/src/app/pricing/pricing-client.dom.test.tsx
@@ -9,11 +9,16 @@ const state = vi.hoisted(() => ({
search: new URLSearchParams(),
push: vi.fn(), api: vi.fn(), checkout: vi.fn(), portal: vi.fn(), refresh: vi.fn(),
billing: {} as Record<string, unknown>,
+ pricingView: vi.fn(), pricingCta: vi.fn(),
}))
vi.mock("@/lib/auth-client", () => ({ useSession: () => state.session }))
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: state.push }), useSearchParams: () => state.search }))
vi.mock("@/lib/api/client", () => ({ apiFetch: state.api }))
vi.mock("@/hooks/community/use-billing", () => ({ useBilling: () => ({ ...state.billing, checkout: state.checkout, portal: state.portal, refresh: state.refresh }) }))
+vi.mock("@/lib/analytics", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/lib/analytics")>()
+ return { ...original, trackPricingView: state.pricingView, trackPricingCtaClick: state.pricingCta }
+})
const offers = [
{ plan: { id: "studio", displayName: "Studio" }, botLimit: 10, machineLimit: 5, priceId: "price_server_studio", unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1 },
@@ -38,6 +43,7 @@ it("sends guests to sign-in with a valid selected plan preserved", async () => {
expect(url.pathname).toBe("/sign-in")
expect(url.searchParams.get("redirect")).toBe("/pricing?plan=studio")
expect(state.checkout).not.toHaveBeenCalled()
+ expect(state.pricingCta).toHaveBeenCalledWith({ plan_id: "studio", cta_action: "choose_plan", auth_state: "guest", current_plan: "none", entry_point: "pricing_page" })
})
it("preserves selected plan after sign-in without automatically starting payment", async () => {
@@ -49,7 +55,8 @@ it("preserves selected plan after sign-in without automatically starting payment
expect(state.checkout).not.toHaveBeenCalled()
await waitFor(() => expect(view.getByRole("button", { name: "Choose Studio" })).toBeEnabled())
await setupUser().click(view.getByRole("button", { name: "Choose Studio" }))
- expect(state.checkout).toHaveBeenCalledWith("price_server_studio")
+ expect(state.checkout).toHaveBeenCalledWith("price_server_studio", false, "pricing_page")
+ expect(state.pricingCta).toHaveBeenCalledWith({ plan_id: "studio", cta_action: "choose_plan", auth_state: "signed_in", current_plan: "free", entry_point: "pricing_page" })
})
it("uses the authenticated offer price and Portal for subscription changes", async () => {
@@ -62,6 +69,7 @@ it("uses the authenticated offer price and Portal for subscription changes", asy
expect(view.getByRole("button", { name: "Current plan" })).toBeDisabled()
await setupUser().click(view.getByRole("button", { name: "Manage cancellation" }))
expect(state.portal).toHaveBeenLastCalledWith()
+ expect(state.pricingCta).toHaveBeenLastCalledWith({ plan_id: "free", cta_action: "manage_cancellation", auth_state: "signed_in", current_plan: "studio", entry_point: "pricing_page" })
})
it.each(["Studio", "House"])("requires explicit Founder confirmation for %s", async (name) => {
@@ -79,7 +87,7 @@ it.each(["Studio", "House"])("requires explicit Founder confirmation for %s", as
await user.click(view.getByRole("button", { name: `Choose ${name}` }))
await user.click(view.getByRole("button", { name: "Continue to checkout" }))
expect(state.checkout).toHaveBeenCalledTimes(1)
- expect(state.checkout).toHaveBeenCalledWith(offers.find((offer) => offer.plan.displayName === name)!.priceId, true)
+ expect(state.checkout).toHaveBeenCalledWith(offers.find((offer) => offer.plan.displayName === name)!.priceId, true, "pricing_page")
expect(state.portal).not.toHaveBeenCalled()
})
@@ -117,6 +125,30 @@ it("does not allow stale public prices to initiate purchase when account loading
expect(state.checkout).not.toHaveBeenCalled()
})
+it("emits one pricing view across rerenders and a session-key change", async () => {
+ const view = render(<PricingClient />)
+ await waitFor(() => expect(state.pricingView).toHaveBeenCalledWith({ auth_state: "guest", current_plan: "none" }))
+ view.rerender(<PricingClient />)
+ state.session.data = { user: { id: "buyer" } }
+ state.billing.data = free
+ view.rerender(<PricingClient />)
+ await waitFor(() => expect(view.getByText("Your current plan: Free.")).toBeInTheDocument())
+ expect(state.pricingView).toHaveBeenCalledTimes(1)
+})
+
+it("uses fixed CTA actions instead of deriving analytics from button labels", async () => {
+ const guest = render(<PricingClient />)
+ await setupUser().click(await guest.findByRole("button", { name: "Start free" }))
+ expect(state.pricingCta).toHaveBeenLastCalledWith({ plan_id: "free", cta_action: "start_free", auth_state: "guest", current_plan: "none", entry_point: "pricing_page" })
+ guest.unmount()
+ vi.clearAllMocks()
+ state.session.data = { user: { id: "buyer" } }
+ state.billing.data = free
+ const signed = render(<PricingClient />)
+ await setupUser().click(await signed.findByRole("button", { name: "Open Alook" }))
+ expect(state.pricingCta).toHaveBeenLastCalledWith({ plan_id: "free", cta_action: "open_app", auth_state: "signed_in", current_plan: "free", entry_point: "pricing_page" })
+})
+
it("shows machine allowances supplied by the catalog", async () => {
state.api.mockResolvedValue({ ...catalog, offers: [{ ...offers[0], machineLimit: 7 }, offers[1]] })
diff --git a/src/web/src/app/pricing/pricing-client.tsx b/src/web/src/app/pricing/pricing-client.tsx
index daa160f2b..44644a9a3 100644
--- a/src/web/src/app/pricing/pricing-client.tsx
+++ b/src/web/src/app/pricing/pricing-client.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useState } from "react"
+import { useEffect, useRef, useState, type MutableRefObject } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
import { PublicPricingSchema, type PublicPricing, type BillingOffer } from "@alook/shared"
@@ -8,9 +8,15 @@ import { useSession } from "@/lib/auth-client"
import { apiFetch } from "@/lib/api/client"
import { useBilling } from "@/hooks/community/use-billing"
import { FounderPlanChangeDialog } from "@/components/community/billing/founder-plan-change-dialog"
+import { toAnalyticsCurrentPlan, toAnalyticsPlanId, trackPricingCtaClick, trackPricingView, type PricingCtaAction } from "@/lib/analytics"
import { PricingView } from "./pricing-view"
-function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn: boolean; sessionPending: boolean; sessionError: boolean }) {
+function PricingContent({ signedIn, sessionPending, sessionError, viewTrackedRef }: {
+ signedIn: boolean
+ sessionPending: boolean
+ sessionError: boolean
+ viewTrackedRef: MutableRefObject<boolean>
+}) {
const router = useRouter()
const search = useSearchParams()
const catalog = useQuery({
@@ -30,6 +36,12 @@ function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn:
const disabled = (plan: string) => busy || unavailable || (plan !== "free" && (
!offer(plan) || (signedIn && !paymentOffer(plan)) || (!summary?.isFounder && summary?.plan.id === plan) || summary?.subscription?.scheduledChange?.plan.id === plan
))
+ const currentPlan = signedIn && summary ? toAnalyticsCurrentPlan(summary.plan.id, summary.isFounder) : "none"
+ useEffect(() => {
+ if (viewTrackedRef.current || !catalog.data || sessionPending || sessionError || (signedIn && !summary)) return
+ viewTrackedRef.current = true
+ trackPricingView({ auth_state: signedIn ? "signed_in" : "guest", current_plan: currentPlan })
+ }, [catalog.data, currentPlan, sessionError, sessionPending, signedIn, summary, viewTrackedRef])
const label = (plan: string) => {
if (busy) return "Loading…"
if (plan === "free") return summary?.subscription && !summary.isFounder ? "Manage cancellation" : signedIn ? "Open Alook" : "Start free"
@@ -40,6 +52,19 @@ function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn:
}
const choose = (plan: string) => {
if (disabled(plan)) return
+ const planId = toAnalyticsPlanId(plan)
+ if (planId) {
+ const action: PricingCtaAction = planId !== "free" ? "choose_plan"
+ : !signedIn ? "start_free"
+ : summary?.subscription && !summary.isFounder ? "manage_cancellation" : "open_app"
+ trackPricingCtaClick({
+ plan_id: planId,
+ cta_action: action,
+ auth_state: signedIn ? "signed_in" : "guest",
+ current_plan: currentPlan,
+ entry_point: "pricing_page",
+ })
+ }
if (!signedIn) {
const destination = plan === "free" ? "/c/me/bots" : `/pricing?${new URLSearchParams({ plan })}`
router.push(`/sign-in?${new URLSearchParams({ redirect: destination })}`)
@@ -53,7 +78,7 @@ function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn:
const item = paymentOffer(plan)
if (!item) return
if (summary?.isFounder) { setFounderOffer(item); return }
- void (summary?.subscription ? billing.portal(item.priceId) : billing.checkout(item.priceId))
+ void (summary?.subscription ? billing.portal(item.priceId) : billing.checkout(item.priceId, false, "pricing_page"))
}
const message = summary?.isFounder
? `Your Founder plan includes permanent ${summary.plan.displayName} access.`
@@ -74,7 +99,7 @@ function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn:
const current = paymentOffer(founderOffer.plan.id)
if (!current || current.priceId !== founderOffer.priceId) { setFounderOffer(null); return }
setFounderOffer(null)
- void billing.checkout(current.priceId, true)
+ void billing.checkout(current.priceId, true, "pricing_page")
}} />
</>
}
@@ -90,12 +115,18 @@ export type PricingController = {
retry: () => void
}
-function PricingSession({ signedIn, sessionPending, sessionError }: { signedIn: boolean; sessionPending: boolean; sessionError: boolean }) {
+function PricingSession({ signedIn, sessionPending, sessionError, viewTrackedRef }: {
+ signedIn: boolean
+ sessionPending: boolean
+ sessionError: boolean
+ viewTrackedRef: MutableRefObject<boolean>
+}) {
const [client] = useState(() => new QueryClient())
- return <QueryClientProvider client={client}><PricingContent signedIn={signedIn} sessionPending={sessionPending} sessionError={sessionError} /></QueryClientProvider>
+ return <QueryClientProvider client={client}><PricingContent signedIn={signedIn} sessionPending={sessionPending} sessionError={sessionError} viewTrackedRef={viewTrackedRef} /></QueryClientProvider>
}
export default function PricingClient() {
const session = useSession()
- return <PricingSession key={session.data?.user.id ?? "guest"} signedIn={Boolean(session.data?.user)} sessionPending={session.isPending} sessionError={Boolean(session.error)} />
+ const viewTrackedRef = useRef(false)
+ return <PricingSession key={session.data?.user.id ?? "guest"} signedIn={Boolean(session.data?.user)} sessionPending={session.isPending} sessionError={Boolean(session.error)} viewTrackedRef={viewTrackedRef} />
}
diff --git a/src/web/src/components/community/billing/billing-sheet.dom.test.tsx b/src/web/src/components/community/billing/billing-sheet.dom.test.tsx
index 703e229bd..f723da6ea 100644
--- a/src/web/src/components/community/billing/billing-sheet.dom.test.tsx
+++ b/src/web/src/components/community/billing/billing-sheet.dom.test.tsx
@@ -1,10 +1,16 @@
import React from "react"
-import { describe, expect, it, vi } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
import type { BillingSummary } from "@alook/shared"
import { fireEvent, render } from "@/test/react-dom-harness"
import type { BillingController } from "@/hooks/community/use-billing"
import { BillingContent, BillingSheet } from "./billing-sheet"
+const analytics = vi.hoisted(() => ({ cta: vi.fn() }))
+vi.mock("@/lib/analytics", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/lib/analytics")>()
+ return { ...original, trackPricingCtaClick: analytics.cta }
+})
+
vi.mock("./billing-plan.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))
vi.mock("@/components/community/shell/community-sheet", () => ({
@@ -20,6 +26,8 @@ function state(overrides: Partial<BillingController> = {}): BillingController {
}
function view(billing: BillingController) { return render(<BillingContent billing={billing} />) }
+beforeEach(() => analytics.cta.mockReset())
+
describe("billing sheet", () => {
it("shows server offers without fixed plan IDs and sends only the selected price", () => {
const billing = state()
@@ -30,7 +38,8 @@ describe("billing sheet", () => {
expect(ui.getByText((_text, element) => element?.tagName === "P" && element.textContent === "Up to 10 active bots")).toBeInTheDocument()
expect(ui.getByRole("img", { name: "10 bot slots" })).toBeInTheDocument()
fireEvent.click(ui.getByRole("button", { name: "Choose Studio" }))
- expect(billing.checkout).toHaveBeenCalledWith("price_a")
+ expect(billing.checkout).toHaveBeenCalledWith("price_a", false, "billing_sheet")
+ expect(analytics.cta).not.toHaveBeenCalled()
})
it("shows Founder paid offers and requires explicit confirmation before checkout", () => {
const billing = state({ data: { ...free, isFounder: true, plan: { id: "house", displayName: "House" }, offers: [...free.offers, { ...free.offers[0]!, priceId: "price_house", plan: { id: "house", displayName: "House" } }] } })
@@ -45,8 +54,9 @@ describe("billing sheet", () => {
expect(billing.checkout).not.toHaveBeenCalled()
fireEvent.click(ui.getByRole("button", { name: "Choose House" }))
fireEvent.click(ui.getByRole("button", { name: "Continue to checkout" }))
- expect(billing.checkout).toHaveBeenCalledWith("price_house", true)
+ expect(billing.checkout).toHaveBeenCalledWith("price_house", true, "billing_sheet")
expect(billing.portal).not.toHaveBeenCalled()
+ expect(analytics.cta).toHaveBeenCalledWith({ plan_id: "house", cta_action: "choose_plan", auth_state: "signed_in", current_plan: "founder", entry_point: "billing_sheet" })
})
it("keeps Founder while a payment is awaiting confirmation", () => {
const ui = view(state({ data: { ...free, isFounder: true }, returnFrom: "checkout", polling: true }))
@@ -101,6 +111,14 @@ describe("billing sheet", () => {
expect(billing.checkout).not.toHaveBeenCalled()
})
+ it("emits a fixed billing-sheet CTA payload for a known paid plan", () => {
+ const studio = { ...free.offers[0]!, plan: { id: "studio", displayName: "Untrusted display name" } }
+ const billing = state({ data: { ...free, offers: [studio] } })
+ const ui = view(billing)
+ fireEvent.click(ui.getByRole("button", { name: "Choose Untrusted display name" }))
+ expect(analytics.cta).toHaveBeenCalledWith({ plan_id: "studio", cta_action: "choose_plan", auth_state: "signed_in", current_plan: "free", entry_point: "billing_sheet" })
+ })
+
it("does not send the current price back to Portal when a downgrade is scheduled", () => {
const house = { id: "house", displayName: "House" }
const billing = state({ data: { ...free, plan: house, offers: [...free.offers, { ...free.offers[0]!, priceId: "price_house", plan: house, botLimit: 40, unitAmount: 4000 }], subscription: {
diff --git a/src/web/src/components/community/billing/billing-sheet.tsx b/src/web/src/components/community/billing/billing-sheet.tsx
index fa70bd39b..8c2f8535d 100644
--- a/src/web/src/components/community/billing/billing-sheet.tsx
+++ b/src/web/src/components/community/billing/billing-sheet.tsx
@@ -11,6 +11,7 @@ import type { BillingController } from "@/hooks/community/use-billing"
import { PlanBotDots } from "@/components/pricing/plan-bot-dots"
import styles from "./billing-plan.module.css"
import { tid } from "@/lib/community/testids"
+import { toAnalyticsCurrentPlan, toAnalyticsPlanId, trackPricingCtaClick } from "@/lib/analytics"
function formatOffer(offer: BillingSummary["offers"][number]) {
const currency = offer.currency.toUpperCase()
@@ -30,6 +31,21 @@ export function BillingContent({ billing }: { billing: BillingController }) {
const subscription = summary?.isFounder ? null : summary?.subscription
const currentOffer = summary?.offers.find((offer) => offer.plan.id === summary.plan.id)
const checkoutPending = billing.returnFrom === "checkout" && (summary?.isFounder || !subscription || subscription.plan.id !== summary?.plan.id)
+ const chooseOffer = (offer: BillingSummary["offers"][number]) => {
+ if (!summary) return
+ const planId = toAnalyticsPlanId(offer.plan.id)
+ if (planId && planId !== "free") {
+ trackPricingCtaClick({
+ plan_id: planId,
+ cta_action: "choose_plan",
+ auth_state: "signed_in",
+ current_plan: toAnalyticsCurrentPlan(summary.plan.id, summary.isFounder),
+ entry_point: "billing_sheet",
+ })
+ }
+ if (summary.isFounder) setFounderOffer(offer)
+ else void (subscription ? billing.portal(offer.priceId) : billing.checkout(offer.priceId, false, "billing_sheet"))
+ }
return <div className={styles.content} data-testid={tid.billingSheet}>
<section className="pb-2" aria-label="Current plan">
@@ -81,7 +97,7 @@ export function BillingContent({ billing }: { billing: BillingController }) {
<p className={styles.limit}>Up to <strong>{offer.botLimit}</strong> active bots</p>
<p className={styles.limit}>Up to <strong>{offer.machineLimit}</strong> online machine{offer.machineLimit === 1 ? "" : "s"}</p>
</div>
- <Button className={styles.action} variant={isCurrent || isScheduled ? "outline" : "default"} onClick={() => { if (summary.isFounder) setFounderOffer(offer); else void (subscription ? billing.portal(offer.priceId) : billing.checkout(offer.priceId)) }} disabled={billing.isBusy || Boolean(checkoutPending) || isCurrent || isScheduled} data-testid={subscription ? tid.billingChangePlan : tid.billingCheckout} data-price-id={offer.priceId}>
+ <Button className={styles.action} variant={isCurrent || isScheduled ? "outline" : "default"} onClick={() => chooseOffer(offer)} disabled={billing.isBusy || Boolean(checkoutPending) || isCurrent || isScheduled} data-testid={subscription ? tid.billingChangePlan : tid.billingCheckout} data-price-id={offer.priceId}>
{billing.isBusy && !billing.isCancelingChange ? "Opening…" : isScheduled ? "Scheduled" : isCurrent ? "Current plan" : `Choose ${offer.plan.displayName}`}
</Button>
<div className={styles.stub}><span>Alook · {offer.botLimit} bots</span><PlanBotDots count={offer.botLimit} className={styles.botDots} /></div>
@@ -90,7 +106,7 @@ export function BillingContent({ billing }: { billing: BillingController }) {
</div>
<p className="text-xs text-muted-foreground">{subscription ? "Review changes and any payment on Stripe." : "Continue to Stripe to review and pay."}</p>
</section>}
- <FounderPlanChangeDialog offer={founderOffer} busy={billing.isBusy} onCancel={() => setFounderOffer(null)} onConfirm={() => { if (!founderOffer) return; const priceId = founderOffer.priceId; setFounderOffer(null); void billing.checkout(priceId, true) }} />
+ <FounderPlanChangeDialog offer={founderOffer} busy={billing.isBusy} onCancel={() => setFounderOffer(null)} onConfirm={() => { if (!founderOffer) return; const priceId = founderOffer.priceId; setFounderOffer(null); void billing.checkout(priceId, true, "billing_sheet") }} />
{billing.actionError && <p role="alert" className="text-sm text-destructive">{billing.actionError}</p>}
</div>
}
diff --git a/src/web/src/hooks/community/use-billing.dom.test.tsx b/src/web/src/hooks/community/use-billing.dom.test.tsx
index 1858fdca5..326bbed46 100644
--- a/src/web/src/hooks/community/use-billing.dom.test.tsx
+++ b/src/web/src/hooks/community/use-billing.dom.test.tsx
@@ -5,8 +5,12 @@ import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
import { readBillingReturn, useBilling } from "./use-billing"
-const mocks = vi.hoisted(() => ({ api: vi.fn() }))
+const mocks = vi.hoisted(() => ({ api: vi.fn(), beginCheckout: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api }))
+vi.mock("@/lib/analytics", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/lib/analytics")>()
+ return { ...original, trackBeginCheckout: mocks.beginCheckout }
+})
const free = { plan: { id: "free", displayName: "Free" }, isFounder: false, offers: [], subscription: null }
function setup(returnFrom: Parameters<typeof useBilling>[0] = null, enabled = true) {
@@ -17,7 +21,7 @@ function setup(returnFrom: Parameters<typeof useBilling>[0] = null, enabled = tr
}
describe("billing queries and redirects", () => {
- beforeEach(() => { mocks.api.mockReset(); mocks.api.mockResolvedValue(free) })
+ beforeEach(() => { mocks.api.mockReset(); mocks.api.mockResolvedValue(free); mocks.beginCheckout.mockReset() })
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })
it("does not load billing for the ordinary My Bots view", () => {
@@ -132,7 +136,7 @@ describe("billing queries and redirects", () => {
mocks.api.mockResolvedValue({ ...free, isFounder: true })
const view = setup()
await waitFor(() => expect(view.result.current.data?.isFounder).toBe(true))
- await act(async () => { await view.result.current.checkout("price_any"); await view.result.current.portal(); await view.result.current.cancelChange() })
+ await act(async () => { await view.result.current.checkout("price_any", false, "pricing_page"); await view.result.current.portal(); await view.result.current.cancelChange() })
expect(mocks.api.mock.calls.every(([url]) => url === "/api/community/billing")).toBe(true)
view.unmount()
})
@@ -147,8 +151,8 @@ describe("billing queries and redirects", () => {
? new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) : Promise.resolve(founder))
let request!: Promise<void>
await act(async () => {
- request = view.result.current.checkout("price_house", true)
- void view.result.current.checkout("price_studio", true)
+ request = view.result.current.checkout("price_house", true, "pricing_page")
+ void view.result.current.checkout("price_studio", true, "billing_sheet")
})
expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(1)
expect(mocks.api).toHaveBeenCalledWith("/api/community/billing/checkout", { method: "POST", body: '{"priceId":"price_house","founderAcknowledged":true}' })
@@ -166,8 +170,8 @@ describe("billing queries and redirects", () => {
: Promise.resolve(free))
let request!: Promise<void>
await act(async () => {
- request = view.result.current.checkout("price_one")
- void view.result.current.checkout("price_two")
+ request = view.result.current.checkout("price_one", false, "pricing_page")
+ void view.result.current.checkout("price_two", false, "billing_sheet")
})
expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(1)
expect(mocks.api).toHaveBeenCalledWith("/api/community/billing/checkout", { method: "POST", body: '{"priceId":"price_one"}' })
@@ -175,7 +179,7 @@ describe("billing queries and redirects", () => {
expect(view.result.current.isBusy).toBe(false)
expect(view.result.current.actionError).toContain("resume your purchase")
mocks.api.mockImplementation((url: string) => url.endsWith("/checkout") ? Promise.reject(new Error("timeout")) : Promise.resolve(free))
- await act(async () => { await view.result.current.checkout("price_one") })
+ await act(async () => { await view.result.current.checkout("price_one", false, "pricing_page") })
expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(2)
view.unmount()
})
@@ -213,6 +217,51 @@ describe("billing queries and redirects", () => {
view.unmount()
})
+ it("emits one checkout event after URL creation and before navigation", async () => {
+ const offer = { priceId: "price_studio", plan: { id: "studio", displayName: "Mutable label" }, botLimit: 10, machineLimit: 5, unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1 }
+ const priced = { ...free, offers: [offer] }
+ mocks.api.mockResolvedValue(priced)
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(priced))
+ const originalWindow = window
+ const assign = vi.fn()
+ vi.stubGlobal("window", new Proxy(originalWindow, { get: (target, key) => key === "location" ? { assign } : Reflect.get(target, key, target) }))
+ mocks.api.mockImplementation((url: string) => Promise.resolve(url.endsWith("/checkout") ? { url: "https://checkout.stripe.com/session" } : priced))
+
+ await act(async () => {
+ const first = view.result.current.checkout("price_studio", false, "pricing_page")
+ const duplicate = view.result.current.checkout("price_studio", false, "pricing_page")
+ await Promise.all([first, duplicate])
+ })
+
+ expect(mocks.beginCheckout).toHaveBeenCalledOnce()
+ expect(mocks.beginCheckout).toHaveBeenCalledWith({ plan_id: "studio", currency: "usd", value: 20, entry_point: "pricing_page" })
+ expect(mocks.beginCheckout.mock.invocationCallOrder[0]).toBeLessThan(assign.mock.invocationCallOrder[0]!)
+ expect(assign).toHaveBeenCalledOnce()
+ view.unmount()
+ })
+
+ it.each([
+ { plan: { id: "custom", displayName: "Custom" }, currency: "usd" },
+ { plan: { id: "studio", displayName: "Studio" }, currency: "invalid" },
+ ])("keeps checkout usable without emitting invalid analytics", async ({ plan, currency }) => {
+ const offer = { priceId: "price_target", plan, botLimit: 10, machineLimit: 5, unitAmount: 2000, currency, interval: "month", intervalCount: 1 }
+ const priced = { ...free, offers: [offer] }
+ mocks.api.mockResolvedValue(priced)
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(priced))
+ const originalWindow = window
+ const assign = vi.fn()
+ vi.stubGlobal("window", new Proxy(originalWindow, { get: (target, key) => key === "location" ? { assign } : Reflect.get(target, key, target) }))
+ mocks.api.mockImplementation((url: string) => Promise.resolve(url.endsWith("/checkout") ? { url: "https://checkout.stripe.com/session" } : priced))
+
+ await act(async () => { await view.result.current.checkout("price_target", false, "billing_sheet") })
+
+ expect(mocks.beginCheckout).not.toHaveBeenCalled()
+ expect(assign).toHaveBeenCalledWith("https://checkout.stripe.com/session")
+ view.unmount()
+ })
+
it.each([false, true])("uses the cancel-change response without assuming the old plan survives (crossed period: %s)", async (crossedPeriod) => {
const house = { id: "house", displayName: "House" }
const scheduled = { ...free, plan: house, subscription: {
diff --git a/src/web/src/hooks/community/use-billing.ts b/src/web/src/hooks/community/use-billing.ts
index 9bfae06f3..734347f99 100644
--- a/src/web/src/hooks/community/use-billing.ts
+++ b/src/web/src/hooks/community/use-billing.ts
@@ -5,9 +5,16 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { BillingSummarySchema, BillingRedirectResponseSchema } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
+import { toAnalyticsPlanId, trackBeginCheckout, type BillingEntryPoint } from "@/lib/analytics"
+import { stripeAmountToMajorUnit } from "@/lib/billing/currency"
export type BillingReturn = "checkout" | "cancel" | "portal" | null
-type BillingAction = { kind: "checkout"; priceId: string; founderAcknowledged?: boolean } | { kind: "portal"; priceId?: string }
+type BillingAction = {
+ kind: "checkout"
+ priceId: string
+ founderAcknowledged: boolean
+ entryPoint: BillingEntryPoint
+} | { kind: "portal"; priceId?: string }
export function readBillingReturn(value: string | null): BillingReturn {
return value === "checkout" || value === "cancel" || value === "portal" ? value : null
@@ -127,6 +134,18 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false) {
setActionError(null)
try {
const url = await redirect.mutateAsync(action)
+ if (action.kind === "checkout") {
+ const offer = query.data.offers.find((item) => item.priceId === action.priceId)
+ const planId = offer ? toAnalyticsPlanId(offer.plan.id) : null
+ if (offer && planId && planId !== "free") {
+ try {
+ const value = stripeAmountToMajorUnit(offer.unitAmount, offer.currency)
+ if (value !== null) {
+ trackBeginCheckout({ plan_id: planId, currency: offer.currency, value, entry_point: action.entryPoint })
+ }
+ } catch {}
+ }
+ }
setRedirecting(true)
window.location.assign(url)
} catch {
@@ -176,7 +195,7 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false) {
isBusy: redirect.isPending || redirecting || cancelChangeMutation.isPending,
isCancelingChange: cancelChangeMutation.isPending,
cancelChange,
- checkout: (priceId: string, founderAcknowledged = false) => start({ kind: "checkout", priceId, founderAcknowledged }),
+ checkout: (priceId: string, founderAcknowledged: boolean, entryPoint: BillingEntryPoint) => start({ kind: "checkout", priceId, founderAcknowledged, entryPoint }),
portal: (priceId?: string) => start({ kind: "portal", priceId }),
refresh,
}
diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.ts
index e669b4505..2730a0c05 100644
--- a/src/web/src/lib/analytics.test.ts
+++ b/src/web/src/lib/analytics.test.ts
@@ -38,6 +38,11 @@ import {
trackCommunityWsReconcileComplete,
trackCommunityWsReconcileFailure,
trackCommunityWsRetryScheduled,
+ toAnalyticsCurrentPlan,
+ toAnalyticsPlanId,
+ trackBeginCheckout,
+ trackPricingCtaClick,
+ trackPricingView,
} from "./analytics"
describe("analytics utility", () => {
@@ -249,6 +254,66 @@ describe("analytics utility", () => {
})
})
+ describe("pricing checkout instrumentation", () => {
+ it("pushes only the approved required pricing fields", () => {
+ trackPricingView({ auth_state: "guest", current_plan: "none", email: "[email protected]" } as never)
+ trackPricingCtaClick({
+ plan_id: "house",
+ cta_action: "choose_plan",
+ auth_state: "signed_in",
+ current_plan: "studio",
+ entry_point: "pricing_page",
+ user_id: "ignored",
+ } as never)
+
+ expect(mockSendGTMEvent.mock.calls).toEqual([
+ [{ event: "pricing_view", auth_state: "guest", current_plan: "none" }],
+ [{
+ event: "pricing_cta_click",
+ plan_id: "house",
+ cta_id: "pricing_house",
+ cta_action: "choose_plan",
+ auth_state: "signed_in",
+ current_plan: "studio",
+ entry_point: "pricing_page",
+ }],
+ ])
+ })
+
+ it("uses fixed plan and current-plan enums", () => {
+ expect(toAnalyticsPlanId("studio")).toBe("studio")
+ expect(toAnalyticsPlanId("enterprise")).toBeNull()
+ expect(toAnalyticsCurrentPlan("house")).toBe("house")
+ expect(toAnalyticsCurrentPlan("enterprise")).toBe("unknown")
+ expect(toAnalyticsCurrentPlan("house", true)).toBe("founder")
+ })
+
+ it("pushes a GA4-compatible checkout payload from stable plan metadata", () => {
+ trackBeginCheckout({ plan_id: "studio", currency: "usd", value: 20, entry_point: "billing_sheet" })
+ expect(mockSendGTMEvent).toHaveBeenCalledWith({
+ event: "begin_checkout",
+ currency: "USD",
+ value: 20,
+ items: [{ item_id: "studio", item_name: "Studio", price: 20, quantity: 1 }],
+ entry_point: "billing_sheet",
+ })
+ })
+
+ it.each([
+ { plan_id: "studio", currency: "invalid", value: 20, entry_point: "pricing_page" },
+ { plan_id: "studio", currency: "USD", value: -1, entry_point: "pricing_page" },
+ { plan_id: "studio", currency: "USD", value: Number.NaN, entry_point: "pricing_page" },
+ ])("drops invalid checkout data", (payload) => {
+ trackBeginCheckout(payload as never)
+ expect(mockSendGTMEvent).not.toHaveBeenCalled()
+ })
+
+ it("does not break the product path when GTM throws", () => {
+ mockSendGTMEvent.mockImplementationOnce(() => { throw new Error("blocked") })
+ expect(() => trackPricingView({ auth_state: "guest", current_plan: "none" })).not.toThrow()
+ })
+ })
+
describe("community WebSocket runtime contract", () => {
it("reports only bounded frame metadata", () => {
trackCommunityWsFrameDropped({
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 6b68153f6..5415d7f13 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -2,6 +2,91 @@
import { sendGTMEvent } from "@next/third-parties/google";
+const analyticsAuthStates = ["guest", "signed_in"] as const
+const analyticsPlanIds = ["free", "studio", "house"] as const
+const analyticsCurrentPlans = ["none", "free", "studio", "house", "founder", "unknown"] as const
+const billingEntryPoints = ["pricing_page", "billing_sheet"] as const
+const pricingCtaActions = ["start_free", "open_app", "manage_cancellation", "choose_plan"] as const
+const pricingCtaIds = ["pricing_free", "pricing_studio", "pricing_house", "billing_studio", "billing_house"] as const
+
+export type AnalyticsAuthState = typeof analyticsAuthStates[number]
+export type AnalyticsPlanId = typeof analyticsPlanIds[number]
+export type AnalyticsCurrentPlan = typeof analyticsCurrentPlans[number]
+export type BillingEntryPoint = typeof billingEntryPoints[number]
+export type PricingCtaAction = typeof pricingCtaActions[number]
+type PricingCtaId = typeof pricingCtaIds[number]
+
+const analyticsPlanNames: Record<AnalyticsPlanId, string> = {
+ free: "Free",
+ studio: "Studio",
+ house: "House",
+}
+
+const pricingCtaIdByEntryPoint: Record<BillingEntryPoint, Partial<Record<AnalyticsPlanId, PricingCtaId>>> = {
+ pricing_page: {
+ free: "pricing_free",
+ studio: "pricing_studio",
+ house: "pricing_house",
+ },
+ billing_sheet: {
+ studio: "billing_studio",
+ house: "billing_house",
+ },
+}
+
+const analyticsPlanIdSet = new Set<string>(analyticsPlanIds)
+
+export function toAnalyticsPlanId(value: string): AnalyticsPlanId | null {
+ return analyticsPlanIdSet.has(value) ? value as AnalyticsPlanId : null
+}
+
+export function toAnalyticsCurrentPlan(value: string, isFounder = false): AnalyticsCurrentPlan {
+ if (isFounder) return "founder"
+ return toAnalyticsPlanId(value) ?? "unknown"
+}
+
+function sendCommercialEvent(payload: Record<string, unknown>) {
+ try {
+ sendGTMEvent(payload)
+ } catch {
+ return
+ }
+}
+
+export function trackPricingView(params: {
+ auth_state: AnalyticsAuthState
+ current_plan: AnalyticsCurrentPlan
+}) {
+ const { auth_state, current_plan } = params
+ sendCommercialEvent({ event: "pricing_view", auth_state, current_plan })
+}
+
+export function trackPricingCtaClick(params: {
+ plan_id: AnalyticsPlanId
+ cta_action: PricingCtaAction
+ auth_state: AnalyticsAuthState
+ current_plan: AnalyticsCurrentPlan
+ entry_point: BillingEntryPoint
+}) {
+ const { plan_id, cta_action, auth_state, current_plan, entry_point } = params
+ const cta_id = pricingCtaIdByEntryPoint[entry_point][plan_id]
+ if (!cta_id) return
+ sendCommercialEvent({ event: "pricing_cta_click", plan_id, cta_id, cta_action, auth_state, current_plan, entry_point })
+}
+
+export function trackBeginCheckout(params: {
+ plan_id: Exclude<AnalyticsPlanId, "free">
+ currency: string
+ value: number
+ entry_point: BillingEntryPoint
+}) {
+ const { plan_id, value, entry_point } = params
+ const currency = params.currency.toUpperCase()
+ if (!Intl.supportedValuesOf("currency").includes(currency) || !Number.isFinite(value) || value < 0) return
+ const item = { item_id: plan_id, item_name: analyticsPlanNames[plan_id], price: value, quantity: 1 as const }
+ sendCommercialEvent({ event: "begin_checkout", currency, value: item.price * item.quantity, items: [item], entry_point })
+}
+
// ─── P0 — Core Funnel Events ───────────────────────────────────────────────
export function trackSignUp(method: string) {
diff --git a/src/web/src/lib/billing/currency.test.ts b/src/web/src/lib/billing/currency.test.ts
new file mode 100644
index 000000000..959aa8627
--- /dev/null
+++ b/src/web/src/lib/billing/currency.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest"
+import { stripeAmountToMajorUnit } from "./currency"
+
+describe("Stripe charge currency amounts", () => {
+ it.each([
+ ["usd", 500, 5],
+ ["jpy", 500, 500],
+ ["isk", 500, 5],
+ ["huf", 500, 5],
+ ["twd", 500, 5],
+ ["ugx", 500, 5],
+ ] as const)("converts %s from Stripe minor units", (currency, amount, expected) => {
+ expect(stripeAmountToMajorUnit(amount, currency)).toBe(expected)
+ })
+
+ it.each([
+ [-1, "usd"],
+ [1.5, "usd"],
+ [Number.MAX_SAFE_INTEGER + 1, "usd"],
+ [500, "invalid"],
+ ] as const)("rejects an invalid amount or currency", (amount, currency) => {
+ expect(stripeAmountToMajorUnit(amount, currency)).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/billing/currency.ts b/src/web/src/lib/billing/currency.ts
new file mode 100644
index 000000000..74578b3e1
--- /dev/null
+++ b/src/web/src/lib/billing/currency.ts
@@ -0,0 +1,25 @@
+const stripeZeroDecimalChargeCurrencies = new Set([
+ "bif",
+ "clp",
+ "djf",
+ "gnf",
+ "jpy",
+ "kmf",
+ "krw",
+ "mga",
+ "pyg",
+ "rwf",
+ "vnd",
+ "vuv",
+ "xaf",
+ "xof",
+ "xpf",
+])
+
+const iso4217Currencies = new Set(Intl.supportedValuesOf("currency"))
+
+export function stripeAmountToMajorUnit(amount: number, currency: string): number | null {
+ const normalizedCurrency = currency.toUpperCase()
+ if (!Number.isSafeInteger(amount) || amount < 0 || !iso4217Currencies.has(normalizedCurrency)) return null
+ return amount / (stripeZeroDecimalChargeCurrencies.has(normalizedCurrency.toLowerCase()) ? 1 : 100)
+}