Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: cancel flow, yearly-first billing, usage & data-health alerts, onboarding activation (#455)

Carl-Gerhard Lindesvärdd0d9895b7c57
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.ts
index 0432daa9c..e6c31f398 100644
--- a/apps/api/src/controllers/webhook.controller.ts
+++ b/apps/api/src/controllers/webhook.controller.ts
@@ -6,7 +6,7 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import { tryCatch } from '@openpanel/common';
-import { db, getOrganizationByProjectIdCached } from '@openpanel/db';
+import { db, getOrganizationByProjectIdCached, Prisma } from '@openpanel/db';
import { safeWebhookFetcher } from '@openpanel/integrations/src/safe-fetcher';
import {
sendSlackNotification,
@@ -145,10 +145,65 @@ const TRACKED_SUBSCRIPTION_FIELDS = [
'subscriptionStartsAt',
'subscriptionEndsAt',
'subscriptionCanceledAt',
+ 'subscriptionCancelReason',
'subscriptionInterval',
'subscriptionPeriodEventsLimit',
+ 'subscriptionPauseAtPeriodEnd',
+ 'subscriptionResumesAt',
+ 'subscriptionFirstStartedAt',
] as const;
+const CANCELLATION_REASONS = [
+ 'too_expensive',
+ 'missing_features',
+ 'switched_service',
+ 'unused',
+ 'customer_service',
+ 'low_quality',
+ 'too_complex',
+ 'other',
+] as const;
+
+type CancellationReason = (typeof CANCELLATION_REASONS)[number];
+
+// Polar types the reason as an open enum (unknown strings can appear); only
+// store values our own union knows about.
+function parseCancellationReason(
+ reason: string | null | undefined
+): CancellationReason | null {
+ return CANCELLATION_REASONS.includes(reason as CancellationReason)
+ ? (reason as CancellationReason)
+ : null;
+}
+
+type PolarSubscriptionDiscount = PolarSubscriptionData['discount'];
+
+// Compact summary of Polar's embedded discount object so the dashboard can
+// show that a discount is active (save offer or any Polar discount code).
+export function toSubscriptionDiscount(
+ discount: PolarSubscriptionDiscount
+): PrismaJson.IPrismaSubscriptionDiscount | null {
+ if (!discount) {
+ return null;
+ }
+ return {
+ id: discount.id,
+ name: discount.name,
+ type: discount.type === 'fixed' ? 'fixed' : 'percentage',
+ basisPoints: 'basisPoints' in discount ? discount.basisPoints : null,
+ amount: 'amount' in discount ? discount.amount : null,
+ currency: 'currency' in discount ? discount.currency : null,
+ duration:
+ discount.duration === 'repeating'
+ ? 'repeating'
+ : discount.duration === 'forever'
+ ? 'forever'
+ : 'once',
+ durationInMonths:
+ 'durationInMonths' in discount ? discount.durationInMonths : null,
+ };
+}
+
const normalizeLogValue = (value: unknown) =>
value instanceof Date ? value.toISOString() : (value ?? null);
@@ -269,6 +324,23 @@ async function syncSubscriptionToOrg(
: data.canceledAt
: data.currentPeriodEnd,
subscriptionInterval: data.recurringInterval,
+ // Cancellation feedback + pause state mirror Polar so portal-driven cancels
+ // and pauses are captured too (our in-app flows also set them via the API,
+ // which just echoes back through here).
+ subscriptionCancelReason: parseCancellationReason(
+ data.customerCancellationReason
+ ),
+ subscriptionCancelComment: data.customerCancellationComment ?? null,
+ subscriptionPauseAtPeriodEnd: data.pauseAtPeriodEnd,
+ subscriptionResumesAt: data.resumesAt,
+ subscriptionDiscount:
+ toSubscriptionDiscount(data.discount) ?? Prisma.DbNull,
+ // Stable tenure anchor: keep the stored value while the subscription id is
+ // unchanged; a new subscription (re-subscribe) restarts tenure.
+ subscriptionFirstStartedAt:
+ organization.subscriptionId === data.id
+ ? (organization.subscriptionFirstStartedAt ?? data.createdAt)
+ : data.createdAt,
subscriptionPeriodEventsLimit,
subscriptionPeriodEventsCountExceededAt:
typeof subscriptionPeriodEventsLimit === 'number' &&
@@ -277,6 +349,12 @@ async function syncSubscriptionToOrg(
organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit
? null
: undefined,
+ // A raised limit re-arms the usage alerts for the new headroom.
+ ...(typeof subscriptionPeriodEventsLimit === 'number' &&
+ typeof organization.subscriptionPeriodEventsLimit === 'number' &&
+ organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit
+ ? { usageWarningSentAt: null, usageExceededSentAt: null }
+ : {}),
};
const changes = diffOrganizationFields(
@@ -319,7 +397,10 @@ export async function polarWebhook(
}>,
reply: FastifyReply
) {
- request.log.info({ body: request.body }, 'polar webhook received');
+ // Don't log the raw body: it can carry customer free text (e.g. the
+ // cancellation comment) that the logger's redaction patterns don't cover.
+ // `eventCtx` is logged right after validation instead.
+ request.log.info('polar webhook received');
const validation = await tryCatch(async () =>
validatePolarEvent(
@@ -404,6 +485,9 @@ export async function polarWebhook(
data: {
subscriptionPeriodEventsCount: 0,
subscriptionPeriodEventsCountExceededAt: null,
+ // New cycle — the usage alerts may fire again.
+ usageWarningSentAt: null,
+ usageExceededSentAt: null,
},
});
@@ -421,6 +505,9 @@ export async function polarWebhook(
// All subscription lifecycle events carry the same Subscription object;
// sync them through a single path (new subs, cancellations, revokes,
// reactivations, plan changes, payment-state changes).
+ // Pause/resume transitions arrive via `subscription.updated` (the SDK's
+ // webhook union has no dedicated paused/reactivated payloads yet) and are
+ // reflected in `status` / `pauseAtPeriodEnd` / `resumesAt` below.
case 'subscription.created':
case 'subscription.active':
case 'subscription.updated':
diff --git a/apps/public/src/app/(home)/_sections/pricing.tsx b/apps/public/src/app/(home)/_sections/pricing.tsx
index 10669f851..476e18467 100644
--- a/apps/public/src/app/(home)/_sections/pricing.tsx
+++ b/apps/public/src/app/(home)/_sections/pricing.tsx
@@ -79,6 +79,9 @@ export function Pricing() {
+ VAT if applicable
</span>
</div>
+ <span className="mt-2 text-emerald-600 text-sm dark:text-emerald-500">
+ Pay yearly and get 2 months free
+ </span>
</>
) : (
<div className="text-lg">
diff --git a/apps/public/src/components/pricing-slider.tsx b/apps/public/src/components/pricing-slider.tsx
index b557f8802..31a52c772 100644
--- a/apps/public/src/components/pricing-slider.tsx
+++ b/apps/public/src/components/pricing-slider.tsx
@@ -49,6 +49,9 @@ export function PricingSlider() {
>
+ VAT if applicable
</span>
+ <div className="mt-1 text-emerald-600 text-sm dark:text-emerald-500">
+ Pay yearly and get 2 months free
+ </div>
</div>
) : (
<div className="text-lg">
diff --git a/apps/start/src/components/clients/create-client-success.tsx b/apps/start/src/components/clients/create-client-success.tsx
index 09e0c7fe5..2a252822b 100644
--- a/apps/start/src/components/clients/create-client-success.tsx
+++ b/apps/start/src/components/clients/create-client-success.tsx
@@ -1,19 +1,28 @@
+import { CopyIcon, DownloadIcon, RocketIcon } from 'lucide-react';
+import CopyInput from '../forms/copy-input';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
-import { DownloadIcon, RocketIcon } from 'lucide-react';
-
-import CopyInput from '../forms/copy-input';
+import { isRealClientSecret } from '@/hooks/use-client-secret';
+import { clipboard } from '@/utils/clipboard';
type Props = { id: string; secret: string; type?: 'read' | 'write' | 'root' };
export function CreateClientSuccess({ id, secret, type }: Props) {
- const mcpToken = btoa(`${id}:${secret}`);
- const showMcpToken = type === 'root' || type === 'read';
+ // Only derive credentials from a real secret — the '[CLIENT_SECRET]'
+ // placeholder is truthy and would render a valid-looking but broken token.
+ const hasSecret = isRealClientSecret(secret);
+ const mcpToken = hasSecret ? btoa(`${id}:${secret}`) : null;
+ const showMcpToken = !!mcpToken && (type === 'root' || type === 'read');
+
+ const credentials = [
+ `CLIENT_ID=${id}`,
+ hasSecret && `CLIENT_SECRET=${secret}`,
+ showMcpToken && `MCP_TOKEN=${mcpToken}`,
+ ]
+ .filter(Boolean)
+ .join('\n');
const download = () => {
- const credentials = showMcpToken
- ? `CLIENT_ID=${id}\nCLIENT_SECRET=${secret}\nMCP_TOKEN=${mcpToken}`
- : `CLIENT_ID=${id}\nCLIENT_SECRET=${secret}`;
const blob = new Blob([credentials], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -25,36 +34,45 @@ export function CreateClientSuccess({ id, secret, type }: Props) {
return (
<div className="grid min-w-0 gap-4 [&>*]:min-w-0">
<CopyInput label="Client ID" value={id} />
- {secret && (
+ {hasSecret && (
<div className="w-full min-w-0">
<CopyInput label="Secret" value={secret} />
- <p className="mt-1 text-sm text-muted-foreground">
+ <p className="mt-1 text-muted-foreground text-sm">
You will only need the secret if you want to send server events.
</p>
</div>
)}
- {secret && showMcpToken && (
+ {showMcpToken && (
<div className="w-full min-w-0">
<CopyInput label="MCP Token" value={mcpToken} />
- <p className="mt-1 text-sm text-muted-foreground">
+ <p className="mt-1 text-muted-foreground text-sm">
Use this token to authenticate with the MCP server (base64 encoded
client ID and secret).
</p>
</div>
)}
- <Button variant="outline" icon={DownloadIcon} onClick={download}>
- Save credentials
- </Button>
+ <div className="row gap-2 [&>*]:flex-1">
+ <Button
+ icon={CopyIcon}
+ onClick={() => clipboard(credentials)}
+ variant="outline"
+ >
+ Copy all
+ </Button>
+ <Button icon={DownloadIcon} onClick={download} variant="outline">
+ Save credentials
+ </Button>
+ </div>
<Alert>
<RocketIcon className="h-4 w-4" />
<AlertTitle>Get started!</AlertTitle>
<AlertDescription>
Read our{' '}
<a
- target="_blank"
- href="https://openpanel.dev/docs"
className="underline"
+ href="https://openpanel.dev/docs"
rel="noreferrer"
+ target="_blank"
>
documentation
</a>{' '}
diff --git a/apps/start/src/components/onboarding/activation-banner.tsx b/apps/start/src/components/onboarding/activation-banner.tsx
new file mode 100644
index 000000000..8df35b5b0
--- /dev/null
+++ b/apps/start/src/components/onboarding/activation-banner.tsx
@@ -0,0 +1,256 @@
+import { useQuery } from '@tanstack/react-query';
+import { useNavigate } from '@tanstack/react-router';
+import { CheckIcon } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { Ping } from '@/components/ping';
+import { Button } from '@/components/ui/button';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
+import { cn } from '@/utils/cn';
+import { op } from '@/utils/op';
+
+// The project's first funnel: event -> report -> teammate, drawn as three
+// nodes on a progress track. The current step carries the product's live ping
+// dot, and while the first event is missing the query polls so the banner
+// flips green by itself the moment data arrives. Steps derive from existing
+// data (Project.firstEventAt, report count, member count) — no state machine.
+
+const dismissKey = (projectId: string) =>
+ `op-activation-checklist-dismissed:${projectId}`;
+
+const readDismissed = (projectId: string) => {
+ try {
+ return localStorage.getItem(dismissKey(projectId)) === '1';
+ } catch {
+ // Storage unavailable: show the checklist — new users in storage-blocked
+ // browsers should still get onboarding help, at the cost of the dismissal
+ // only lasting the session.
+ return false;
+ }
+};
+
+const HEADLINES = {
+ 'first-event': {
+ title: 'Waiting for your first event',
+ sub: 'Install the snippet — this banner lights up the moment data arrives.',
+ },
+ 'first-report': {
+ title: 'Data is flowing — now shape it',
+ sub: 'Build your first report from the events coming in.',
+ },
+ 'invite-teammate': {
+ title: 'Bring your team in',
+ sub: 'Invite a teammate to see what you are seeing.',
+ },
+} as const;
+
+type StepKey = keyof typeof HEADLINES;
+
+export default function ActivationBanner() {
+ const { organizationId, projectId } = useAppParams();
+ const trpc = useTRPC();
+ const navigate = useNavigate();
+
+ // Hidden until mounted so SSR and the first client render agree.
+ const [dismissed, setDismissed] = useState(true);
+ useEffect(() => {
+ setDismissed(readDismissed(projectId));
+ }, [projectId]);
+
+ const statusQuery = useQuery(
+ trpc.project.activationStatus.queryOptions(
+ { projectId },
+ {
+ enabled: !dismissed,
+ // Poll only while listening for the first event, so the banner reacts
+ // on its own; afterwards the remaining steps are user-driven.
+ refetchInterval: (query) =>
+ query.state.data && !query.state.data.hasFirstEvent ? 10_000 : false,
+ }
+ )
+ );
+ const status = statusQuery.data;
+
+ if (dismissed || !status) {
+ return null;
+ }
+
+ const steps: {
+ key: StepKey;
+ label: string;
+ done: boolean;
+ go: () => void;
+ }[] = [
+ {
+ key: 'first-event',
+ label: 'First event',
+ done: status.hasFirstEvent,
+ go: () => {
+ op.track('activation_checklist_setup_clicked', { projectId });
+ navigate({
+ to: '/onboarding/$projectId/connect',
+ params: { projectId },
+ });
+ },
+ },
+ {
+ key: 'first-report',
+ label: 'First report',
+ done: status.hasReport,
+ go: () => {
+ op.track('activation_checklist_report_clicked', { projectId });
+ navigate({
+ to: '/$organizationId/$projectId/reports',
+ params: { organizationId, projectId },
+ });
+ },
+ },
+ {
+ key: 'invite-teammate',
+ label: 'Invite a teammate',
+ done: status.hasTeammate,
+ go: () => {
+ op.track('activation_checklist_invite_clicked', { projectId });
+ pushModal('CreateInvite');
+ },
+ },
+ ];
+
+ const doneCount = steps.filter((step) => step.done).length;
+ if (doneCount === steps.length) {
+ return null;
+ }
+
+ const current = steps.find((step) => !step.done) ?? steps[0]!;
+ const headline = HEADLINES[current.key];
+
+ const dismiss = () => {
+ op.track('activation_checklist_dismissed', { projectId });
+ try {
+ localStorage.setItem(dismissKey(projectId), '1');
+ } catch {
+ // Storage unavailable — the banner just shows again next session.
+ }
+ setDismissed(true);
+ };
+
+ const actions = (
+ <>
+ <Button onClick={current.go} size="sm">
+ {current.key === 'first-event'
+ ? 'Set up tracking'
+ : current.key === 'first-report'
+ ? 'Create a report'
+ : 'Invite'}
+ </Button>
+ <Button onClick={dismiss} size="sm" variant="ghost">
+ Skip setup
+ </Button>
+ </>
+ );
+
+ return (
+ // Container queries, not viewport breakpoints: the banner sits beside the
+ // sidebar, so its own width — not the window's — decides when the
+ // three-column row fits. In the stacked layout the actions move up to the
+ // headline row (top-right corner) instead of dangling below the funnel.
+ <div className="@container relative overflow-hidden border-b bg-card">
+ <div
+ className="pointer-events-none absolute -top-24 -right-24 size-64 rounded-full opacity-20 blur-3xl"
+ style={{
+ background:
+ 'radial-gradient(circle, rgb(16 185 129) 0%, transparent 70%)',
+ }}
+ />
+
+ <div className="@5xl:row col relative @5xl:items-center @5xl:justify-between @5xl:gap-10 gap-6 @5xl:p-6 p-4 @5xl:px-8">
+ <div className="row @5xl:contents min-w-0 flex-wrap items-start justify-between gap-4">
+ <div className="col min-w-0 gap-1">
+ <div className="row items-center gap-2 font-mono text-muted-foreground text-xs uppercase tracking-widest">
+ Setup funnel
+ <span className="text-emerald-600 dark:text-emerald-500">
+ {doneCount}/{steps.length}
+ </span>
+ </div>
+ <div className="font-medium text-lg leading-tight">
+ {headline.title}
+ </div>
+ <div className="text-muted-foreground text-sm">{headline.sub}</div>
+ </div>
+
+ <div className="row @5xl:hidden shrink-0 items-center gap-2">
+ {actions}
+ </div>
+ </div>
+
+ <div className="row min-w-0 max-w-xl flex-1 items-center gap-0">
+ {steps.map((step, index) => {
+ const isCurrent = step.key === current.key;
+ return (
+ <div
+ className={cn('row items-center', index > 0 && 'flex-1')}
+ key={step.key}
+ >
+ {index > 0 && (
+ <div
+ className={cn(
+ // Aligned to the node centers (size-7 nodes), not the
+ // taller node+label buttons the row centers against.
+ 'mx-2 mt-[13px] h-0.5 min-w-4 flex-1 self-start rounded-full transition-colors',
+ steps[index - 1]!.done ? 'bg-emerald-500' : 'bg-border'
+ )}
+ />
+ )}
+ <button
+ className={cn(
+ 'group col shrink-0 items-center gap-1.5 outline-none',
+ step.done && 'cursor-default'
+ )}
+ disabled={step.done}
+ onClick={step.go}
+ type="button"
+ >
+ <span
+ className={cn(
+ 'center-center size-7 rounded-full border transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring',
+ step.done &&
+ 'border-emerald-500 bg-emerald-500 text-white',
+ !step.done &&
+ isCurrent &&
+ 'border-emerald-500/50 bg-background group-hover:border-emerald-500',
+ !(step.done || isCurrent) &&
+ 'border-dashed bg-background text-muted-foreground group-hover:border-foreground/40'
+ )}
+ >
+ {step.done ? (
+ <CheckIcon className="size-3.5" />
+ ) : isCurrent ? (
+ <Ping className="motion-reduce:animate-none" />
+ ) : (
+ <span className="size-1.5 rounded-full bg-current opacity-40" />
+ )}
+ </span>
+ <span
+ className={cn(
+ 'whitespace-nowrap text-xs transition-colors',
+ step.done && 'text-muted-foreground line-through',
+ !step.done && isCurrent && 'font-medium',
+ !(step.done || isCurrent) && 'text-muted-foreground'
+ )}
+ >
+ {step.label}
+ </span>
+ </button>
+ </div>
+ );
+ })}
+ </div>
+
+ <div className="@5xl:flex hidden shrink-0 items-center gap-2">
+ {actions}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/organization/billing-plan-picker.tsx b/apps/start/src/components/organization/billing-plan-picker.tsx
index 488119b84..80ac819ba 100644
--- a/apps/start/src/components/organization/billing-plan-picker.tsx
+++ b/apps/start/src/components/organization/billing-plan-picker.tsx
@@ -19,6 +19,10 @@ interface Props {
organization: IServiceOrganization;
currentProduct: IPolarProduct | null;
onComplete?: () => void;
+ // Switches the host modal to the cancel flow; the cancel action only
+ // renders when provided.
+ onCancel?: () => void;
+ defaultInterval?: 'year' | 'month';
}
const getPrice = (product: IPolarProduct) => {
@@ -31,6 +35,8 @@ export default function BillingPlanPicker({
organization,
currentProduct,
onComplete,
+ onCancel,
+ defaultInterval,
}: Props) {
const number = useNumber();
const trpc = useTRPC();
@@ -38,18 +44,27 @@ export default function BillingPlanPicker({
const productsQuery = useQuery(
trpc.subscription.products.queryOptions({
organizationId: organization.id,
- }),
+ })
);
+ // Yearly is the default for new subscribers — it churns far less and saves
+ // them 2 months. Existing subscribers land on their current interval.
const [recurringInterval, setRecurringInterval] = useState<'year' | 'month'>(
- (organization.subscriptionInterval as 'year' | 'month') || 'month',
+ defaultInterval ??
+ ((organization.subscriptionInterval as 'year' | 'month') || 'year')
);
const [selectedProductId, setSelectedProductId] = useState<string | null>(
- organization.subscriptionProductId || null,
+ organization.subscriptionProductId || null
);
const [pendingProductId, setPendingProductId] = useState<string | null>(null);
const products = productsQuery.data || [];
+ // Only treat a product as selected while it belongs to the displayed
+ // interval. Opening the picker preset to yearly for a monthly subscriber
+ // (or toggling the interval) must not keep the monthly plan "selected" —
+ // that would render the cancel action under a list it isn't part of.
const selectedProduct = products.find(
- (product) => product.id === selectedProductId,
+ (product) =>
+ product.id === selectedProductId &&
+ product.recurringInterval === recurringInterval
);
// No current plan to compare against → a plan row is the buy button (straight
@@ -66,13 +81,13 @@ export default function BillingPlanPicker({
queryClient.invalidateQueries(
trpc.organization.get.queryOptions({
organizationId: organization.id,
- }),
+ })
);
queryClient.invalidateQueries(
trpc.subscription.getCurrent.queryOptions({
organizationId: organization.id,
- }),
+ })
);
toast.success('Subscription updated', {
description: 'It might take a few seconds to update',
@@ -84,31 +99,7 @@ export default function BillingPlanPicker({
setPendingProductId(null);
toast.error(error.message);
},
- }),
- );
-
- const cancelSubscription = useMutation(
- trpc.subscription.cancelSubscription.mutationOptions({
- onSuccess() {
- queryClient.invalidateQueries(
- trpc.organization.get.queryOptions({
- organizationId: organization.id,
- }),
- );
- queryClient.invalidateQueries(
- trpc.subscription.getCurrent.queryOptions({
- organizationId: organization.id,
- }),
- );
- toast.success('Subscription canceled', {
- description: 'It might take a few seconds to update',
- });
- onComplete?.();
- },
- onError(error) {
- toast.error(error.message);
- },
- }),
+ })
);
const startCheckout = (product: IPolarProduct) => {
@@ -126,7 +117,9 @@ export default function BillingPlanPicker({
};
const handleCheckout = () => {
- if (!selectedProduct) return;
+ if (!selectedProduct) {
+ return;
+ }
startCheckout(selectedProduct);
};
@@ -143,7 +136,7 @@ export default function BillingPlanPicker({
}
if (selectedProductId === product.id) {
return (
- <div className="size-4 center-center rounded-full bg-emerald-600 text-primary-foreground">
+ <div className="center-center size-4 rounded-full bg-emerald-600 text-primary-foreground">
<CheckIcon className="size-2" />
</div>
);
@@ -152,15 +145,10 @@ export default function BillingPlanPicker({
};
const handleCancelSubscription = () => {
- if (!selectedProduct) return;
- op.track('subscription_canceled', {
- organizationId: organization.id,
- limit: selectedProduct.metadata.eventsLimit,
- price: getPrice(selectedProduct),
- });
- cancelSubscription.mutate({
+ op.track('cancel_flow_opened', {
organizationId: organization.id,
});
+ onCancel?.();
};
const renderAction = () => {
@@ -170,13 +158,13 @@ export default function BillingPlanPicker({
const isCurrentProduct = selectedProduct.id === currentProduct?.id;
- if (isCurrentProduct && organization.isActive) {
+ if (isCurrentProduct && organization.isActive && onCancel) {
return (
<Button
- className="w-full mt-4"
- variant="destructive"
- size="lg"
+ className="mt-4 w-full"
onClick={handleCancelSubscription}
+ size="lg"
+ variant="destructive"
>
Cancel subscription
</Button>
@@ -203,45 +191,45 @@ export default function BillingPlanPicker({
return (
<button
- type="button"
- className="w-full mt-4 rounded-lg overflow-hidden hover:translate-y-[-1px] transition-all group"
+ className="group mt-4 w-full overflow-hidden rounded-lg transition-all hover:translate-y-[-1px]"
onClick={handleCheckout}
+ type="button"
>
{currentProduct && (
- <div className="row justify-between p-2 px-4 border-t border-l border-r border-border rounded-t-lg bg-def-200 group-hover:bg-def-100 transition-colors line-through">
+ <div className="row justify-between rounded-t-lg border-border border-t border-r border-l bg-def-200 p-2 px-4 line-through transition-colors group-hover:bg-def-100">
<span>{currentProduct?.name}</span>
<span>{number.currency(getPrice(currentProduct))}</span>
</div>
)}
<div
className={cn(
- 'row justify-between p-2 px-4 border-t border-l border-r border-border bg-def-200 group-hover:bg-def-100 transition-colors',
- !currentProduct && 'rounded-t-lg',
+ 'row justify-between border-border border-t border-r border-l bg-def-200 p-2 px-4 transition-colors group-hover:bg-def-100',
+ !currentProduct && 'rounded-t-lg'
)}
>
<span>{selectedProduct.name}</span>
<span>{number.currency(getPrice(selectedProduct))}</span>
</div>
- <div className="center-center gap-4 row bg-primary text-primary-foreground p-4 group-hover:bg-primary/90 transition-colors">
+ <div className="center-center row gap-4 bg-primary p-4 text-primary-foreground transition-colors group-hover:bg-primary/90">
<svg
className="size-6"
- width="300"
+ fill="none"
height="300"
viewBox="0 0 300 300"
- fill="none"
+ width="300"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1_4)">
<path
- fill-rule="evenodd"
clip-rule="evenodd"
d="M66.4284 274.26C134.876 320.593 227.925 302.666 274.258 234.219C320.593 165.771 302.666 72.7222 234.218 26.3885C165.77 -19.9451 72.721 -2.0181 26.3873 66.4297C-19.9465 134.877 -2.01938 227.927 66.4284 274.26ZM47.9555 116.67C30.8375 169.263 36.5445 221.893 59.2454 256.373C18.0412 217.361 7.27564 150.307 36.9437 92.318C55.9152 55.2362 87.5665 29.3937 122.5 18.3483C90.5911 36.7105 62.5549 71.8144 47.9555 116.67ZM175.347 283.137C211.377 272.606 244.211 246.385 263.685 208.322C293.101 150.825 282.768 84.4172 242.427 45.2673C264.22 79.7626 269.473 131.542 252.631 183.287C237.615 229.421 208.385 265.239 175.347 283.137ZM183.627 266.229C207.945 245.418 228.016 210.604 236.936 168.79C251.033 102.693 232.551 41.1978 195.112 20.6768C214.97 47.3945 225.022 99.2902 218.824 157.333C214.085 201.724 200.814 240.593 183.627 266.229ZM63.7178 131.844C49.5155 198.43 68.377 260.345 106.374 280.405C85.9962 254.009 75.5969 201.514 81.8758 142.711C86.5375 99.0536 99.4504 60.737 116.225 35.0969C92.2678 55.983 72.5384 90.4892 63.7178 131.844ZM199.834 149.561C200.908 217.473 179.59 272.878 152.222 273.309C124.853 273.742 101.797 219.039 100.724 151.127C99.6511 83.2138 120.968 27.8094 148.337 27.377C175.705 26.9446 198.762 81.648 199.834 149.561Z"
fill="currentColor"
+ fill-rule="evenodd"
/>
</g>
<defs>
<clipPath id="clip0_1_4">
- <rect width="300" height="300" fill="white" />
+ <rect fill="white" height="300" width="300" />
</clipPath>
</defs>
</svg>
@@ -253,7 +241,7 @@ export default function BillingPlanPicker({
return (
<>
- <div className="col gap-4 shrink-0">
+ <div className="col shrink-0 gap-4">
{currentProduct && (
<div className="font-medium">
Your current usage is{' '}
@@ -266,14 +254,20 @@ export default function BillingPlanPicker({
</span>
</div>
)}
- <div className="row items-center justify-between gap-2 -mb-2">
+ <div className="row -mb-2 items-center justify-between gap-2">
<div className="font-medium">
{recurringInterval === 'year' ? (
- 'Switch to monthly'
+ <>
+ Yearly billing —{' '}
+ <span className="text-emerald-500">2 months free</span>{' '}
+ <span className="font-normal text-muted-foreground">
+ (pay for 10 months, get 12)
+ </span>
+ </>
) : (
<>
Switch to yearly and get{' '}
- <span className="underline text-emerald-500">
+ <span className="text-emerald-500 underline">
2 months for free
</span>
</>
@@ -281,20 +275,22 @@ export default function BillingPlanPicker({
</div>
<Button
- variant="outline"
onClick={() =>
setRecurringInterval((p) => (p === 'year' ? 'month' : 'year'))
}
+ variant="outline"
>
{recurringInterval === 'year' ? 'Monthly' : 'Yearly'}
- <ShuffleIcon className="size-4 ml-2" />
+ <ShuffleIcon className="ml-2 size-4" />
</Button>
</div>
</div>
- <div className="col divide-y divide-border border rounded-lg overflow-y-auto min-h-0">
+ <div className="col min-h-0 divide-y divide-border overflow-y-auto rounded-lg border">
{products
.filter((product) =>
- product.prices.some((p) => p.amountType !== 'free'),
+ // `free` no longer exists in the SDK's amountType union, but
+ // retired free-plan products can still come back from Polar's API.
+ product.prices.some((p) => (p.amountType as string) !== 'free')
)
.filter((product) => product.metadata.eventsLimit)
.filter((product) => product.recurringInterval === recurringInterval)
@@ -312,29 +308,34 @@ export default function BillingPlanPicker({
return (
<button
- key={product.id}
- type="button"
- disabled={
- isProductDisabled ||
- (directCheckout && checkoutMutation.isPending)
- }
className={cn(
- 'group row justify-between p-4 py-3 hover:bg-def-100 shrink-0',
+ 'group row shrink-0 justify-between p-4 py-3 hover:bg-def-100',
!directCheckout &&
currentProduct?.id === product.id &&
selectedProductId !== product.id &&
'text-muted-foreground line-through',
- isProductDisabled && 'opacity-50 !cursor-not-allowed',
+ isProductDisabled && '!cursor-not-allowed opacity-50'
)}
+ disabled={
+ isProductDisabled ||
+ (directCheckout && checkoutMutation.isPending)
+ }
+ key={product.id}
onClick={() =>
directCheckout
? startCheckout(product)
: setSelectedProductId(product.id)
}
+ type="button"
>
<span className={'font-medium'}>{product.name}</span>
<div className="row items-center gap-2">
- <span className="font-bold">{number.currency(price)}</span>
+ <span className="font-bold">
+ {number.currency(price)}
+ <span className="font-normal text-muted-foreground">
+ /{recurringInterval === 'year' ? 'yr' : 'mo'}
+ </span>
+ </span>
{renderRowIndicator(product)}
</div>
</button>
diff --git a/apps/start/src/components/organization/billing-prompt.tsx b/apps/start/src/components/organization/billing-prompt.tsx
index 92a6db788..33392a3f4 100644
--- a/apps/start/src/components/organization/billing-prompt.tsx
+++ b/apps/start/src/components/organization/billing-prompt.tsx
@@ -1,5 +1,5 @@
import type { IServiceOrganization } from '@openpanel/db';
-import { useMutation, useQuery } from '@tanstack/react-query';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { CheckIcon } from 'lucide-react';
import { useEffect } from 'react';
import { toast } from 'sonner';
@@ -29,13 +29,13 @@ interface CopyVariant {
title: string;
lead: string;
dateLabel: string;
- action: 'checkout' | 'portal';
+ action: 'checkout' | 'portal' | 'resume';
cta: (plan: string, price: string) => string;
note: string | null;
}
const COPY: Record<
- 'expired' | 'trialEnded' | 'unpaid' | 'freePlan',
+ 'expired' | 'trialEnded' | 'unpaid' | 'freePlan' | 'paused',
CopyVariant
> = {
trialEnded: {
@@ -68,6 +68,16 @@ const COPY: Record<
cta: () => 'Update payment method',
note: null,
},
+ paused: {
+ badge: { label: 'Paused', variant: 'secondary' },
+ gradient: 'rgb(16 185 129)',
+ title: 'Your subscription is on a break',
+ lead: "You paused your subscription, so billing is stopped — but we're still collecting every event. Resume whenever you're ready and your dashboards are back immediately, right where you left them.",
+ dateLabel: 'Billing resumes',
+ action: 'resume',
+ cta: () => 'Resume subscription now',
+ note: 'Resuming starts a new billing period right away. Your events keep being collected while paused, so nothing is lost.',
+ },
freePlan: {
badge: { label: 'Plan change', variant: 'secondary' },
gradient: 'rgb(16 185 129)',
@@ -120,6 +130,21 @@ export default function BillingPrompt({
},
})
);
+ const queryClient = useQueryClient();
+ const resume = useMutation(
+ trpc.subscription.resumeSubscription.mutationOptions({
+ onSuccess() {
+ queryClient.invalidateQueries(trpc.organization.pathFilter());
+ queryClient.invalidateQueries(trpc.subscription.pathFilter());
+ toast.success('Welcome back!', {
+ description: 'It might take a few seconds to update',
+ });
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
const eventsCount = organization.subscriptionPeriodEventsCount ?? 0;
const bestProductFit = products
@@ -150,6 +175,25 @@ export default function BillingPrompt({
}, [type]);
const renderCta = () => {
+ if (copy.action === 'resume') {
+ return (
+ <Button
+ className="w-full"
+ loading={resume.isPending}
+ onClick={() => {
+ op.track('billing_prompt_upgrade_clicked', {
+ type,
+ cta: 'resume',
+ });
+ resume.mutate({ organizationId: organization.id });
+ }}
+ size="lg"
+ >
+ {copy.cta('', '')}
+ </Button>
+ );
+ }
+
if (copy.action === 'portal') {
return (
<Button
@@ -238,16 +282,26 @@ export default function BillingPrompt({
Events tracked, all safe and stored
</div>
</div>
- {organization.subscriptionEndsAt && (
- <div className="col flex-1 gap-1 rounded-md bg-def-200 p-4">
- <div className="font-bold font-mono text-2xl">
- {formatDate(organization.subscriptionEndsAt)}
+ {(() => {
+ // Paused shows the automatic resume date instead of the period end.
+ const date =
+ type === 'paused'
+ ? organization.subscriptionResumesAt
+ : organization.subscriptionEndsAt;
+ if (!date) {
+ return null;
+ }
+ return (
+ <div className="col flex-1 gap-1 rounded-md bg-def-200 p-4">
+ <div className="font-bold font-mono text-2xl">
+ {formatDate(date)}
+ </div>
+ <div className="text-muted-foreground text-sm">
+ {copy.dateLabel}
+ </div>
</div>
- <div className="text-muted-foreground text-sm">
- {copy.dateLabel}
- </div>
- </div>
- )}
+ );
+ })()}
</div>
<div className="col gap-3 p-6 md:p-8">
diff --git a/apps/start/src/components/organization/billing.tsx b/apps/start/src/components/organization/billing.tsx
index 47ebf29b5..d956a18b7 100644
--- a/apps/start/src/components/organization/billing.tsx
+++ b/apps/start/src/components/organization/billing.tsx
@@ -1,4 +1,5 @@
import type { IServiceOrganization } from '@openpanel/db';
+import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { differenceInDays } from 'date-fns';
import { useQueryState } from 'nuqs';
@@ -16,7 +17,6 @@ import useWS from '@/hooks/use-ws';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal, useOnPushModal } from '@/modals';
import { formatDate } from '@/utils/date';
-import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';
type Props = {
organization: IServiceOrganization;
@@ -53,6 +53,25 @@ export default function Billing({ organization }: Props) {
})
);
+ const resumeMutation = useMutation(
+ trpc.subscription.resumeSubscription.mutationOptions({
+ onSuccess() {
+ queryClient.invalidateQueries(trpc.organization.pathFilter());
+ queryClient.invalidateQueries(trpc.subscription.pathFilter());
+ toast.success('Subscription resumed', {
+ description: 'It might take a few seconds to update',
+ });
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
+
+ const isPauseState =
+ organization.subscriptionState === 'pausing' ||
+ organization.subscriptionState === 'paused';
+
useWS(`/live/organization/${organization.id}`, () => {
queryClient.invalidateQueries(trpc.organization.pathFilter());
queryClient.invalidateQueries(trpc.subscription.pathFilter());
@@ -65,7 +84,11 @@ export default function Billing({ organization }: Props) {
const products = useMemo(() => {
return (productsQuery.data || [])
.filter((product) => product.recurringInterval === recurringInterval)
- .filter((product) => product.prices.some((p) => p.amountType !== 'free'));
+ .filter((product) =>
+ // `free` no longer exists in the SDK's amountType union, but retired
+ // free-plan products can still come back from Polar's API.
+ product.prices.some((p) => (p.amountType as string) !== 'free')
+ );
}, [productsQuery.data, recurringInterval]);
const currentProduct = currentProductQuery.data ?? null;
@@ -73,10 +96,62 @@ export default function Billing({ organization }: Props) {
p.amountType === 'fixed' ? [p] : []
)[0];
+ // What the customer actually pays while a recurring discount applies. A
+ // `once` discount only hits the next invoice, so the header keeps the list
+ // price and the discount line below explains it.
+ const listPrice = currentPrice ? currentPrice.priceAmount / 100 : null;
+ const discountedPrice = (() => {
+ const active = organization.subscriptionDiscount;
+ if (!active || listPrice === null || active.duration === 'once') {
+ return null;
+ }
+ if (active.type === 'percentage' && active.basisPoints) {
+ return listPrice * (1 - active.basisPoints / 10_000);
+ }
+ if (active.type === 'fixed' && active.amount) {
+ return Math.max(0, listPrice - active.amount / 100);
+ }
+ return null;
+ })();
+
+ // Synced from Polar — covers the cancel-flow save offer and any discount
+ // code the customer redeemed. Without this line the card shows the full
+ // list price and an applied discount is invisible outside Polar's portal.
+ const discount = organization.subscriptionDiscount;
+ const renderDiscount = () => {
+ if (!discount) {
+ return null;
+ }
+ const value =
+ discount.type === 'percentage' && discount.basisPoints
+ ? `−${discount.basisPoints / 100}%`
+ : discount.amount
+ ? `−${number.currency(discount.amount / 100)}`
+ : null;
+ if (!value) {
+ return null;
+ }
+ const duration =
+ discount.duration === 'repeating' && discount.durationInMonths
+ ? `for the next ${discount.durationInMonths} months`
+ : discount.duration === 'forever'
+ ? 'on every invoice'
+ : 'on your next invoice';
+ // Deliberately no discount name here: names are often the redeemable code
+ // itself, and the save offer's name would advertise what the cancel flow
+ // grants. The value + duration is all the customer needs.
+ return (
+ <p className="mt-1 text-emerald-600 dark:text-emerald-500">
+ {value} {duration}
+ </p>
+ );
+ };
+
const renderStatus = () => {
const meta = getSubscriptionStateMeta(organization.subscriptionState, {
endsAt: organization.subscriptionEndsAt,
canceledAt: organization.subscriptionCanceledAt,
+ resumesAt: organization.subscriptionResumesAt,
});
if (!meta.statusLine) {
@@ -86,7 +161,9 @@ export default function Billing({ organization }: Props) {
return (
<p
className={
- meta.statusLine.tone === 'destructive' ? 'text-destructive' : undefined
+ meta.statusLine.tone === 'destructive'
+ ? 'text-destructive'
+ : undefined
}
>
{meta.statusLine.text}
@@ -117,8 +194,15 @@ export default function Billing({ organization }: Props) {
<WidgetHead className="flex items-center justify-between gap-4">
<div className="title flex-1 truncate">{currentProduct.name}</div>
<div className="text-lg">
+ {discountedPrice !== null && (
+ <span className="mr-2 text-muted-foreground line-through">
+ {number.currency(currentPrice.priceAmount / 100)}
+ </span>
+ )}
<span className="font-bold">
- {number.currency(currentPrice.priceAmount / 100)}
+ {number.currency(
+ discountedPrice ?? currentPrice.priceAmount / 100
+ )}
</span>
<span className="text-muted-foreground">
{' / '}
@@ -128,6 +212,7 @@ export default function Billing({ organization }: Props) {
</WidgetHead>
<WidgetBody>
{renderStatus()}
+ {renderDiscount()}
<div className="col mt-4">
<div className="mb-2 font-semibold">
{number.format(organization.subscriptionPeriodEventsCount)} /{' '}
@@ -173,19 +258,37 @@ export default function Billing({ organization }: Props) {
</svg>
Customer portal
</Button>
- <Button
- onClick={() =>
- pushModal('SelectBillingPlan', {
- organization,
- currentProduct,
- })
- }
- size="sm"
- >
- {organization.isWillBeCanceled
- ? 'Reactivate subscription'
- : 'Change subscription'}
- </Button>
+ <div className="row gap-2">
+ {isPauseState && (
+ <Button
+ loading={resumeMutation.isPending}
+ onClick={() =>
+ resumeMutation.mutate({
+ organizationId: organization.id,
+ })
+ }
+ size="sm"
+ >
+ {organization.subscriptionState === 'paused'
+ ? 'Resume subscription'
+ : 'Keep subscription'}
+ </Button>
+ )}
+ <Button
+ onClick={() =>
+ pushModal('SelectBillingPlan', {
+ organization,
+ currentProduct,
+ })
+ }
+ size="sm"
+ variant={isPauseState ? 'outline' : 'default'}
+ >
+ {organization.isWillBeCanceled
+ ? 'Reactivate subscription'
+ : 'Change subscription'}
+ </Button>
+ </div>
</div>
</div>
</WidgetBody>
diff --git a/apps/start/src/components/organization/cancel-subscription-flow.tsx b/apps/start/src/components/organization/cancel-subscription-flow.tsx
new file mode 100644
index 000000000..eb45b0d75
--- /dev/null
+++ b/apps/start/src/components/organization/cancel-subscription-flow.tsx
@@ -0,0 +1,342 @@
+import type { IServiceOrganization } from '@openpanel/db';
+import type { ICancellationReason } from '@openpanel/validation';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { CheckIcon } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { ButtonContainer } from '@/components/button-container';
+import { Button } from '@/components/ui/button';
+import { Textarea } from '@/components/ui/textarea';
+import { useTRPC } from '@/integrations/trpc/react';
+import { ModalHeader } from '@/modals/Modal/Container';
+import { cn } from '@/utils/cn';
+import { formatDate } from '@/utils/date';
+import { op } from '@/utils/op';
+
+// The cancel flow lives inside the SelectBillingPlan modal as internal views
+// (no stacked modals): reason -> pause offer -> discount offer -> cancel.
+
+interface Props {
+ organization: IServiceOrganization;
+ // Back to the plan picker view.
+ onBack: () => void;
+ // A flow outcome happened (paused, discounted, or canceled) — close the modal.
+ onComplete: () => void;
+}
+
+const REASONS: { value: ICancellationReason; label: string }[] = [
+ { value: 'unused', label: "I'm not using it right now" },
+ { value: 'too_expensive', label: "It's too expensive" },
+ { value: 'missing_features', label: "It's missing features I need" },
+ { value: 'switched_service', label: 'I switched to another service' },
+ { value: 'too_complex', label: "It's too complicated" },
+ { value: 'low_quality', label: "Quality didn't meet my expectations" },
+ { value: 'customer_service', label: 'Unhappy with customer service' },
+ { value: 'other', label: 'Other' },
+];
+
+const PAUSE_MONTHS = [1, 2, 3] as const;
+
+type Step = 'reason' | 'pause' | 'discount';
+
+export default function CancelSubscriptionFlow({
+ organization,
+ onBack,
+ onComplete,
+}: Props) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [step, setStep] = useState<Step>('reason');
+ const [reason, setReason] = useState<ICancellationReason | null>(null);
+ const [comment, setComment] = useState('');
+ const [pauseMonths, setPauseMonths] = useState<1 | 2 | 3>(1);
+
+ const discountAvailable = !organization.subscriptionSaveDiscountAppliedAt;
+
+ // Funnel instrumentation. Every step render emits a step_viewed event, and
+ // the unmount cleanup emits cancel_flow_abandoned when the flow closes with
+ // no recorded outcome (X, esc, click-outside, navigation) — that's the
+ // silent drop-off a decisions-only funnel can't see. Refs so the cleanup
+ // reads the latest values.
+ const outcomeRef = useRef<
+ 'paused' | 'discounted' | 'canceled' | 'kept' | null
+ >(null);
+ const stepRef = useRef<Step>('reason');
+ stepRef.current = step;
+ const reasonRef = useRef<ICancellationReason | null>(null);
+ reasonRef.current = reason;
+
+ useEffect(() => {
+ op.track('cancel_flow_step_viewed', {
+ organizationId: organization.id,
+ step,
+ reason: reasonRef.current,
+ });
+ }, [step, organization.id]);
+
+ useEffect(
+ () => () => {
+ if (!outcomeRef.current) {
+ op.track('cancel_flow_abandoned', {
+ organizationId: organization.id,
+ step: stepRef.current,
+ reason: reasonRef.current,
+ });
+ }
+ },
+ [organization.id]
+ );
+
+ const invalidate = () => {
+ queryClient.invalidateQueries(trpc.organization.pathFilter());
+ queryClient.invalidateQueries(trpc.subscription.pathFilter());
+ };
+
+ const pauseMutation = useMutation(
+ trpc.subscription.pauseSubscription.mutationOptions({
+ onSuccess(data) {
+ outcomeRef.current = 'paused';
+ invalidate();
+ toast.success('Subscription paused', {
+ description: `Billing stops at the end of your current period and resumes on ${formatDate(data.resumesAt)}. Your events keep flowing in.`,
+ });
+ onComplete();
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
+
+ const discountMutation = useMutation(
+ trpc.subscription.applySaveDiscount.mutationOptions({
+ onSuccess() {
+ outcomeRef.current = 'discounted';
+ invalidate();
+ toast.success('Discount applied', {
+ description:
+ '30% off for the next 12 months, starting with your next billing cycle.',
+ });
+ onComplete();
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
+
+ const cancelMutation = useMutation(
+ trpc.subscription.cancelSubscription.mutationOptions({
+ onSuccess() {
+ outcomeRef.current = 'canceled';
+ invalidate();
+ toast.success('Subscription canceled', {
+ description: organization.subscriptionEndsAt
+ ? `Your subscription stays active until ${formatDate(organization.subscriptionEndsAt)}.`
+ : 'It might take a few seconds to update',
+ });
+ onComplete();
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
+
+ const isPending =
+ pauseMutation.isPending ||
+ discountMutation.isPending ||
+ cancelMutation.isPending;
+
+ const cancelNow = () => {
+ if (!reason) {
+ return;
+ }
+ op.track('subscription_canceled', {
+ organizationId: organization.id,
+ reason,
+ });
+ cancelMutation.mutate({
+ organizationId: organization.id,
+ reason,
+ comment: comment.trim() || undefined,
+ });
+ };
+
+ if (step === 'reason') {
+ return (
+ <>
+ <ModalHeader
+ text="Before you go — what's the main reason? It genuinely helps us improve."
+ title="Cancel subscription"
+ />
+ <div className="scrollbar-thin col min-h-0 flex-1 gap-4 overflow-y-auto">
+ <div className="col shrink-0 divide-y divide-border overflow-hidden rounded-lg border">
+ {REASONS.map((item) => (
+ <button
+ className={cn(
+ 'row shrink-0 items-center justify-between p-4 py-3 text-left transition-colors hover:bg-def-100',
+ reason === item.value && 'bg-def-100'
+ )}
+ key={item.value}
+ onClick={() => setReason(item.value)}
+ type="button"
+ >
+ <span className="font-medium">{item.label}</span>
+ {reason === item.value && (
+ <div className="center-center size-4 shrink-0 rounded-full bg-emerald-600 text-primary-foreground">
+ <CheckIcon className="size-2" />
+ </div>
+ )}
+ </button>
+ ))}
+ </div>
+ <Textarea
+ className="shrink-0"
+ onChange={(event) => setComment(event.target.value)}
+ placeholder="Anything you want to add? (optional)"
+ value={comment}
+ />
+ </div>
+ <ButtonContainer className="shrink-0 gap-2 [&>*]:flex-1">
+ <Button
+ onClick={() => {
+ outcomeRef.current = 'kept';
+ op.track('cancel_flow_dismissed', {
+ organizationId: organization.id,
+ step: 'reason',
+ reason,
+ });
+ onBack();
+ }}
+ variant="outline"
+ >
+ Never mind
+ </Button>
+ <Button
+ disabled={!reason}
+ onClick={() => {
+ op.track('cancel_reason_selected', {
+ organizationId: organization.id,
+ reason,
+ });
+ setStep('pause');
+ }}
+ variant="destructive"
+ >
+ Continue
+ </Button>
+ </ButtonContainer>
+ </>
+ );
+ }
+
+ if (step === 'pause') {
+ return (
+ <>
+ <ModalHeader
+ text="Pause your subscription: billing stops at the end of your current period, we keep collecting your events, and everything is exactly where you left it when you come back."
+ title="Take a break instead?"
+ />
+ <div className="scrollbar-thin col min-h-0 flex-1 gap-3 overflow-y-auto">
+ <div className="row shrink-0 gap-2">
+ {PAUSE_MONTHS.map((months) => (
+ <Button
+ className="flex-1"
+ key={months}
+ onClick={() => setPauseMonths(months)}
+ variant={pauseMonths === months ? 'default' : 'outline'}
+ >
+ {months} {months === 1 ? 'month' : 'months'}
+ </Button>
+ ))}
+ </div>
+ <p className="shrink-0 text-muted-foreground text-sm">
+ Billing automatically resumes after the pause — or resume earlier
+ any time from the billing page. You pay nothing while paused.
+ </p>
+ </div>
+ <ButtonContainer className="shrink-0 gap-2 [&>*]:flex-1">
+ <Button
+ disabled={isPending}
+ onClick={() => {
+ op.track('cancel_pause_declined', {
+ organizationId: organization.id,
+ reason,
+ });
+ if (discountAvailable) {
+ setStep('discount');
+ } else {
+ cancelNow();
+ }
+ }}
+ variant="outline"
+ >
+ {discountAvailable ? 'No thanks' : 'No thanks, cancel'}
+ </Button>
+ <Button
+ loading={pauseMutation.isPending}
+ onClick={() => {
+ op.track('cancel_pause_accepted', {
+ organizationId: organization.id,
+ reason,
+ months: pauseMonths,
+ });
+ pauseMutation.mutate({
+ organizationId: organization.id,
+ months: pauseMonths,
+ });
+ }}
+ >
+ Pause for {pauseMonths} {pauseMonths === 1 ? 'month' : 'months'}
+ </Button>
+ </ButtonContainer>
+ </>
+ );
+ }
+
+ return (
+ <>
+ <ModalHeader
+ text="We'd love to keep you around. Stay on your current plan and get 30% off for the next 12 months, starting with your next billing cycle."
+ title="One last thing — 30% off for a year"
+ />
+ <div className="scrollbar-thin col min-h-0 flex-1 overflow-y-auto">
+ <div className="row shrink-0 items-center gap-3 rounded-lg border bg-def-100 p-4">
+ <span className="font-bold font-mono text-3xl text-emerald-600 dark:text-emerald-500">
+ −30%
+ </span>
+ <span className="text-muted-foreground">for the next 12 months</span>
+ </div>
+ </div>
+ <ButtonContainer className="shrink-0 gap-2 [&>*]:flex-1">
+ <Button
+ disabled={isPending}
+ loading={cancelMutation.isPending}
+ onClick={() => {
+ op.track('cancel_discount_declined', {
+ organizationId: organization.id,
+ reason,
+ });
+ cancelNow();
+ }}
+ variant="outline"
+ >
+ Cancel subscription
+ </Button>
+ <Button
+ loading={discountMutation.isPending}
+ onClick={() => {
+ op.track('cancel_discount_accepted', {
+ organizationId: organization.id,
+ reason,
+ });
+ discountMutation.mutate({ organizationId: organization.id });
+ }}
+ >
+ Apply 30% discount
+ </Button>
+ </ButtonContainer>
+ </>
+ );
+}
diff --git a/apps/start/src/components/organization/yearly-switch-prompt.tsx b/apps/start/src/components/organization/yearly-switch-prompt.tsx
new file mode 100644
index 000000000..bab8973d9
--- /dev/null
+++ b/apps/start/src/components/organization/yearly-switch-prompt.tsx
@@ -0,0 +1,105 @@
+import type { IServiceOrganization } from '@openpanel/db';
+import { useQuery } from '@tanstack/react-query';
+import { differenceInMonths } from 'date-fns';
+import { useEffect, useState } from 'react';
+import { Button } from '@/components/ui/button';
+import { useTRPC } from '@/integrations/trpc/react';
+import { pushModal } from '@/modals';
+import { op } from '@/utils/op';
+
+// Yearly plans churn a fraction of monthly ones. Nudge monthly subscribers who
+// have stuck around for a while to switch — they get 2 months free, we keep
+// them longer. Dismissal is per-org and per-browser.
+const MIN_TENURE_MONTHS = 3;
+
+const dismissKey = (organizationId: string) =>
+ `op-yearly-prompt-dismissed:${organizationId}`;
+
+const readDismissed = (organizationId: string) => {
+ try {
+ return localStorage.getItem(dismissKey(organizationId)) === '1';
+ } catch {
+ return true;
+ }
+};
+
+export default function YearlySwitchPrompt({
+ organization,
+}: {
+ organization: IServiceOrganization;
+}) {
+ const trpc = useTRPC();
+ // Hidden until mounted so SSR and the first client render agree.
+ const [dismissed, setDismissed] = useState(true);
+ useEffect(() => {
+ setDismissed(readDismissed(organization.id));
+ }, [organization.id]);
+
+ const eligible =
+ organization.subscriptionState === 'active' &&
+ organization.subscriptionInterval === 'month' &&
+ !!organization.subscriptionFirstStartedAt &&
+ differenceInMonths(new Date(), organization.subscriptionFirstStartedAt) >=
+ MIN_TENURE_MONTHS;
+
+ const accessQuery = useQuery(
+ trpc.organization.myAccess.queryOptions(
+ { organizationId: organization.id },
+ { enabled: eligible && !dismissed }
+ )
+ );
+ const isAdmin = accessQuery.data?.role === 'org:admin';
+
+ const currentProductQuery = useQuery(
+ trpc.subscription.getCurrent.queryOptions(
+ { organizationId: organization.id },
+ { enabled: eligible && !dismissed && isAdmin }
+ )
+ );
+
+ if (!(eligible && isAdmin) || dismissed) {
+ return null;
+ }
+
+ const dismiss = () => {
+ op.track('yearly_prompt_dismissed', { organizationId: organization.id });
+ try {
+ localStorage.setItem(dismissKey(organization.id), '1');
+ } catch {
+ // Storage unavailable — the prompt just shows again next session.
+ }
+ setDismissed(true);
+ };
+
+ return (
+ <div className="col gap-1 border-b bg-card p-4 lg:p-8">
+ <div className="font-medium text-lg">
+ Switch to yearly — get 2 months free
+ </div>
+ <div className="mb-1">
+ You've been with us for a while. Pay for 10 months and get 12: same
+ plan, same limits, one invoice a year.
+ </div>
+ <div className="row gap-2">
+ <Button
+ loading={currentProductQuery.isLoading}
+ onClick={() => {
+ op.track('yearly_prompt_clicked', {
+ organizationId: organization.id,
+ });
+ pushModal('SelectBillingPlan', {
+ organization,
+ currentProduct: currentProductQuery.data ?? null,
+ defaultInterval: 'year',
+ });
+ }}
+ >
+ See my yearly price
+ </Button>
+ <Button onClick={dismiss} variant="outline">
+ Maybe later
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/hooks/use-client-secret.ts b/apps/start/src/hooks/use-client-secret.ts
index 50e430ad8..8dc5facd2 100644
--- a/apps/start/src/hooks/use-client-secret.ts
+++ b/apps/start/src/hooks/use-client-secret.ts
@@ -3,19 +3,45 @@ import { useEffect, useState } from 'react';
export const ONBOARDING_SECRET_KEY = 'onboarding.clientSecret';
const DEFAULT_SECRET = '[CLIENT_SECRET]';
+// The secret only exists client-side right after creation (we store a hash).
+// Anything derived from it (MCP token, env snippets) must check this first —
+// deriving from the placeholder produces valid-looking but broken values.
+export const isRealClientSecret = (
+ secret: string | null | undefined
+): secret is string => !!secret && secret !== DEFAULT_SECRET;
+
+// Storage can throw (blocked cookies/site data, some private modes); a missing
+// secret must degrade to the placeholder flow, never crash the page.
+const safeRead = () => {
+ try {
+ return sessionStorage.getItem(ONBOARDING_SECRET_KEY);
+ } catch {
+ return null;
+ }
+};
+
+const safeWrite = (value: string) => {
+ try {
+ sessionStorage.setItem(ONBOARDING_SECRET_KEY, value);
+ } catch {
+ // Unavailable — the connect page falls back to its secret-already-shown
+ // notice.
+ }
+};
+
export function useClientSecret() {
const [clientSecret, setClientSecret] = useState<string>(DEFAULT_SECRET);
useEffect(() => {
if (clientSecret && DEFAULT_SECRET !== clientSecret) {
- sessionStorage.setItem(ONBOARDING_SECRET_KEY, clientSecret);
+ safeWrite(clientSecret);
}
}, [clientSecret]);
useEffect(() => {
- const clientSecret = sessionStorage.getItem(ONBOARDING_SECRET_KEY);
- if (clientSecret) {
- setClientSecret(clientSecret);
+ const stored = safeRead();
+ if (stored) {
+ setClientSecret(stored);
}
}, []);
diff --git a/apps/start/src/hooks/use-ws.ts b/apps/start/src/hooks/use-ws.ts
index b3f01b0eb..fe74da522 100644
--- a/apps/start/src/hooks/use-ws.ts
+++ b/apps/start/src/hooks/use-ws.ts
@@ -1,5 +1,5 @@
import debounce from 'lodash.debounce';
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useWebSocket } from 'react-use-websocket/dist/lib/use-websocket';
import { getSuperJson } from '@openpanel/json';
@@ -21,12 +21,22 @@ export default function useWS<T>(
const ws = context.apiUrl.replace(/^https/, 'wss').replace(/^http/, 'ws');
const [baseUrl, setBaseUrl] = useState(`${ws}${path}`);
+ // Always call the latest onMessage. The memoized (debounced) wrapper below
+ // otherwise captures the first render's callback — if the path changes
+ // without unmounting (e.g. switching projects), the socket would reconnect
+ // but keep invoking a handler closed over the old path's state.
+ const onMessageRef = useRef(onMessage);
+ useEffect(() => {
+ onMessageRef.current = onMessage;
+ });
+
const debouncedOnMessage = useMemo(() => {
+ const invokeLatest = (event: T) => onMessageRef.current(event);
if (options?.debounce) {
- return debounce(onMessage, options.debounce.delay, options.debounce);
+ return debounce(invokeLatest, options.debounce.delay, options.debounce);
}
- return onMessage;
- }, [options?.debounce?.delay]);
+ return invokeLatest;
+ }, [options?.debounce?.delay, options?.debounce?.maxWait]);
useEffect(() => {
if (baseUrl === `${ws}${path}`) return;
diff --git a/apps/start/src/modals/add-project.tsx b/apps/start/src/modals/add-project.tsx
index 860f3a1c3..75b688a62 100644
--- a/apps/start/src/modals/add-project.tsx
+++ b/apps/start/src/modals/add-project.tsx
@@ -22,6 +22,7 @@ import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/use-app-params';
+import { ONBOARDING_SECRET_KEY } from '@/hooks/use-client-secret';
import { handleError, useTRPC } from '@/integrations/trpc/react';
const validator = zOnboardingProject;
@@ -109,9 +110,31 @@ export default function AddProject() {
<CreateClientSuccess {...mutation.data.client} />
)}
<ButtonContainer className="justify-end">
- <Button className="flex-1" onClick={() => popModal()}>
+ <Button onClick={() => popModal()} variant="outline">
Close
</Button>
+ {/* Route through the same connect -> verify steps as onboarding so
+ a second project doesn't skip the install instructions. The
+ connect page reads the secret from sessionStorage — seed it
+ here, since this is the only moment the plain secret exists. */}
+ <Button asChild className="flex-1">
+ <a
+ href={`/onboarding/${mutation.data.id}/connect`}
+ onClick={() => {
+ const secret = mutation.data.client?.secret;
+ if (secret) {
+ try {
+ sessionStorage.setItem(ONBOARDING_SECRET_KEY, secret);
+ } catch {
+ // Storage unavailable — connect falls back to its
+ // secret-already-shown notice.
+ }
+ }
+ }}
+ >
+ Set up tracking
+ </a>
+ </Button>
</ButtonContainer>
</>
) : (
diff --git a/apps/start/src/modals/index.tsx b/apps/start/src/modals/index.tsx
index aa147e648..b96d6ec88 100644
--- a/apps/start/src/modals/index.tsx
+++ b/apps/start/src/modals/index.tsx
@@ -26,12 +26,11 @@ import EditMember from './edit-member';
import EditReference from './edit-reference';
import EditReport from './edit-report';
import EventDetails from './event-details';
-import InsightDetails from './insight-details';
import Instructions from './Instructions';
+import InsightDetails from './insight-details';
import MoveReport from './move-report';
import OverviewChartDetails from './overview-chart-details';
import OverviewFilters from './overview-filters';
-import TableFilters from './table-filters';
import PageDetails from './page-details';
import RegenerateRecoveryCodes from './regenerate-recovery-codes';
import RequestPasswordReset from './request-reset-password';
@@ -41,6 +40,7 @@ import SetupTwoFactor from './setup-two-factor';
import ShareDashboardModal from './share-dashboard-modal';
import ShareOverviewModal from './share-overview-modal';
import ShareReportModal from './share-report-modal';
+import TableFilters from './table-filters';
import ViewChartUsers from './view-chart-users';
import OverviewTopGenericModal from '@/components/overview/overview-top-generic-modal';
import OverviewTopPagesModal from '@/components/overview/overview-top-pages-modal';
diff --git a/apps/start/src/modals/select-billing-plan.tsx b/apps/start/src/modals/select-billing-plan.tsx
index 7ed8d93cd..e5ee1e885 100644
--- a/apps/start/src/modals/select-billing-plan.tsx
+++ b/apps/start/src/modals/select-billing-plan.tsx
@@ -1,26 +1,46 @@
import type { IServiceOrganization } from '@openpanel/db';
import type { IPolarProduct } from '@openpanel/payments';
+import { useState } from 'react';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import BillingPlanPicker from '@/components/organization/billing-plan-picker';
+import CancelSubscriptionFlow from '@/components/organization/cancel-subscription-flow';
interface Props {
organization: IServiceOrganization;
currentProduct: IPolarProduct | null;
+ defaultInterval?: 'year' | 'month';
}
export default function SelectBillingPlan({
organization,
currentProduct,
+ defaultInterval,
}: Props) {
+ // Internal router: the cancel flow renders inside this modal instead of
+ // stacking another modal on top.
+ const [view, setView] = useState<'plans' | 'cancel'>('plans');
+
return (
<ModalContent className="!flex !flex-col !overflow-hidden">
- <ModalHeader title="Select a billing plan" />
- <BillingPlanPicker
- currentProduct={currentProduct}
- onComplete={popModal}
- organization={organization}
- />
+ {view === 'plans' ? (
+ <>
+ <ModalHeader title="Select a billing plan" />
+ <BillingPlanPicker
+ currentProduct={currentProduct}
+ defaultInterval={defaultInterval}
+ onCancel={() => setView('cancel')}
+ onComplete={popModal}
+ organization={organization}
+ />
+ </>
+ ) : (
+ <CancelSubscriptionFlow
+ onBack={() => setView('plans')}
+ onComplete={popModal}
+ organization={organization}
+ />
+ )}
</ModalContent>
);
}
diff --git a/apps/start/src/routes/__root.tsx b/apps/start/src/routes/__root.tsx
index 716025f5b..47b1cdc1e 100644
--- a/apps/start/src/routes/__root.tsx
+++ b/apps/start/src/routes/__root.tsx
@@ -2,7 +2,9 @@ import {
createRootRouteWithContext,
HeadContent,
Scripts,
+ useRouteContext,
} from '@tanstack/react-router';
+import { useEffect } from 'react';
import 'flag-icons/css/flag-icons.min.css';
import 'katex/dist/katex.min.css';
@@ -93,6 +95,26 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({
pendingComponent: FullPageLoadingState,
});
+// Tie dashboard events to the signed-in user so activation funnels
+// (signup -> project created -> first event -> report) can be measured.
+function OpIdentify() {
+ const context = useRouteContext({ strict: false });
+ const user = context.session?.user;
+
+ useEffect(() => {
+ if (user?.id) {
+ op.identify({
+ profileId: user.id,
+ email: user.email,
+ firstName: user.firstName ?? undefined,
+ lastName: user.lastName ?? undefined,
+ });
+ }
+ }, [user?.id, user?.email, user?.firstName, user?.lastName]);
+
+ return null;
+}
+
function RootDocument({ children }: { children: React.ReactNode }) {
useSessionExtension();
@@ -102,6 +124,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<HeadContent />
</head>
<body className="grainy min-h-screen bg-def-100 font-sans text-base leading-normal antialiased">
+ <OpIdentify />
<Providers>{children}</Providers>
<ThemeScriptOnce />
<Scripts />
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
index c89425b2c..706a3cd85 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
@@ -1,5 +1,6 @@
import { createFileRoute } from '@tanstack/react-router';
import { LazyComponent } from '@/components/lazy-component';
+import ActivationBanner from '@/components/onboarding/activation-banner';
import { useRangePageContext } from '@/hooks/use-page-context-helpers';
import {
OverviewFilterButton,
@@ -39,6 +40,7 @@ function ProjectDashboard() {
useRangePageContext('overview');
return (
<div>
+ <ActivationBanner />
<div className="sticky-header -top-px!">
<div className="col gap-2 p-4">
<div className="flex justify-between gap-2">
diff --git a/apps/start/src/routes/_app.$organizationId.tsx b/apps/start/src/routes/_app.$organizationId.tsx
index 0bcb911a6..e86ad5f62 100644
--- a/apps/start/src/routes/_app.$organizationId.tsx
+++ b/apps/start/src/routes/_app.$organizationId.tsx
@@ -2,6 +2,7 @@ import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import FeedbackPrompt from '@/components/organization/feedback-prompt';
import SupporterPrompt from '@/components/organization/supporter-prompt';
+import YearlySwitchPrompt from '@/components/organization/yearly-switch-prompt';
import { LinkButton } from '@/components/ui/button';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
@@ -122,6 +123,7 @@ function Component() {
const stateMeta = getSubscriptionStateMeta(organization.subscriptionState, {
endsAt: organization.subscriptionEndsAt,
canceledAt: organization.subscriptionCanceledAt,
+ resumesAt: organization.subscriptionResumesAt,
});
// Project routes show the full-screen BillingPrompt for blocking states;
@@ -137,8 +139,14 @@ function Component() {
isProjectRoute &&
subscriptionBlocksDashboard(organization.subscriptionState);
+ const location = useLocation();
+ const isBillingPage = /\/.+\/billing/.test(location.pathname);
+
return (
<>
+ {!stateMeta.banner && !isBillingPage && (
+ <YearlySwitchPrompt organization={organization} />
+ )}
{stateMeta.banner && !hideBannerForPrompt && (
<Alert
title={stateMeta.banner.title}
@@ -154,12 +162,31 @@ function Component() {
</LinkButton>
</Alert>
)}
+ {organization.isActive &&
+ !organization.isExceeded &&
+ organization.subscriptionPeriodEventsLimit > 0 &&
+ organization.subscriptionPeriodEventsCount >=
+ organization.subscriptionPeriodEventsLimit * 0.8 && (
+ <Alert
+ title="Approaching your events limit"
+ description={`You've used ${Math.round((organization.subscriptionPeriodEventsCount / organization.subscriptionPeriodEventsLimit) * 100)}% of your ${organization.subscriptionPeriodEventsLimit.toLocaleString()} monthly events. If you go over, we keep collecting your events but charts pause until you upgrade.`}
+ >
+ <LinkButton
+ to="/$organizationId/billing"
+ params={{
+ organizationId: organizationId,
+ }}
+ >
+ See plans
+ </LinkButton>
+ </Alert>
+ )}
{organization.subscriptionPeriodEventsCountExceededAt &&
organization.isActive &&
organization.isExceeded && (
<Alert
title="Events limit exceeded"
- description={`Your subscription has exceeded the limit on ${format(organization.subscriptionPeriodEventsCountExceededAt, 'PPP')}`}
+ description={`You hit your monthly events limit on ${format(organization.subscriptionPeriodEventsCountExceededAt, 'PPP')}. We're still collecting your events — nothing is lost — but charts won't show new data until you upgrade or your next cycle starts.`}
>
<LinkButton
to="/$organizationId/billing"
diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
index 81ca446a2..66371782f 100644
--- a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
+++ b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
@@ -2,12 +2,12 @@ import { useQuery } from '@tanstack/react-query';
import { createFileRoute, redirect } from '@tanstack/react-router';
import { CopyIcon, DownloadIcon, LockIcon, XIcon } from 'lucide-react';
import { ButtonContainer } from '@/components/button-container';
+import CopyInput from '@/components/forms/copy-input';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import ConnectWeb from '@/components/onboarding/connect-web';
-import Syntax from '@/components/syntax';
import { Button, LinkButton } from '@/components/ui/button';
-import { useClientSecret } from '@/hooks/use-client-secret';
+import { isRealClientSecret, useClientSecret } from '@/hooks/use-client-secret';
import { useTRPC } from '@/integrations/trpc/react';
import { clipboard } from '@/utils/clipboard';
import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
@@ -53,8 +53,18 @@ function Component() {
);
}
- const mcpToken = btoa(`${client.id}:${secret}`);
- const credentials = `CLIENT_ID=${client.id}\nCLIENT_SECRET=${secret}\nMCP_TOKEN=${mcpToken}`;
+ // The secret only exists in this browser session right after creation (we
+ // store a hash server-side). Never derive the MCP token — or print secret
+ // lines — from the placeholder: that produces valid-looking broken values.
+ const hasSecret = isRealClientSecret(secret);
+ const mcpToken = hasSecret ? btoa(`${client.id}:${secret}`) : null;
+ const credentials = [
+ `CLIENT_ID=${client.id}`,
+ hasSecret && `CLIENT_SECRET=${secret}`,
+ mcpToken && `MCP_TOKEN=${mcpToken}`,
+ ]
+ .filter(Boolean)
+ .join('\n');
const download = () => {
const blob = new Blob([credentials], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
@@ -80,7 +90,7 @@ function Component() {
onClick={() => clipboard(credentials)}
variant="outline"
>
- Copy
+ Copy all
</Button>
<Button
icon={DownloadIcon}
@@ -91,12 +101,26 @@ function Component() {
</Button>
</div>
</div>
- <Syntax
- className="border"
- code={`CLIENT_ID=${client.id}\nCLIENT_SECRET=${secret}\nMCP_TOKEN=${mcpToken}`}
- copyable={false}
- language="bash"
- />
+ <div className="col gap-3">
+ <CopyInput label="Client ID" value={client.id} />
+ {hasSecret && <CopyInput label="Client secret" value={secret} />}
+ {mcpToken && (
+ <div className="w-full min-w-0">
+ <CopyInput label="MCP token" value={mcpToken} />
+ <p className="mt-1 text-muted-foreground text-sm">
+ Authenticates the MCP server (base64-encoded client ID and
+ secret).
+ </p>
+ </div>
+ )}
+ {!hasSecret && (
+ <p className="text-muted-foreground text-sm">
+ Your client secret (and the MCP token derived from it) is only
+ shown once, right after the client is created. If you need it
+ again, create a new client under Settings → Clients.
+ </p>
+ )}
+ </div>
</div>
<div className="-mx-4 h-px bg-muted" />
<ConnectWeb client={{ ...client, secret }} />
diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
index f600605c4..abe43ebcd 100644
--- a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
+++ b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
@@ -1,4 +1,4 @@
-import { useQuery } from '@tanstack/react-query';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import { createFileRoute, Link, redirect } from '@tanstack/react-router';
import { BoxSelectIcon } from 'lucide-react';
import { ButtonContainer } from '@/components/button-container';
@@ -7,8 +7,11 @@ import FullPageLoadingState from '@/components/full-page-loading-state';
import VerifyListener from '@/components/onboarding/onboarding-verify-listener';
import { VerifyFaq } from '@/components/onboarding/verify-faq';
import { LinkButton } from '@/components/ui/button';
+import { useEffect } from 'react';
+import useWS from '@/hooks/use-ws';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/lib/utils';
+import { op } from '@/utils/op';
import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({
@@ -34,15 +37,35 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({
function Component() {
const { projectId } = Route.useParams();
const trpc = useTRPC();
+ const queryClient = useQueryClient();
const { data: events } = useQuery(
trpc.event.events.queryOptions(
{ projectId },
{
- refetchInterval: 2500,
+ // The live websocket below flips the verifier instantly; this poll is
+ // only a fallback for when the socket can't connect.
+ refetchInterval: 10_000,
}
)
);
+ // Refetch the event list the moment an event arrives instead of waiting for
+ // the next poll — same channel the in-app live event feed uses.
+ useWS(`/live/events/${projectId}`, () => {
+ queryClient.invalidateQueries(
+ trpc.event.events.queryFilter({ projectId })
+ );
+ });
const isVerified = events?.data && events.data.length > 0;
+
+ useEffect(() => {
+ op.track('onboarding_verify_viewed', { projectId });
+ }, [projectId]);
+
+ useEffect(() => {
+ if (isVerified) {
+ op.track('onboarding_first_event_verified', { projectId });
+ }
+ }, [isVerified, projectId]);
const { data: project } = useQuery(
trpc.project.getProjectWithClients.queryOptions({ projectId })
);
diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsx
index a6e616259..108617504 100644
--- a/apps/start/src/routes/_steps.onboarding.project.tsx
+++ b/apps/start/src/routes/_steps.onboarding.project.tsx
@@ -27,6 +27,7 @@ import { Label } from '@/components/ui/label';
import { useClientSecret } from '@/hooks/use-client-secret';
import { handleError, useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
+import { op } from '@/utils/op';
const validateSearch = z.object({
inviteId: z.string().optional(),
@@ -74,6 +75,7 @@ function Component() {
trpc.onboarding.project.mutationOptions({
onError: handleError,
onSuccess(res) {
+ op.track('onboarding_project_created', { projectId: res.projectId });
queryClient.invalidateQueries(trpc.organization.list.queryFilter());
setSecret(res.secret);
navigate({
diff --git a/apps/worker/src/boot-cron.ts b/apps/worker/src/boot-cron.ts
index 9e17b845e..7c110d3c0 100644
--- a/apps/worker/src/boot-cron.ts
+++ b/apps/worker/src/boot-cron.ts
@@ -113,6 +113,11 @@ export async function bootCron() {
type: 'weeklyDigest',
pattern: '0 8 * * 1', // Mondays 08:00 UTC — weekly analytics digest email
},
+ {
+ name: 'dataHealth',
+ type: 'dataHealth',
+ pattern: '30 7 * * *', // Daily 07:30 UTC — no-data / data-stopped rescue emails
+ },
];
if (process.env.SELF_HOSTED && process.env.NODE_ENV === 'production') {
diff --git a/apps/worker/src/boot-debug.ts b/apps/worker/src/boot-debug.ts
index 28bb2dd1e..95c0f9a44 100644
--- a/apps/worker/src/boot-debug.ts
+++ b/apps/worker/src/boot-debug.ts
@@ -30,6 +30,7 @@ const CRON_TYPES = [
'sessionVacuum',
'insightCleanup',
'weeklyDigest',
+ 'dataHealth',
] as const satisfies readonly CronQueueType[];
function escapeHtml(value: string) {
diff --git a/apps/worker/src/jobs/cron.data-health.ts b/apps/worker/src/jobs/cron.data-health.ts
new file mode 100644
index 000000000..5dc2e7513
--- /dev/null
+++ b/apps/worker/src/jobs/cron.data-health.ts
@@ -0,0 +1,207 @@
+import { db, getLastEventPerProject } from '@openpanel/db';
+import { sendEmail } from '@openpanel/email';
+import { logger as baseLogger } from '@/utils/logger';
+
+const logger = baseLogger.child({ job: 'data-health' });
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+// A brand-new project gets 48h to send its first event before we reach out.
+const NO_DATA_AFTER_MS = 2 * DAY_MS;
+// An active project whose newest event is older than this counts as stalled.
+const STALLED_AFTER_MS = 7 * DAY_MS;
+
+interface OrgAlert {
+ organizationId: string;
+ noData: { id: string; name: string }[];
+ stalled: { id: string; name: string; lastEventAt: Date }[];
+}
+
+async function recipientsForOrg(organizationId: string) {
+ const members = await db.member.findMany({
+ where: {
+ organizationId,
+ user: { deletedAt: null },
+ },
+ include: { user: { select: { email: true, firstName: true } } },
+ });
+ const seen = new Map<string, string | undefined>();
+ for (const member of members) {
+ if (member.user?.email && !seen.has(member.user.email)) {
+ seen.set(member.user.email, member.user.firstName ?? undefined);
+ }
+ }
+ return seen;
+}
+
+/**
+ * Daily rescue emails for paying/trialing orgs whose tracking is broken:
+ * projects that never received an event (48h grace) and projects whose event
+ * flow stalled for 7+ days. A silently broken install reads as "the product
+ * stopped working" — a working install is the cheapest retention there is.
+ *
+ * Dedupe: `noDataNotifiedAt` is sent once per project; `dataStoppedNotifiedAt`
+ * is compared against the newest event, so data resuming and stalling again
+ * notifies again without any clearing step.
+ */
+export async function dataHealthCronJob() {
+ if (process.env.SELF_HOSTED === 'true') {
+ return;
+ }
+
+ const now = Date.now();
+ const lastEventByProject = await getLastEventPerProject();
+
+ // Prefilter on the raw status column (computed fields can't be used in
+ // `where`), then refine with the canonical subscription state below.
+ const projects = await db.project.findMany({
+ where: {
+ deleteAt: null,
+ organization: { subscriptionStatus: { in: ['active', 'trialing'] } },
+ },
+ select: {
+ id: true,
+ name: true,
+ createdAt: true,
+ organizationId: true,
+ noDataNotifiedAt: true,
+ dataStoppedNotifiedAt: true,
+ organization: {
+ select: { id: true, subscriptionState: true, onboarding: true },
+ },
+ },
+ });
+
+ const byOrg = new Map<string, OrgAlert>();
+
+ for (const project of projects) {
+ const state = project.organization.subscriptionState;
+ if (state !== 'active' && state !== 'trialing') {
+ continue;
+ }
+
+ const lastEventAt = lastEventByProject.get(project.id);
+
+ if (!lastEventAt) {
+ // Never received an event. One notice per project, after the grace
+ // period. Orgs still in the onboarding email drip are excluded — its
+ // day-2/6 emails already carry "stuck on the install?" variants, so this
+ // notice targets post-onboarding orgs and additional projects.
+ const inOnboardingDrip = project.organization.onboarding !== 'completed';
+ const oldEnough = now - project.createdAt.getTime() > NO_DATA_AFTER_MS;
+ if (oldEnough && !project.noDataNotifiedAt && !inOnboardingDrip) {
+ const entry = byOrg.get(project.organizationId) ?? {
+ organizationId: project.organizationId,
+ noData: [],
+ stalled: [],
+ };
+ entry.noData.push({ id: project.id, name: project.name });
+ byOrg.set(project.organizationId, entry);
+ }
+ continue;
+ }
+
+ const stalled = now - lastEventAt.getTime() > STALLED_AFTER_MS;
+ const alreadyNotifiedForThisStall =
+ project.dataStoppedNotifiedAt &&
+ project.dataStoppedNotifiedAt > lastEventAt;
+ if (stalled && !alreadyNotifiedForThisStall) {
+ const entry = byOrg.get(project.organizationId) ?? {
+ organizationId: project.organizationId,
+ noData: [],
+ stalled: [],
+ };
+ entry.stalled.push({
+ id: project.id,
+ name: project.name,
+ lastEventAt,
+ });
+ byOrg.set(project.organizationId, entry);
+ }
+ }
+
+ let emailsSent = 0;
+
+ for (const alert of byOrg.values()) {
+ try {
+ const recipients = await recipientsForOrg(alert.organizationId);
+ if (recipients.size === 0) {
+ continue;
+ }
+
+ const dashboardUrl = `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${alert.organizationId}`;
+
+ if (alert.noData.length > 0) {
+ for (const [to, firstName] of recipients) {
+ // Per-recipient guard: one bad address must not block the marker
+ // update below — that would re-email everyone tomorrow.
+ try {
+ await sendEmail('tracking-no-data', {
+ to,
+ data: {
+ firstName,
+ projectNames: alert.noData.map((p) => p.name),
+ dashboardUrl,
+ },
+ });
+ emailsSent++;
+ } catch (err) {
+ logger.error(
+ { err, organizationId: alert.organizationId, recipient: to },
+ 'Failed to send no-data alert to recipient'
+ );
+ }
+ }
+ await db.project.updateMany({
+ where: { id: { in: alert.noData.map((p) => p.id) } },
+ data: { noDataNotifiedAt: new Date() },
+ });
+ }
+
+ if (alert.stalled.length > 0) {
+ const newestLastEvent = alert.stalled
+ .map((p) => p.lastEventAt)
+ .sort((a, b) => b.getTime() - a.getTime())[0];
+ for (const [to, firstName] of recipients) {
+ try {
+ await sendEmail('tracking-data-stopped', {
+ to,
+ data: {
+ firstName,
+ projectNames: alert.stalled.map((p) => p.name),
+ lastEventDate: newestLastEvent?.toLocaleDateString('en-US', {
+ month: 'long',
+ day: 'numeric',
+ }),
+ dashboardUrl,
+ },
+ });
+ emailsSent++;
+ } catch (err) {
+ logger.error(
+ { err, organizationId: alert.organizationId, recipient: to },
+ 'Failed to send data-stopped alert to recipient'
+ );
+ }
+ }
+ await db.project.updateMany({
+ where: { id: { in: alert.stalled.map((p) => p.id) } },
+ data: { dataStoppedNotifiedAt: new Date() },
+ });
+ }
+ } catch (err) {
+ logger.error(
+ { err, organizationId: alert.organizationId },
+ 'Data-health alert failed'
+ );
+ }
+ }
+
+ logger.info(
+ {
+ projects: projects.length,
+ organizations: byOrg.size,
+ emailsSent,
+ },
+ 'Data-health check complete'
+ );
+}
diff --git a/apps/worker/src/jobs/cron.ts b/apps/worker/src/jobs/cron.ts
index 008d2dbd5..b922ab670 100644
--- a/apps/worker/src/jobs/cron.ts
+++ b/apps/worker/src/jobs/cron.ts
@@ -9,6 +9,7 @@ import {
import type { CronQueuePayload } from '@openpanel/queue';
import type { Job } from 'bullmq';
import { cohortRefreshCronJob } from './cron.cohort-refresh';
+import { dataHealthCronJob } from './cron.data-health';
import { jobDelete } from './cron.delete';
import { insightCleanupCronJob } from './cron.insight-cleanup';
import { weeklyDigestCronJob } from './cron.weekly-digest';
@@ -75,5 +76,8 @@ export async function cronJob(job: Job<CronQueuePayload>) {
case 'weeklyDigest': {
return await weeklyDigestCronJob();
}
+ case 'dataHealth': {
+ return await dataHealthCronJob();
+ }
}
}
diff --git a/apps/worker/src/jobs/cron.weekly-digest.ts b/apps/worker/src/jobs/cron.weekly-digest.ts
index 6902bc4cd..6a9435fb2 100644
--- a/apps/worker/src/jobs/cron.weekly-digest.ts
+++ b/apps/worker/src/jobs/cron.weekly-digest.ts
@@ -6,7 +6,11 @@ import { logger as baseLogger } from '@/utils/logger';
const logger = baseLogger.child({ job: 'weekly-digest' });
const DAY_MS = 24 * 60 * 60 * 1000;
-const MIN_EVENTS = 5000;
+// Keep this low: the digest is our main "value without logging in" touchpoint,
+// and the old 5000 gate excluded customers on smaller plans — exactly the ones
+// who benefit most from the reminder. Zero-visitor weeks are still skipped per
+// send, so quiet projects don't get empty emails.
+const MIN_EVENTS = 100;
const MAX_INSIGHTS = 5;
type DigestData = EmailData<'weekly-digest'>;
diff --git a/apps/worker/src/jobs/events.incoming-event.ts b/apps/worker/src/jobs/events.incoming-event.ts
index 0cac12864..8d13de7dd 100644
--- a/apps/worker/src/jobs/events.incoming-event.ts
+++ b/apps/worker/src/jobs/events.incoming-event.ts
@@ -4,6 +4,7 @@ import type { IServiceCreateEventPayload, IServiceEvent } from '@openpanel/db';
import {
checkNotificationRulesForEvent,
createEvent,
+ db,
getProjectByIdCached,
matchEvent,
sessionBuffer,
@@ -35,6 +36,24 @@ async function isEventExcludedByProjectFilter(
return eventExcludeFilters.some((filter) => matchEvent(payload, filter));
}
+/**
+ * Records the project's first-ever event timestamp exactly once. The cached
+ * project read makes this a no-op on every event after the first; the
+ * conditional update keeps concurrent workers idempotent.
+ */
+async function markFirstEvent(projectId: string, logger: ILogger) {
+ const project = await getProjectByIdCached(projectId);
+ if (!project || project.firstEventAt) {
+ return;
+ }
+ await db.project.updateMany({
+ where: { id: projectId, firstEventAt: null },
+ data: { firstEventAt: new Date() },
+ });
+ await getProjectByIdCached.clear(projectId);
+ logger.info({ projectId }, 'Project received its first event');
+}
+
async function createEventAndNotify(
payload: IServiceCreateEventPayload,
logger: ILogger,
@@ -54,6 +73,10 @@ async function createEventAndNotify(
createEvent(payload),
checkNotificationRulesForEvent(payload).catch(() => null),
]);
+ // Only after the event is accepted — recording the first event before a
+ // failed createEvent would leave the activation checklist claiming data
+ // arrived that was never persisted.
+ await markFirstEvent(projectId, logger).catch(() => null);
return event;
}
diff --git a/apps/worker/src/jobs/notification.ts b/apps/worker/src/jobs/notification.ts
index d56bc24df..58b076b20 100644
--- a/apps/worker/src/jobs/notification.ts
+++ b/apps/worker/src/jobs/notification.ts
@@ -1,6 +1,7 @@
import type { Job } from 'bullmq';
import { Prisma, db } from '@openpanel/db';
+import { sendEmail } from '@openpanel/email';
import { sendDiscordNotification } from '@openpanel/integrations/src/discord';
import { postWebhook } from '@openpanel/integrations/src/fetcher';
import { safeWebhookFetcher } from '@openpanel/integrations/src/safe-fetcher';
@@ -31,6 +32,35 @@ export async function notificationJob(job: Job<NotificationQueuePayload>) {
}
if (notification.sendToEmail) {
+ const project = await db.project.findUniqueOrThrow({
+ where: { id: notification.projectId },
+ select: { name: true, organizationId: true },
+ });
+ const members = await db.member.findMany({
+ where: {
+ organizationId: project.organizationId,
+ user: { deletedAt: null },
+ },
+ include: { user: { select: { email: true } } },
+ });
+ const emails = new Set(
+ members.flatMap((member) =>
+ member.user?.email ? [member.user.email] : [],
+ ),
+ );
+ for (const to of emails) {
+ // Per-recipient unsubscribe (product_alerts category) is handled
+ // inside sendEmail.
+ await sendEmail('notification-rule', {
+ to,
+ data: {
+ title: notification.title,
+ message: notification.message,
+ projectName: project.name,
+ dashboardUrl: `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${project.organizationId}/${notification.projectId}`,
+ },
+ });
+ }
return;
}
diff --git a/apps/worker/src/jobs/sessions.ts b/apps/worker/src/jobs/sessions.ts
index d41303ae6..808d7ba51 100644
--- a/apps/worker/src/jobs/sessions.ts
+++ b/apps/worker/src/jobs/sessions.ts
@@ -1,17 +1,18 @@
-import type { Job } from 'bullmq';
-
-import type { SessionsQueuePayload } from '@openpanel/queue';
-
-import { logger } from '@/utils/logger';
+import type { Organization } from '@openpanel/db';
import {
db,
getOrganizationBillingEventsCount,
getProjectEventsCount,
} from '@openpanel/db';
+import { sendEmail } from '@openpanel/email';
+import type { SessionsQueuePayload } from '@openpanel/queue';
import { cacheable } from '@openpanel/redis';
+import type { Job } from 'bullmq';
import { createSessionEnd } from './events.create-session-end';
+import { logger } from '@/utils/logger';
const INT4_MAX = 2_147_483_647;
+const USAGE_WARNING_THRESHOLD = 0.8;
export async function sessionsJob(job: Job<SessionsQueuePayload>) {
const res = await createSessionEnd(job);
@@ -24,7 +25,7 @@ export async function sessionsJob(job: Job<SessionsQueuePayload>) {
}
const updateEventsCount = cacheable(async function updateEventsCount(
- projectId: string,
+ projectId: string
) {
const organization = await db.organization.findFirst({
where: {
@@ -74,7 +75,7 @@ const updateEventsCount = cacheable(async function updateEventsCount(
data: {
subscriptionPeriodEventsCount: Math.min(
organizationEventsCount,
- INT4_MAX,
+ INT4_MAX
),
subscriptionPeriodEventsCountExceededAt: isSelfHosted
? null
@@ -88,7 +89,140 @@ const updateEventsCount = cacheable(async function updateEventsCount(
: organization.subscriptionPeriodEventsCountExceededAt,
},
});
+
+ if (!isSelfHosted) {
+ try {
+ await sendUsageAlerts(organization, organizationEventsCount);
+ } catch (e) {
+ logger.error({ err: e }, 'Failed to send usage alert emails');
+ }
+ }
}
return true;
}, 60 * 60);
+
+/**
+ * One warning at 80% and one notice at 100% per billing cycle. The sent-at
+ * markers are cleared by the Polar webhook when a new cycle resets the usage
+ * counter (or the limit is raised), so each cycle can alert again.
+ */
+async function sendUsageAlerts(organization: Organization, count: number) {
+ const limit = organization.subscriptionPeriodEventsLimit;
+ if (!limit || limit <= 0) {
+ return;
+ }
+
+ const exceeded = count > limit && !organization.usageExceededSentAt;
+ const nearLimit =
+ !exceeded &&
+ count >= limit * USAGE_WARNING_THRESHOLD &&
+ count <= limit &&
+ !organization.usageWarningSentAt;
+
+ if (!(exceeded || nearLimit)) {
+ return;
+ }
+
+ // Claim the alert atomically BEFORE sending: session jobs for different
+ // projects of the same org can run concurrently, and both would otherwise
+ // read null markers and double-send. Marking the warning together with the
+ // exceeded notice keeps a both-thresholds-in-one-jump crossing from queueing
+ // a redundant warning afterwards. Rolled back if every send fails.
+ const claimedAt = new Date();
+ const claimed = await db.organization.updateMany({
+ where: {
+ id: organization.id,
+ ...(exceeded
+ ? { usageExceededSentAt: null }
+ : { usageWarningSentAt: null }),
+ },
+ data: exceeded
+ ? { usageExceededSentAt: claimedAt, usageWarningSentAt: claimedAt }
+ : { usageWarningSentAt: claimedAt },
+ });
+ if (claimed.count === 0) {
+ return;
+ }
+
+ try {
+ const admins = await db.member.findMany({
+ where: {
+ organizationId: organization.id,
+ role: 'org:admin',
+ user: { deletedAt: null },
+ },
+ include: { user: { select: { email: true, firstName: true } } },
+ });
+
+ const billingUrl = `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${organization.id}/billing`;
+ const recipients = new Map(
+ admins
+ .filter((member) => member.user?.email)
+ .map((member) => [
+ member.user!.email,
+ member.user!.firstName ?? undefined,
+ ])
+ );
+
+ let failedRecipients = 0;
+ for (const [email, firstName] of recipients) {
+ // Per-recipient guard: one bad address must not abort the loop or roll
+ // back the claim — that would re-email the recipients that succeeded.
+ try {
+ if (exceeded) {
+ await sendEmail('usage-limit-exceeded', {
+ to: email,
+ data: {
+ firstName,
+ organizationName: organization.name,
+ billingUrl,
+ eventsLimit: limit,
+ },
+ });
+ } else {
+ await sendEmail('usage-near-limit', {
+ to: email,
+ data: {
+ firstName,
+ organizationName: organization.name,
+ billingUrl,
+ eventsCount: count,
+ eventsLimit: limit,
+ },
+ });
+ }
+ } catch (error) {
+ failedRecipients++;
+ logger.error(
+ { err: error, organizationId: organization.id, recipient: email },
+ 'Failed to send usage alert to recipient'
+ );
+ }
+ }
+
+ logger.info(
+ {
+ organizationId: organization.id,
+ count,
+ limit,
+ kind: exceeded ? 'exceeded' : 'near-limit',
+ recipients: recipients.size,
+ failedRecipients,
+ },
+ 'Sent usage alert emails'
+ );
+ } catch (error) {
+ // Release the claim so the next usage update retries the alert.
+ await db.organization.updateMany({
+ where: { id: organization.id },
+ data: exceeded
+ ? {
+ usageExceededSentAt: null,
+ usageWarningSentAt: organization.usageWarningSentAt,
+ }
+ : { usageWarningSentAt: null },
+ });
+ throw error;
+ }
+}
diff --git a/packages/constants/index.ts b/packages/constants/index.ts
index 4a186c8d0..6f4324ebf 100644
--- a/packages/constants/index.ts
+++ b/packages/constants/index.ts
@@ -606,6 +606,11 @@ export const emailCategories = {
label: 'Weekly digest',
description: 'A weekly summary of your analytics with AI-surfaced insights',
},
+ product_alerts: {
+ label: 'Product alerts',
+ description:
+ 'Important notices about your projects: tracking stopped sending data, event limits, and alerts from your notification rules',
+ },
} as const;
export type EmailCategory = keyof typeof emailCategories;
diff --git a/packages/db/prisma/migrations/20260822090000_churn_cancel_flow_pause_discount/migration.sql b/packages/db/prisma/migrations/20260822090000_churn_cancel_flow_pause_discount/migration.sql
new file mode 100644
index 000000000..4a909a0cc
--- /dev/null
+++ b/packages/db/prisma/migrations/20260822090000_churn_cancel_flow_pause_discount/migration.sql
@@ -0,0 +1,10 @@
+-- Cancel-flow churn work: capture the customer's cancellation reason/comment,
+-- guard the one-time save-offer discount, and mirror Polar's pause state
+-- (pause-at-period-end keeps status `active` until the period ends, then the
+-- subscription flips to `paused`; `resumesAt` schedules the automatic resume).
+ALTER TABLE "organizations"
+ ADD COLUMN "subscriptionCancelReason" TEXT,
+ ADD COLUMN "subscriptionCancelComment" TEXT,
+ ADD COLUMN "subscriptionSaveDiscountAppliedAt" TIMESTAMP(3),
+ ADD COLUMN "subscriptionPauseAtPeriodEnd" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN "subscriptionResumesAt" TIMESTAMP(3);
diff --git a/packages/db/prisma/migrations/20260822100000_subscription_first_started_at/migration.sql b/packages/db/prisma/migrations/20260822100000_subscription_first_started_at/migration.sql
new file mode 100644
index 000000000..67e08a2ca
--- /dev/null
+++ b/packages/db/prisma/migrations/20260822100000_subscription_first_started_at/migration.sql
@@ -0,0 +1,6 @@
+-- Stable subscription-creation timestamp for tenure. subscriptionStartsAt is
+-- overwritten with the current period start on every renewal, so it cannot
+-- answer "how long has this customer been subscribed" — this column can.
+-- Backfilled from Polar via packages/payments/scripts/sync-subscriptions.ts.
+ALTER TABLE "organizations"
+ ADD COLUMN "subscriptionFirstStartedAt" TIMESTAMP(3);
diff --git a/packages/db/prisma/migrations/20260822110000_data_health_and_usage_alerts/migration.sql b/packages/db/prisma/migrations/20260822110000_data_health_and_usage_alerts/migration.sql
new file mode 100644
index 000000000..0650394f8
--- /dev/null
+++ b/packages/db/prisma/migrations/20260822110000_data_health_and_usage_alerts/migration.sql
@@ -0,0 +1,9 @@
+-- Usage-alert dedupe markers (cleared on billing-cycle reset / limit raise)
+-- and data-health notice markers for the dataHealth cron.
+ALTER TABLE "organizations"
+ ADD COLUMN "usageWarningSentAt" TIMESTAMP(3),
+ ADD COLUMN "usageExceededSentAt" TIMESTAMP(3);
+
+ALTER TABLE "projects"
+ ADD COLUMN "noDataNotifiedAt" TIMESTAMP(3),
+ ADD COLUMN "dataStoppedNotifiedAt" TIMESTAMP(3);
diff --git a/packages/db/prisma/migrations/20260822120000_project_first_event_at/migration.sql b/packages/db/prisma/migrations/20260822120000_project_first_event_at/migration.sql
new file mode 100644
index 000000000..bc7169354
--- /dev/null
+++ b/packages/db/prisma/migrations/20260822120000_project_first_event_at/migration.sql
@@ -0,0 +1,4 @@
+-- Set once by the worker when a project's first event arrives. Powers the
+-- activation checklist and onboarding verification.
+ALTER TABLE "projects"
+ ADD COLUMN "firstEventAt" TIMESTAMP(3);
diff --git a/packages/db/prisma/migrations/20260822130000_subscription_discount/migration.sql b/packages/db/prisma/migrations/20260822130000_subscription_discount/migration.sql
new file mode 100644
index 000000000..b2bfbba5c
--- /dev/null
+++ b/packages/db/prisma/migrations/20260822130000_subscription_discount/migration.sql
@@ -0,0 +1,5 @@
+-- Compact summary of the discount applied to the subscription (synced from
+-- Polar's embedded discount object) so the dashboard can show that a discount
+-- is active — including the cancel-flow save offer.
+ALTER TABLE "organizations"
+ ADD COLUMN "subscriptionDiscount" JSONB;
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 4b8c75be7..e3dbdda50 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -101,6 +101,25 @@ model Organization {
subscriptionPeriodEventsCountExceededAt DateTime?
subscriptionPeriodEventsLimit Int @default(0)
subscriptionInterval String?
+ /// [IPrismaCancellationReason]
+ subscriptionCancelReason String?
+ subscriptionCancelComment String?
+ // When the one-time save-offer discount was applied; guards re-offering it.
+ subscriptionSaveDiscountAppliedAt DateTime?
+ // Pause-at-period-end mirrors Polar: status stays `active` with this flag set
+ // until the period ends, then flips to `paused`.
+ subscriptionPauseAtPeriodEnd Boolean @default(false)
+ subscriptionResumesAt DateTime?
+ // When the current Polar subscription was first created. Unlike
+ // subscriptionStartsAt (overwritten with each period start on renewal) this
+ // is stable, so it can measure tenure (e.g. the switch-to-yearly prompt).
+ subscriptionFirstStartedAt DateTime?
+ // Usage-alert dedupe markers — cleared when a new billing cycle resets the
+ // usage counter (or the limit is raised), so each cycle can warn once.
+ usageWarningSentAt DateTime?
+ usageExceededSentAt DateTime?
+ /// [IPrismaSubscriptionDiscount]
+ subscriptionDiscount Json?
// When deleteAt > now(), the organization will be deleted
deleteAt DateTime?
@@ -238,6 +257,15 @@ model Project {
allowUnsafeRevenueTracking Boolean @default(false)
/// [IPrismaProjectFilters]
filters Json @default("[]")
+ // Set once when the project's first event arrives (activation checklist,
+ // onboarding). Never updated after that.
+ firstEventAt DateTime?
+ // Data-health notice markers set by the dataHealth cron. `noDataNotifiedAt`:
+ // told the org this project never received events. `dataStoppedNotifiedAt`:
+ // told them the event flow stalled — compared against the last event time, so
+ // a resume followed by a new stall notifies again without clearing.
+ noDataNotifiedAt DateTime?
+ dataStoppedNotifiedAt DateTime?
clients Client[]
reports Report[]
diff --git a/packages/db/scripts/set-subscription-state.ts b/packages/db/scripts/set-subscription-state.ts
index d7d8e8444..71362534e 100644
--- a/packages/db/scripts/set-subscription-state.ts
+++ b/packages/db/scripts/set-subscription-state.ts
@@ -23,62 +23,95 @@ type Recipe = {
subscriptionCanceledAt: Date | null;
subscriptionStartsAt: Date | null;
subscriptionEndsAt: Date | null;
+ subscriptionPauseAtPeriodEnd: boolean;
+ subscriptionResumesAt: Date | null;
};
+const base = {
+ subscriptionPauseAtPeriodEnd: false,
+ subscriptionResumesAt: null,
+} as const;
+
const recipes: Record<string, () => Recipe> = {
trialing: () => ({
+ ...base,
subscriptionStatus: null,
subscriptionCanceledAt: null,
subscriptionStartsAt: null,
subscriptionEndsAt: future(),
}),
trial_expired: () => ({
+ ...base,
subscriptionStatus: null,
subscriptionCanceledAt: null,
subscriptionStartsAt: null,
subscriptionEndsAt: past(),
}),
active: () => ({
+ ...base,
subscriptionStatus: 'active',
subscriptionCanceledAt: null,
subscriptionStartsAt: new Date(),
subscriptionEndsAt: future(),
}),
canceling: () => ({
+ ...base,
subscriptionStatus: 'active',
subscriptionCanceledAt: new Date(),
subscriptionStartsAt: new Date(),
subscriptionEndsAt: future(),
}),
canceled: () => ({
+ ...base,
subscriptionStatus: 'canceled',
subscriptionCanceledAt: past(),
subscriptionStartsAt: monthAgo(),
subscriptionEndsAt: past(),
}),
past_due: () => ({
+ ...base,
subscriptionStatus: 'past_due',
subscriptionCanceledAt: null,
subscriptionStartsAt: monthAgo(),
subscriptionEndsAt: future(),
}),
unpaid: () => ({
+ ...base,
subscriptionStatus: 'unpaid',
subscriptionCanceledAt: null,
subscriptionStartsAt: monthAgo(),
subscriptionEndsAt: future(),
}),
incomplete: () => ({
+ ...base,
subscriptionStatus: 'incomplete',
subscriptionCanceledAt: null,
subscriptionStartsAt: new Date(),
subscriptionEndsAt: future(),
}),
expired: () => ({
+ ...base,
+ subscriptionStatus: 'active',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: monthAgo(),
+ subscriptionEndsAt: past(),
+ }),
+ pausing: () => ({
+ ...base,
subscriptionStatus: 'active',
subscriptionCanceledAt: null,
+ subscriptionStartsAt: new Date(),
+ subscriptionEndsAt: future(),
+ subscriptionPauseAtPeriodEnd: true,
+ subscriptionResumesAt: new Date(Date.now() + 60 * DAY),
+ }),
+ paused: () => ({
+ ...base,
+ subscriptionStatus: 'paused',
+ subscriptionCanceledAt: null,
subscriptionStartsAt: monthAgo(),
subscriptionEndsAt: past(),
+ subscriptionResumesAt: new Date(Date.now() + 30 * DAY),
}),
};
diff --git a/packages/db/src/prisma-client.ts b/packages/db/src/prisma-client.ts
index 3edb87d0d..a4eb1edcd 100644
--- a/packages/db/src/prisma-client.ts
+++ b/packages/db/src/prisma-client.ts
@@ -8,6 +8,7 @@ const subscriptionStateNeeds = {
subscriptionStatus: true,
subscriptionCanceledAt: true,
subscriptionEndsAt: true,
+ subscriptionPauseAtPeriodEnd: true,
} as const;
const getPrismaClient = () => {
@@ -54,6 +55,8 @@ const getPrismaClient = () => {
return (
state === 'active' ||
state === 'canceling' ||
+ state === 'pausing' ||
+ state === 'paused' ||
state === 'past_due' ||
state === 'unpaid' ||
state === 'incomplete'
diff --git a/packages/db/src/services/notification.service.ts b/packages/db/src/services/notification.service.ts
index 5b357151a..9348a4849 100644
--- a/packages/db/src/services/notification.service.ts
+++ b/packages/db/src/services/notification.service.ts
@@ -50,16 +50,16 @@ export const BASE_INTEGRATIONS: Integration[] = [
},
organizationId: '',
},
- // {
- // id: EMAIL_NOTIFICATION_INTEGRATION_ID,
- // name: 'Email',
- // createdAt: new Date(),
- // updatedAt: new Date(),
- // config: {
- // type: EMAIL_NOTIFICATION_INTEGRATION_ID,
- // },
- // organizationId: '',
- // },
+ {
+ id: EMAIL_NOTIFICATION_INTEGRATION_ID,
+ name: 'Email',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ config: {
+ type: EMAIL_NOTIFICATION_INTEGRATION_ID,
+ },
+ organizationId: '',
+ },
];
export const isBaseIntegration = (id: string) =>
diff --git a/packages/db/src/services/project.service.ts b/packages/db/src/services/project.service.ts
index 1639ba1c4..66b8ad211 100644
--- a/packages/db/src/services/project.service.ts
+++ b/packages/db/src/services/project.service.ts
@@ -1,8 +1,13 @@
import { cacheable } from '@openpanel/redis';
import sqlstring from 'sqlstring';
-import { chQuery, TABLE_NAMES } from '../clickhouse/client';
-import { ClientType, type Prisma, type Project } from '../prisma-client';
-import { db } from '../prisma-client';
+import {
+ ch,
+ chQuery,
+ convertClickhouseDateToJs,
+ TABLE_NAMES,
+} from '../clickhouse/client';
+import { clix } from '../clickhouse/query-builder';
+import { db, type Prisma, type Project } from '../prisma-client';
export type IServiceProject = Project;
export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{
@@ -119,6 +124,33 @@ export const getProjectEventsCount = async (projectId: string) => {
return res[0]?.count;
};
+/**
+ * Newest event timestamp per project, for the whole instance in one query.
+ * Reads the same pre-aggregated MV as getProjectEventsCount (it stores
+ * max(created_at) per (project_id, name) block), so this scans thousands of
+ * rows instead of the raw events table. Projects with no events are absent
+ * from the map.
+ */
+export const getLastEventPerProject = async (): Promise<Map<string, Date>> => {
+ const res = await clix(ch)
+ .select<{ project_id: string; last_event_at: string }>([
+ 'project_id',
+ 'max(created_at) AS last_event_at',
+ ])
+ .from(TABLE_NAMES.event_names_mv)
+ // Session rows are worker-generated (the reaper can emit session_end after
+ // tracking already stopped) — only real tracking activity should count.
+ .where('name', 'NOT IN', ['session_start', 'session_end'])
+ .groupBy(['project_id'])
+ .execute();
+ return new Map(
+ res.map((row) => [
+ row.project_id,
+ convertClickhouseDateToJs(row.last_event_at),
+ ])
+ );
+};
+
/**
* Resolve and validate a projectId for an API client.
*
@@ -147,7 +179,9 @@ export async function resolveClientProjectId({
}
if (!inputProjectId) {
- throw new Error('projectId is required when using a root (organization-level) client');
+ throw new Error(
+ 'projectId is required when using a root (organization-level) client'
+ );
}
const project = await db.project.findFirst({
@@ -156,7 +190,9 @@ export async function resolveClientProjectId({
});
if (!project) {
- throw new Error('Project not found or does not belong to your organization');
+ throw new Error(
+ 'Project not found or does not belong to your organization'
+ );
}
return inputProjectId;
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index 28e5210be..160f3a85b 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -42,6 +42,31 @@ declare global {
| 'active'
| 'past_due'
| 'canceled'
- | 'unpaid';
+ | 'unpaid'
+ | 'paused';
+ // Compact summary of the discount applied to the subscription, synced
+ // from Polar's embedded discount object so the dashboard can show it.
+ type IPrismaSubscriptionDiscount = {
+ id: string;
+ name: string;
+ type: 'percentage' | 'fixed';
+ // Set for percentage discounts (3000 = 30%).
+ basisPoints: number | null;
+ // Set for fixed discounts (minor units + currency).
+ amount: number | null;
+ currency: string | null;
+ duration: 'once' | 'forever' | 'repeating';
+ durationInMonths: number | null;
+ };
+ // Mirrors Polar's CustomerCancellationReason enum.
+ type IPrismaCancellationReason =
+ | 'too_expensive'
+ | 'missing_features'
+ | 'switched_service'
+ | 'unused'
+ | 'customer_service'
+ | 'low_quality'
+ | 'too_complex'
+ | 'other';
}
}
diff --git a/packages/email/src/emails/index.tsx b/packages/email/src/emails/index.tsx
index cba787a80..60a5ea258 100644
--- a/packages/email/src/emails/index.tsx
+++ b/packages/email/src/emails/index.tsx
@@ -15,10 +15,19 @@ import OnboardingTrialEnded, {
import OnboardingTrialEnding, {
zOnboardingTrialEnding,
} from './onboarding-trial-ending';
+import NotificationRule, { zNotificationRule } from './notification-rule';
import OnboardingWelcome, { zOnboardingWelcome } from './onboarding-welcome';
import OnboardingWhatToTrack, {
zOnboardingWhatToTrack,
} from './onboarding-what-to-track';
+import TrackingDataStopped, {
+ zTrackingDataStopped,
+} from './tracking-data-stopped';
+import TrackingNoData, { zTrackingNoData } from './tracking-no-data';
+import UsageLimitExceeded, {
+ zUsageLimitExceeded,
+} from './usage-limit-exceeded';
+import UsageNearLimit, { zUsageNearLimit } from './usage-near-limit';
import WeeklyDigest, { zWeeklyDigest } from './weekly-digest';
export const templates = {
@@ -67,11 +76,15 @@ export const templates = {
: 'Your OpenPanel trial ends soon',
Component: OnboardingTrialEnding,
schema: zOnboardingTrialEnding,
+ // Without a category these bypassed unsubscribe entirely (no suppression
+ // check, no List-Unsubscribe header).
+ category: 'onboarding' as const,
},
'onboarding-trial-ended': {
subject: () => 'Your trial ended, dashboard is locked',
Component: OnboardingTrialEnded,
schema: zOnboardingTrialEnded,
+ category: 'onboarding' as const,
},
'weekly-digest': {
subject: (data: z.infer<typeof zWeeklyDigest>) =>
@@ -80,6 +93,40 @@ export const templates = {
schema: zWeeklyDigest,
category: 'weekly_digest' as const,
},
+ 'usage-near-limit': {
+ subject: (data: z.infer<typeof zUsageNearLimit>) =>
+ `You've used ${Math.round((data.eventsCount / data.eventsLimit) * 100)}% of your monthly events`,
+ Component: UsageNearLimit,
+ schema: zUsageNearLimit,
+ category: 'product_alerts' as const,
+ },
+ 'usage-limit-exceeded': {
+ subject: () => 'Event limit reached — charts paused, data still collected',
+ Component: UsageLimitExceeded,
+ schema: zUsageLimitExceeded,
+ category: 'product_alerts' as const,
+ },
+ 'tracking-no-data': {
+ subject: () => "Your tracking isn't sending data yet",
+ Component: TrackingNoData,
+ schema: zTrackingNoData,
+ category: 'product_alerts' as const,
+ },
+ 'tracking-data-stopped': {
+ subject: (data: z.infer<typeof zTrackingDataStopped>) =>
+ data.projectNames.length === 1
+ ? `${data.projectNames[0]} stopped sending events`
+ : 'Some of your projects stopped sending events',
+ Component: TrackingDataStopped,
+ schema: zTrackingDataStopped,
+ category: 'product_alerts' as const,
+ },
+ 'notification-rule': {
+ subject: (data: z.infer<typeof zNotificationRule>) => data.title,
+ Component: NotificationRule,
+ schema: zNotificationRule,
+ category: 'product_alerts' as const,
+ },
} as const;
export type Templates = typeof templates;
diff --git a/packages/email/src/emails/notification-rule.tsx b/packages/email/src/emails/notification-rule.tsx
new file mode 100644
index 000000000..d45de0eff
--- /dev/null
+++ b/packages/email/src/emails/notification-rule.tsx
@@ -0,0 +1,51 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zNotificationRule = z.object({
+ title: z.string(),
+ message: z.string(),
+ projectName: z.string().optional(),
+ dashboardUrl: z.string().optional(),
+});
+
+export type Props = z.infer<typeof zNotificationRule>;
+export default NotificationRule;
+export function NotificationRule({
+ title,
+ message,
+ projectName,
+ dashboardUrl,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>
+ 🔔 <strong>{title}</strong>
+ {projectName ? ` — ${projectName}` : ''}
+ </Text>
+ <Text>{message}</Text>
+ {dashboardUrl && (
+ <Text>
+ <Button href={withUtm(dashboardUrl, 'notification-rule')}>
+ Open dashboard
+ </Button>
+ </Text>
+ )}
+ <Text>
+ You're receiving this because a notification rule you set up matched.
+ Manage rules under Notifications in your project.
+ </Text>
+ </Layout>
+ );
+}
+
+NotificationRule.PreviewProps = {
+ title: 'Conversion: Sign up completed',
+ message: 'A user completed the sign-up funnel.',
+ projectName: 'My website',
+ dashboardUrl: 'https://dashboard.openpanel.dev/org-id/project-id',
+};
diff --git a/packages/email/src/emails/tracking-data-stopped.tsx b/packages/email/src/emails/tracking-data-stopped.tsx
new file mode 100644
index 000000000..6b8398b28
--- /dev/null
+++ b/packages/email/src/emails/tracking-data-stopped.tsx
@@ -0,0 +1,74 @@
+import { Link, Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zTrackingDataStopped = z.object({
+ firstName: z.string().optional(),
+ projectNames: z.array(z.string()).min(1),
+ lastEventDate: z.string().optional(),
+ dashboardUrl: z.string(),
+});
+
+export type Props = z.infer<typeof zTrackingDataStopped>;
+export default TrackingDataStopped;
+export function TrackingDataStopped({
+ firstName,
+ projectNames,
+ lastEventDate,
+ dashboardUrl = 'https://dashboard.openpanel.dev',
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const single = projectNames.length === 1;
+ const names = projectNames.join(', ');
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ {single
+ ? `Your project ${names} stopped`
+ : `Your projects (${names}) stopped`}{' '}
+ sending events
+ {lastEventDate
+ ? ` — the last one arrived on ${lastEventDate}`
+ : ' about a week ago'}
+ .
+ </Text>
+ <Text>
+ This usually isn't intentional: a deploy that dropped the tracking
+ snippet, a changed client ID, or a new domain that isn't in your allowed
+ origins. Worth a quick check so you don't end up with a gap in your
+ data.
+ </Text>
+ <Text>
+ <Button href={withUtm(dashboardUrl, 'tracking-data-stopped')}>
+ Check your project
+ </Button>
+ </Text>
+ <Text>
+ The{' '}
+ <Link
+ href={withUtm(
+ 'https://openpanel.dev/docs/get-started/install-openpanel',
+ 'tracking-data-stopped'
+ )}
+ >
+ install guide
+ </Link>{' '}
+ covers a re-install for every framework. If it stopped on purpose — no
+ action needed, and sorry for the noise. Otherwise, reply and I'll help
+ you debug it.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+TrackingDataStopped.PreviewProps = {
+ firstName: 'Alex',
+ projectNames: ['My website'],
+ lastEventDate: 'August 14',
+ dashboardUrl: 'https://dashboard.openpanel.dev/org-id',
+};
diff --git a/packages/email/src/emails/tracking-no-data.tsx b/packages/email/src/emails/tracking-no-data.tsx
new file mode 100644
index 000000000..a92939317
--- /dev/null
+++ b/packages/email/src/emails/tracking-no-data.tsx
@@ -0,0 +1,66 @@
+import { Link, Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zTrackingNoData = z.object({
+ firstName: z.string().optional(),
+ projectNames: z.array(z.string()).min(1),
+ dashboardUrl: z.string(),
+});
+
+export type Props = z.infer<typeof zTrackingNoData>;
+export default TrackingNoData;
+export function TrackingNoData({
+ firstName,
+ projectNames,
+ dashboardUrl = 'https://dashboard.openpanel.dev',
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const single = projectNames.length === 1;
+ const names = projectNames.join(', ');
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ {single
+ ? `Your project ${names} hasn't`
+ : `Your projects (${names}) haven't`}{' '}
+ received any events yet — which usually means the tracking snippet isn't
+ installed, or something is blocking it.
+ </Text>
+ <Text>
+ The most common fixes: the snippet isn't on the page (or not deployed
+ yet), the client ID doesn't match, or the domain isn't in your allowed
+ origins.
+ </Text>
+ <Text>
+ <Button href={withUtm(dashboardUrl, 'tracking-no-data')}>
+ Verify your install
+ </Button>
+ </Text>
+ <Text>
+ Framework-specific instructions are in the{' '}
+ <Link
+ href={withUtm(
+ 'https://openpanel.dev/docs/get-started/install-openpanel',
+ 'tracking-no-data'
+ )}
+ >
+ install guide
+ </Link>
+ . And if you've tried and it still doesn't work, reply to this email —
+ I'll personally help you get it running.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+TrackingNoData.PreviewProps = {
+ firstName: 'Alex',
+ projectNames: ['My website'],
+ dashboardUrl: 'https://dashboard.openpanel.dev/org-id',
+};
diff --git a/packages/email/src/emails/usage-limit-exceeded.tsx b/packages/email/src/emails/usage-limit-exceeded.tsx
new file mode 100644
index 000000000..596ead383
--- /dev/null
+++ b/packages/email/src/emails/usage-limit-exceeded.tsx
@@ -0,0 +1,62 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zUsageLimitExceeded = z.object({
+ firstName: z.string().optional(),
+ organizationName: z.string(),
+ billingUrl: z.string(),
+ eventsLimit: z.number(),
+});
+
+const formatNumber = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zUsageLimitExceeded>;
+export default UsageLimitExceeded;
+export function UsageLimitExceeded({
+ firstName,
+ organizationName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ eventsLimit,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ {organizationName} has reached its monthly limit of{' '}
+ {formatNumber(eventsLimit)} events.
+ </Text>
+ <Text>
+ Important: we're still collecting every incoming event, so nothing is
+ being lost. But your charts are paused at the moment you hit the limit —
+ new data won't show until you upgrade or your next billing cycle starts.
+ </Text>
+ <Text>
+ Upgrading takes a minute and unlocks everything collected in the
+ meantime.
+ </Text>
+ <Text>
+ <Button href={withUtm(billingUrl, 'usage-limit-exceeded')}>
+ Upgrade your plan
+ </Button>
+ </Text>
+ <Text>
+ If this month was an outlier, you can also just wait for the cycle to
+ reset. And if you're stuck between plans, reply and I'll help.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+UsageLimitExceeded.PreviewProps = {
+ firstName: 'Alex',
+ organizationName: 'Acme',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ eventsLimit: 5000,
+};
diff --git a/packages/email/src/emails/usage-near-limit.tsx b/packages/email/src/emails/usage-near-limit.tsx
new file mode 100644
index 000000000..cff14cad2
--- /dev/null
+++ b/packages/email/src/emails/usage-near-limit.tsx
@@ -0,0 +1,62 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zUsageNearLimit = z.object({
+ firstName: z.string().optional(),
+ organizationName: z.string(),
+ billingUrl: z.string(),
+ eventsCount: z.number(),
+ eventsLimit: z.number(),
+});
+
+const formatNumber = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zUsageNearLimit>;
+export default UsageNearLimit;
+export function UsageNearLimit({
+ firstName,
+ organizationName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ eventsCount,
+ eventsLimit,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const percent = Math.round((eventsCount / eventsLimit) * 100);
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ Heads up: {organizationName} has used {formatNumber(eventsCount)} of its{' '}
+ {formatNumber(eventsLimit)} monthly events ({percent}%).
+ </Text>
+ <Text>
+ If you go over the limit, we keep collecting every event — nothing is
+ lost — but your charts stop showing new data until you upgrade or the
+ next billing cycle starts.
+ </Text>
+ <Text>
+ <Button href={withUtm(billingUrl, 'usage-near-limit')}>
+ See usage &amp; plans
+ </Button>
+ </Text>
+ <Text>
+ Questions about which plan fits? Reply to this email and I'll help you
+ pick.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+UsageNearLimit.PreviewProps = {
+ firstName: 'Alex',
+ organizationName: 'Acme',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ eventsCount: 4200,
+ eventsLimit: 5000,
+};
diff --git a/packages/payments/package.json b/packages/payments/package.json
index 21da6b5c9..1d6dd0655 100644
--- a/packages/payments/package.json
+++ b/packages/payments/package.json
@@ -13,7 +13,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "@polar-sh/sdk": "^0.48.1",
+ "@polar-sh/sdk": "^0.49.0",
"date-fns": "^3.3.1"
},
"devDependencies": {
diff --git a/packages/payments/scripts/create-save-discount.ts b/packages/payments/scripts/create-save-discount.ts
new file mode 100644
index 000000000..63da46089
--- /dev/null
+++ b/packages/payments/scripts/create-save-discount.ts
@@ -0,0 +1,104 @@
+import { Polar } from '@polar-sh/sdk';
+import inquirer from 'inquirer';
+
+// Creates the reusable save-offer discount used by the cancel flow: 30% off,
+// repeating for the next 12 billing cycles. Run once per environment (sandbox +
+// production) and put the printed ID in POLAR_SAVE_DISCOUNT_ID.
+const DISCOUNT_NAME = 'Save offer — 30% off for 12 months';
+const BASIS_POINTS = 3000;
+const DURATION_IN_MONTHS = 12;
+
+interface Answers {
+ isProduction: boolean;
+ polarOrganizationId: string;
+ polarApiKey: string;
+}
+
+async function promptForInput() {
+ const answers = await inquirer.prompt<Answers>([
+ {
+ type: 'list',
+ name: 'isProduction',
+ message: 'Is this for production?',
+ choices: [
+ { name: 'Yes', value: true },
+ { name: 'No', value: false },
+ ],
+ default: true,
+ },
+ {
+ type: 'string',
+ name: 'polarOrganizationId',
+ message: 'Enter your Polar organization ID:',
+ },
+ {
+ type: 'password',
+ mask: '*',
+ name: 'polarApiKey',
+ message: 'Enter your Polar API key:',
+ validate: (input: string) => {
+ if (!input) {
+ return 'API key is required';
+ }
+ return true;
+ },
+ },
+ ]);
+
+ return answers;
+}
+
+async function main() {
+ const input = await promptForInput();
+
+ const polar = new Polar({
+ accessToken: input.polarApiKey!,
+ server: input.isProduction ? 'production' : 'sandbox',
+ });
+
+ // The list response is a page iterator — walk every page so an existing
+ // discount beyond the first page doesn't get duplicated. Scoped to the same
+ // organization we'd create in, so a same-named discount from another org
+ // can't be picked up.
+ let match: { id: string; name: string } | undefined;
+ const pages = await polar.discounts.list({
+ limit: 100,
+ organizationId: input.polarApiKey.includes('_oat_')
+ ? undefined
+ : input.polarOrganizationId,
+ });
+ for await (const page of pages) {
+ match = page.result.items.find(
+ (discount) => discount.name === DISCOUNT_NAME
+ );
+ if (match) {
+ break;
+ }
+ }
+
+ if (match) {
+ console.log('Save discount already exists:');
+ console.log(' - ID:', match.id);
+ console.log(' - Name:', match.name);
+ console.log(`\nSet POLAR_SAVE_DISCOUNT_ID=${match.id}`);
+ return;
+ }
+
+ const discount = await polar.discounts.create({
+ organizationId: input.polarApiKey.includes('_oat_')
+ ? undefined
+ : input.polarOrganizationId,
+ name: DISCOUNT_NAME,
+ type: 'percentage',
+ basisPoints: BASIS_POINTS,
+ duration: 'repeating',
+ durationInMonths: DURATION_IN_MONTHS,
+ });
+
+ console.log('Save discount created:');
+ console.log(' - ID:', discount.id);
+ console.log(' - Name:', discount.name);
+ console.log(`\nSet POLAR_SAVE_DISCOUNT_ID=${discount.id}`);
+}
+
+main();
diff --git a/packages/payments/scripts/sync-subscriptions.ts b/packages/payments/scripts/sync-subscriptions.ts
index 28231a19d..8053a5f8d 100644
--- a/packages/payments/scripts/sync-subscriptions.ts
+++ b/packages/payments/scripts/sync-subscriptions.ts
@@ -1,5 +1,29 @@
-import { db } from '@openpanel/db';
+import { db, Prisma } from '@openpanel/db';
import { Polar } from '@polar-sh/sdk';
+import type { Subscription } from '@polar-sh/sdk/dist/esm/models/components/subscription';
+
+// Mirrors toSubscriptionDiscount in apps/api webhook.controller.ts — a compact
+// summary of Polar's embedded discount so the dashboard can show it.
+function toSubscriptionDiscount(discount: Subscription['discount']) {
+ if (!discount) {
+ return null;
+ }
+ return {
+ id: discount.id,
+ name: discount.name,
+ type:
+ discount.type === 'fixed' ? ('fixed' as const) : ('percentage' as const),
+ basisPoints: 'basisPoints' in discount ? discount.basisPoints : null,
+ amount: 'amount' in discount ? discount.amount : null,
+ currency: 'currency' in discount ? discount.currency : null,
+ duration:
+ discount.duration === 'repeating' || discount.duration === 'forever'
+ ? discount.duration
+ : ('once' as const),
+ durationInMonths:
+ 'durationInMonths' in discount ? discount.durationInMonths : null,
+ };
+}
type PolarSubscriptionStatus =
| 'incomplete'
@@ -8,17 +32,19 @@ type PolarSubscriptionStatus =
| 'active'
| 'past_due'
| 'canceled'
- | 'unpaid';
+ | 'unpaid'
+ | 'paused';
const ACTIVE_LIKE_STATUSES: PolarSubscriptionStatus[] = [
'active',
'trialing',
'past_due',
'unpaid',
+ // Paused subs still exist in Polar and must stay synchronized (pause state,
+ // tenure, discount) so the dashboard can offer resume.
+ 'paused',
];
-const IGNORED_PRODUCT_IDS = new Set([
- 'ac5fe58b-0a89-4851-ae41-67be34ae696f',
-]);
+const IGNORED_PRODUCT_IDS = new Set(['ac5fe58b-0a89-4851-ae41-67be34ae696f']);
const IGNORED_ORGANIZATION_IDS = new Set(['openpanel-dev']);
const isDryRun = process.argv.includes('--dry');
@@ -49,7 +75,7 @@ function getServer() {
}
function resolveStatus(
- status: string | null | undefined,
+ status: string | null | undefined
): PolarSubscriptionStatus | null {
if (!status) {
return null;
@@ -63,6 +89,7 @@ function resolveStatus(
'past_due',
'canceled',
'unpaid',
+ 'paused',
];
return values.includes(status as PolarSubscriptionStatus)
@@ -87,7 +114,9 @@ function calculateSubscriptionEndsAt(subscription: {
return subscription.canceledAt;
}
-function toComparable(value: Date | string | number | null | undefined) {
+function toComparable(
+ value: Date | string | number | boolean | null | undefined
+) {
if (value instanceof Date) {
return value.toISOString();
}
@@ -95,8 +124,11 @@ function toComparable(value: Date | string | number | null | undefined) {
}
async function getAllSubscriptions(polar: Polar) {
- const all: Array<Awaited<ReturnType<typeof polar.subscriptions.list>>['result']['items'][number]> =
- [];
+ const all: Array<
+ Awaited<
+ ReturnType<typeof polar.subscriptions.list>
+ >['result']['items'][number]
+ > = [];
const limit = 100;
let page = 1;
@@ -122,7 +154,7 @@ async function getAllSubscriptions(polar: Polar) {
async function main() {
if (!process.env.POLAR_ACCESS_TOKEN) {
throw new Error(
- 'POLAR_ACCESS_TOKEN is missing. Add it to your env before running this script.',
+ 'POLAR_ACCESS_TOKEN is missing. Add it to your env before running this script.'
);
}
@@ -137,7 +169,10 @@ async function main() {
: await getAllSubscriptions(polar);
const scopedSubscriptions = subscriptions.filter((subscription) => {
- if (subscription.productId && IGNORED_PRODUCT_IDS.has(subscription.productId)) {
+ if (
+ subscription.productId &&
+ IGNORED_PRODUCT_IDS.has(subscription.productId)
+ ) {
return false;
}
@@ -154,7 +189,7 @@ async function main() {
});
console.log(
- `Found ${subscriptions.length} total subscriptions (${scopedSubscriptions.length} in scope).`,
+ `Found ${subscriptions.length} total subscriptions (${scopedSubscriptions.length} in scope).`
);
if (targetSubscriptionId) {
console.log(`Filtering by subscription ID: ${targetSubscriptionId}`);
@@ -175,7 +210,10 @@ async function main() {
};
for (const subscription of subscriptions) {
- if (subscription.productId && IGNORED_PRODUCT_IDS.has(subscription.productId)) {
+ if (
+ subscription.productId &&
+ IGNORED_PRODUCT_IDS.has(subscription.productId)
+ ) {
stats.skippedIgnoredProduct += 1;
continue;
}
@@ -186,7 +224,7 @@ async function main() {
continue;
}
- if (!includeCanceled && !ACTIVE_LIKE_STATUSES.includes(status)) {
+ if (!(includeCanceled || ACTIVE_LIKE_STATUSES.includes(status))) {
continue;
}
@@ -226,7 +264,7 @@ async function main() {
if (!organization) {
stats.skippedNoOrg += 1;
console.warn(
- `Skipping ${subscription.id} (${status}) - no organization match found.`,
+ `Skipping ${subscription.id} (${status}) - no organization match found.`
);
continue;
}
@@ -239,11 +277,13 @@ async function main() {
let subscriptionPeriodEventsLimit: number | undefined;
if (subscription.productId) {
if (!productEventsLimit.has(subscription.productId)) {
- const product = await polar.products.get({ id: subscription.productId });
+ const product = await polar.products.get({
+ id: subscription.productId,
+ });
const eventsLimit = product.metadata?.eventsLimit;
productEventsLimit.set(
subscription.productId,
- typeof eventsLimit === 'number' ? eventsLimit : null,
+ typeof eventsLimit === 'number' ? eventsLimit : null
);
}
@@ -277,12 +317,22 @@ async function main() {
subscriptionCreatedByUserId:
metadataUserId ?? organization.subscriptionCreatedByUserId,
subscriptionInterval: subscription.recurringInterval,
+ subscriptionFirstStartedAt:
+ organization.subscriptionId === subscription.id
+ ? (organization.subscriptionFirstStartedAt ?? subscription.createdAt)
+ : subscription.createdAt,
+ subscriptionPauseAtPeriodEnd: subscription.pauseAtPeriodEnd,
+ subscriptionResumesAt: subscription.resumesAt,
+ subscriptionDiscount:
+ toSubscriptionDiscount(subscription.discount) ?? Prisma.DbNull,
subscriptionPeriodEventsLimit:
- subscriptionPeriodEventsLimit ?? organization.subscriptionPeriodEventsLimit,
+ subscriptionPeriodEventsLimit ??
+ organization.subscriptionPeriodEventsLimit,
subscriptionPeriodEventsCountExceededAt:
typeof subscriptionPeriodEventsLimit === 'number' &&
organization.subscriptionPeriodEventsCountExceededAt &&
- organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit
+ organization.subscriptionPeriodEventsLimit <
+ subscriptionPeriodEventsLimit
? null
: undefined,
};
@@ -299,6 +349,9 @@ async function main() {
'subscriptionEndsAt',
'subscriptionCreatedByUserId',
'subscriptionInterval',
+ 'subscriptionFirstStartedAt',
+ 'subscriptionPauseAtPeriodEnd',
+ 'subscriptionResumesAt',
'subscriptionPeriodEventsLimit',
] as const;
@@ -316,7 +369,7 @@ async function main() {
stats.unchanged += 1;
if (isDryRun) {
console.log(
- `[dry] No changes for organization ${organization.id} from subscription ${subscription.id}.`,
+ `[dry] No changes for organization ${organization.id} from subscription ${subscription.id}.`
);
}
continue;
@@ -325,7 +378,7 @@ async function main() {
try {
if (isDryRun) {
console.log(
- `[dry] Changes for organization ${organization.id} from subscription ${subscription.id}:`,
+ `[dry] Changes for organization ${organization.id} from subscription ${subscription.id}:`
);
for (const change of changes) {
console.log(` - ${change.field}:`, change.from, '=>', change.to);
@@ -342,13 +395,13 @@ async function main() {
}
stats.updated += 1;
console.log(
- `${isDryRun ? '[dry] ' : ''}Synced organization ${organization.id} from subscription ${subscription.id} (${status}).`,
+ `${isDryRun ? '[dry] ' : ''}Synced organization ${organization.id} from subscription ${subscription.id} (${status}).`
);
} catch (error) {
stats.failed += 1;
console.error(
`Failed syncing organization ${organization.id} from subscription ${subscription.id}:`,
- error,
+ error
);
}
}
diff --git a/packages/payments/src/polar.ts b/packages/payments/src/polar.ts
index da77ecc5d..89da90b87 100644
--- a/packages/payments/src/polar.ts
+++ b/packages/payments/src/polar.ts
@@ -76,12 +76,30 @@ export async function createCheckout({
});
}
-export async function cancelSubscription(subscriptionId: string) {
+export type ICancellationReason =
+ | 'too_expensive'
+ | 'missing_features'
+ | 'switched_service'
+ | 'unused'
+ | 'customer_service'
+ | 'low_quality'
+ | 'too_complex'
+ | 'other';
+
+export async function cancelSubscription(
+ subscriptionId: string,
+ cancellation?: {
+ reason?: ICancellationReason;
+ comment?: string;
+ }
+) {
try {
return await polar.subscriptions.update({
id: subscriptionId,
subscriptionUpdate: {
cancelAtPeriodEnd: true,
+ customerCancellationReason: cancellation?.reason ?? null,
+ customerCancellationComment: cancellation?.comment ?? null,
},
});
} catch (error) {
@@ -96,6 +114,61 @@ export async function cancelSubscription(subscriptionId: string) {
}
}
+/**
+ * Pause an active subscription at the end of the current period. Billing stops
+ * but the subscription (and its payment method) is kept, so the customer can
+ * come back without a new checkout. `resumesAt` must be after the current
+ * period end; omitted means paused until manually resumed.
+ */
+export function pauseSubscription(subscriptionId: string, resumesAt?: Date) {
+ return polar.subscriptions.update({
+ id: subscriptionId,
+ subscriptionUpdate: {
+ pauseAtPeriodEnd: true,
+ resumesAt: resumesAt ?? null,
+ },
+ });
+}
+
+/** Cancel a scheduled pause while the subscription is still active. */
+export function unpauseSubscription(subscriptionId: string) {
+ return polar.subscriptions.update({
+ id: subscriptionId,
+ subscriptionUpdate: {
+ pauseAtPeriodEnd: false,
+ },
+ });
+}
+
+/**
+ * Resume an already-paused subscription immediately — starts a new billing
+ * period and charges the customer.
+ */
+export function resumeSubscription(subscriptionId: string) {
+ return polar.subscriptions.update({
+ id: subscriptionId,
+ subscriptionUpdate: {
+ resume: true,
+ },
+ });
+}
+
+/**
+ * Attach a discount to an active subscription. Polar applies it starting with
+ * the next billing cycle.
+ */
+export function applySubscriptionDiscount(
+ subscriptionId: string,
+ discountId: string
+) {
+ return polar.subscriptions.update({
+ id: subscriptionId,
+ subscriptionUpdate: {
+ discountId,
+ },
+ });
+}
+
export function reactivateSubscription(subscriptionId: string) {
return polar.subscriptions.update({
id: subscriptionId,
diff --git a/packages/payments/src/subscription-state-meta.ts b/packages/payments/src/subscription-state-meta.ts
index 632715ada..ff6dd5def 100644
--- a/packages/payments/src/subscription-state-meta.ts
+++ b/packages/payments/src/subscription-state-meta.ts
@@ -22,7 +22,7 @@ export type SubscriptionStateMeta = {
/** Inline status line on the billing page, or null. */
statusLine: { text: string; tone: Tone } | null;
/** BillingPrompt copy key when this state blocks the dashboard. */
- blockType: 'expired' | 'trialEnded' | 'unpaid' | null;
+ blockType: 'expired' | 'trialEnded' | 'unpaid' | 'paused' | null;
};
const fmt = (date: Date | null | undefined) =>
@@ -35,10 +35,15 @@ const fmt = (date: Date | null | undefined) =>
*/
export function getSubscriptionStateMeta(
state: SubscriptionState,
- opts: { endsAt?: Date | null; canceledAt?: Date | null }
+ opts: {
+ endsAt?: Date | null;
+ canceledAt?: Date | null;
+ resumesAt?: Date | null;
+ }
): SubscriptionStateMeta {
const endsAt = fmt(opts.endsAt);
const canceledAt = fmt(opts.canceledAt);
+ const resumesAt = fmt(opts.resumesAt);
switch (state) {
case 'self_hosted':
@@ -123,6 +128,49 @@ export function getSubscriptionStateMeta(
blockType: 'expired',
};
+ case 'pausing':
+ return {
+ badge: { label: 'Pausing', variant: 'warning' },
+ banner: {
+ title: 'Subscription will be paused',
+ description: endsAt
+ ? `Your subscription pauses on ${endsAt}. We keep collecting your events while it's paused${resumesAt ? `, and billing resumes on ${resumesAt}` : ''}.`
+ : `Your subscription is scheduled to pause at the end of the current period. We keep collecting your events while it's paused.`,
+ cta: 'Keep subscription',
+ tone: 'warning',
+ },
+ statusLine: endsAt
+ ? {
+ text: `Your subscription will be paused on ${endsAt}`,
+ tone: 'warning',
+ }
+ : {
+ text: 'Your subscription will be paused at the end of the current period',
+ tone: 'warning',
+ },
+ blockType: null,
+ };
+
+ case 'paused':
+ return {
+ badge: { label: 'Paused', variant: 'warning' },
+ banner: {
+ title: 'Subscription paused',
+ description: resumesAt
+ ? `Your subscription is paused and resumes on ${resumesAt}. Your events are still being collected.`
+ : 'Your subscription is paused. Your events are still being collected — resume any time to pick up where you left off.',
+ cta: 'Resume subscription',
+ tone: 'warning',
+ },
+ statusLine: {
+ text: resumesAt
+ ? `Your subscription is paused until ${resumesAt}`
+ : 'Your subscription is paused',
+ tone: 'warning',
+ },
+ blockType: 'paused',
+ };
+
case 'past_due':
return {
badge: { label: 'Past due', variant: 'warning' },
diff --git a/packages/payments/src/subscription-state.test.ts b/packages/payments/src/subscription-state.test.ts
index 0c0e4d10d..1a9a4a38c 100644
--- a/packages/payments/src/subscription-state.test.ts
+++ b/packages/payments/src/subscription-state.test.ts
@@ -14,6 +14,7 @@ type Case = {
status: string | null;
canceledAt: Date | null;
endsAt: Date | null;
+ pauseAtPeriodEnd?: boolean;
expected: SubscriptionState;
};
@@ -55,6 +56,16 @@ describe('getSubscriptionState', () => {
{ name: 'incomplete', status: 'incomplete', canceledAt: null, endsAt: future, expected: 'incomplete' },
{ name: 'incomplete_expired', status: 'incomplete_expired', canceledAt: null, endsAt: past, expected: 'expired' },
+ // Pause-at-period-end keeps status active while the flag is set
+ { name: 'active + pause scheduled (pausing)', status: 'active', canceledAt: null, endsAt: future, pauseAtPeriodEnd: true, expected: 'pausing' },
+ { name: 'cancel wins over scheduled pause', status: 'active', canceledAt: past, endsAt: future, pauseAtPeriodEnd: true, expected: 'canceling' },
+ // Stale data: period ended but status wasn't flipped (missed webhook).
+ // Must resolve to paused (blocks dashboard), never a lingering pausing.
+ { name: 'pause scheduled, period already ended', status: 'active', canceledAt: null, endsAt: past, pauseAtPeriodEnd: true, expected: 'paused' },
+ { name: 'pause scheduled, no end date', status: 'active', canceledAt: null, endsAt: null, pauseAtPeriodEnd: true, expected: 'paused' },
+ { name: 'paused', status: 'paused', canceledAt: null, endsAt: past, expected: 'paused' },
+ { name: 'paused ignores stale pause flag', status: 'paused', canceledAt: null, endsAt: past, pauseAtPeriodEnd: true, expected: 'paused' },
+
// Fully canceled / revoked
{ name: 'canceled', status: 'canceled', canceledAt: past, endsAt: past, expected: 'canceled' },
@@ -69,6 +80,7 @@ describe('getSubscriptionState', () => {
subscriptionStatus: c.status,
subscriptionCanceledAt: c.canceledAt,
subscriptionEndsAt: c.endsAt,
+ subscriptionPauseAtPeriodEnd: c.pauseAtPeriodEnd ?? false,
})
).toBe(c.expected);
});
@@ -81,6 +93,7 @@ describe('getSubscriptionState', () => {
subscriptionStatus: 'canceled',
subscriptionCanceledAt: past,
subscriptionEndsAt: past,
+ subscriptionPauseAtPeriodEnd: false,
})
).toBe('self_hosted');
});
@@ -92,12 +105,14 @@ describe('subscriptionBlocksDashboard', () => {
'expired',
'unpaid',
'canceled',
+ 'paused',
];
const allowed: SubscriptionState[] = [
'self_hosted',
'trialing',
'active',
'canceling',
+ 'pausing',
'past_due',
'incomplete',
];
diff --git a/packages/payments/src/subscription-state.ts b/packages/payments/src/subscription-state.ts
index f95943318..a40d99c2e 100644
--- a/packages/payments/src/subscription-state.ts
+++ b/packages/payments/src/subscription-state.ts
@@ -14,6 +14,8 @@ export type SubscriptionState =
| 'active' // paid, renewing
| 'canceling' // active but scheduled to cancel at period end
| 'canceled' // fully canceled / revoked (access ended)
+ | 'pausing' // active but scheduled to pause at period end
+ | 'paused' // paused — billing stopped, data still collected
| 'past_due' // payment failed, in dunning (still has access)
| 'unpaid' // payment failed terminally
| 'incomplete' // initial checkout not completed
@@ -23,6 +25,7 @@ export interface SubscriptionStateInput {
subscriptionStatus: string | null;
subscriptionCanceledAt: Date | null;
subscriptionEndsAt: Date | null;
+ subscriptionPauseAtPeriodEnd: boolean;
}
export function getSubscriptionState(
@@ -33,7 +36,12 @@ export function getSubscriptionState(
}
const now = new Date();
- const { subscriptionStatus, subscriptionCanceledAt, subscriptionEndsAt } = org;
+ const {
+ subscriptionStatus,
+ subscriptionCanceledAt,
+ subscriptionEndsAt,
+ subscriptionPauseAtPeriodEnd,
+ } = org;
const endsInFuture = Boolean(subscriptionEndsAt && subscriptionEndsAt > now);
switch (subscriptionStatus) {
@@ -43,12 +51,24 @@ export function getSubscriptionState(
case 'active':
// Cancel-at-period-end keeps the Polar status as `active` while
// `canceledAt` is set; the subscription stays usable until it expires.
+ // Cancellation wins over a scheduled pause — Polar clears the pause flag
+ // on cancel, but a stale combination must not hide that it's ending.
if (subscriptionCanceledAt) {
return 'canceling';
}
+ // Pause-at-period-end works the same way: status stays `active` with the
+ // flag set until the period ends, then Polar flips it to `paused`. If the
+ // period already ended and our status is stale (missed webhook), fail
+ // safe to `paused` — `pausing` would keep dashboard access open past the
+ // paid period.
+ if (subscriptionPauseAtPeriodEnd) {
+ return endsInFuture ? 'pausing' : 'paused';
+ }
return subscriptionEndsAt && subscriptionEndsAt <= now
? 'expired'
: 'active';
+ case 'paused':
+ return 'paused';
case 'past_due':
return 'past_due';
case 'unpaid':
@@ -75,6 +95,9 @@ export function subscriptionBlocksDashboard(state: SubscriptionState): boolean {
case 'expired':
case 'unpaid':
case 'canceled':
+ // Paused blocks the dashboard too (billing has stopped), but with its own
+ // prompt: data is still collected and one click resumes the subscription.
+ case 'paused':
return true;
default:
return false;
diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.ts
index 14fe72d26..6e22782cb 100644
--- a/packages/queue/src/queues.ts
+++ b/packages/queue/src/queues.ts
@@ -177,6 +177,10 @@ export type CronQueuePayloadWeeklyDigest = {
type: 'weeklyDigest';
payload: undefined;
};
+export type CronQueuePayloadDataHealth = {
+ type: 'dataHealth';
+ payload: undefined;
+};
export type CronQueuePayload =
| CronQueuePayloadSalt
| CronQueuePayloadFlushEvents
@@ -194,7 +198,8 @@ export type CronQueuePayload =
| CronQueuePayloadSessionReaper
| CronQueuePayloadSessionVacuum
| CronQueuePayloadInsightCleanup
- | CronQueuePayloadWeeklyDigest;
+ | CronQueuePayloadWeeklyDigest
+ | CronQueuePayloadDataHealth;
export type CronQueueType = CronQueuePayload['type'];
diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.ts
index e1b6f9e3b..448a3c01e 100644
--- a/packages/trpc/src/routers/project.ts
+++ b/packages/trpc/src/routers/project.ts
@@ -42,6 +42,52 @@ export const projectRouter = createTRPCRouter({
return getProjectWithClients(projectId);
}),
+ // Powers the activation checklist on the project overview: has the project
+ // received data, built a report, and invited a teammate yet?
+ activationStatus: protectedProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input: { projectId }, ctx }) => {
+ const access = await getProjectAccess({
+ userId: ctx.session.userId,
+ projectId,
+ });
+
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ const project = await db.project.findUniqueOrThrow({
+ where: { id: projectId },
+ select: {
+ firstEventAt: true,
+ eventsCount: true,
+ organizationId: true,
+ createdAt: true,
+ },
+ });
+
+ const [reportCount, memberCount] = await Promise.all([
+ db.report.count({ where: { projectId } }),
+ db.member.count({
+ where: { organizationId: project.organizationId },
+ }),
+ ]);
+
+ return {
+ // firstEventAt only exists for projects created after the column was
+ // added; the lifetime counter covers everything older.
+ hasFirstEvent: !!project.firstEventAt || project.eventsCount > 0,
+ firstEventAt: project.firstEventAt,
+ projectCreatedAt: project.createdAt,
+ hasReport: reportCount > 0,
+ hasTeammate: memberCount > 1,
+ };
+ }),
+
list: protectedProcedure
.input(
z.object({
diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.ts
index 893551ed9..7dad05686 100644
--- a/packages/trpc/src/routers/subscription.ts
+++ b/packages/trpc/src/routers/subscription.ts
@@ -5,20 +5,27 @@ import {
getOrganizationById,
} from '@openpanel/db';
import {
+ applySubscriptionDiscount,
cancelSubscription,
changeSubscription,
createCheckout,
createPortal,
getProduct,
getProducts,
+ pauseSubscription,
reactivateSubscription,
+ resumeSubscription,
+ unpauseSubscription,
} from '@openpanel/payments';
-import { zCheckout } from '@openpanel/validation';
-
import { getCache } from '@openpanel/redis';
-import { subDays } from 'date-fns';
+import {
+ zCancelSubscription,
+ zCheckout,
+ zPauseSubscription,
+} from '@openpanel/validation';
+import { addMonths, subDays } from 'date-fns';
import { z } from 'zod';
-import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
+import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
async function requireAdmin(userId: string, organizationId: string) {
@@ -58,6 +65,19 @@ export const subscriptionRouter = createTRPCRouter({
}),
]);
+ // A paused (or pause-scheduled) subscription still exists in Polar — a
+ // checkout here would create a second one, and a plan change would race
+ // the pending pause. Resume first, then change plans.
+ if (
+ organization.subscriptionId &&
+ (organization.subscriptionStatus === 'paused' ||
+ organization.subscriptionPauseAtPeriodEnd)
+ ) {
+ throw new TRPCBadRequestError(
+ 'Your subscription is paused or scheduled to pause — resume it before changing plans'
+ );
+ }
+
// An organization has at most one Polar subscription (we have no free
// tier in Polar — the free plan is handled on our side). So an upgrade or
// downgrade is an in-place product change, never a cancel + re-subscribe.
@@ -124,7 +144,7 @@ export const subscriptionRouter = createTRPCRouter({
.input(
z.object({
organizationId: z.string(),
- }),
+ })
)
.query(async ({ input }) => {
const organization = await db.organization.findUniqueOrThrow({
@@ -154,7 +174,7 @@ export const subscriptionRouter = createTRPCRouter({
}),
cancelSubscription: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
+ .input(zCancelSubscription)
.mutation(async ({ input, ctx }) => {
await requireAdmin(ctx.session.userId, input.organizationId);
const organization = await getOrganizationById(input.organizationId);
@@ -162,11 +182,147 @@ export const subscriptionRouter = createTRPCRouter({
throw new TRPCBadRequestError('Organization has no subscription');
}
- const res = await cancelSubscription(organization.subscriptionId);
+ const res = await cancelSubscription(organization.subscriptionId, {
+ reason: input.reason,
+ comment: input.comment,
+ });
+
+ // The webhook echoes these back, but persist immediately so a missed or
+ // delayed delivery can't lose the reason — or leave `canceledAt` unset,
+ // which would make the plan-change path skip reactivation and silently
+ // keep the cancellation scheduled.
+ await db.organization.update({
+ where: { id: input.organizationId },
+ data: {
+ subscriptionCancelReason: input.reason,
+ subscriptionCancelComment: input.comment ?? null,
+ subscriptionCanceledAt: res.canceledAt,
+ subscriptionEndsAt: res.cancelAtPeriodEnd
+ ? res.currentPeriodEnd
+ : (res.canceledAt ?? organization.subscriptionEndsAt),
+ },
+ });
return res;
}),
+ pauseSubscription: protectedProcedure
+ .input(zPauseSubscription)
+ .mutation(async ({ input, ctx }) => {
+ await requireAdmin(ctx.session.userId, input.organizationId);
+ const organization = await getOrganizationById(input.organizationId);
+ if (!organization.subscriptionId) {
+ throw new TRPCBadRequestError('Organization has no subscription');
+ }
+ // Only a plain active subscription can be paused — this rejects paused,
+ // pause-scheduled (pausing), canceling, canceled, unpaid, etc. before we
+ // hit Polar with a nonsensical update.
+ if (organization.subscriptionState !== 'active') {
+ throw new TRPCBadRequestError(
+ 'Only an active subscription can be paused'
+ );
+ }
+ if (!organization.subscriptionEndsAt) {
+ throw new TRPCBadRequestError('Subscription has no current period end');
+ }
+
+ // Polar pauses at period end; the resume date counts from there.
+ const resumesAt = addMonths(
+ organization.subscriptionEndsAt,
+ input.months
+ );
+
+ await pauseSubscription(organization.subscriptionId, resumesAt);
+
+ // Optimistic mirror — the subscription.updated webhook confirms it.
+ await db.organization.update({
+ where: { id: input.organizationId },
+ data: {
+ subscriptionPauseAtPeriodEnd: true,
+ subscriptionResumesAt: resumesAt,
+ },
+ });
+
+ return { resumesAt };
+ }),
+
+ resumeSubscription: protectedProcedure
+ .input(z.object({ organizationId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await requireAdmin(ctx.session.userId, input.organizationId);
+ const organization = await getOrganizationById(input.organizationId);
+ if (!organization.subscriptionId) {
+ throw new TRPCBadRequestError('Organization has no subscription');
+ }
+
+ if (organization.subscriptionStatus === 'paused') {
+ // Already paused — resuming starts a new billing period immediately.
+ await resumeSubscription(organization.subscriptionId);
+ } else if (organization.subscriptionPauseAtPeriodEnd) {
+ // Pause is only scheduled — just clear it.
+ await unpauseSubscription(organization.subscriptionId);
+ } else {
+ throw new TRPCBadRequestError('Subscription is not paused');
+ }
+
+ await db.organization.update({
+ where: { id: input.organizationId },
+ data: {
+ subscriptionPauseAtPeriodEnd: false,
+ subscriptionResumesAt: null,
+ },
+ });
+
+ return { success: true };
+ }),
+
+ applySaveDiscount: protectedProcedure
+ .input(z.object({ organizationId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await requireAdmin(ctx.session.userId, input.organizationId);
+ const discountId = process.env.POLAR_SAVE_DISCOUNT_ID;
+ if (!discountId) {
+ throw new TRPCBadRequestError('Save discount is not configured');
+ }
+
+ const organization = await getOrganizationById(input.organizationId);
+ if (!organization.subscriptionId) {
+ throw new TRPCBadRequestError('Organization has no subscription');
+ }
+
+ // Claim the one-time offer atomically BEFORE calling Polar: a
+ // conditional update lets exactly one concurrent request through. Roll
+ // the claim back if Polar rejects, so a transient failure doesn't burn
+ // the offer.
+ const claimed = await db.organization.updateMany({
+ where: {
+ id: input.organizationId,
+ subscriptionSaveDiscountAppliedAt: null,
+ },
+ data: { subscriptionSaveDiscountAppliedAt: new Date() },
+ });
+ if (claimed.count === 0) {
+ throw new TRPCBadRequestError(
+ 'The save discount has already been used'
+ );
+ }
+
+ try {
+ await applySubscriptionDiscount(
+ organization.subscriptionId,
+ discountId
+ );
+ } catch (error) {
+ await db.organization.updateMany({
+ where: { id: input.organizationId },
+ data: { subscriptionSaveDiscountAppliedAt: null },
+ });
+ throw error;
+ }
+
+ return { success: true };
+ }),
+
portal: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(async ({ input, ctx }) => {
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 4516b4ce9..0044246e5 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -652,6 +652,33 @@ export const zCheckout = z.object({
});
export type ICheckout = z.infer<typeof zCheckout>;
+// Mirrors Polar's CustomerCancellationReason enum.
+export const zCancellationReason = z.enum([
+ 'too_expensive',
+ 'missing_features',
+ 'switched_service',
+ 'unused',
+ 'customer_service',
+ 'low_quality',
+ 'too_complex',
+ 'other',
+]);
+export type ICancellationReason = z.infer<typeof zCancellationReason>;
+
+export const zCancelSubscription = z.object({
+ organizationId: z.string(),
+ reason: zCancellationReason,
+ comment: z.string().trim().max(1000).optional(),
+});
+export type ICancelSubscription = z.infer<typeof zCancelSubscription>;
+
+export const zPauseSubscription = z.object({
+ organizationId: z.string(),
+ // Months after the current period end before billing automatically resumes.
+ months: z.union([z.literal(1), z.literal(2), z.literal(3)]),
+});
+export type IPauseSubscription = z.infer<typeof zPauseSubscription>;
+
export const zGroupId = z
.string()
.min(1)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6a8e14703..6bfe983ec 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1587,8 +1587,8 @@ importers:
packages/payments:
dependencies:
'@polar-sh/sdk':
- specifier: ^0.48.1
- version: 0.48.1
+ specifier: ^0.49.0
+ version: 0.49.0
date-fns:
specifier: ^3.3.1
version: 3.3.1
@@ -6855,8 +6855,8 @@ packages:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
- '@polar-sh/[email protected]':
- resolution: {integrity: sha512-FmU6eLJRXJ6Zau0IkqscfkFta8xxYbFV1VD9zzS2Ki2btCuFmUyPZOkHOXU77R892h2zyBegLnHS7jrOhMN1Sw==}
+ '@polar-sh/[email protected]':
+ resolution: {integrity: sha512-9UYb70iKjJCtWYlu0OF5HLYBLmkxHwqr2RlXwuxXQgRGqq56IQWlVG+NO7e1YJ7I5GW0CBHhGIjRbQ9hYM6ycQ==}
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
@@ -26288,7 +26288,7 @@ snapshots:
optional: true
- '@polar-sh/[email protected]':
+ '@polar-sh/[email protected]':
dependencies:
standardwebhooks: 1.0.0
zod: 4.3.6