πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Ask for a site and a trial on an empty home page; switch off sites with no plan (#1265)
Goldflag2795948a6398
diff --git a/client/messages/en.json b/client/messages/en.jsonindex c8a530920..c8fac8b68 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -201,6 +201,7 @@"54Ob9x": "Yes, move site","55vTH+": "User ID","56nzII": "Week {value}",+ "5BuYtq": "{site} isn't collecting data","5CbP3g": "Experiment name","5QYdPU": "Start Time","5QiCvx": "Select at least one permission, or turn off restrictions for a full-access key",@@ -272,6 +273,7 @@"7O/+X2": "Users online in past 5 minutes","7OL11E": "Only over limit","7X21Cw": "Weekly Trends",+ "7Xx8IX": "Continue to checkout","7aQjYn": "Showing {from} to {to} of {total} {items}","7df153": "Exclude traffic from specific networks by autonomous system number, such as a corporate VPN or hosting provider. Enter the number with or without the AS prefix (e.g., AS13335 or 13335).","7frRRa": "Failed to import file. Please try again.",@@ -296,6 +298,7 @@"8Nc/jD": "No websites yet","8O/fqy": "Connect this experiment to a goal you already track.","8O9cAb": "Last 24 hours",+ "8SdI/q": "Only the owner can start one. Once they do, you can add websites here.","8UJSrw": "No emoji matches that","8UzT6d": "CSV","8VHF7f": "URL Pattern (optional)",@@ -419,8 +422,10 @@"Cn4/rZ": "Payload","CnmIg8": "Subscribe ($1)","CoSEZb": "everyone matched",+ "CsaHOS": "Copy email","Ctj1re": "Feature flag created","CuDqpf": "Web Vitals disabled",+ "CvOdcz": "Your websites aren't collecting data","CxfKLC": "Pages","Cxfsf1": "Send Verification Code","D+v5e+": "Tracking",@@ -640,6 +645,7 @@"JfUnvy": "Changing the CTA copy will increase signup conversions.","JgKGg8": "Not an owner","JgXnsC": "No sessions found",+ "Jh8pKq": "Enter a domain like example.com","JiYl78": "Update the goal details below.","JkLHGw": "Website","JoUePd": "Use * to match a single path segment. Use ** to match across segments.",@@ -793,6 +799,7 @@"OZJsCo": "Funnel cloned successfully","OfmST8": "Accept Invitation","Oh4usQ": "Select metric",+ "OhDId7": "Enter your domain and choose a plan. Your site will be ready to install as soon as checkout is done.","Oj6AtK": "OS Version","OlRI+i": "Organization API Keys","Omj2fC": "Disabling...",@@ -861,6 +868,7 @@"Qo9UL3": "Limits must be positive whole numbers","Qp/Bnx": "No users match the current filters","Qp1beM": "Path",+ "Qssxr4": "No charge until the trial ends. Cancel anytime.","Quiu+4": "If the snippet doesn't work, try JavaScript injection","QyVOhk": "Last {count, plural, one {# week} other {# weeks}}","Qzul6+": "Site ID",@@ -1037,12 +1045,14 @@"WdvGbR": "Optionally add this member to a team when they accept the invitation.","WeoAO7": "Add, edit, or remove attributes attached to this user.","WhVNRN": "Save current filters as segment",+ "WhfKQX": "{email} Β· Owner","WlfMc4": "API keys let your scripts and integrations access your analytics data.","WnQ/AZ": "Contact us","WoPGPp": "Failed to ban user","WuGkfJ": "Returns","WuHoZ9": "Conversions","Wzg+A9": "Unable to load this application.",+ "Wzi76f": "What site do you want to track?","X0ha1a": "Save changes","X0ppsC": "websites","X2PZ7D": "Create Goal",@@ -1093,6 +1103,7 @@"Z184O6": "Show {count} more","Z1mx8T": "Site analytics made private","Z2Mi3c": "Min pageviews",+ "Z2yHrT": "Start your 7-day free trial to turn tracking on. You won't be charged until the trial ends.","Z3EDd9": "Sessions","Z3IDkP": "Outbound Click","Z5dM3R": "Referrer",@@ -1177,6 +1188,7 @@"cOkfeK": "not contains","cPbI/I": "You don't have permission to view team settings.","cQyKR1": "Endpoints",+ "cRkggJ": "This organization doesn't have a plan yet","cSzyIV": "Analyzing funnel...","cT4fRl": "No clear winner","cTiCAi": "Import Data",@@ -1184,6 +1196,7 @@"cUXDNU": "The site moves into this organization.","cWfEt0": "Error tracking enabled","cXuLtT": "Events exceeded quota or date range limits",+ "cYDkeP": "Pick up where you left off. You can cancel anytime.","cb2kY6": "Standard","ccU6l/": "Online","cdVnd3": "Please select an organization to subscribe.",@@ -1225,6 +1238,7 @@"du1laW": "Never","dv+Q6J": "Use the generated flag key in your app and branch your UI or behavior by variant.","dv4SpB": "No imports yet",+ "dyhF/4": "Cancel anytime.","e/U0Xt": "Conversion Rate","eA5EH7": "Search organizations...","eDqstJ": "24h Events",@@ -1242,6 +1256,7 @@"ekfOaV": "Go Back","enuxmm": "Copy tracking disabled","eoMVii": "Banning revokes the user's active sessions.",+ "f/GWPY": "Your domain","f/Kzd0": "Save override","f0fbLE": "Failed to unban user","f19YrE": "contains",@@ -1293,6 +1308,7 @@"gYNBdv": "Maximum 100 ASN exclusions allowed","gb6dSb": "No organizations available","gcYCT/": "{count} days",+ "gczcC5": "Subscribe","ggVKyN": "Toggle details","giLKKG": "Clone this goal with the same configuration.","gjAv1x": "Ban expiry must be in the future",@@ -1342,6 +1358,7 @@"hncBRq": "Invite Member","hnp8iI": "Generate a private link to share a read-only view of this dashboard with your team.","hq3XcK": "Last {count, plural, one {# hour} other {# hours}}",+ "hsxHXY": "Choose a plan to turn tracking back on.","hw9VFi": "More emoji","hxZIZ2": "This action cannot be undone. This will permanently delete your account and remove all your data from our servers.","hyfdry": "Pageview",@@ -1501,6 +1518,7 @@"mhmZ+P": "Session Replay","mkp+qF": "Additional Parameters","mlMQEA": "Send Weekly Email Reports",+ "mtBS10": "You'll be charged when you subscribe. You can cancel anytime.","n+GeZI": "with events in the last 30 days","n+tV1v": "Exclude traffic to specific pages. Use * as a wildcard (e.g., /admin/* or /preview). Matching is case-insensitive.","n02jRA": "Accent color",@@ -1522,6 +1540,7 @@"naIILe": "Delete Import","nhaiN+": "Add your first website to start tracking analytics","ni0MP6": "You are approaching your monthly event limit. Please contact support if you need more capacity.",+ "niC6Ub": "Choose a plan","nnuMWB": "Paths containing /blog/ followed by anything","noZdV2": "Deleting...","npZO3g": "Right-clicked",@@ -1659,6 +1678,7 @@"sW/jiZ": "All sites in {organization}","sWVioT": "Objects","sXo0km": "Experiment created as a draft",+ "sYa3LK": "Enter your domain to start a 7-day free trial. Your site will be ready to install as soon as checkout is done.","sYxMKr": "Loading import history...","sbjdWu": "Outbound tracking disabled","scL+IP": "Widget Enabled",@@ -1692,6 +1712,7 @@"tUEyB3": "Importing...","tWsaCv": "Copied text (optional)","tf1lIh": "Free",+ "tgfrrb": "Only the organization owner can start a plan. Tracking turns on as soon as they do.","to5LyQ": "Last 14 Days","trk2RK": "Could not delete the annotation","ttyUm0": "{sessions} sessions Β· {conversions} conversions",diff --git a/client/src/api/admin/endpoints/sites.ts b/client/src/api/admin/endpoints/sites.tsindex 0b6cb9f42..cfa80ec9b 100644--- a/client/src/api/admin/endpoints/sites.ts+++ b/client/src/api/admin/endpoints/sites.ts@@ -19,6 +19,8 @@ export type SiteResponse = {blockBots: boolean;firstPartyProxy?: boolean;isOwner: boolean;+ // Cloud only: the site collects nothing until its organization starts a trial or plan.+ requiresPlan?: boolean;// Analytics featuressessionReplay?: boolean;webVitals?: boolean;@@ -63,6 +65,8 @@ export type GetSitesFromOrgResponse = {isOwner: boolean;tags?: string[] | null;teams?: { id: string; name: string }[];+ // Cloud only: the site collects nothing until its organization starts a trial or plan.+ requiresPlan?: boolean;}>;subscription: {monthlyEventCount: number;diff --git a/client/src/api/admin/hooks/useSites.ts b/client/src/api/admin/hooks/useSites.tsindex 093866668..dac6d47e7 100644--- a/client/src/api/admin/hooks/useSites.ts+++ b/client/src/api/admin/hooks/useSites.ts@@ -1,4 +1,4 @@-import { useQuery } from "@tanstack/react-query";+import { Query, useQuery } from "@tanstack/react-query";import { usePathname } from "next/navigation";import { authClient } from "../../../lib/auth";import { useStore } from "../../../lib/store";@@ -9,9 +9,16 @@ import {fetchSitesFromOrg,fetchSiteUsage,GetSitesFromOrgResponse,+ SiteResponse,} from "../endpoints";-export function useGetSitesFromOrg(organizationId?: string, options?: { enabled?: boolean }) {+export function useGetSitesFromOrg(+ organizationId?: string,+ options?: {+ enabled?: boolean;+ refetchInterval?: number | false | ((query: Query<GetSitesFromOrgResponse>) => number | false | undefined);+ }+) {return useQuery<GetSitesFromOrgResponse>({queryKey: ["get-sites-from-org", organizationId],queryFn: () => {@@ -19,6 +26,7 @@ export function useGetSitesFromOrg(organizationId?: string, options?: { enabled?},staleTime: 60000, // 1 minuteenabled: !!organizationId && options?.enabled !== false,+ refetchInterval: options?.refetchInterval,});}@@ -45,7 +53,13 @@ export function useSiteHasData(siteId: string) {});}-export function useGetSite(siteId?: string | number, options?: { enabled?: boolean }) {+export function useGetSite(+ siteId?: string | number,+ options?: {+ enabled?: boolean;+ refetchInterval?: number | false | ((query: Query<SiteResponse | null>) => number | false | undefined);+ }+) {const { site: storeSelectedSite } = useStore();const siteIdToUse = siteId ?? storeSelectedSite;@@ -62,6 +76,7 @@ export function useGetSite(siteId?: string | number, options?: { enabled?: boole},staleTime: 60000,enabled: !!siteIdToUse && options?.enabled !== false,+ refetchInterval: options?.refetchInterval,});}diff --git a/client/src/app/(home)/StartTrial.test.tsx b/client/src/app/(home)/StartTrial.test.tsxnew file mode 100644index 000000000..d538aac5c--- /dev/null+++ b/client/src/app/(home)/StartTrial.test.tsx@@ -0,0 +1,112 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { StartTrial } from "./StartTrial";++const mocks = vi.hoisted(() => ({+ addSite: vi.fn(),+ onSiteCreated: vi.fn(),+ prompt: { isLoading: false, isOwner: true, trialEligible: true },+}));++vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));+vi.mock("../../api/admin/endpoints", () => ({ addSite: mocks.addSite }));+vi.mock("../../components/RybbitLogo", () => ({ RybbitLogo: () => null }));+vi.mock("../components/PlanRequired", () => ({+ usePlanPrompt: () => mocks.prompt,+ OrganizationOwnerContact: ({ organizationId }: { organizationId: string }) => <div>owner of {organizationId}</div>,+ LazyStartPlanDialog: ({+ open,+ returnPath,+ trialEligible,+ }: {+ open: boolean;+ returnPath: string;+ trialEligible: boolean;+ }) =>+ open ? (+ <div role="dialog">+ plans for {returnPath} {trialEligible ? "with trial" : "without trial"}+ </div>+ ) : null,+}));++beforeEach(() => {+ mocks.prompt = { isLoading: false, isOwner: true, trialEligible: true };+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderStartTrial() {+ return render(<StartTrial organizationId="org_1" onSiteCreated={mocks.onSiteCreated} />);+}++function submitDomain(domain: string) {+ fireEvent.change(screen.getByLabelText("Your domain"), { target: { value: domain } });+ fireEvent.submit(screen.getByLabelText("Your domain").closest("form")!);+}++describe("StartTrial β owner", () => {+ it("creates the site from a pasted URL, then opens the plan picker returning to that site", async () => {+ mocks.addSite.mockResolvedValue({ siteId: 42 });+ renderStartTrial();++ submitDomain("https://www.example.com/pricing");++ await waitFor(() => expect(mocks.addSite).toHaveBeenCalledWith("example.com", "example.com", "org_1"));+ expect((await screen.findByRole("dialog")).textContent).toContain("plans for /42 with trial");+ });++ it("rejects something that isn't a domain without creating a site", () => {+ renderStartTrial();++ submitDomain("not a domain");++ expect(screen.getByRole("alert").textContent).toContain("Enter a domain like example.com");+ expect(screen.getByLabelText("Your domain").getAttribute("aria-invalid")).toBe("true");+ expect(mocks.addSite).not.toHaveBeenCalled();+ });++ it("shows the server's reason when the site can't be created", async () => {+ mocks.addSite.mockRejectedValue(new Error("Domain already in use"));+ renderStartTrial();++ submitDomain("example.com");++ expect((await screen.findByRole("alert")).textContent).toContain("Domain already in use");+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("offers a trial to an organization that never had a subscription", () => {+ renderStartTrial();++ screen.getByRole("button", { name: "Start free trial" });+ screen.getByText("No charge until the trial ends. Cancel anytime.");+ });++ it("offers plans, not another trial, to a returning organization", async () => {+ mocks.prompt = { isLoading: false, isOwner: true, trialEligible: false };+ mocks.addSite.mockResolvedValue({ siteId: 7 });+ renderStartTrial();++ screen.getByRole("button", { name: "Choose a plan" });+ expect(screen.queryByText(/trial/i)).toBeNull();++ submitDomain("example.com");+ expect((await screen.findByRole("dialog")).textContent).toContain("plans for /7 without trial");+ });+});++describe("StartTrial β admins and members", () => {+ it("points at the owner instead of offering a checkout they can't complete", () => {+ mocks.prompt = { isLoading: false, isOwner: false, trialEligible: true };+ renderStartTrial();++ screen.getByRole("heading", { name: "This organization doesn't have a plan yet" });+ screen.getByText("owner of org_1");+ expect(screen.queryByLabelText("Your domain")).toBeNull();+ });+});diff --git a/client/src/app/(home)/StartTrial.tsx b/client/src/app/(home)/StartTrial.tsxnew file mode 100644index 000000000..905ccf625--- /dev/null+++ b/client/src/app/(home)/StartTrial.tsx@@ -0,0 +1,149 @@+"use client";++import { Globe } from "lucide-react";+import { useExtracted } from "next-intl";+import { useId, useState } from "react";+import { addSite } from "../../api/admin/endpoints";+import { RybbitLogo } from "../../components/RybbitLogo";+import { Button } from "../../components/ui/button";+import { Input } from "../../components/ui/input";+import { isValidDomain, normalizeDomain } from "../../lib/utils";+import { LazyStartPlanDialog, OrganizationOwnerContact, usePlanPrompt } from "../components/PlanRequired";++/**+ * The home page of a cloud organization with no websites and no plan. The owner names the+ * site first, then picks a plan; checkout returns them to the new site's install+ * instructions. The site exists from the first step (as it does in signup) but collects+ * nothing until the plan starts. Other members are pointed at the owner, who alone can+ * start checkout.+ */+export function StartTrial({ organizationId, onSiteCreated }: { organizationId: string; onSiteCreated: () => void }) {+ const t = useExtracted();+ const { isLoading, isOwner, trialEligible } = usePlanPrompt(organizationId);+ const inputId = useId();+ const messageId = useId();++ const [domain, setDomain] = useState("");+ const [error, setError] = useState("");+ const [isCreating, setIsCreating] = useState(false);+ const [siteId, setSiteId] = useState<number | null>(null);+ const [planDialogOpen, setPlanDialogOpen] = useState(false);++ if (isLoading) return null;++ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();++ const normalizedDomain = normalizeDomain(domain);+ if (!isValidDomain(normalizedDomain)) {+ setError(t("Enter a domain like example.com"));+ return;+ }++ setIsCreating(true);+ setError("");+ try {+ const site = await addSite(normalizedDomain, normalizedDomain, organizationId);+ setSiteId(site.siteId);+ setPlanDialogOpen(true);+ } catch (addError) {+ setError(addError instanceof Error ? addError.message : String(addError));+ } finally {+ setIsCreating(false);+ }+ };++ return (+ <div className="flex flex-col items-center px-4 pt-16 pb-24 text-center sm:pt-24">+ <div className="mb-7">+ <RybbitLogo width={56} height={37} />+ </div>++ {isOwner ? (+ <div className="flex w-full max-w-[560px] flex-col items-center">+ <h1 className="mb-2.5 text-3xl font-semibold leading-tight tracking-tight">+ {t("What site do you want to track?")}+ </h1>+ <p className="mb-7 text-sm text-pretty text-neutral-500 dark:text-neutral-400">+ {trialEligible+ ? t(+ "Enter your domain to start a 7-day free trial. Your site will be ready to install as soon as checkout is done."+ )+ : t(+ "Enter your domain and choose a plan. Your site will be ready to install as soon as checkout is done."+ )}+ </p>++ <form onSubmit={handleSubmit} className="flex w-full flex-col gap-2 sm:flex-row">+ <label htmlFor={inputId} className="sr-only">+ {t("Your domain")}+ </label>+ <div className="relative flex-1">+ <Globe+ aria-hidden="true"+ className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-neutral-400 dark:text-neutral-500"+ />+ <Input+ id={inputId}+ value={domain}+ onChange={event => setDomain(event.target.value)}+ placeholder="yourdomain.com"+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ aria-invalid={!!error}+ aria-describedby={messageId}+ disabled={siteId !== null}+ className="h-10 pl-9 text-base sm:text-sm"+ />+ </div>+ {siteId === null ? (+ <Button type="submit" variant="success" className="h-10 px-4" loading={isCreating}>+ {trialEligible ? t("Start free trial") : t("Choose a plan")}+ </Button>+ ) : (+ <Button type="button" variant="success" className="h-10 px-4" onClick={() => setPlanDialogOpen(true)}>+ {trialEligible ? t("Start free trial") : t("Choose a plan")}+ </Button>+ )}+ </form>++ {error ? (+ <p id={messageId} role="alert" className="mt-3.5 text-sm text-red-500 dark:text-red-400">+ {error}+ </p>+ ) : (+ <p id={messageId} className="mt-3.5 text-xs text-neutral-500 dark:text-neutral-400">+ {trialEligible ? t("No charge until the trial ends. Cancel anytime.") : t("Cancel anytime.")}+ </p>+ )}++ {siteId !== null && (+ <LazyStartPlanDialog+ open={planDialogOpen}+ onOpenChange={setPlanDialogOpen}+ organizationId={organizationId}+ returnPath={`/${siteId}`}+ trialEligible={trialEligible}+ onDone={onSiteCreated}+ />+ )}+ </div>+ ) : (+ <div className="flex w-full max-w-[440px] flex-col items-center gap-5">+ <div className="flex flex-col gap-2.5">+ <h1 className="text-xl font-semibold leading-tight tracking-tight">+ {t("This organization doesn't have a plan yet")}+ </h1>+ <p className="text-sm text-pretty text-neutral-500 dark:text-neutral-400">+ {t("Only the owner can start one. Once they do, you can add websites here.")}+ </p>+ </div>+ <div className="w-full">+ <OrganizationOwnerContact organizationId={organizationId} />+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/app/(home)/page.tsx b/client/src/app/(home)/page.tsxindex e8dee7d44..3f2bdc23a 100644--- a/client/src/app/(home)/page.tsx+++ b/client/src/app/(home)/page.tsx@@ -22,10 +22,14 @@ import { MultiSelect } from "../../components/ui/multi-select";import { Pagination } from "../../components/pagination";import { useSetPageTitle } from "../../hooks/useSetPageTitle";import { authClient } from "../../lib/auth";+import { IS_CLOUD } from "../../lib/const";import { canGoBack, canGoForward, goBack, goForward, useStore } from "../../lib/store";+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";import { useSyncStateWithUrl } from "../../lib/urlParams";import { AddSite } from "../components/AddSite";+import { PlanRequiredNotice, useCheckoutReturn } from "../components/PlanRequired";import { SiteCards } from "./SiteCards";+import { StartTrial } from "./StartTrial";// Bound both rendering and the lite analytics batch for large organizations.const PAGE_SIZE = 20;@@ -41,7 +45,17 @@ export default function Home() {const { time, setTime } = useStore();const { data: activeOrganization, isPending } = authClient.useActiveOrganization();- const { data: sites, refetch: refetchSites, isLoading: isLoadingSites } = useGetSitesFromOrg(activeOrganization?.id);+ // Back from checkout started from the banner below: keep asking until the sites are on.+ const checkoutReturnPending = useCheckoutReturn();+ const {+ data: sites,+ refetch: refetchSites,+ isLoading: isLoadingSites,+ } = useGetSitesFromOrg(activeOrganization?.id, {+ refetchInterval: checkoutReturnPending+ ? query => (query.state.data?.sites.some(site => site.requiresPlan) ? 3000 : false)+ : undefined,+ });const {data: userOrganizationsData,@@ -49,8 +63,14 @@ export default function Home() {refetch: refetchOrganizations,} = useUserOrganizations();+ // On cloud an organization without a trial or plan can't track anything, so an empty+ // home page asks for a website and a plan instead of offering "Add Website".+ const { data: subscription, isLoading: isLoadingSubscription } = useStripeSubscription();+ const hasNoPlan =+ IS_CLOUD && !!subscription && subscription.status !== "active" && subscription.status !== "trialing";+// Consolidated loading state- const isLoading = isLoadingOrganizations || isPending || isLoadingSites;+ const isLoading = isLoadingOrganizations || isPending || isLoadingSites || (IS_CLOUD && isLoadingSubscription);// Check if user has organizationsconst hasOrganizations = Array.isArray(userOrganizationsData) && userOrganizationsData.length > 0;@@ -65,6 +85,8 @@ export default function Home() {// Check if we should show sites contentconst shouldShowSites = hasOrganizations && !isLoading;const hasNoSites = shouldShowSites && (!sites?.sites || sites.sites.length === 0);+ const sitesRequirePlan =+ shouldShowSites && !checkoutReturnPending && !!sites?.sites?.some(site => site.requiresPlan);const { data: teamsData } = useTeams(activeOrganization?.id);@@ -208,7 +230,10 @@ export default function Home() {<CardDescription>{t("Try adjusting your filters")}</CardDescription></Card>) : null}- {hasNoSites ? (+ {hasNoSites && hasNoPlan && activeOrganization ? (+ <StartTrial organizationId={activeOrganization.id} onSiteCreated={refetchSites} />+ ) : null}+ {hasNoSites && !hasNoPlan ? (<Card className="p-6 flex flex-col items-center text-center"><CardTitle className="mb-2 text-xl">{t("No websites yet")}</CardTitle><CardDescription className="mb-4">{t("Add your first website to start tracking analytics")}</CardDescription>@@ -242,6 +267,9 @@ export default function Home() {const content = (<>{hasNoOrganizations && <NoOrganization />}+ {sitesRequirePlan && activeOrganization ? (+ <PlanRequiredNotice organizationId={activeOrganization.id} returnPath="/" className="mb-4" />+ ) : null}{filterBar}{siteCards}{pagination}diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsxindex 67df19f61..b556c2495 100644--- a/client/src/app/[site]/components/Header/Header.tsx+++ b/client/src/app/[site]/components/Header/Header.tsx@@ -5,6 +5,7 @@ import { useGetSite } from "../../../../api/admin/hooks/useSites";import { FreePlanBanner } from "../../../../components/FreePlanBanner";import { useStore } from "../../../../lib/store";import { userStore } from "../../../../lib/userStore";+import { PlanRequiredNotice, useCheckoutReturn } from "../../../components/PlanRequired";import { AffiliateBanner } from "./AffiliateBanner";import { ClaimSiteBanner } from "./ClaimSiteBanner";import { DemoSignupBanner } from "./DemoSignupBanner";@@ -14,8 +15,16 @@ import { UsageBanners } from "./UsageBanners";export function Header() {const { user } = userStore();const { site } = useStore();- const { data: siteMetadata } = useGetSite(site);const pathname = usePathname();+ // Back from checkout: keep asking until the site stops needing a plan.+ const checkoutReturnPending = useCheckoutReturn();+ const { data: siteMetadata } = useGetSite(site, {+ refetchInterval: checkoutReturnPending ? query => (query.state.data?.requiresPlan ? 3000 : false) : undefined,+ });+ // The site collects nothing until its organization starts a plan: ask for one instead of+ // showing usage banners and install instructions that can't work yet. Straight after+ // checkout, show the install card while the plan catches up.+ const requiresPlan = !!siteMetadata?.requiresPlan && !!siteMetadata.organizationId && !checkoutReturnPending;// An unclaimed site's visitor has no session, but still needs the claim// banner and the install instructions.@@ -31,7 +40,15 @@ export function Header() {<div className="flex flex-col"><div className="flex flex-col px-2 md:px-4"><ClaimSiteBanner />- {user && !isGlobe && !isUnclaimed && (+ {user && !isGlobe && !isUnclaimed && requiresPlan && siteMetadata?.organizationId && (+ <PlanRequiredNotice+ organizationId={siteMetadata.organizationId}+ siteName={siteMetadata.name}+ returnPath={`/${siteMetadata.siteId}`}+ className="mt-4"+ />+ )}+ {user && !isGlobe && !isUnclaimed && !requiresPlan && (<><DemoSignupBanner />{/* <AffiliateBanner /> */}@@ -39,7 +56,7 @@ export function Header() {<UsageBanners /></>)}- {!isGlobe && <NoData />}+ {!isGlobe && !requiresPlan && <NoData />}</div></div>);diff --git a/client/src/app/components/PlanRequired.test.tsx b/client/src/app/components/PlanRequired.test.tsxnew file mode 100644index 000000000..51819a1b5--- /dev/null+++ b/client/src/app/components/PlanRequired.test.tsx@@ -0,0 +1,83 @@+import { act, cleanup, render, renderHook, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { PlanRequiredNotice, useCheckoutReturn } from "./PlanRequired";++const mocks = vi.hoisted(() => ({+ useStripeSubscription: vi.fn(),+ organizations: { data: [{ id: "org_b", role: "owner" }], isLoading: false } as {+ data: { id: string; role: string }[] | undefined;+ isLoading: boolean;+ },+ search: "",+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, string>) =>+ message.replace(/\{(\w+)\}/g, (_, key) => values?.[key] ?? ""),+}));+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(mocks.search) }));+vi.mock("next/dynamic", () => ({ default: () => () => null }));+vi.mock("@/api/admin/hooks/useOrganizations", () => ({ useUserOrganizations: () => mocks.organizations }));+vi.mock("@/api/admin/hooks/useOrganizationMembers", () => ({ useOrganizationMembers: () => ({ data: undefined }) }));+vi.mock("@/lib/subscription/useStripeSubscription", () => ({ useStripeSubscription: mocks.useStripeSubscription }));++beforeEach(() => {+ mocks.organizations = { data: [{ id: "org_b", role: "owner" }], isLoading: false };+ mocks.useStripeSubscription.mockReturnValue({ data: { trialEligible: true }, isLoading: false });+ mocks.search = "";+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.useRealTimers();+});++describe("PlanRequiredNotice", () => {+ it("reads trial eligibility from the site's organization, not the active one", () => {+ mocks.useStripeSubscription.mockReturnValue({ data: { trialEligible: false }, isLoading: false });++ render(<PlanRequiredNotice organizationId="org_b" siteName="example.com" returnPath="/42" />);++ expect(mocks.useStripeSubscription).toHaveBeenCalledWith("org_b");+ screen.getByRole("button", { name: "Choose a plan" });+ expect(screen.queryByText(/trial/i)).toBeNull();+ });++ it("promises nothing until the organization's history has loaded", () => {+ mocks.useStripeSubscription.mockReturnValue({ data: undefined, isLoading: true });++ const { container } = render(<PlanRequiredNotice organizationId="org_b" returnPath="/" />);++ expect(container.textContent).toBe("");+ });+});++describe("useCheckoutReturn", () => {+ it("holds back the notice for two minutes after checkout and drops session_id from the URL", () => {+ vi.useFakeTimers();+ mocks.search = "session_id=cs_123";+ window.history.replaceState(null, "", "/42/main?session_id=cs_123&timeMode=day");++ const { result } = renderHook(() => useCheckoutReturn());++ expect(result.current).toBe(true);+ expect(window.location.search).toBe("?timeMode=day");++ act(() => {+ vi.advanceTimersByTime(119_000);+ });+ expect(result.current).toBe(true);+ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ expect(result.current).toBe(false);+ });++ it("is false on an ordinary visit", () => {+ const { result } = renderHook(() => useCheckoutReturn());++ expect(result.current).toBe(false);+ });+});diff --git a/client/src/app/components/PlanRequired.tsx b/client/src/app/components/PlanRequired.tsxnew file mode 100644index 000000000..0f29dfa76--- /dev/null+++ b/client/src/app/components/PlanRequired.tsx@@ -0,0 +1,181 @@+"use client";++import { ArrowRight } from "lucide-react";+import { useExtracted } from "next-intl";+import dynamic from "next/dynamic";+import { useSearchParams } from "next/navigation";+import { useEffect, useState } from "react";+import { useOrganizationMembers } from "@/api/admin/hooks/useOrganizationMembers";+import { useUserOrganizations } from "@/api/admin/hooks/useOrganizations";+import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/sonner";+import { useStripeSubscription } from "@/lib/subscription/useStripeSubscription";+import { cn } from "@/lib/utils";++// Code-split: @stripe/stripe-js injects Stripe.js as soon as it is imported, and these+// prompts render on the home page and every dashboard page. Mount it only once someone+// starts choosing a plan.+export const LazyStartPlanDialog = dynamic(() => import("./StartPlanDialog").then(mod => mod.StartPlanDialog), {+ ssr: false,+});++/**+ * Who is looking at an organization with no plan, and what they can do about it. Only the+ * owner can start checkout (the server enforces it). An organization that already had a+ * subscription is offered plans, not another trial.+ */+export function usePlanPrompt(organizationId: string | undefined) {+ const { data: organizations, isLoading: isLoadingOrganizations } = useUserOrganizations();+ // This organization's subscription, not the active one's: a dashboard can belong to another+ // organization the person is in, and only that one's history decides whether a trial is on offer.+ const { data: subscription, isLoading: isLoadingSubscription } = useStripeSubscription(organizationId);+ const role = organizations?.find(org => org.id === organizationId)?.role;+ return {+ isLoading: isLoadingOrganizations || isLoadingSubscription,+ isOwner: role === "owner",+ trialEligible: subscription?.trialEligible !== false,+ };+}++// Longer than the server's 60-second per-worker subscription cache, so the polling below+// outlasts any cached "no plan" answer from before checkout.+const CHECKOUT_RETURN_WINDOW_MS = 2 * 60_000;++/**+ * True for two minutes after Stripe checkout sends someone back (`?session_id=`): the new+ * plan can take a while to reach every server, so callers keep polling and hold back the+ * "no plan" notice meanwhile. The parameter leaves the URL straight away, so a saved or+ * reloaded link can't hide the notice again.+ */+export function useCheckoutReturn(): boolean {+ const searchParams = useSearchParams();+ const [pending, setPending] = useState(() => searchParams.has("session_id"));++ useEffect(() => {+ if (!pending) return;+ const url = new URL(window.location.href);+ if (url.searchParams.has("session_id")) {+ url.searchParams.delete("session_id");+ window.history.replaceState(null, "", url);+ }+ const timer = setTimeout(() => setPending(false), CHECKOUT_RETURN_WINDOW_MS);+ return () => clearTimeout(timer);+ }, [pending]);++ return pending;+}++/** The organization owner's name and email, for members who can't start a plan themselves. */+export function OrganizationOwnerContact({ organizationId }: { organizationId: string }) {+ const t = useExtracted();+ const { data: members } = useOrganizationMembers(organizationId);+ const owner = members?.data.find(member => member.role === "owner");++ if (!owner) return null;++ const displayName = owner.user.name || owner.user.email;++ const copyEmail = async () => {+ await navigator.clipboard.writeText(owner.user.email);+ toast.success(t("Copied to clipboard"));+ };++ return (+ <div className="flex items-center gap-3 rounded-lg border border-neutral-150 px-3 py-2.5 text-left dark:border-neutral-800">+ <div+ aria-hidden="true"+ className="flex size-8 shrink-0 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200"+ >+ {displayName.slice(0, 1).toUpperCase()}+ </div>+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm text-neutral-900 dark:text-neutral-100">{displayName}</span>+ <span className="truncate text-xs text-neutral-500 dark:text-neutral-400">+ {t("{email} Β· Owner", { email: owner.user.email })}+ </span>+ </div>+ <Button size="sm" onClick={copyEmail} className="ml-auto">+ {t("Copy email")}+ </Button>+ </div>+ );+}++/**+ * Shown in place of the install instructions on a site that collects nothing until its+ * organization starts a plan, and above the site list when any site is in that state.+ * `siteName` names the site on its own dashboard; without it the copy covers every site.+ */+export function PlanRequiredNotice({+ organizationId,+ siteName,+ returnPath,+ className,+}: {+ organizationId: string;+ siteName?: string;+ returnPath: string;+ className?: string;+}) {+ const t = useExtracted();+ const { isLoading, isOwner, trialEligible } = usePlanPrompt(organizationId);+ const [planDialogOpen, setPlanDialogOpen] = useState(false);+ const [planFlowStarted, setPlanFlowStarted] = useState(false);++ // Wait for the role and the organization's history rather than promising a trial it can't have.+ if (isLoading) return null;++ const title = siteName+ ? t("{site} isn't collecting data", { site: siteName })+ : t("Your websites aren't collecting data");++ let description = t("Only the organization owner can start a plan. Tracking turns on as soon as they do.");+ if (isOwner) {+ description = trialEligible+ ? t("Start your 7-day free trial to turn tracking on. You won't be charged until the trial ends.")+ : t("Choose a plan to turn tracking back on.");+ }++ return (+ <section+ aria-label={title}+ className={cn(+ "flex flex-col gap-4 rounded-lg border border-neutral-100 bg-white p-4 dark:border-neutral-850 dark:bg-neutral-900 sm:flex-row sm:items-center sm:justify-between",+ className+ )}+ >+ <div className="flex flex-col gap-1.5">+ <h2 className="text-base font-semibold leading-tight tracking-tight">{title}</h2>+ <p className="text-sm text-neutral-500 dark:text-neutral-400">{description}</p>+ </div>+ {isOwner ? (+ <>+ <Button+ variant="success"+ className="shrink-0"+ onClick={() => {+ setPlanFlowStarted(true);+ setPlanDialogOpen(true);+ }}+ >+ {trialEligible ? t("Start free trial") : t("Choose a plan")}+ <ArrowRight />+ </Button>+ {planFlowStarted && (+ <LazyStartPlanDialog+ open={planDialogOpen}+ onOpenChange={setPlanDialogOpen}+ organizationId={organizationId}+ returnPath={returnPath}+ trialEligible={trialEligible}+ />+ )}+ </>+ ) : (+ <div className="shrink-0 sm:w-96">+ <OrganizationOwnerContact organizationId={organizationId} />+ </div>+ )}+ </section>+ );+}diff --git a/client/src/app/components/StartPlanDialog.tsx b/client/src/app/components/StartPlanDialog.tsxnew file mode 100644index 000000000..35220709c--- /dev/null+++ b/client/src/app/components/StartPlanDialog.tsx@@ -0,0 +1,104 @@+"use client";++import { useExtracted } from "next-intl";+import { useState } from "react";+import { AuthError } from "@/components/auth/AuthError";+import { CheckoutModal } from "@/components/subscription/components/CheckoutModal";+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";+import { createCheckoutSession } from "@/lib/subscription/checkout";+import { EVENT_TIERS, findPriceForTier } from "@/lib/subscription/planUtils";+import { trackAdEvent } from "@/lib/trackAdEvent";+import { PlanStep } from "../signup/components/PlanStep";++/**+ * Picks a plan and opens embedded checkout for an organization that has none: the signup+ * plan step in a dialog. Stripe returns the customer to `returnPath`. `onDone` runs once the+ * flow is over, whether it ended in checkout or the person closed it.+ */+export function StartPlanDialog({+ open,+ onOpenChange,+ organizationId,+ returnPath,+ trialEligible,+ onDone,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ organizationId: string;+ returnPath: string;+ trialEligible: boolean;+ onDone?: () => void;+}) {+ const t = useExtracted();+ const [eventLimitIndex, setEventLimitIndex] = useState(0);+ const [isAnnual, setIsAnnual] = useState(true);+ const [selectedPlan, setSelectedPlan] = useState<"standard" | "pro">("pro");+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState("");+ const [checkoutClientSecret, setCheckoutClientSecret] = useState<string | null>(null);++ const handleSubscribe = async () => {+ const eventLimit = EVENT_TIERS[eventLimitIndex];+ if (eventLimit === "Custom") return;++ const price = findPriceForTier(eventLimit, isAnnual ? "year" : "month", selectedPlan);+ if (!price) {+ setError(t("Could not find a matching plan. Please try a different selection."));+ return;+ }++ setIsLoading(true);+ setError("");+ try {+ const clientSecret = await createCheckoutSession({ priceId: price.priceId, organizationId, returnPath });+ trackAdEvent("checkout", { tier: price.name });+ setCheckoutClientSecret(clientSecret);+ onOpenChange(false);+ } catch (checkoutError) {+ setError(checkoutError instanceof Error ? checkoutError.message : String(checkoutError));+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <>+ <Dialog+ open={open}+ onOpenChange={next => {+ onOpenChange(next);+ if (!next && !checkoutClientSecret) onDone?.();+ }}+ >+ <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">+ <DialogTitle className="sr-only">{t("Choose your plan")}</DialogTitle>+ <div className="flex flex-col gap-4">+ <PlanStep+ eventLimitIndex={eventLimitIndex}+ setEventLimitIndex={setEventLimitIndex}+ isAnnual={isAnnual}+ setIsAnnual={setIsAnnual}+ selectedPlan={selectedPlan}+ setSelectedPlan={setSelectedPlan}+ onSubscribe={handleSubscribe}+ isLoading={isLoading}+ trialEligible={trialEligible}+ />+ <AuthError error={error} />+ </div>+ </DialogContent>+ </Dialog>+ <CheckoutModal+ clientSecret={checkoutClientSecret}+ open={!!checkoutClientSecret}+ onOpenChange={next => {+ if (!next) {+ setCheckoutClientSecret(null);+ onDone?.();+ }+ }}+ />+ </>+ );+}diff --git a/client/src/app/signup/components/PlanStep.tsx b/client/src/app/signup/components/PlanStep.tsxindex 3d01c17fd..90a77df51 100644--- a/client/src/app/signup/components/PlanStep.tsx+++ b/client/src/app/signup/components/PlanStep.tsx@@ -17,6 +17,8 @@ interface PlanStepProps {setSelectedPlan: (v: "standard" | "pro") => void;onSubscribe: () => void;isLoading: boolean;+ // False for an organization that already had a subscription: checkout charges straight away.+ trialEligible?: boolean;}export function PlanStep({@@ -28,6 +30,7 @@ export function PlanStep({setSelectedPlan,onSubscribe,isLoading,+ trialEligible = true,}: PlanStepProps) {const t = useExtracted();const eventLimit = EVENT_TIERS[eventLimitIndex];@@ -132,7 +135,7 @@ export function PlanStep({disabled={isLoading}variant="success">- {isLoading ? t("Loading...") : t("Start free trial")}+ {isLoading ? t("Loading...") : trialEligible ? t("Start free trial") : t("Continue to checkout")}<ArrowRight className="ml-2 h-4 w-4" /></Button>)}@@ -140,7 +143,9 @@ export function PlanStep({{/* Footer text */}{eventLimit !== "Custom" && (<p className="text-xs text-neutral-500 dark:text-neutral-400">- {t("Your card won't be charged until your 7-day trial has ended. You can cancel anytime.")}+ {trialEligible+ ? t("Your card won't be charged until your 7-day trial has ended. You can cancel anytime.")+ : t("You'll be charged when you subscribe. You can cancel anytime.")}</p>)}</div>diff --git a/client/src/app/subscribe/components/PricingCards.tsx b/client/src/app/subscribe/components/PricingCards.tsxindex 989e889d4..cabb20ac3 100644--- a/client/src/app/subscribe/components/PricingCards.tsx+++ b/client/src/app/subscribe/components/PricingCards.tsx@@ -21,6 +21,7 @@ import {} from "./utils";import { CheckoutModal } from "@/components/subscription/components/CheckoutModal";+import { useStripeSubscription } from "@/lib/subscription/useStripeSubscription";import { useRouter } from "next/navigation";import { useQueryState } from "nuqs";@@ -35,6 +36,9 @@ export function PricingCards({ isLoggedIn }: { isLoggedIn: boolean }) {const [showTestPlan, setShowTestPlan] = useState(false);const [checkoutClientSecret, setCheckoutClientSecret] = useState<string | null>(null);const { data: activeOrg } = authClient.useActiveOrganization();+ const { data: subscription } = useStripeSubscription();+ // Checkout skips the trial for an organization that already had a subscription.+ const subscribeLabel = subscription?.trialEligible === false ? t("Subscribe") : t("Start free trial");useEffect(() => {function handleKeyDown(e: KeyboardEvent) {@@ -246,7 +250,7 @@ export function PricingCards({ isLoggedIn }: { isLoggedIn: boolean }) {annualPrice={standardAnnualPrice}isAnnual={isAnnual}isCustomTier={isCustomTier}- buttonText={isLoading ? t("Processing...") : isCustomTier ? t("Contact us") : t("Start free trial")}+ buttonText={isLoading ? t("Processing...") : isCustomTier ? t("Contact us") : subscribeLabel}features={STANDARD_FEATURES}onClick={() => handleSubscribe("standard")}disabled={isLoading}@@ -258,7 +262,7 @@ export function PricingCards({ isLoggedIn }: { isLoggedIn: boolean }) {monthlyPrice={proMonthlyPrice}annualPrice={proAnnualPrice}isAnnual={isAnnual}- buttonText={isLoading ? t("Processing...") : isCustomTier ? t("Contact us") : t("Start free trial")}+ buttonText={isLoading ? t("Processing...") : isCustomTier ? t("Contact us") : subscribeLabel}features={PRO_FEATURES}recommended={true}onClick={() => handleSubscribe("pro")}diff --git a/client/src/app/subscribe/components/PricingHeader.tsx b/client/src/app/subscribe/components/PricingHeader.tsxindex 43ac07cf2..f553741f0 100644--- a/client/src/app/subscribe/components/PricingHeader.tsx+++ b/client/src/app/subscribe/components/PricingHeader.tsx@@ -1,13 +1,32 @@import { useExtracted } from "next-intl";+import { useStripeSubscription } from "../../../lib/subscription/useStripeSubscription";export function PricingHeader() {const t = useExtracted();+ const { data: subscription } = useStripeSubscription();++ // An organization that already had a subscription gets plans, not another trial.+ if (subscription?.trialEligible === false) {+ return (+ <div className="mb-10 text-center max-w-3xl mx-auto">+ <h1 className="text-4xl md:text-5xl font-bold tracking-tight pb-4 text-transparent bg-clip-text bg-linear-to-b from-neutral-900 via-neutral-700 to-neutral-500 dark:from-white dark:via-gray-200 dark:to-gray-400">+ {t("Choose a plan")}+ </h1>+ <p className="text-lg text-neutral-600 dark:text-neutral-300 mb-6">+ {t("Pick up where you left off. You can cancel anytime.")}+ </p>+ </div>+ );+ }+return (<div className="mb-10 text-center max-w-3xl mx-auto"><h1 className="text-4xl md:text-5xl font-bold tracking-tight pb-4 text-transparent bg-clip-text bg-linear-to-b from-neutral-900 via-neutral-700 to-neutral-500 dark:from-white dark:via-gray-200 dark:to-gray-400">{t("Start for Free")}</h1>- <p className="text-lg text-neutral-600 dark:text-neutral-300 mb-6">{t("Start your 7-day free trial β no credit card charges until the trial ends.")}</p>+ <p className="text-lg text-neutral-600 dark:text-neutral-300 mb-6">+ {t("Start your 7-day free trial β no credit card charges until the trial ends.")}+ </p></div>);}diff --git a/client/src/lib/subscription/checkout.ts b/client/src/lib/subscription/checkout.tsnew file mode 100644index 000000000..364fa5581--- /dev/null+++ b/client/src/lib/subscription/checkout.ts@@ -0,0 +1,37 @@+import { BACKEND_URL } from "../const";++/**+ * Creates an embedded Stripe Checkout session for an organization and returns its client+ * secret. Stripe sends the customer back to `returnPath` with the session id appended.+ */+export async function createCheckoutSession({+ priceId,+ organizationId,+ returnPath,+}: {+ priceId: string;+ organizationId: string;+ returnPath: string;+}): Promise<string> {+ const separator = returnPath.includes("?") ? "&" : "?";+ const response = await fetch(`${BACKEND_URL}/stripe/create-checkout-session`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify({+ priceId,+ returnUrl: `${window.location.origin}${returnPath}${separator}session_id={CHECKOUT_SESSION_ID}`,+ organizationId,+ referral: window.Rewardful?.referral || undefined,+ }),+ });++ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || "Failed to create checkout session");+ }+ if (!data.clientSecret) {+ throw new Error("Checkout session not received");+ }+ return data.clientSecret;+}diff --git a/client/src/lib/subscription/useStripeSubscription.ts b/client/src/lib/subscription/useStripeSubscription.tsindex d67248bf2..2e78b7216 100644--- a/client/src/lib/subscription/useStripeSubscription.ts+++ b/client/src/lib/subscription/useStripeSubscription.ts@@ -18,26 +18,31 @@ export interface SubscriptionData {trialDaysRemaining?: number;message?: string; // For expired trial messageisOverride?: boolean;+ // Only on "free": false once the organization has had any subscription, so it is offered+ // plans instead of another trial (checkout skips the trial too).+ trialEligible?: boolean;memberLimit: number | null;siteLimit: number | null;}-export function useStripeSubscription(): UseQueryResult<SubscriptionData | undefined, Error> {+/** The subscription of `organizationId`, or of the active organization when omitted. */+export function useStripeSubscription(organizationId?: string): UseQueryResult<SubscriptionData | undefined, Error> {const { data: activeOrg } = authClient.useActiveOrganization();+ const orgId = organizationId ?? activeOrg?.id;const fetchSubscription = async () => {- if (!activeOrg || !IS_CLOUD) {+ if (!orgId || !IS_CLOUD) {return undefined;}- return authedFetch<SubscriptionData>(`/stripe/subscription?organizationId=${activeOrg.id}`);+ return authedFetch<SubscriptionData>(`/stripe/subscription?organizationId=${orgId}`);};return useQuery<SubscriptionData | undefined>({- queryKey: ["stripe-subscription", activeOrg?.id],+ queryKey: ["stripe-subscription", orgId],queryFn: fetchSubscription,staleTime: 5 * 60 * 1000,retry: false,- enabled: !!activeOrg,+ enabled: !!orgId,});}diff --git a/server/src/api/admin/adminOrganizationManagement.ts b/server/src/api/admin/adminOrganizationManagement.tsindex 368f57a4e..0bdb5f811 100644--- a/server/src/api/admin/adminOrganizationManagement.ts+++ b/server/src/api/admin/adminOrganizationManagement.ts@@ -7,6 +7,7 @@ import { member, memberSiteAccess, organization, sites, user } from "../../db/poimport { siteIdsInOrganization } from "../../lib/access.js";import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";import { APPSUMO_TIER_LIMITS, getStripePrices } from "../../lib/const.js";+import { usageService } from "../../services/usageService.js";const organizationOptionsQuerySchema = z.object({search: z.string().trim().max(200).optional().default(""),@@ -121,6 +122,7 @@ export async function updateAdminSubscriptionOverride(: { planOverride: null, customPlan: value.customPlan };await db.update(organization).set(update).where(eq(organization.id, org.id));+ usageService.requestOrganizationRefresh(org.id);return reply.send({ success: true, ...update });} catch (error) {request.log.error({ err: error }, "Failed to update subscription override");diff --git a/server/src/api/as/activate.ts b/server/src/api/as/activate.tsindex 4121745d2..3868cc561 100644--- a/server/src/api/as/activate.ts+++ b/server/src/api/as/activate.ts@@ -4,6 +4,7 @@ import { db } from "../../db/postgres/postgres.js";import { asLicenses } from "../../db/postgres/schema-appsumo.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { IS_CLOUD } from "../../lib/const.js";+import { usageService } from "../../services/usageService.js";/*** Check if AppSumo integration is enabled@@ -191,6 +192,9 @@ export async function activateAppSumoLicense(`);}+ // Turn on sites that were waiting for a plan without waiting for the usage check.+ usageService.requestOrganizationRefresh(organizationId);+return reply.status(200).send({success: true,license: {diff --git a/server/src/api/sites/addSite.test.ts b/server/src/api/sites/addSite.test.tsindex a8467e046..9ed915540 100644--- a/server/src/api/sites/addSite.test.ts+++ b/server/src/api/sites/addSite.test.ts@@ -10,6 +10,7 @@ const state = vi.hoisted(() => ({const mocks = vi.hoisted(() => ({getSubscriptionInner: vi.fn(),invalidateSitesAccessCache: vi.fn(),+ requestOrganizationRefresh: vi.fn(),}));vi.mock("../../db/postgres/postgres.js", () => ({@@ -48,6 +49,10 @@ vi.mock("../stripe/getSubscription.js", () => ({getSubscriptionInner: mocks.getSubscriptionInner,}));+vi.mock("../../services/usageService.js", () => ({+ usageService: { requestOrganizationRefresh: mocks.requestOrganizationRefresh },+}));+vi.mock("../../lib/auth-utils.js", () => ({invalidateSitesAccessCache: mocks.invalidateSitesAccessCache,}));@@ -183,6 +188,9 @@ describe("addSite β cloud standard-feature gating (active subscription requireexpect(reply.statusCode).toBe(201);expect(state.insertedValues).toHaveLength(1);+ // The site is created, but the usage service is asked to block it right away until the+ // organization starts a plan.+ expect(mocks.requestOrganizationRefresh).toHaveBeenCalledWith(state.insertedValues[0].organizationId);});});diff --git a/server/src/api/sites/applySiteMove.ts b/server/src/api/sites/applySiteMove.tsindex 92d9faed6..c6abc1615 100644--- a/server/src/api/sites/applySiteMove.ts+++ b/server/src/api/sites/applySiteMove.ts@@ -3,6 +3,7 @@ import { db } from "../../db/postgres/postgres.js";import { memberSiteAccess, segments, sites, teamSiteAccess } from "../../db/postgres/schema.js";import type { SiteTransaction } from "../../services/sites/withOrganizationSiteLock.js";import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";+import { usageService } from "../../services/usageService.js";/*** Reassigns a site to a different organization and clears the access grants@@ -50,4 +51,9 @@ export async function invalidateSiteMoveAccess(sourceOrganizationId: string | nufor (const { userId } of affectedMembers) {invalidateSitesAccessCache(userId);}+ // The moved site now follows the target organization's plan. Refreshing the source too marks+ // it as newer than any cron run already holding the old ownership, which would otherwise+ // re-apply the source organization's blocks to the moved site.+ usageService.requestOrganizationRefresh(targetOrganizationId);+ usageService.requestOrganizationRefresh(sourceOrganizationId);}diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.tsindex abc2256a5..a99894f97 100644--- a/server/src/api/sites/getSite.ts+++ b/server/src/api/sites/getSite.ts@@ -2,8 +2,26 @@ import { claimExpiryIso } from "../../services/sites/claimExpiry.js";import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { sites } from "../../db/postgres/schema.js";+import { organization, sites } from "../../db/postgres/schema.js";import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";+import { getBestSubscription, siteRequiresPlan } from "../../lib/subscriptionUtils.js";++/**+ * Whether the site is switched off until its organization starts a plan. Sites from before+ * the free plan ended never need one, so only newer sites pay for the subscription lookup.+ */+async function getSiteRequiresPlan(site: { organizationId: string | null; createdAt: string | null }) {+ if (!site.organizationId || !siteRequiresPlan({ status: "free" }, site.createdAt)) {+ return false;+ }+ const [org] = await db+ .select({ stripeCustomerId: organization.stripeCustomerId })+ .from(organization)+ .where(eq(organization.id, site.organizationId))+ .limit(1);+ const subscription = await getBestSubscription(site.organizationId, org?.stripeCustomerId ?? null);+ return siteRequiresPlan(subscription, site.createdAt);+}interface GetSiteParams {Params: {@@ -24,8 +42,10 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fasreturn reply.status(404).send({ error: "Site not found" });}- // Check if user has admin access- const isOwner = await getUserHasAdminAccessToSite(request, site.siteId);+ const [isOwner, requiresPlan] = await Promise.all([+ getUserHasAdminAccessToSite(request, site.siteId),+ getSiteRequiresPlan(site),+ ]);return reply.status(200).send({id: site.id,@@ -45,6 +65,7 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: FasfirstPartyProxy: site.firstPartyProxy,trackIp: site.trackIp,isOwner: isOwner,+ requiresPlan,// Analytics featuressessionReplay: site.sessionReplay,webVitals: site.webVitals,diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.tsindex b10d469cb..adcb4893f 100644--- a/server/src/api/sites/getSitesFromOrg.ts+++ b/server/src/api/sites/getSitesFromOrg.ts@@ -7,6 +7,7 @@ import { DEFAULT_EVENT_LIMIT, IS_CLOUD, LITE_DASHBOARD } from "../../lib/const.jimport { getUserIdFromRequest } from "../../lib/auth-utils.js";import { filterSitesByMemberAccess, getOrgMembership } from "../../lib/access.js";import { processResults } from "../analytics/utils/utils.js";+import { siteRequiresPlan } from "../../lib/subscriptionUtils.js";import { getSubscriptionInner } from "../stripe/getSubscription.js";import { buildSiteSessionCountsQuery } from "./siteSessionCountsQuery.js";@@ -109,6 +110,7 @@ export async function getSitesFromOrg(sessionsLast24Hours: sessionCountMap.get(site.siteId) || 0,isOwner: memberRecord?.role !== "member",teams: siteTeamMap.get(site.siteId) || [],+ requiresPlan: siteRequiresPlan(subscription, site.createdAt),}));// Sort by sessions descendingdiff --git a/server/src/api/sites/updateSiteConfig.test.ts b/server/src/api/sites/updateSiteConfig.test.tsindex 4b934c792..32e2fd6f4 100644--- a/server/src/api/sites/updateSiteConfig.test.ts+++ b/server/src/api/sites/updateSiteConfig.test.ts@@ -12,6 +12,10 @@ const mocks = vi.hoisted(() => ({getConfig: vi.fn(async () => ({ siteId: 1 })),}));+vi.mock("../../services/usageService.js", () => ({+ usageService: { requestOrganizationRefresh: vi.fn() },+}));+vi.mock("../../db/postgres/postgres.js", () => ({db: {query: {diff --git a/server/src/api/stripe/createCheckoutSession.test.ts b/server/src/api/stripe/createCheckoutSession.test.tsindex 94d00caf1..e8d56c2a8 100644--- a/server/src/api/stripe/createCheckoutSession.test.ts+++ b/server/src/api/stripe/createCheckoutSession.test.ts@@ -3,12 +3,14 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({customersCreate: vi.fn(),checkoutSessionsCreate: vi.fn(),+ subscriptionsList: vi.fn(),}));vi.mock("../../lib/stripe.js", () => ({stripe: {customers: { create: mocks.customersCreate },checkout: { sessions: { create: mocks.checkoutSessionsCreate } },+ subscriptions: { list: mocks.subscriptionsList },},}));@@ -24,6 +26,7 @@ vi.mock("../../db/postgres/postgres.js", async () => {});import { sql } from "../../db/postgres/postgres.js";+import { invalidateStripeSubscriptionCache } from "../../lib/subscriptionUtils.js";import { createCheckoutSession } from "./createCheckoutSession.js";const DDL = `@@ -78,6 +81,47 @@ beforeEach(async () => {`);mocks.customersCreate.mockResolvedValue({ id: "cus_new" });mocks.checkoutSessionsCreate.mockResolvedValue({ client_secret: "cs_secret_123" });+ mocks.subscriptionsList.mockResolvedValue({ data: [] });+ invalidateStripeSubscriptionCache("cus_1");+});++describe("createCheckoutSession β one trial per organization", () => {+ it("gives an organization with no subscription history the 7-day trial", async () => {+ await createCheckoutSession(requestStub("u_owner", validBody), replyStub());++ expect(mocks.checkoutSessionsCreate).toHaveBeenCalledWith(+ expect.objectContaining({ subscription_data: { trial_period_days: 7 } })+ );+ });++ it("charges a returning customer straight away instead of starting another trial", async () => {+ mocks.subscriptionsList.mockResolvedValue({ data: [{ id: "sub_old", status: "canceled" }] });++ await createCheckoutSession(requestStub("u_owner", validBody), replyStub());++ expect(mocks.subscriptionsList).toHaveBeenCalledWith(expect.objectContaining({ customer: "cus_1" }));+ expect(mocks.checkoutSessionsCreate.mock.calls[0][0]).not.toHaveProperty("subscription_data");+ });++ it("fails the checkout instead of granting a trial when the customer's history can't be read", async () => {+ mocks.subscriptionsList.mockRejectedValue(new Error("stripe unavailable"));+ const reply = replyStub();++ await createCheckoutSession({ ...requestStub("u_owner", validBody), log: { error: vi.fn() } }, reply);++ expect(reply.statusCode).toBe(500);+ expect(mocks.checkoutSessionsCreate).not.toHaveBeenCalled();+ });++ it("still offers the trial after an abandoned checkout", async () => {+ mocks.subscriptionsList.mockResolvedValue({ data: [{ id: "sub_abandoned", status: "incomplete_expired" }] });++ await createCheckoutSession(requestStub("u_owner", validBody), replyStub());++ expect(mocks.checkoutSessionsCreate).toHaveBeenCalledWith(+ expect.objectContaining({ subscription_data: { trial_period_days: 7 } })+ );+ });});describe("createCheckoutSession β authorization", () => {diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.tsindex 1b065cdfb..844ec08f2 100644--- a/server/src/api/stripe/createCheckoutSession.ts+++ b/server/src/api/stripe/createCheckoutSession.ts@@ -5,6 +5,7 @@ import { db } from "../../db/postgres/postgres.js";import { organization, user as userSchema } from "../../db/postgres/schema.js";import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import { stripe } from "../../lib/stripe.js";+import { hasHadStripeSubscription } from "../../lib/subscriptionUtils.js";interface CheckoutRequestBody {priceId: string;@@ -69,6 +70,10 @@ export async function createCheckoutSession(}let stripeCustomerId = org.stripeCustomerId;+ // One free trial per organization. A customer created just below has no history. If the+ // history can't be read this throws, so checkout fails and can be retried rather than+ // handing a returning customer another trial.+ const trialEligible = !(await hasHadStripeSubscription(stripeCustomerId, { throwOnError: true }));// 3. If the organization doesn't have a Stripe Customer ID, create oneif (!stripeCustomerId) {@@ -105,8 +110,8 @@ export async function createCheckoutSession(metadata: {organizationId: organizationId,},- // 7-day free trial before charging- subscription_data: { trial_period_days: 7 },+ // 7-day free trial before charging, unless this organization already had one+ ...(trialEligible && { subscription_data: { trial_period_days: 7 } }),// Allow promotion codesallow_promotion_codes: true,// Enable automatic tax calculation if configured in Stripe Tax settingsdiff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.tsindex 2b51fcd99..d48d3c940 100644--- a/server/src/api/stripe/getSubscription.ts+++ b/server/src/api/stripe/getSubscription.ts@@ -15,7 +15,12 @@ import {STANDARD_MEMBER_LIMIT,STANDARD_SITE_LIMIT,} from "../../lib/const.js";-import { getBestSubscription, subscriptionIncludesReplay, SubscriptionInfo } from "../../lib/subscriptionUtils.js";+import {+ getBestSubscription,+ hasHadStripeSubscription,+ subscriptionIncludesReplay,+ SubscriptionInfo,+} from "../../lib/subscriptionUtils.js";function getStartOfMonth() {return DateTime.now().startOf("month").toJSDate();@@ -204,6 +209,9 @@ export async function getSubscriptionInner(organizationId: string) {eventLimit: subscription.eventLimit,monthlyEventCount: org.monthlyEventCount || 0,trialDaysRemaining: 0,+ // One trial per organization: false once it has had any subscription (trial ended,+ // canceled, lapsed), so the app offers plans instead of a trial.+ trialEligible: !(await hasHadStripeSubscription(org.stripeCustomerId)),includesReplay,...limits,};diff --git a/server/src/api/stripe/webhook.test.ts b/server/src/api/stripe/webhook.test.tsindex 9a35ea99a..b74421c3c 100644--- a/server/src/api/stripe/webhook.test.ts+++ b/server/src/api/stripe/webhook.test.ts@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => {previousWebhookSecret,constructEvent: vi.fn(),invalidateStripeSubscriptionCache: vi.fn(),+ requestOrganizationRefresh: vi.fn(),select,selectWhere,selectLimit,@@ -43,6 +44,10 @@ vi.mock("../../lib/subscriptionUtils.js", () => ({invalidateStripeSubscriptionCache: mocks.invalidateStripeSubscriptionCache,}));+vi.mock("../../services/usageService.js", () => ({+ usageService: { requestOrganizationRefresh: mocks.requestOrganizationRefresh },+}));+import { handleWebhook } from "./webhook.js";const dialect = new PgDialect();@@ -210,6 +215,9 @@ describe("handleWebhook β checkout.session.completed", () => {const updateWhere = dialect.sqlToQuery(mocks.updateWhere.mock.calls[0][0] as SQL);expect(updateWhere.params).toEqual(["org_1"]);+ // And turned the org's sites on without waiting for the usage cron.+ expect(mocks.requestOrganizationRefresh).toHaveBeenCalledWith("org_1");+expect(reply.statusCode).toBe(200);expect(reply.payload).toEqual({ received: true });});@@ -230,6 +238,7 @@ describe("handleWebhook β checkout.session.completed", () => {expect(mocks.select).toHaveBeenCalledTimes(1);expect(mocks.update).not.toHaveBeenCalled();+ expect(mocks.requestOrganizationRefresh).toHaveBeenCalledWith("org_existing");expect(reply.payload).toEqual({ received: true });});@@ -318,8 +327,9 @@ describe("handleWebhook β checkout.session.completed", () => {describe("handleWebhook β subscription lifecycle events", () => {it.each(["customer.subscription.updated", "customer.subscription.deleted"])(- "invalidates the subscription cache for the event's customer on %s",+ "invalidates the subscription cache and refreshes the customer's org on %s",async eventType => {+ mocks.selectLimit.mockResolvedValue([{ id: "org_lifecycle" }]);mocks.constructEvent.mockReturnValue(stripeEvent(eventType, { id: "sub_1", customer: "cus_lifecycle" }));const reply = createReply();@@ -327,10 +337,27 @@ describe("handleWebhook β subscription lifecycle events", () => {expect(mocks.invalidateStripeSubscriptionCache).toHaveBeenCalledTimes(1);expect(mocks.invalidateStripeSubscriptionCache).toHaveBeenCalledWith("cus_lifecycle");- expectNoDbWrites();+ const lookupWhere = dialect.sqlToQuery(mocks.selectWhere.mock.calls[0][0] as SQL);+ expect(lookupWhere.params).toEqual(["cus_lifecycle"]);+ expect(mocks.requestOrganizationRefresh).toHaveBeenCalledWith("org_lifecycle");+ expect(mocks.update).not.toHaveBeenCalled();expect(reply.payload).toEqual({ received: true });});++ it("still acknowledges a lifecycle event when the org lookup fails", async () => {+ mocks.selectLimit.mockRejectedValue(new Error("db down"));+ mocks.constructEvent.mockReturnValue(+ stripeEvent("customer.subscription.deleted", { id: "sub_2", customer: "cus_lifecycle" })+ );++ const reply = createReply();+ await handleWebhook(createRequest(), reply);++ expect(mocks.requestOrganizationRefresh).not.toHaveBeenCalled();+ expect(reply.statusCode).toBe(200);+ expect(reply.payload).toEqual({ received: true });+ });});describe("handleWebhook β unhandled event types", () => {diff --git a/server/src/api/stripe/webhook.ts b/server/src/api/stripe/webhook.tsindex 1a75310d2..05b237e7c 100644--- a/server/src/api/stripe/webhook.ts+++ b/server/src/api/stripe/webhook.ts@@ -5,6 +5,7 @@ import { organization } from "../../db/postgres/schema.js";import { eq } from "drizzle-orm";import Stripe from "stripe";import { invalidateStripeSubscriptionCache } from "../../lib/subscriptionUtils.js";+import { usageService } from "../../services/usageService.js";import dotenv from "dotenv";dotenv.config();@@ -70,6 +71,8 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply"Organization already linked to Stripe customer");}+ // Turn the organization's sites on now rather than at the next usage check.+ usageService.requestOrganizationRefresh(existingOrg[0]?.id ?? organizationId);} catch (dbError: any) {request.log.error({ err: dbError, stripeCustomerId }, "Failed to link organization to Stripe customer");// Retriable failure: the org is still not linked to its Stripe customer.@@ -95,10 +98,24 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply// Note: invalidateStripeSubscriptionCache is a synchronous in-process Map delete β// it cannot fail, so there is no swallowed-error path here to convert to a 5xx.case "customer.subscription.updated":- case "customer.subscription.deleted":+ case "customer.subscription.deleted": {const changedSubscription = event.data.object as Stripe.Subscription;- invalidateStripeSubscriptionCache(changedSubscription.customer as string);+ const changedCustomerId = changedSubscription.customer as string;+ invalidateStripeSubscriptionCache(changedCustomerId);+ try {+ // A lapsed or canceled plan switches off sites that need one; a renewed plan switches+ // them back on. The usage cron would get there too, up to 30 minutes later.+ const [changedOrg] = await db+ .select({ id: organization.id })+ .from(organization)+ .where(eq(organization.stripeCustomerId, changedCustomerId))+ .limit(1);+ usageService.requestOrganizationRefresh(changedOrg?.id);+ } catch (dbError) {+ request.log.warn({ err: dbError, stripeCustomerId: changedCustomerId }, "Could not refresh organization usage");+ }break;+ }// ... handle other event types as neededdiff --git a/server/src/cluster.ts b/server/src/cluster.tsindex f053cfbf7..74fd51868 100644--- a/server/src/cluster.ts+++ b/server/src/cluster.ts@@ -7,7 +7,7 @@ import { lifecycleEmailService } from "./services/lifecycleEmails/lifecycleEmailimport { sessionsService } from "./services/sessions/sessionsService.js";import { telemetryService } from "./services/telemetryService.js";import { unclaimedSiteCleanupService } from "./services/sites/unclaimedSiteCleanupService.js";-import { usageService } from "./services/usageService.js";+import { REFRESH_ORGANIZATION_USAGE_MESSAGE, usageService } from "./services/usageService.js";import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";const logger = createServiceLogger("cluster");@@ -64,10 +64,19 @@ if (workerCount === 0) {cluster.fork();}+ // Workers ask the primary to re-evaluate an organization's blocked sites when a trial+ // starts or a site is added, so the change reaches every worker without waiting for the cron+ cluster.on("message", (_worker, message: { type?: string; organizationId?: unknown }) => {+ if (message?.type === REFRESH_ORGANIZATION_USAGE_MESSAGE && typeof message.organizationId === "string") {+ void usageService.refreshOrganizationWithRetry(message.organizationId);+ }+ });+// Send current usage state to a worker when it comes onlinecluster.on("online", worker => {logger.info(`Worker ${worker.process.pid} is online`);worker.send({ type: "sites-over-limit", siteIds: Array.from(usageService.getSitesOverLimit()) });+ worker.send({ type: "sites-without-plan", siteIds: Array.from(usageService.getSitesWithoutPlan()) });worker.send({ type: "sites-without-replay", siteIds: Array.from(usageService.getSitesWithoutReplay()) });});@@ -86,16 +95,18 @@ if (workerCount === 0) {*/function broadcastUsageState() {const overLimitIds = Array.from(usageService.getSitesOverLimit());+ const withoutPlanIds = Array.from(usageService.getSitesWithoutPlan());const withoutReplayIds = Array.from(usageService.getSitesWithoutReplay());for (const id in cluster.workers) {const worker = cluster.workers[id];if (worker && !worker.isDead()) {worker.send({ type: "sites-over-limit", siteIds: overLimitIds });+ worker.send({ type: "sites-without-plan", siteIds: withoutPlanIds });worker.send({ type: "sites-without-replay", siteIds: withoutReplayIds });}}logger.debug(- `Broadcasted ${overLimitIds.length} sites-over-limit and ${withoutReplayIds.length} sites-without-replay to workers`+ `Broadcasted ${overLimitIds.length} sites-over-limit, ${withoutPlanIds.length} sites-without-plan and ${withoutReplayIds.length} sites-without-replay to workers`);}diff --git a/server/src/index.ts b/server/src/index.tsindex 08f71ef1f..a119b6050 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -719,6 +719,9 @@ const start = async () => {if (message?.type === "sites-over-limit") {usageService.setSitesOverLimit(new Set(message.siteIds));server.log.debug(`Received ${message.siteIds.length} sites-over-limit from primary`);+ } else if (message?.type === "sites-without-plan") {+ usageService.setSitesWithoutPlan(new Set(message.siteIds));+ server.log.debug(`Received ${message.siteIds.length} sites-without-plan from primary`);} else if (message?.type === "sites-without-replay") {usageService.setSitesWithoutReplay(new Set(message.siteIds));server.log.debug(`Received ${message.siteIds.length} sites-without-replay from primary`);diff --git a/server/src/lib/const.ts b/server/src/lib/const.tsindex 2e112fa86..167b257df 100644--- a/server/src/lib/const.ts+++ b/server/src/lib/const.ts@@ -16,6 +16,12 @@ export const MAPBOX_TOKEN = process.env.MAPBOX_TOKEN;export const DEFAULT_EVENT_LIMIT = 3_000;+// Rybbit Cloud stopped offering the free plan on this date. Sites created before it keep+// the legacy free tier (DEFAULT_EVENT_LIMIT); sites created on or after it collect nothing+// until their organization starts a trial or paid plan. Compared against the "YYYY-MM-DD"+// prefix of sites.created_at.+export const FREE_PLAN_CUTOFF_DATE = "2026-02-13";+// Event types that count toward an organization's monthly usage limit.// Keep in sync with billing/usage docs; used by the usage cron and per-site usage endpoint.export const USAGE_COUNTED_EVENT_TYPES = [diff --git a/server/src/lib/subscriptionUtils.test.ts b/server/src/lib/subscriptionUtils.test.tsindex 2bb4f7386..edf43d85c 100644--- a/server/src/lib/subscriptionUtils.test.ts+++ b/server/src/lib/subscriptionUtils.test.ts@@ -18,8 +18,19 @@ const state = vi.hoisted(() => ({const mocks = vi.hoisted(() => ({list: vi.fn(),stripeEnabled: true,+ isCloud: true,}));+vi.mock("./const.js", async importOriginal => {+ const actual = await importOriginal<typeof import("./const.js")>();+ return {+ ...actual,+ get IS_CLOUD() {+ return mocks.isCloud;+ },+ };+});+vi.mock("../db/postgres/postgres.js", () => {// Drizzle builders are thenable; both org lookups await `.limit(1)`.function chain(rows: () => unknown[]) {@@ -73,11 +84,13 @@ import {getOverrideSubscription,getReplayLimit,getStripeSubscription,+ hasHadStripeSubscription,invalidateAllStripeSubscriptionsCache,invalidateStripeSubscriptionCache,OverrideSubscriptionInfo,StripeSubscriptionInfo,stripeSubscriptionInfoFromSnapshot,+ siteRequiresPlan,subscriptionIncludesReplay,} from "./subscriptionUtils.js";@@ -257,6 +270,7 @@ beforeEach(() => {state.orgSelectError = null;state.appsumoError = null;mocks.stripeEnabled = true;+ mocks.isCloud = true;mocks.list.mockReset();listReturns([]);invalidateAllStripeSubscriptionsCache();@@ -867,3 +881,93 @@ describe("getBestSubscriptionFromStripeSub", () => {expect(mocks.list).not.toHaveBeenCalled();});});++describe("siteRequiresPlan", () => {+ const free = { status: "free" };++ it("switches off a site created on or after the free plan ended in an org with no plan", () => {+ expect(siteRequiresPlan(free, "2026-02-13 00:00:00")).toBe(true);+ expect(siteRequiresPlan(free, "2026-09-29 12:34:56.789")).toBe(true);+ });++ it("keeps sites from the free-plan era on the legacy free tier", () => {+ expect(siteRequiresPlan(free, "2026-02-12 23:59:59")).toBe(false);+ expect(siteRequiresPlan(free, "2025-06-01 08:00:00")).toBe(false);+ });++ it("never switches off a site whose org has a plan", () => {+ for (const status of ["active", "trialing"]) {+ expect(siteRequiresPlan({ status }, "2026-09-29 12:00:00")).toBe(false);+ }+ });++ it("treats a missing creation date or subscription as not requiring a plan", () => {+ expect(siteRequiresPlan(free, null)).toBe(false);+ expect(siteRequiresPlan(null, "2026-09-29 12:00:00")).toBe(false);+ });++ it("never applies to self-hosted instances", () => {+ mocks.isCloud = false;+ expect(siteRequiresPlan(free, "2026-09-29 12:00:00")).toBe(false);+ });+});++describe("hasHadStripeSubscription", () => {+ beforeEach(() => {+ invalidateStripeSubscriptionCache("cus_history");+ });++ it("is false for an org that never reached checkout", async () => {+ await expect(hasHadStripeSubscription(null)).resolves.toBe(false);+ expect(mocks.list).not.toHaveBeenCalled();+ });++ it("is false when checkouts were only ever abandoned", async () => {+ listReturns([stripeSub({ customer: "cus_history", status: "incomplete_expired" })]);+ await expect(hasHadStripeSubscription("cus_history")).resolves.toBe(false);+ });++ it.each(["canceled", "past_due", "trialing", "active", "unpaid"])("is true once a %s subscription exists", async status => {+ listReturns([stripeSub({ customer: "cus_history", status })]);+ await expect(hasHadStripeSubscription("cus_history")).resolves.toBe(true);+ });++ it("caches per customer until the subscription cache is invalidated", async () => {+ listReturns([stripeSub({ customer: "cus_history", status: "canceled" })]);+ await hasHadStripeSubscription("cus_history");+ await hasHadStripeSubscription("cus_history");+ expect(mocks.list).toHaveBeenCalledTimes(1);++ invalidateStripeSubscriptionCache("cus_history");+ await hasHadStripeSubscription("cus_history");+ expect(mocks.list).toHaveBeenCalledTimes(2);+ });++ it("does not trust an expired 'never subscribed' answer when the caller needs certainty", async () => {+ listReturns([]);+ await hasHadStripeSubscription("cus_history");+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(Date.now() + 61_000);+ mocks.list.mockRejectedValue(new Error("stripe down"));++ await expect(hasHadStripeSubscription("cus_history", { throwOnError: true })).rejects.toThrow("stripe down");+ await expect(hasHadStripeSubscription("cus_history")).resolves.toBe(false);+ vi.useRealTimers();+ });++ it("keeps an expired 'had a subscription' answer when Stripe cannot be reached", async () => {+ listReturns([stripeSub({ customer: "cus_history", status: "canceled" })]);+ await hasHadStripeSubscription("cus_history");+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(Date.now() + 61_000);+ mocks.list.mockRejectedValue(new Error("stripe down"));++ await expect(hasHadStripeSubscription("cus_history", { throwOnError: true })).resolves.toBe(true);+ vi.useRealTimers();+ });++ it("offers the trial when Stripe cannot be reached", async () => {+ mocks.list.mockRejectedValue(new Error("stripe down"));+ await expect(hasHadStripeSubscription("cus_history")).resolves.toBe(false);+ });+});diff --git a/server/src/lib/subscriptionUtils.ts b/server/src/lib/subscriptionUtils.tsindex 602094363..5b7076808 100644--- a/server/src/lib/subscriptionUtils.ts+++ b/server/src/lib/subscriptionUtils.ts@@ -7,7 +7,9 @@ import {APPSUMO_REPLAY_LIMITS,APPSUMO_TIER_LIMITS,DEFAULT_EVENT_LIMIT,+ FREE_PLAN_CUTOFF_DATE,getStripePrices,+ IS_CLOUD,StripePlan,} from "./const.js";import { stripe } from "./stripe.js";@@ -82,6 +84,13 @@ export type SubscriptionInfo =/*** Gets the first day of the current month in YYYY-MM-DD format*/+/**+ * `throwOnError`: rethrow a failed lookup instead of reporting "no plan from this source".+ * Callers that act on a missing plan (the usage cron blocking sites) opt in, so a database+ * or Stripe hiccup can't turn a paying organization into a free one.+ */+type LookupOptions = { throwOnError?: boolean };+function getStartOfMonth(): string {return DateTime.now().startOf("month").toISODate() as string;}@@ -90,7 +99,10 @@ function getStartOfMonth(): string {* Gets AppSumo subscription info for an organization* @returns AppSumo subscription info or null if no active license found*/-export async function getAppSumoSubscription(organizationId: string): Promise<AppSumoSubscriptionInfo | null> {+export async function getAppSumoSubscription(+ organizationId: string,+ { throwOnError = false }: LookupOptions = {}+): Promise<AppSumoSubscriptionInfo | null> {try {const appsumoLicense = await db.execute(sql`SELECT tier, status FROM appsumo.licenses WHERE organization_id = ${organizationId} AND status = 'active' LIMIT 1`@@ -117,6 +129,7 @@ export async function getAppSumoSubscription(organizationId: string): Promise<Apreturn null;} catch (error) {console.error("Error checking AppSumo license:", error);+ if (throwOnError) throw error;return null;}}@@ -125,7 +138,10 @@ export async function getAppSumoSubscription(organizationId: string): Promise<Ap* Gets plan override subscription info for an organization* @returns Override subscription info or null if no override set*/-export async function getOverrideSubscription(organizationId: string): Promise<OverrideSubscriptionInfo | null> {+export async function getOverrideSubscription(+ organizationId: string,+ { throwOnError = false }: LookupOptions = {}+): Promise<OverrideSubscriptionInfo | null> {try {const orgResult = await db.select({ planOverride: organization.planOverride })@@ -176,6 +192,7 @@ export async function getOverrideSubscription(organizationId: string): Promise<O};} catch (error) {console.error("Error checking plan override:", error);+ if (throwOnError) throw error;return null;}}@@ -199,6 +216,7 @@ const stripeSubscriptionCache = new Map<string, { value: StripeSubscriptionInfoexport function invalidateStripeSubscriptionCache(stripeCustomerId: string | null): void {if (stripeCustomerId) {stripeSubscriptionCache.delete(stripeCustomerId);+ subscriptionHistoryCache.delete(stripeCustomerId);}// Also drop the account-wide snapshot so admin/cron reads pick up the change promptly.allStripeSubscriptionsCache = null;@@ -344,6 +362,46 @@ export async function getStripeSubscription(}}+const subscriptionHistoryCache = new Map<string, { value: boolean; expiresAt: number }>();++/**+ * Whether a customer has ever had a subscription, in any state. Organizations get one free+ * trial: once they have had a subscription, checkout charges straight away and the app says+ * "Choose a plan" instead of "Start free trial". Abandoned checkouts leave no subscription+ * (or only an incomplete one), so they do not use up the trial.+ */+export async function hasHadStripeSubscription(+ stripeCustomerId: string | null,+ { throwOnError = false }: LookupOptions = {}+): Promise<boolean> {+ if (!stripe || !stripeCustomerId) {+ return false;+ }++ const cached = subscriptionHistoryCache.get(stripeCustomerId);+ if (cached && cached.expiresAt > Date.now()) {+ return cached.value;+ }++ try {+ const subs = await (stripe as Stripe).subscriptions.list({ customer: stripeCustomerId, status: "all", limit: 100 });+ const value = subs.data.some(sub => sub.status !== "incomplete" && sub.status !== "incomplete_expired");+ subscriptionHistoryCache.set(stripeCustomerId, {+ value,+ expiresAt: Date.now() + STRIPE_SUBSCRIPTION_CACHE_TTL_MS,+ });+ return value;+ } catch (error) {+ logger.error({ err: error, stripeCustomerId }, "Error fetching Stripe subscription history");+ // An expired "had a subscription" is still true; an expired "never had one" may be out of+ // date. Checkout opts into throwing so it never grants a second trial by accident; display+ // callers fall back to the last answer, or to showing the trial copy.+ if (cached?.value) return true;+ if (throwOnError) throw error;+ return cached?.value ?? false;+ }+}+/*** Performs the actual Stripe API lookup for a customer's best subscription.* Uses a single list call (status "all") to halve request volume versus separate@@ -436,7 +494,10 @@ function buildStripeSubscriptionInfo(subscription: Stripe.Subscription): StripeS* Gets custom plan subscription info for an organization* @returns Custom plan subscription info or null if no custom plan set*/-export async function getCustomPlanSubscription(organizationId: string): Promise<CustomPlanSubscriptionInfo | null> {+export async function getCustomPlanSubscription(+ organizationId: string,+ { throwOnError = false }: LookupOptions = {}+): Promise<CustomPlanSubscriptionInfo | null> {try {const orgResult = await db.select({ customPlan: organization.customPlan })@@ -464,6 +525,7 @@ export async function getCustomPlanSubscription(organizationId: string): Promise};} catch (error) {console.error("Error checking custom plan:", error);+ if (throwOnError) throw error;return null;}}@@ -476,24 +538,26 @@ export async function getCustomPlanSubscription(organizationId: string): Promiseexport async function getBestSubscription(organizationId: string,stripeCustomerId: string | null,- { throwOnStripeError = false }: { throwOnStripeError?: boolean } = {}+ { throwOnStripeError = false, throwOnLookupError = false }: { throwOnStripeError?: boolean; throwOnLookupError?: boolean } = {}): Promise<SubscriptionInfo> {+ const lookup = { throwOnError: throwOnLookupError };+// Check custom plan first - highest priority- const customSub = await getCustomPlanSubscription(organizationId);+ const customSub = await getCustomPlanSubscription(organizationId, lookup);if (customSub) {return customSub;}// Check override next- const overrideSub = await getOverrideSubscription(organizationId);+ const overrideSub = await getOverrideSubscription(organizationId, lookup);if (overrideSub) {return overrideSub;}// Get both subscription typesconst [appsumoSub, stripeSub] = await Promise.all([- getAppSumoSubscription(organizationId),- getStripeSubscription(stripeCustomerId, { throwOnError: throwOnStripeError }),+ getAppSumoSubscription(organizationId, lookup),+ getStripeSubscription(stripeCustomerId, { throwOnError: throwOnStripeError || throwOnLookupError }),]);if (stripeSub) {@@ -515,14 +579,15 @@ export async function getBestSubscription(*/export async function getBestSubscriptionFromStripeSub(organizationId: string,- stripeSub: StripeSubscriptionInfo | null+ stripeSub: StripeSubscriptionInfo | null,+ lookup: LookupOptions = {}): Promise<SubscriptionInfo> {- const customSub = await getCustomPlanSubscription(organizationId);+ const customSub = await getCustomPlanSubscription(organizationId, lookup);if (customSub) {return customSub;}- const overrideSub = await getOverrideSubscription(organizationId);+ const overrideSub = await getOverrideSubscription(organizationId, lookup);if (overrideSub) {return overrideSub;}@@ -531,7 +596,7 @@ export async function getBestSubscriptionFromStripeSub(return stripeSub;}- const appsumoSub = await getAppSumoSubscription(organizationId);+ const appsumoSub = await getAppSumoSubscription(organizationId, lookup);if (appsumoSub) {return appsumoSub;}@@ -589,6 +654,22 @@ export function getReplayLimit(subscription: SubscriptionInfo): number {}}+/**+ * Whether a site is switched off because its organization has no plan. Only sites created+ * after the free plan ended are affected; older ones keep the legacy free tier. Accepts either+ * a SubscriptionInfo or the getSubscriptionInner payload β both report status "free" exactly+ * when there is no custom plan, override, Stripe subscription or AppSumo license.+ */+export function siteRequiresPlan(+ subscription: { status: string } | null | undefined,+ siteCreatedAt: string | null | undefined+): boolean {+ if (!IS_CLOUD || subscription?.status !== "free" || !siteCreatedAt) {+ return false;+ }+ return siteCreatedAt.slice(0, 10) >= FREE_PLAN_CUTOFF_DATE;+}+function freeSubscription(): FreeSubscriptionInfo {return {source: "free",diff --git a/server/src/services/sites/siteConfigurationLifecycle.ts b/server/src/services/sites/siteConfigurationLifecycle.tsindex ba3760fdf..da411e735 100644--- a/server/src/services/sites/siteConfigurationLifecycle.ts+++ b/server/src/services/sites/siteConfigurationLifecycle.ts@@ -7,6 +7,7 @@ import { sites } from "../../db/postgres/schema.js";import { IS_CLOUD } from "../../lib/const.js";import { validateIPPattern } from "../../lib/ipUtils.js";import { detectPlatform } from "../lifecycleEmails/platformDetect.js";+import { usageService } from "../usageService.js";import { siteConfig, type SiteConfigData } from "../../lib/siteConfig.js";import { claimExpiryIso } from "./claimExpiry.js";@@ -303,6 +304,9 @@ class SiteConfigurationLifecycle {}});if (siteType === "web") this.detectSitePlatform(createdSite);+ // A site added to an organization with no plan must stop collecting now, not at the next+ // usage check.+ usageService.requestOrganizationRefresh(createdSite.organizationId);return createdSite;}@@ -416,6 +420,7 @@ class SiteConfigurationLifecycle {siteConfig.invalidate(claimedSite);this.detectSitePlatform(claimedSite);+ usageService.requestOrganizationRefresh(claimedSite.organizationId);return claimedSite;}diff --git a/server/src/services/tracker/identifyService.test.ts b/server/src/services/tracker/identifyService.test.tsnew file mode 100644index 000000000..ed081c98a--- /dev/null+++ b/server/src/services/tracker/identifyService.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getConfig: vi.fn(),+ isSiteWithoutPlan: vi.fn(),+ insert: vi.fn(),+ select: vi.fn(),+ generateUserId: vi.fn(),+ generateUserIdFromClientId: vi.fn(),+ backfillAdd: vi.fn(),+}));++vi.mock("../../lib/siteConfig.js", () => ({ siteConfig: { getConfig: mocks.getConfig } }));+vi.mock("../usageService.js", () => ({ usageService: { isSiteWithoutPlan: mocks.isSiteWithoutPlan } }));+vi.mock("../../db/postgres/postgres.js", () => ({ db: { insert: mocks.insert, select: mocks.select } }));+vi.mock("../userId/userIdService.js", () => ({+ userIdService: {+ generateUserId: mocks.generateUserId,+ generateUserIdFromClientId: mocks.generateUserIdFromClientId,+ },+}));+vi.mock("./identityBackfillQueue.js", () => ({ identityBackfillQueue: { add: mocks.backfillAdd } }));+vi.mock("../../lib/logger/logger.js", () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };+ return { logger, createServiceLogger: () => logger };+});++import { handleIdentify } from "./identifyService.js";++function replyStub() {+ const reply: any = {};+ reply.status = vi.fn(() => reply);+ reply.send = vi.fn(() => reply);+ return reply;+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getConfig.mockResolvedValue({ siteId: 7, firstPartyProxy: false });+});++describe("handleIdentify β site with no plan", () => {+ it("stores no profile, alias or traits while the organization has no plan", async () => {+ mocks.isSiteWithoutPlan.mockReturnValue(true);+ const reply = replyStub();++ await handleIdentify(+ {+ body: { site_id: "7", user_id: "user_1", anonymous_id: "anon_1", is_new_identify: true, traits: { plan: "pro" } },+ headers: {},+ } as any,+ reply+ );++ expect(mocks.isSiteWithoutPlan).toHaveBeenCalledWith(7);+ expect(reply.status).toHaveBeenCalledWith(200);+ expect(mocks.generateUserIdFromClientId).not.toHaveBeenCalled();+ expect(mocks.insert).not.toHaveBeenCalled();+ expect(mocks.select).not.toHaveBeenCalled();+ expect(mocks.backfillAdd).not.toHaveBeenCalled();+ });+});diff --git a/server/src/services/tracker/identifyService.ts b/server/src/services/tracker/identifyService.tsindex 492085010..cc17b3bd0 100644--- a/server/src/services/tracker/identifyService.ts+++ b/server/src/services/tracker/identifyService.ts@@ -4,6 +4,7 @@ import { z } from "zod";import { db } from "../../db/postgres/postgres.js";import { userProfiles, userAliases } from "../../db/postgres/schema.js";import { siteConfig } from "../../lib/siteConfig.js";+import { usageService } from "../usageService.js";import { identityBackfillQueue } from "./identityBackfillQueue.js";import { userIdService } from "../userId/userIdService.js";import { resolveClientIp } from "./resolveClientIp.js";@@ -81,6 +82,11 @@ export async function handleIdentify(request: FastifyRequest, reply: FastifyReplconst siteId = siteConfiguration.siteId;+ // A site whose organization has no plan collects nothing, profiles and aliases included.+ if (usageService.isSiteWithoutPlan(siteId)) {+ return reply.status(200).send("Site has no plan, identify not stored");+ }+const anonymousId = anonymous_id? await userIdService.generateUserIdFromClientId(anonymous_id, siteId): await userIdService.generateUserId(diff --git a/server/src/services/tracker/ingestEvent.test.ts b/server/src/services/tracker/ingestEvent.test.tsindex 7b82d4123..2acad452c 100644--- a/server/src/services/tracker/ingestEvent.test.ts+++ b/server/src/services/tracker/ingestEvent.test.ts@@ -9,13 +9,14 @@ const mocks = vi.hoisted(() => ({checkBotBlocking: vi.fn(),decideSiteExclusion: vi.fn(),isSiteOverLimit: vi.fn(),+ isSiteWithoutPlan: vi.fn(),updateSession: vi.fn(),generateUserId: vi.fn(),generateUserIdFromClientId: vi.fn(),}));vi.mock("../usageService.js", () => ({- usageService: { isSiteOverLimit: mocks.isSiteOverLimit },+ usageService: { isSiteOverLimit: mocks.isSiteOverLimit, isSiteWithoutPlan: mocks.isSiteWithoutPlan },}));vi.mock("./pageviewQueue.js", () => ({@@ -92,6 +93,7 @@ describe("ingestEvent", () => {vi.clearAllMocks();mocks.decideSiteExclusion.mockResolvedValue({ excluded: false });mocks.isSiteOverLimit.mockReturnValue(false);+ mocks.isSiteWithoutPlan.mockReturnValue(false);mocks.checkBotBlocking.mockResolvedValue(null);mocks.updateSession.mockResolvedValue({ sessionId: "session-alice" });mocks.generateUserId.mockResolvedValue("shared-fingerprint");@@ -187,6 +189,17 @@ describe("ingestEvent", () => {expect(mocks.addPageview).not.toHaveBeenCalled();});+ it("drops every event for a site whose organization has no plan", async () => {+ mocks.isSiteWithoutPlan.mockReturnValue(true);++ const outcome = await ingestEvent(trackingRequest());++ expect(outcome).toEqual({ status: "no_plan" });+ expect(mocks.checkBotBlocking).not.toHaveBeenCalled();+ expect(mocks.generateUserId).not.toHaveBeenCalled();+ expect(mocks.addPageview).not.toHaveBeenCalled();+ });+it("routes enforced bot detections to the bot queue instead of a session", async () => {mocks.checkBotBlocking.mockResolvedValue({enforced: true,diff --git a/server/src/services/tracker/ingestEvent.ts b/server/src/services/tracker/ingestEvent.tsindex da35c8524..9e8d2cbef 100644--- a/server/src/services/tracker/ingestEvent.ts+++ b/server/src/services/tracker/ingestEvent.ts@@ -20,6 +20,7 @@ type MatchedExclusion = Extract<SiteExclusionDecision, { excluded: true }>;export type IngestOutcome =| { status: "excluded"; exclusion: MatchedExclusion }| { status: "over_limit" }+ | { status: "no_plan" }| { status: "bot" }| { status: "tracked"; sessionId: string };@@ -34,8 +35,8 @@ export type IngestOutcome =* (their own office IP, a staging hostname) leaves no trace at all. It* used to run third, after bot detection, which meant an excluded visitor* still moved every anomaly counter for the Site.- * 2. Over-limit β before any Redis or ClickHouse work, since the event is- * going to be dropped regardless.+ * 2. Over-limit or no plan β before any Redis or ClickHouse work, since the+ * event is going to be dropped regardless.* 3. Bot detection β needs a real event; charges a Redis round-trip. It runs* for every Site, whether or not the Site blocks bots; `blockBots` decides* only where a detection is sent, at stage 5.@@ -66,6 +67,10 @@ export async function ingestEvent(trackingRequest: TrackingRequest): Promise<Ingreturn { status: "over_limit" };}+ if (usageService.isSiteWithoutPlan(site.siteId)) {+ return { status: "no_plan" };+ }+const botDetectionResult = await checkBotBlocking({headers: trackingRequest.headers,blockBots: site.blockBots,diff --git a/server/src/services/tracker/trackEvent.test.ts b/server/src/services/tracker/trackEvent.test.tsindex 96b1098d0..06b9753e6 100644--- a/server/src/services/tracker/trackEvent.test.ts+++ b/server/src/services/tracker/trackEvent.test.ts@@ -98,6 +98,16 @@ describe("trackEvent", () => {expect(reply.send).toHaveBeenCalledWith("Site over monthly limit, event not tracked");});+ it("reports a site with no plan without failing the request", async () => {+ mocks.ingestEvent.mockResolvedValue({ status: "no_plan" });+ const reply = replyStub();++ await trackEvent(requestWithBody({ type: "pageview", site_id: "site_abc" }), reply);++ expect(reply.status).toHaveBeenCalledWith(200);+ expect(reply.send).toHaveBeenCalledWith("Site has no plan, event not tracked");+ });+it("answers a detected bot with the same success shape as a tracked event", async () => {mocks.ingestEvent.mockResolvedValue({ status: "bot" });const reply = replyStub();diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex b22c9c629..d692786cf 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -42,6 +42,10 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {return reply.status(200).send("Site over monthly limit, event not tracked");}+ if (outcome.status === "no_plan") {+ return reply.status(200).send("Site has no plan, event not tracked");+ }+if (outcome.status === "excluded") {return reply.status(200).send({success: true,diff --git a/server/src/services/usageService.test.ts b/server/src/services/usageService.test.tsindex afcdeccb7..6b13e5edf 100644--- a/server/src/services/usageService.test.ts+++ b/server/src/services/usageService.test.ts@@ -9,7 +9,8 @@ import type { SubscriptionInfo } from "../lib/subscriptionUtils.js";* subject under test.*/const state = vi.hoisted(() => ({- sites: [] as Array<{ siteId: number; organizationId: string | null }>,+ isCloud: false,+ sites: [] as Array<{ siteId: number; organizationId: string | null; createdAt?: string | null }>,organizations: [] as Array<{id: string;name: string;@@ -40,6 +41,7 @@ vi.mock("../db/postgres/postgres.js", () => {from: () => builder,innerJoin: () => builder,where: () => builder,+ limit: () => builder,then: (resolve: any, reject: any) => Promise.resolve(rows()).then(resolve, reject),};return builder;@@ -102,6 +104,13 @@ vi.mock("../lib/subscriptionUtils.js", async importOriginal => {...actual,getAllStripeSubscriptionsByCustomer: mocks.getAllStripeSubscriptionsByCustomer,stripeSubscriptionInfoFromSnapshot: () => null,+ getBestSubscription: async (organizationId: string) => {+ const subscription = state.subscriptions.get(organizationId);+ if (subscription instanceof Error) {+ throw subscription;+ }+ return subscription ?? freeSub();+ },getBestSubscriptionFromStripeSub: async (organizationId: string) => {const subscription = state.subscriptions.get(organizationId);if (subscription instanceof Error) {@@ -114,6 +123,16 @@ vi.mock("../lib/subscriptionUtils.js", async importOriginal => {vi.mock("../lib/stripe.js", () => ({ stripe: null }));+vi.mock("../lib/const.js", async importOriginal => {+ const actual = await importOriginal<typeof import("../lib/const.js")>();+ return {+ ...actual,+ get IS_CLOUD() {+ return state.isCloud;+ },+ };+});+import { usageService } from "./usageService.js";function freeSub(): SubscriptionInfo {@@ -182,6 +201,7 @@ beforeEach(() => {vi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(new Date(2026, 7, 3, 12, 0, 0));+ state.isCloud = false;state.sites = [];state.organizations = [];state.owners = [{ email: "[email protected]" }];@@ -200,6 +220,7 @@ beforeEach(() => {// The service is a singleton; clear the blocked sets between tests.usageService.setSitesOverLimit(new Set());+ usageService.setSitesWithoutPlan(new Set());usageService.setSitesWithoutReplay(new Set());});@@ -564,3 +585,124 @@ describe("updateOrganizationsMonthlyUsage β resilience and notification", () =expect(callback).not.toHaveBeenCalled();});});++describe("sites that need a plan (cloud, free plan ended 2026-02-13)", () => {+ beforeEach(() => {+ state.isCloud = true;+ state.organizations = [org("org_1", { stripeCustomerId: null })];+ state.sites = [+ { siteId: 1, organizationId: "org_1", createdAt: "2025-11-02 10:00:00" },+ { siteId: 2, organizationId: "org_1", createdAt: "2026-09-01 10:00:00" },+ ];+ });++ it("blocks sites created after the cutoff in an org with no plan, and keeps legacy sites on the free tier", async () => {+ await usageService.updateOrganizationsMonthlyUsage();++ expect(usageService.isSiteWithoutPlan(1)).toBe(false);+ expect(usageService.isSiteWithoutPlan(2)).toBe(true);+ // Needing a plan is not exceeding a limit: no over-limit block, flag or email.+ expect(usageService.isSiteOverLimit(2)).toBe(false);+ expect(state.updates[0]).toMatchObject({ overMonthlyLimit: false });+ expect(mocks.sendLimitExceededEmail).not.toHaveBeenCalled();+ });++ it("does not block any site once the org has a trial", async () => {+ state.subscriptions.set("org_1", stripeSub({ status: "trialing" }));++ await usageService.updateOrganizationsMonthlyUsage();++ expect(usageService.getSitesWithoutPlan().size).toBe(0);+ });++ it("keeps the org's blocks when its plan lookup fails, instead of treating it as free", async () => {+ state.subscriptions.set("org_1", stripeSub({ status: "trialing" }));+ await usageService.updateOrganizationsMonthlyUsage();++ state.subscriptions.set("org_1", new Error("appsumo lookup timed out"));+ await usageService.updateOrganizationsMonthlyUsage();++ expect(usageService.isSiteWithoutPlan(2)).toBe(false);+ });++ it("refreshOrganization unblocks the org's sites as soon as a trial starts", async () => {+ await usageService.updateOrganizationsMonthlyUsage();+ expect(usageService.isSiteWithoutPlan(2)).toBe(true);++ state.subscriptions.set("org_1", stripeSub({ status: "trialing" }));+ await usageService.refreshOrganization("org_1");++ expect(usageService.isSiteWithoutPlan(2)).toBe(false);+ // Pro includes replays, so the plan block on replays lifts too.+ expect(usageService.isSiteWithoutReplay(2)).toBe(false);+ });++ it("refreshOrganization blocks a new site in an org with no plan before the next cron run", async () => {+ await usageService.refreshOrganization("org_1");++ expect(usageService.isSiteWithoutPlan(1)).toBe(false);+ expect(usageService.isSiteWithoutPlan(2)).toBe(true);+ expect(usageService.isSiteWithoutReplay(2)).toBe(true);+ });++ it("refreshOrganization keeps a replay quota the last cron run found exhausted", async () => {+ state.subscriptions.set("org_1", stripeSub());+ state.replayCounts = [{ site_id: 2, count: "1000" }];+ await usageService.updateOrganizationsMonthlyUsage();+ expect(usageService.isSiteWithoutReplay(2)).toBe(true);++ await usageService.refreshOrganization("org_1");++ expect(usageService.isSiteWithoutReplay(2)).toBe(true);+ });++ it("refreshOrganization leaves the blocks alone when the plan can't be resolved", async () => {+ await usageService.updateOrganizationsMonthlyUsage();+ state.subscriptions.set("org_1", new Error("db down"));++ await expect(usageService.refreshOrganization("org_1")).rejects.toThrow("db down");+ expect(usageService.isSiteWithoutPlan(2)).toBe(true);+ });++ it("does not let a cron run that started before a refresh overwrite it with older data", async () => {+ // The cron resolves the org as free, then waits on the email/database work while+ // checkout completes and a refresh unblocks the site.+ state.organizations = [org("org_1", { stripeCustomerId: null, overMonthlyLimit: false })];+ let releaseCron!: () => void;+ const cronPaused = new Promise<void>(resolve => (releaseCron = resolve));+ mocks.getAllStripeSubscriptionsByCustomer.mockImplementation(async () => {+ await cronPaused;+ return new Map();+ });++ const cronRun = usageService.updateOrganizationsMonthlyUsage();+ state.subscriptions.set("org_1", stripeSub({ status: "trialing" }));+ vi.setSystemTime(Date.now() + 1_000);+ await usageService.refreshOrganization("org_1");+ state.subscriptions.set("org_1", freeSub());+ releaseCron();+ await cronRun;++ expect(usageService.isSiteWithoutPlan(2)).toBe(false);+ });++ it("runs overlapping refreshes one after another, so an older one can't undo a newer one", async () => {+ // A site-create refresh reads "free" and stalls on its site query while checkout's+ // refresh starts; the checkout refresh must be the one that sticks.+ const firstRefresh = usageService.refreshOrganization("org_1");+ state.subscriptions.set("org_1", stripeSub({ status: "trialing" }));+ const secondRefresh = usageService.refreshOrganization("org_1");++ await Promise.all([firstRefresh, secondRefresh]);++ expect(usageService.isSiteWithoutPlan(2)).toBe(false);+ });++ it("never blocks sites for needing a plan when self-hosted", async () => {+ state.isCloud = false;++ await usageService.updateOrganizationsMonthlyUsage();++ expect(usageService.getSitesWithoutPlan().size).toBe(0);+ });+});diff --git a/server/src/services/usageService.ts b/server/src/services/usageService.tsindex 6ec11cc52..d3164a80c 100644--- a/server/src/services/usageService.ts+++ b/server/src/services/usageService.ts@@ -1,3 +1,4 @@+import cluster from "node:cluster";import { and, eq } from "drizzle-orm";import { DateTime } from "luxon";import * as cron from "node-cron";@@ -11,8 +12,11 @@ import { sendApproachingLimitEmail, sendLimitExceededEmail } from "../lib/email/import { createServiceLogger } from "../lib/logger/logger.js";import {getAllStripeSubscriptionsByCustomer,+ getBestSubscription,getBestSubscriptionFromStripeSub,getReplayLimit,+ invalidateStripeSubscriptionCache,+ siteRequiresPlan,stripeSubscriptionInfoFromSnapshot,subscriptionIncludesReplay,SubscriptionInfo,@@ -20,12 +24,30 @@ import {type UsageUpdateCallback = () => void;+type OrgSite = { siteId: number; createdAt: string | null };++// IPC message a worker sends the cluster primary, which owns the blocked-site sets.+export const REFRESH_ORGANIZATION_USAGE_MESSAGE = "refresh-organization-usage";+const REFRESH_RETRY_DELAYS_MS = [0, 15_000, 60_000];+class UsageService {private sitesOverLimit = new Set<number>();+ // Sites that collect nothing because their organization has no plan (see siteRequiresPlan):+ // no events, replays or identify calls.+ private sitesWithoutPlan = new Set<number>();// Sites that should not record session replays right now: their organization's plan// doesn't include replays, or its monthly replay quota is exhausted. Empty until the// usage cron runs (and always empty when self-hosted), so enforcement fails open.private sitesWithoutReplay = new Set<number>();+ // Replay count per organization from the last cron run, so an on-demand refresh can apply+ // the replay quota without its own ClickHouse query.+ private orgReplayCounts = new Map<string, number>();+ // When each organization was last refreshed on demand. A cron run that started before then+ // holds older subscription data and must not overwrite that organization's blocks.+ private orgRefreshedAt = new Map<string, number>();+ // In-flight refreshes per organization. Refreshes run one after another so an older one+ // (a site create that read "free") can't finish after a newer one (checkout) and undo it.+ private orgRefreshQueue = new Map<string, Promise<void>>();private usageCheckTask: cron.ScheduledTask | null = null;private logger = createServiceLogger("usage-checker");private onUsageUpdatedCallbacks: UsageUpdateCallback[] = [];@@ -39,6 +61,13 @@ class UsageService {this.sitesOverLimit = sites;}+ /**+ * Sets the sitesWithoutPlan set (used by workers receiving IPC updates from primary)+ */+ public setSitesWithoutPlan(sites: Set<number>): void {+ this.sitesWithoutPlan = sites;+ }+/*** Sets the sitesWithoutReplay set (used by workers receiving IPC updates from primary)*/@@ -57,8 +86,12 @@ class UsageService {/*** Initialize the cron job for checking monthly usage*/+ private isUsageCheckEnabled(): boolean {+ return IS_CLOUD && process.env.NODE_ENV !== "development";+ }+private initializeUsageCheckCron() {- if (IS_CLOUD && process.env.NODE_ENV !== "development") {+ if (this.isUsageCheckEnabled()) {// Schedule the monthly usage checker to run every 30 minutesthis.usageCheckTask = cron.schedule("*/30 * * * *",@@ -73,6 +106,12 @@ class UsageService {);this.logger.info("Monthly usage check cron initialized (runs every 30 minutes)");++ // The blocked-site sets live in memory and start empty, so without a run now an over-limit+ // or plan-less site would collect for up to 30 minutes after every restart or deploy.+ this.updateOrganizationsMonthlyUsage().catch(error => {+ this.logger.error(error as Error, "Error during startup usage check");+ });}}@@ -90,6 +129,17 @@ class UsageService {return this.sitesOverLimit.has(siteId);}+ public getSitesWithoutPlan(): Set<number> {+ return this.sitesWithoutPlan;+ }++ /**+ * Checks if a site collects nothing until its organization starts a plan+ */+ public isSiteWithoutPlan(siteId: number): boolean {+ return this.sitesWithoutPlan.has(siteId);+ }+/*** Gets the set of site IDs whose plan does not include session replay*/@@ -134,17 +184,18 @@ class UsageService {/*** Gets all sites with their organization IDs (excludes sites without an organization)*/- private async getAllSites(): Promise<Array<{ siteId: number; organizationId: string }>> {+ private async getAllSites(): Promise<Array<OrgSite & { organizationId: string }>> {try {const allSites = await db.select({siteId: sites.siteId,organizationId: sites.organizationId,+ createdAt: sites.createdAt,}).from(sites);// Filter out sites without an organization ID- return allSites.filter(site => site.organizationId !== null) as Array<{ siteId: number; organizationId: string }>;+ return allSites.filter(site => site.organizationId !== null) as Array<OrgSite & { organizationId: string }>;} catch (error) {this.logger.error(error as Error, `Error getting all sites`);return [];@@ -166,7 +217,9 @@ class UsageService {// Resolve this org's Stripe subscription from the bulk snapshot (no per-org Stripe call),// then layer in custom plan / override / AppSumo via the same priority rules as elsewhere.const stripeSub = stripeSubscriptionInfoFromSnapshot(stripeSubscriptions, orgData.stripeCustomerId);- const subscription = await getBestSubscriptionFromStripeSub(orgData.id, stripeSub);+ // A failed plan lookup throws, so the caller skips this org and keeps its current blocks+ // instead of treating a paying organization as free.+ const subscription = await getBestSubscriptionFromStripeSub(orgData.id, stripeSub, { throwOnError: true });// Log subscription detailsif (subscription.source === "appsumo") {@@ -267,6 +320,7 @@ class UsageService {*/public async updateOrganizationsMonthlyUsage(): Promise<void> {this.logger.info("Starting check of monthly event usage for organizations...");+ const runStartedAt = Date.now();try {// Step 0: Pull every customer's subscription from Stripe in one bulk pass (a handful of@@ -290,11 +344,11 @@ class UsageService {this.getAllSiteReplayCounts(),]);- // Step 3: Build a map of organizationId -> { siteIds, eventCount, replayCount }- const orgDataMap = new Map<string, { siteIds: number[]; eventCount: number; replayCount: number }>();+ // Step 3: Build a map of organizationId -> { sites, eventCount, replayCount }+ const orgDataMap = new Map<string, { sites: OrgSite[]; eventCount: number; replayCount: number }>();for (const site of allSites) {- const orgData = orgDataMap.get(site.organizationId) || { siteIds: [], eventCount: 0, replayCount: 0 };- orgData.siteIds.push(site.siteId);+ const orgData = orgDataMap.get(site.organizationId) || { sites: [], eventCount: 0, replayCount: 0 };+ orgData.sites.push({ siteId: site.siteId, createdAt: site.createdAt });orgData.eventCount += eventCountMap.get(site.siteId) || 0;orgData.replayCount += replayCountMap.get(site.siteId) || 0;orgDataMap.set(site.organizationId, orgData);@@ -323,18 +377,18 @@ class UsageService {try {const orgStats = orgDataMap.get(orgData.id);const eventCount = orgStats?.eventCount || 0;- const siteIds = orgStats?.siteIds || [];+ const orgSites = orgStats?.sites || [];const wasOverLimit = orgData.overMonthlyLimit ?? false;const alreadyNotifiedApproaching = orgData.approachingLimitNotifiedPeriodStart === monthStart;const subscription = await this.getOrganizationSubscriptionInfo(orgData, stripeSubscriptions);+ if (this.refreshedSince(orgData.id, runStartedAt)) continue;const eventLimit = subscription.eventLimit;const isOverLimit = eventCount > eventLimit;const replayCount = orgStats?.replayCount || 0;- const replayBlocked =- !subscriptionIncludesReplay(subscription) || replayCount >= getReplayLimit(subscription);+ this.orgReplayCounts.set(orgData.id, replayCount);let sendApproaching = false;if (!alreadyNotifiedApproaching && !isOverLimit && Number.isFinite(eventLimit) && daysRemaining >= 2) {@@ -404,29 +458,19 @@ class UsageService {}}- // If over the limit, add all this organization's sites to the global set+ // The emails above awaited; a refresh may have landed with newer data meanwhile.+ if (this.refreshedSince(orgData.id, runStartedAt)) continue;++ const withoutPlanCount = this.applySiteBlocks(orgSites, subscription, isOverLimit, replayCount);if (isOverLimit) {- for (const siteId of siteIds) {- this.sitesOverLimit.add(siteId);- }this.logger.info(- `Organization ${orgData.name} is over limit. Added ${siteIds.length} sites to blocked list.`+ `Organization ${orgData.name} is over limit. Added ${orgSites.length} sites to blocked list.`);- } else {- for (const siteId of siteIds) {- this.sitesOverLimit.delete(siteId);- }}-- // Track sites that shouldn't record session replays β plan doesn't include- // them (e.g. after a downgrade from Pro) or the monthly quota is exhausted β- // so ingest/config endpoints can stop recording for them- for (const siteId of siteIds) {- if (replayBlocked) {- this.sitesWithoutReplay.add(siteId);- } else {- this.sitesWithoutReplay.delete(siteId);- }+ if (withoutPlanCount > 0) {+ this.logger.info(+ `Organization ${orgData.name} has no plan. Blocked ${withoutPlanCount} sites until it starts one.`+ );}this.logger.info(@@ -439,6 +483,7 @@ class UsageService {this.logger.info(`Completed monthly event usage check. ${this.sitesOverLimit.size} sites are over their limit, ` ++ `${this.sitesWithoutPlan.size} sites have no plan, ` +`${this.sitesWithoutReplay.size} sites lack session replay access.`);@@ -451,6 +496,119 @@ class UsageService {}}+ private refreshedSince(organizationId: string, time: number): boolean {+ return (this.orgRefreshedAt.get(organizationId) ?? 0) > time;+ }++ /**+ * Sets each of an organization's sites' blocks from its subscription: events dropped when the+ * organization is over its limit, everything dropped when the site needs a plan, and replays+ * dropped when the plan excludes them (e.g. after a downgrade from Pro) or the monthly replay+ * quota is used up. Returns how many sites need a plan.+ */+ private applySiteBlocks(+ orgSites: OrgSite[],+ subscription: SubscriptionInfo,+ isOverLimit: boolean,+ replayCount: number+ ): number {+ const replayBlocked = !subscriptionIncludesReplay(subscription) || replayCount >= getReplayLimit(subscription);+ let withoutPlanCount = 0;+ for (const site of orgSites) {+ if (isOverLimit) this.sitesOverLimit.add(site.siteId);+ else this.sitesOverLimit.delete(site.siteId);++ if (siteRequiresPlan(subscription, site.createdAt)) {+ this.sitesWithoutPlan.add(site.siteId);+ withoutPlanCount++;+ } else {+ this.sitesWithoutPlan.delete(site.siteId);+ }++ if (replayBlocked) this.sitesWithoutReplay.add(site.siteId);+ else this.sitesWithoutReplay.delete(site.siteId);+ }+ return withoutPlanCount;+ }++ /**+ * Re-evaluates one organization's site blocks now instead of at the next cron run (up to 30+ * minutes away): a new site in an organization with no plan must stop collecting straight+ * away, and a trial that just started must start it. Uses the event and replay counts from+ * the last cron run. Throws if the plan can't be resolved, leaving the blocks as they were.+ */+ public refreshOrganization(organizationId: string): Promise<void> {+ const previous = this.orgRefreshQueue.get(organizationId) ?? Promise.resolve();+ const next = previous.catch(() => {}).then(() => this.refreshOrganizationNow(organizationId));+ this.orgRefreshQueue.set(organizationId, next);+ const forget = () => {+ if (this.orgRefreshQueue.get(organizationId) === next) this.orgRefreshQueue.delete(organizationId);+ };+ next.then(forget, forget);+ return next;+ }++ private async refreshOrganizationNow(organizationId: string): Promise<void> {+ const [org] = await db+ .select({ stripeCustomerId: organization.stripeCustomerId, monthlyEventCount: organization.monthlyEventCount })+ .from(organization)+ .where(eq(organization.id, organizationId))+ .limit(1);+ if (!org) return;++ // This process's cached subscription may predate the checkout or cancellation that+ // triggered the refresh.+ invalidateStripeSubscriptionCache(org.stripeCustomerId);+ const subscription = await getBestSubscription(organizationId, org.stripeCustomerId, { throwOnLookupError: true });++ const orgSites = await db+ .select({ siteId: sites.siteId, createdAt: sites.createdAt })+ .from(sites)+ .where(eq(sites.organizationId, organizationId));++ const isOverLimit = (org.monthlyEventCount ?? 0) > subscription.eventLimit;+ this.applySiteBlocks(orgSites, subscription, isOverLimit, this.orgReplayCounts.get(organizationId) ?? 0);+ this.orgRefreshedAt.set(organizationId, Date.now());++ for (const callback of this.onUsageUpdatedCallbacks) {+ callback();+ }+ }++ /**+ * refreshOrganization with a couple of retries, for callers that can't wait on it (webhooks+ * already acknowledged, sites already created). If every attempt fails, the next cron run+ * reconciles the organization.+ */+ public async refreshOrganizationWithRetry(organizationId: string): Promise<void> {+ for (const delayMs of REFRESH_RETRY_DELAYS_MS) {+ if (delayMs > 0) await new Promise(resolve => setTimeout(resolve, delayMs));+ try {+ await this.refreshOrganization(organizationId);+ return;+ } catch (error) {+ this.logger.warn({ err: error, organizationId }, "Refreshing organization usage failed");+ }+ }+ this.logger.error({ organizationId }, "Gave up refreshing organization usage; the next usage check will reconcile it");+ }++ /**+ * Asks the process that owns the blocked-site sets to refresh an organization: the cluster+ * primary when this is a worker, otherwise this process. Never throws, so callers can fire+ * it after a request has already succeeded.+ */+ public requestOrganizationRefresh(organizationId: string | null | undefined): void {+ if (!organizationId || !this.isUsageCheckEnabled()) return;++ if (cluster.isWorker) {+ process.send?.({ type: REFRESH_ORGANIZATION_USAGE_MESSAGE, organizationId });+ return;+ }++ void this.refreshOrganizationWithRetry(organizationId);+ }+/*** Method to start the usage check cron job*/