Skip to content

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

fix: payments

Carl-Gerhard Lindesvärd241d2597324c
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.ts
index b190482e2..38c30bfa1 100644
--- a/apps/api/src/controllers/webhook.controller.ts
+++ b/apps/api/src/controllers/webhook.controller.ts
@@ -121,6 +121,198 @@ async function clearOrganizationCache(organizationId: string) {
}
}
+type PolarEvent = ReturnType<typeof validatePolarEvent>;
+type PolarSubscriptionData = Extract<
+ PolarEvent,
+ { type: 'subscription.updated' }
+>['data'];
+
+const subscriptionMetadataSchema = z.object({
+ organizationId: z.string(),
+ // `userId` is only used for the `subscriptionCreatedByUserId` audit field, so
+ // it is optional — a missing one must not block syncing the subscription.
+ userId: z.string().optional(),
+});
+
+// Org columns whose before→after transition is logged on every sync.
+const TRACKED_SUBSCRIPTION_FIELDS = [
+ 'subscriptionId',
+ 'subscriptionStatus',
+ 'subscriptionProductId',
+ 'subscriptionPriceId',
+ 'subscriptionStartsAt',
+ 'subscriptionEndsAt',
+ 'subscriptionCanceledAt',
+ 'subscriptionInterval',
+ 'subscriptionPeriodEventsLimit',
+] as const;
+
+const normalizeLogValue = (value: unknown) =>
+ value instanceof Date ? value.toISOString() : (value ?? null);
+
+// Builds a `{ field: { from, to } }` map of changed columns. `undefined`
+// after-values are skipped — Prisma reads them as "leave the column untouched".
+function diffOrganizationFields(
+ before: Record<string, unknown>,
+ after: Record<string, unknown>,
+ fields: readonly string[]
+) {
+ const changes: Record<string, { from: unknown; to: unknown }> = {};
+ for (const field of fields) {
+ if (after[field] === undefined) {
+ continue;
+ }
+ const from = normalizeLogValue(before[field]);
+ const to = normalizeLogValue(after[field]);
+ if (from !== to) {
+ changes[field] = { from, to };
+ }
+ }
+ return changes;
+}
+
+/**
+ * Syncs the full Polar subscription state onto the organization. Used for every
+ * `subscription.*` event (created, active, updated, canceled, revoked,
+ * past_due, uncanceled) since they all carry the same Subscription object and
+ * `status` drives the rest. This covers new subscriptions, cancellations,
+ * reactivations, plan changes and payment-state changes in one place.
+ */
+async function syncSubscriptionToOrg(
+ data: PolarSubscriptionData,
+ eventType: string,
+ log: FastifyRequest['log']
+) {
+ const metadata = subscriptionMetadataSchema.parse(data.metadata);
+ const isCanceled = data.status === 'canceled';
+
+ const organization = await db.organization.findUniqueOrThrow({
+ where: {
+ id: metadata.organizationId,
+ },
+ });
+
+ // An organization maps to a single subscription in our DB, but can have
+ // several in Polar (e.g. after re-subscribing). A canceled/revoked event for
+ // a subscription that is no longer the org's current one must not clobber the
+ // newer active subscription.
+ if (isCanceled && organization.subscriptionId !== data.id) {
+ log.info(
+ {
+ organizationId: metadata.organizationId,
+ eventType,
+ eventSubscriptionId: data.id,
+ orgSubscriptionId: organization.subscriptionId,
+ },
+ 'polar webhook: ignoring canceled event for non-current subscription'
+ );
+ return;
+ }
+
+ // Polar can deliver subscription events out of order: at renewal the new
+ // period can arrive first, then a stale event for the *previous* period lands
+ // a few seconds later. A billing period never moves backwards, so for the
+ // same subscription we ignore any event whose period starts before the one we
+ // already stored — otherwise the stale event resets the org to the expired
+ // period and the usage counter (recomputed over that window) gets stuck.
+ if (
+ organization.subscriptionId === data.id &&
+ organization.subscriptionStartsAt &&
+ data.currentPeriodStart < organization.subscriptionStartsAt
+ ) {
+ log.info(
+ {
+ organizationId: metadata.organizationId,
+ eventType,
+ eventSubscriptionId: data.id,
+ eventPeriodStart: data.currentPeriodStart,
+ storedPeriodStart: organization.subscriptionStartsAt,
+ },
+ 'polar webhook: ignoring stale subscription event (older billing period)'
+ );
+ return;
+ }
+
+ const product = await getProduct(data.productId);
+ const rawEventsLimit = product.metadata?.eventsLimit;
+ const parsedEventsLimit =
+ typeof rawEventsLimit === 'number'
+ ? rawEventsLimit
+ : typeof rawEventsLimit === 'string'
+ ? Number(rawEventsLimit)
+ : Number.NaN;
+ const hasValidEventsLimit = Number.isFinite(parsedEventsLimit);
+ const subscriptionPeriodEventsLimit = hasValidEventsLimit
+ ? parsedEventsLimit
+ : organization.subscriptionPeriodEventsLimit;
+
+ if (!hasValidEventsLimit) {
+ log.warn(
+ { product },
+ 'No valid eventsLimit on product, preserving existing organization limit'
+ );
+ }
+
+ const updateData = {
+ subscriptionId: data.id,
+ subscriptionCustomerId: data.customer.id,
+ subscriptionPriceId: data.prices[0]?.id ?? null,
+ subscriptionProductId: data.productId,
+ subscriptionStatus: data.status,
+ subscriptionStartsAt: data.currentPeriodStart,
+ subscriptionCanceledAt: data.canceledAt,
+ subscriptionEndsAt: isCanceled
+ ? data.cancelAtPeriodEnd
+ ? data.currentPeriodEnd
+ : data.canceledAt
+ : data.currentPeriodEnd,
+ subscriptionCreatedByUserId:
+ metadata.userId ?? organization.subscriptionCreatedByUserId,
+ subscriptionInterval: data.recurringInterval,
+ subscriptionPeriodEventsLimit,
+ subscriptionPeriodEventsCountExceededAt:
+ typeof subscriptionPeriodEventsLimit === 'number' &&
+ organization.subscriptionPeriodEventsCountExceededAt &&
+ typeof organization.subscriptionPeriodEventsLimit === 'number' &&
+ organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit
+ ? null
+ : undefined,
+ };
+
+ const changes = diffOrganizationFields(
+ organization as unknown as Record<string, unknown>,
+ updateData as unknown as Record<string, unknown>,
+ TRACKED_SUBSCRIPTION_FIELDS
+ );
+
+ await db.organization.update({
+ where: {
+ id: metadata.organizationId,
+ },
+ data: updateData,
+ });
+
+ await clearOrganizationCache(metadata.organizationId);
+
+ await publishEvent('organization', 'subscription_updated', {
+ organizationId: metadata.organizationId,
+ });
+
+ log.info(
+ {
+ organizationId: metadata.organizationId,
+ eventType,
+ subscriptionId: data.id,
+ previousStatus: organization.subscriptionStatus,
+ status: data.status,
+ changes,
+ },
+ Object.keys(changes).length > 0
+ ? `polar webhook: synced subscription for ${metadata.organizationId} (${Object.keys(changes).join(', ')} changed)`
+ : `polar webhook: synced subscription for ${metadata.organizationId} (no field changes)`
+ );
+}
+
export async function polarWebhook(
request: FastifyRequest<{
Querystring: unknown;
@@ -147,11 +339,25 @@ export async function polarWebhook(
const event = validation.data;
+ const eventOrganizationId =
+ 'metadata' in event.data &&
+ event.data.metadata &&
+ typeof event.data.metadata === 'object' &&
+ 'organizationId' in event.data.metadata
+ ? String(event.data.metadata.organizationId)
+ : undefined;
+
const eventCtx = {
eventType: event.type,
eventId: 'id' in event.data ? event.data.id : undefined,
+ organizationId: eventOrganizationId,
};
+ request.log.info(
+ eventCtx,
+ `polar webhook: processing ${event.type}${eventOrganizationId ? ` for ${eventOrganizationId}` : ''}`
+ );
+
if (
'data' in event &&
'product' in event.data &&
@@ -163,118 +369,66 @@ export async function polarWebhook(
const handler = await tryCatch(async () => {
switch (event.type) {
- case 'order.created': {
- const metadata = z
- .object({
- organizationId: z.string(),
- })
- .parse(event.data.metadata);
-
- if (event.data.billingReason === 'subscription_cycle') {
- await db.organization.update({
- where: {
- id: metadata.organizationId,
- },
- data: {
- subscriptionPeriodEventsCount: 0,
- subscriptionPeriodEventsCountExceededAt: null,
- },
- });
-
- await clearOrganizationCache(metadata.organizationId);
+ // A new paid billing cycle resets the org's usage counter. Polar sends
+ // `order.updated` (not `order.created`) and the order moves through
+ // pending -> paid, so we only act on the `paid` + `subscription_cycle`
+ // transition. Re-deliveries of the same paid order just reset to 0 again,
+ // which is harmless (and safely under-counts at worst).
+ case 'order.updated': {
+ if (
+ event.data.billingReason !== 'subscription_cycle' ||
+ event.data.status !== 'paid'
+ ) {
+ request.log.info(
+ { ...eventCtx, billingReason: event.data.billingReason },
+ 'polar webhook: order.updated ignored (not a paid billing cycle)'
+ );
+ return;
}
- return;
- }
- case 'subscription.updated': {
+
const metadata = z
.object({
organizationId: z.string(),
- userId: z.string(),
})
.parse(event.data.metadata);
- const product = await getProduct(event.data.productId);
- const organization = await db.organization.findUniqueOrThrow({
- where: {
- id: metadata.organizationId,
- },
+ const previous = await db.organization.findUnique({
+ where: { id: metadata.organizationId },
+ select: { subscriptionPeriodEventsCount: true },
});
- const rawEventsLimit = product.metadata?.eventsLimit;
- const parsedEventsLimit =
- typeof rawEventsLimit === 'number'
- ? rawEventsLimit
- : typeof rawEventsLimit === 'string'
- ? Number(rawEventsLimit)
- : Number.NaN;
- const hasValidEventsLimit = Number.isFinite(parsedEventsLimit);
- const subscriptionPeriodEventsLimit = hasValidEventsLimit
- ? parsedEventsLimit
- : organization.subscriptionPeriodEventsLimit;
-
- if (!hasValidEventsLimit) {
- request.log.warn(
- { product },
- 'No valid eventsLimit on product, preserving existing organization limit'
- );
- }
- // If we get a cancel event and we cant find it we should ignore it
- // Since we only have one subscription per organization but you can have several in polar
- // we dont want to override the existing subscription with a canceled one
- // TODO: might be other events that we should handle like this?!
- if (event.data.status === 'canceled') {
- const orgSubscription = await db.organization.findFirst({
- where: {
- subscriptionCustomerId: event.data.customer.id,
- subscriptionId: event.data.id,
- subscriptionStatus: {
- in: ['active', 'past_due', 'unpaid'],
- },
- },
- });
-
- if (!orgSubscription) {
- return;
- }
- }
await db.organization.update({
where: {
id: metadata.organizationId,
},
data: {
- subscriptionId: event.data.id,
- subscriptionCustomerId: event.data.customer.id,
- subscriptionPriceId: event.data.prices[0]?.id ?? null,
- subscriptionProductId: event.data.productId,
- subscriptionStatus: event.data.status,
- subscriptionStartsAt: event.data.currentPeriodStart,
- subscriptionCanceledAt: event.data.canceledAt,
- subscriptionEndsAt:
- event.data.status === 'canceled'
- ? event.data.cancelAtPeriodEnd
- ? event.data.currentPeriodEnd
- : event.data.canceledAt
- : event.data.currentPeriodEnd,
- subscriptionCreatedByUserId: metadata.userId,
- subscriptionInterval: event.data.recurringInterval,
- subscriptionPeriodEventsLimit,
- subscriptionPeriodEventsCountExceededAt:
- typeof subscriptionPeriodEventsLimit === 'number' &&
- organization.subscriptionPeriodEventsCountExceededAt &&
- typeof organization.subscriptionPeriodEventsLimit === 'number' &&
- organization.subscriptionPeriodEventsLimit <
- subscriptionPeriodEventsLimit
- ? null
- : undefined,
+ subscriptionPeriodEventsCount: 0,
+ subscriptionPeriodEventsCountExceededAt: null,
},
});
await clearOrganizationCache(metadata.organizationId);
- await publishEvent('organization', 'subscription_updated', {
- organizationId: metadata.organizationId,
- });
-
+ request.log.info(
+ {
+ ...eventCtx,
+ previousEventsCount: previous?.subscriptionPeriodEventsCount,
+ },
+ `polar webhook: new billing cycle for ${metadata.organizationId}, reset usage counter ${previous?.subscriptionPeriodEventsCount ?? 0} -> 0`
+ );
+ return;
+ }
+ // 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).
+ case 'subscription.created':
+ case 'subscription.active':
+ case 'subscription.updated':
+ case 'subscription.uncanceled':
+ case 'subscription.canceled':
+ case 'subscription.revoked':
+ case 'subscription.past_due': {
+ await syncSubscriptionToOrg(event.data, event.type, request.log);
return;
}
default: {
diff --git a/apps/api/src/utils/graceful-shutdown.ts b/apps/api/src/utils/graceful-shutdown.ts
index aac69538a..c16626521 100644
--- a/apps/api/src/utils/graceful-shutdown.ts
+++ b/apps/api/src/utils/graceful-shutdown.ts
@@ -3,7 +3,6 @@ import {
cronQueue,
disconnectKafka,
eventsGroupQueues,
- miscQueue,
notificationQueue,
sessionsQueue,
} from '@openpanel/queue';
@@ -98,7 +97,6 @@ export async function shutdown(
...eventsGroupQueues.map((queue) => queue.close()),
sessionsQueue.close(),
cronQueue.close(),
- miscQueue.close(),
notificationQueue.close(),
]);
logger.info('Queue state closed');
diff --git a/apps/start/src/components/organization/billing-plan-picker.tsx b/apps/start/src/components/organization/billing-plan-picker.tsx
new file mode 100644
index 000000000..488119b84
--- /dev/null
+++ b/apps/start/src/components/organization/billing-plan-picker.tsx
@@ -0,0 +1,347 @@
+import type { IServiceOrganization } from '@openpanel/db';
+import type { IPolarProduct } from '@openpanel/payments';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import {
+ CheckIcon,
+ ChevronRightIcon,
+ Loader2Icon,
+ ShuffleIcon,
+} from 'lucide-react';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { useNumber } from '@/hooks/use-numer-formatter';
+import { useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/utils/cn';
+import { op } from '@/utils/op';
+
+interface Props {
+ organization: IServiceOrganization;
+ currentProduct: IPolarProduct | null;
+ onComplete?: () => void;
+}
+
+const getPrice = (product: IPolarProduct) => {
+ return product.prices[0] && 'priceAmount' in product.prices[0]
+ ? product.prices[0].priceAmount / 100
+ : 0;
+};
+
+export default function BillingPlanPicker({
+ organization,
+ currentProduct,
+ onComplete,
+}: Props) {
+ const number = useNumber();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const productsQuery = useQuery(
+ trpc.subscription.products.queryOptions({
+ organizationId: organization.id,
+ }),
+ );
+ const [recurringInterval, setRecurringInterval] = useState<'year' | 'month'>(
+ (organization.subscriptionInterval as 'year' | 'month') || 'month',
+ );
+ const [selectedProductId, setSelectedProductId] = useState<string | null>(
+ organization.subscriptionProductId || null,
+ );
+ const [pendingProductId, setPendingProductId] = useState<string | null>(null);
+ const products = productsQuery.data || [];
+ const selectedProduct = products.find(
+ (product) => product.id === selectedProductId,
+ );
+
+ // No current plan to compare against → a plan row is the buy button (straight
+ // to Polar checkout). When changing an existing plan we keep the select→confirm
+ // step so the user sees the current→new price comparison.
+ const directCheckout = !currentProduct;
+
+ const checkoutMutation = useMutation(
+ trpc.subscription.checkout.mutationOptions({
+ onSuccess(data) {
+ if (data?.url) {
+ window.location.href = data.url;
+ } else {
+ 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',
+ });
+ onComplete?.();
+ }
+ },
+ onError(error) {
+ 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) => {
+ setPendingProductId(product.id);
+ op.track('subscription_checkout_started', {
+ organizationId: organization.id,
+ limit: product.metadata.eventsLimit,
+ price: getPrice(product),
+ });
+ checkoutMutation.mutate({
+ organizationId: organization.id,
+ productPriceId: product.prices[0].id,
+ productId: product.id,
+ });
+ };
+
+ const handleCheckout = () => {
+ if (!selectedProduct) return;
+ startCheckout(selectedProduct);
+ };
+
+ const renderRowIndicator = (product: IPolarProduct) => {
+ if (directCheckout) {
+ if (pendingProductId === product.id) {
+ return (
+ <Loader2Icon className="size-4 animate-spin text-muted-foreground" />
+ );
+ }
+ return (
+ <ChevronRightIcon className="size-4 text-muted-foreground opacity-40 transition-opacity group-hover:opacity-100" />
+ );
+ }
+ if (selectedProductId === product.id) {
+ return (
+ <div className="size-4 center-center rounded-full bg-emerald-600 text-primary-foreground">
+ <CheckIcon className="size-2" />
+ </div>
+ );
+ }
+ return null;
+ };
+
+ const handleCancelSubscription = () => {
+ if (!selectedProduct) return;
+ op.track('subscription_canceled', {
+ organizationId: organization.id,
+ limit: selectedProduct.metadata.eventsLimit,
+ price: getPrice(selectedProduct),
+ });
+ cancelSubscription.mutate({
+ organizationId: organization.id,
+ });
+ };
+
+ const renderAction = () => {
+ if (!selectedProduct) {
+ return null;
+ }
+
+ const isCurrentProduct = selectedProduct.id === currentProduct?.id;
+
+ if (isCurrentProduct && organization.isActive) {
+ return (
+ <Button
+ className="w-full mt-4"
+ variant="destructive"
+ size="lg"
+ onClick={handleCancelSubscription}
+ >
+ Cancel subscription
+ </Button>
+ );
+ }
+
+ const payLabel = (() => {
+ if (
+ organization.isCanceled ||
+ organization.isWillBeCanceled ||
+ organization.isExpired
+ ) {
+ return isCurrentProduct
+ ? 'Reactivate subscription'
+ : 'Change subscription';
+ }
+
+ if (currentProduct) {
+ return 'Change subscription';
+ }
+
+ return 'Pay with Polar';
+ })();
+
+ return (
+ <button
+ type="button"
+ className="w-full mt-4 rounded-lg overflow-hidden hover:translate-y-[-1px] transition-all group"
+ onClick={handleCheckout}
+ >
+ {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">
+ <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',
+ )}
+ >
+ <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">
+ <svg
+ className="size-6"
+ width="300"
+ height="300"
+ viewBox="0 0 300 300"
+ fill="none"
+ 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"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_1_4">
+ <rect width="300" height="300" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+ <span className="font-semibold">{payLabel}</span>
+ </div>
+ </button>
+ );
+ };
+
+ return (
+ <>
+ <div className="col gap-4 shrink-0">
+ {currentProduct && (
+ <div className="font-medium">
+ Your current usage is{' '}
+ {number.format(organization.subscriptionPeriodEventsCount)} out of{' '}
+ {number.format(Number(currentProduct?.metadata.eventsLimit))}{' '}
+ events.{' '}
+ <span className="text-muted-foreground">
+ You cannot downgrade if your usage exceeds the limit of the new
+ plan.
+ </span>
+ </div>
+ )}
+ <div className="row items-center justify-between gap-2 -mb-2">
+ <div className="font-medium">
+ {recurringInterval === 'year' ? (
+ 'Switch to monthly'
+ ) : (
+ <>
+ Switch to yearly and get{' '}
+ <span className="underline text-emerald-500">
+ 2 months for free
+ </span>
+ </>
+ )}
+ </div>
+
+ <Button
+ variant="outline"
+ onClick={() =>
+ setRecurringInterval((p) => (p === 'year' ? 'month' : 'year'))
+ }
+ >
+ {recurringInterval === 'year' ? 'Monthly' : 'Yearly'}
+ <ShuffleIcon className="size-4 ml-2" />
+ </Button>
+ </div>
+ </div>
+ <div className="col divide-y divide-border border rounded-lg overflow-y-auto min-h-0">
+ {products
+ .filter((product) =>
+ product.prices.some((p) => p.amountType !== 'free'),
+ )
+ .filter((product) => product.metadata.eventsLimit)
+ .filter((product) => product.recurringInterval === recurringInterval)
+ .map((product) => {
+ const price = getPrice(product);
+
+ const limit = product.metadata.eventsLimit
+ ? Number(product.metadata.eventsLimit)
+ : 0;
+
+ const isProductDisabled =
+ (limit > 0 &&
+ organization.subscriptionPeriodEventsCount >= limit) ||
+ !!product.disabled;
+
+ 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',
+ !directCheckout &&
+ currentProduct?.id === product.id &&
+ selectedProductId !== product.id &&
+ 'text-muted-foreground line-through',
+ isProductDisabled && 'opacity-50 !cursor-not-allowed',
+ )}
+ onClick={() =>
+ directCheckout
+ ? startCheckout(product)
+ : setSelectedProductId(product.id)
+ }
+ >
+ <span className={'font-medium'}>{product.name}</span>
+ <div className="row items-center gap-2">
+ <span className="font-bold">{number.currency(price)}</span>
+ {renderRowIndicator(product)}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ {!directCheckout && <div className="shrink-0">{renderAction()}</div>}
+ </>
+ );
+}
diff --git a/apps/start/src/components/organization/billing-prompt.tsx b/apps/start/src/components/organization/billing-prompt.tsx
index 3a7283c82..b08387af8 100644
--- a/apps/start/src/components/organization/billing-prompt.tsx
+++ b/apps/start/src/components/organization/billing-prompt.tsx
@@ -1,50 +1,82 @@
import type { IServiceOrganization } from '@openpanel/db';
import { useMutation, useQuery } from '@tanstack/react-query';
-import {
- BarChart3Icon,
- DollarSignIcon,
- InfinityIcon,
- type LucideIcon,
- MapIcon,
- SearchIcon,
- ShieldCheckIcon,
- TrendingUpIcon,
-} from 'lucide-react';
+import { CheckIcon } from 'lucide-react';
import { useEffect } from 'react';
import { toast } from 'sonner';
-import { PageHeader } from '@/components/page-header';
+import { Badge } from '@/components/ui/badge';
import { Button, LinkButton } from '@/components/ui/button';
import { useNumber } from '@/hooks/use-numer-formatter';
import { useTRPC } from '@/integrations/trpc/react';
+import { formatDate } from '@/utils/date';
import { op } from '@/utils/op';
-const COPY = {
+const FEATURES = [
+ 'Plans start at $2.5/month',
+ 'Unlimited reports, members and projects',
+ 'Advanced funnels and conversions',
+ 'Real-time analytics',
+ 'Track KPIs and custom events',
+ 'Privacy-focused and GDPR compliant',
+ 'Revenue tracking',
+ 'Google Search Console integration',
+];
+
+type BadgeVariant = 'secondary' | 'warning' | 'info';
+
+interface CopyVariant {
+ badge: { label: string; variant: BadgeVariant };
+ gradient: string;
+ title: string;
+ lead: string;
+ dateLabel: string;
+ action: 'checkout' | 'portal';
+ cta: (plan: string, price: string) => string;
+ note: string | null;
+}
+
+const COPY: Record<
+ 'expired' | 'trialEnded' | 'unpaid' | 'freePlan',
+ CopyVariant
+> = {
+ trialEnded: {
+ badge: { label: 'Trial ended', variant: 'secondary' },
+ gradient: 'rgb(16 185 129)',
+ title: 'Your 30 days are up',
+ lead: 'Thanks for trying OpenPanel. Everything you set up is still here: your projects, your reports, and every event you tracked. Pick a plan and your dashboards are live again in about a minute.',
+ dateLabel: 'Trial ended',
+ action: 'checkout',
+ cta: (plan, price) => `Continue with ${plan} for ${price}/month`,
+ note: 'We keep collecting your incoming events for now, so nothing is lost while you decide.',
+ },
expired: {
- title: 'Subscription expired',
- description:
- 'Reactivate your subscription to regain access to your analytics data and insights.',
- body: [
- "Your subscription has expired, but your data is safe and waiting for you. Reactivate now to continue tracking your users' behavior and making data-driven decisions.",
- "Don't let gaps in your analytics cost you valuable insights. Every day without data is a day of missed opportunities to understand and grow your audience.",
- ],
+ badge: { label: 'Subscription ended', variant: 'info' },
+ gradient: 'rgb(59 130 246)',
+ title: 'Your data is right where you left it',
+ lead: "Your subscription ended, but we haven't deleted anything. Reactivate and your dashboards, reports, and events are back immediately.",
+ dateLabel: 'Subscription ended',
+ action: 'checkout',
+ cta: (plan, price) => `Reactivate with ${plan} for ${price}/month`,
+ note: null,
},
- trialEnded: {
- title: 'Trial ended',
- description:
- 'Upgrade now to keep the momentum going and continue optimizing your product.',
- body: [
- "You've experienced the power of OpenPanel. Keep the insights flowing and maintain continuity in your analytics data.",
- "We'll still process all your incoming events for the coming 30 days.",
- ],
+ unpaid: {
+ badge: { label: 'Payment issue', variant: 'warning' },
+ gradient: 'rgb(245 158 11)',
+ title: "Your last payment didn't go through",
+ lead: "Usually it's an expired card or a bank block, and it takes a minute to fix. Update your payment method and your dashboards come straight back. Your data hasn't gone anywhere.",
+ dateLabel: 'Paid through',
+ action: 'portal',
+ cta: () => 'Update payment method',
+ note: null,
},
freePlan: {
- title: 'Free plan is removed',
- description:
- "We've removed the free plan to focus on delivering exceptional value to our paid customers.",
- body: [
- "We've evolved our offering to provide better features, faster performance, and dedicated support. Our paid plans ensure we can continue building the analytics platform you deserve.",
- 'Simple, transparent pricing with no hidden fees. Pay for what you use, and scale as you grow. Your investment in analytics pays for itself through better decisions and improved user experiences.',
- ],
+ badge: { label: 'Plan change', variant: 'secondary' },
+ gradient: 'rgb(16 185 129)',
+ title: 'We retired the free plan',
+ lead: "We'd rather run a small, sustainable service than a free one we can't support properly. Paid plans start at $2.5/month and your data carries over as-is.",
+ dateLabel: 'Subscription ended',
+ action: 'checkout',
+ cta: (plan, price) => `Continue with ${plan} for ${price}/month`,
+ note: null,
},
};
@@ -57,6 +89,7 @@ export default function BillingPrompt({
}) {
const number = useNumber();
const trpc = useTRPC();
+ const copy = COPY[type];
const { data: products, isLoading: isLoadingProducts } = useQuery(
trpc.subscription.products.queryOptions({
organizationId: organization.id,
@@ -75,13 +108,40 @@ export default function BillingPrompt({
},
})
);
- const { title, description, body } = COPY[type];
+ const portal = useMutation(
+ trpc.subscription.portal.mutationOptions({
+ onSuccess(data) {
+ if (data?.url) {
+ window.location.href = data.url;
+ }
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ })
+ );
- const bestProductFit = products?.find(
- (product) =>
- typeof product.metadata.eventsLimit === 'number' &&
- product.metadata.eventsLimit >= organization.subscriptionPeriodEventsCount
+ const eventsCount = organization.subscriptionPeriodEventsCount ?? 0;
+ const bestProductFit = products
+ ?.filter(
+ (product) =>
+ product.recurringInterval === 'month' &&
+ !product.disabled &&
+ typeof product.metadata.eventsLimit === 'number' &&
+ product.prices.some((price) => price.amountType === 'fixed')
+ )
+ .find(
+ (product) =>
+ typeof product.metadata.eventsLimit === 'number' &&
+ product.metadata.eventsLimit >= eventsCount
+ );
+ const bestPrice = bestProductFit?.prices.find(
+ (price) => price.amountType === 'fixed'
);
+ const price =
+ bestPrice && 'priceAmount' in bestPrice
+ ? number.currency(bestPrice.priceAmount / 100)
+ : null;
useEffect(() => {
op.track('billing_prompt_viewed', {
@@ -89,114 +149,147 @@ export default function BillingPrompt({
});
}, [type]);
- const price = bestProductFit
- ? new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'usd',
- minimumFractionDigits: 0,
- maximumFractionDigits: 1,
- }).format(
- bestProductFit.prices[0] && 'priceAmount' in bestProductFit.prices[0]
- ? bestProductFit.prices[0].priceAmount / 100
- : 0
- )
- : null;
+ const renderCta = () => {
+ if (copy.action === 'portal') {
+ return (
+ <Button
+ className="w-full"
+ loading={portal.isPending}
+ onClick={() => {
+ op.track('billing_prompt_upgrade_clicked', {
+ type,
+ cta: 'portal',
+ });
+ portal.mutate({ organizationId: organization.id });
+ }}
+ size="lg"
+ >
+ {copy.cta('', '')}
+ </Button>
+ );
+ }
+
+ if (!(bestProductFit && bestPrice && price)) {
+ return (
+ <Button asChild className="w-full" loading={isLoadingProducts} size="lg">
+ <a href="mailto:[email protected]?subject=Custom plan">
+ Get a custom plan
+ </a>
+ </Button>
+ );
+ }
+
+ return (
+ <Button
+ className="w-full"
+ loading={isLoadingProducts || checkout.isPending}
+ onClick={() => {
+ op.track('billing_prompt_upgrade_clicked', {
+ type,
+ cta: 'checkout',
+ price:
+ 'priceAmount' in bestPrice ? bestPrice.priceAmount / 100 : 0,
+ });
+ checkout.mutate({
+ organizationId: organization.id,
+ productPriceId: bestPrice.id,
+ productId: bestProductFit.id,
+ });
+ }}
+ size="lg"
+ >
+ {copy.cta(bestProductFit.name, price)}
+ </Button>
+ );
+ };
return (
- <div className="mx-auto max-w-7xl p-4 md:p-20">
- <div className="items-center overflow-hidden rounded-lg border bg-def-200 p-2">
- <div className="md:row">
- <div className="col flex-1 gap-4 rounded-md border bg-background p-6">
- <PageHeader description={description} title={title} />
- {body.map((paragraph) => (
- <p key={paragraph}>
- {paragraph.replace(
- '{{events}}',
- number.format(organization.subscriptionPeriodEventsCount ?? 0)
- )}
- </p>
- ))}
- <div className="col mt-auto gap-2">
- {bestProductFit && (
- <div className="text-muted-foreground text-sm leading-normal">
- Based on your usage (
- {number.format(
- organization.subscriptionPeriodEventsCount ?? 0
- )}{' '}
- events) we recommend upgrading <br />
- to the <strong>{bestProductFit.name}</strong> plan for{' '}
- <strong>{price}</strong> per month.
- </div>
- )}
- <div className="col md:row gap-2">
- <Button
- disabled={!bestProductFit}
- loading={isLoadingProducts}
- onClick={() => {
- if (bestProductFit) {
- op.track('billing_prompt_upgrade_clicked', {
- type,
- price:
- bestProductFit.prices[0] &&
- 'priceAmount' in bestProductFit.prices[0]
- ? bestProductFit.prices[0].priceAmount / 100
- : 0,
- });
- checkout.mutate({
- organizationId: organization.id,
- productPriceId: bestProductFit.prices[0].id,
- productId: bestProductFit.id,
- });
- }
- }}
- size="lg"
- >
- Upgrade to {price}
- </Button>
- <LinkButton
- params={{ organizationId: organization.id }}
- size="lg"
- to="/$organizationId/billing"
- variant="outline"
- >
- View pricing
- </LinkButton>
- </div>
+ <div className="mx-auto w-full max-w-xl px-4 py-12 md:py-20">
+ <div className="relative overflow-hidden rounded-lg border bg-card">
+ <div
+ className="pointer-events-none absolute -top-16 -right-16 h-64 w-64 rounded-full opacity-20 blur-3xl"
+ style={{
+ background: `radial-gradient(circle, ${copy.gradient} 0%, transparent 70%)`,
+ }}
+ />
+
+ <div className="col gap-3 p-6 md:p-8">
+ <Badge variant={copy.badge.variant}>{copy.badge.label}</Badge>
+ <h1 className="font-semibold text-2xl">{copy.title}</h1>
+ <p className="text-muted-foreground leading-relaxed">{copy.lead}</p>
+ </div>
+
+ <div className="row gap-3 px-6 md:px-8">
+ <div className="col flex-1 gap-1 rounded-md bg-def-200 p-4">
+ <div className="font-bold font-mono text-2xl">
+ {number.short(eventsCount)}
+ </div>
+ <div className="text-muted-foreground text-sm">
+ Events tracked, all safe and stored
</div>
</div>
- <div className="col min-w-[200px] max-w-[300px] flex-1 shrink-0 gap-4 p-6">
- <Point icon={DollarSignIcon}>Plans start at just $2.5/month</Point>
- <Point icon={InfinityIcon}>
- Unlimited reports, members and projects
- </Point>
- <Point icon={BarChart3Icon}>Advanced funnels and conversions</Point>
- <Point icon={MapIcon}>Real-time analytics</Point>
- <Point icon={TrendingUpIcon}>Track KPIs and custom events</Point>
- <Point icon={ShieldCheckIcon}>
- Privacy-focused and GDPR compliant
- </Point>
- <Point icon={DollarSignIcon}>Revenue tracking</Point>
- <Point icon={SearchIcon}>Google Search Console integration</Point>
+ {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)}
+ </div>
+ <div className="text-muted-foreground text-sm">
+ {copy.dateLabel}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="col gap-3 p-6 md:p-8">
+ {copy.action === 'checkout' &&
+ (bestProductFit ? (
+ <p className="text-muted-foreground text-sm">
+ Based on your usage, the{' '}
+ <strong className="text-foreground">
+ {bestProductFit.name}
+ </strong>{' '}
+ plan covers you: up to{' '}
+ {number.short(Number(bestProductFit.metadata.eventsLimit))}{' '}
+ events per month for {price}.
+ </p>
+ ) : (
+ !isLoadingProducts && (
+ <p className="text-muted-foreground text-sm">
+ Your usage is above our standard plans, so let's set you up
+ with a custom one.
+ </p>
+ )
+ ))}
+ {renderCta()}
+ {copy.note && (
+ <p className="text-muted-foreground text-sm">{copy.note}</p>
+ )}
+ <div className="row items-center justify-between gap-2">
+ <LinkButton
+ params={{ organizationId: organization.id }}
+ to="/$organizationId/billing"
+ variant="outline"
+ >
+ See all plans
+ </LinkButton>
+ <a
+ className="text-muted-foreground text-sm hover:underline"
+ href="mailto:[email protected]"
+ >
+ Questions? Email us
+ </a>
</div>
</div>
</div>
- </div>
- );
-}
-function Point({
- icon: Icon,
- children,
-}: {
- icon: LucideIcon;
- children: React.ReactNode;
-}) {
- return (
- <div className="row gap-2">
- <div className="center-center size-6 shrink-0 rounded-full bg-amber-500 text-white">
- <Icon className="size-4" />
+ <div className="mt-8 grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
+ {FEATURES.map((feature) => (
+ <div className="row items-center gap-2" key={feature}>
+ <CheckIcon className="size-4 shrink-0 text-emerald-500" />
+ <span className="text-muted-foreground text-sm">{feature}</span>
+ </div>
+ ))}
</div>
- <h3 className="mt-[1.5px] font-medium">{children}</h3>
</div>
);
}
diff --git a/apps/start/src/components/organization/billing.tsx b/apps/start/src/components/organization/billing.tsx
index 04c5e66a0..47ebf29b5 100644
--- a/apps/start/src/components/organization/billing.tsx
+++ b/apps/start/src/components/organization/billing.tsx
@@ -7,13 +7,16 @@ import { toast } from 'sonner';
import { Progress } from '../ui/progress';
import { Widget, WidgetBody, WidgetHead } from '../widget';
import { BillingFaq } from './billing-faq';
+import BillingPlanPicker from './billing-plan-picker';
import BillingUsage from './billing-usage';
+import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useNumber } from '@/hooks/use-numer-formatter';
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;
@@ -71,58 +74,24 @@ export default function Billing({ organization }: Props) {
)[0];
const renderStatus = () => {
- if (organization.isActive && organization.subscriptionCurrentPeriodEnd) {
- return (
- <p>
- Your subscription will be renewed on{' '}
- {formatDate(organization.subscriptionCurrentPeriodEnd)}
- </p>
- );
- }
-
- if (organization.isCanceled && organization.subscriptionCanceledAt) {
- return (
- <p>
- Your subscription was canceled on{' '}
- {formatDate(organization.subscriptionCanceledAt)}
- </p>
- );
- }
- if (
- organization.isWillBeCanceled &&
- organization.subscriptionCurrentPeriodEnd
- ) {
- return (
- <p className="text-destructive">
- Your subscription will be canceled on{' '}
- {formatDate(organization.subscriptionCurrentPeriodEnd)}
- </p>
- );
- }
+ const meta = getSubscriptionStateMeta(organization.subscriptionState, {
+ endsAt: organization.subscriptionEndsAt,
+ canceledAt: organization.subscriptionCanceledAt,
+ });
- if (
- organization.subscriptionStatus === 'expired' &&
- organization.subscriptionCurrentPeriodEnd
- ) {
- return (
- <p className="text-destructive">
- Your subscription expired on{' '}
- {formatDate(organization.subscriptionCurrentPeriodEnd)}
- </p>
- );
- }
- if (
- organization.subscriptionStatus === 'trialing' &&
- organization.subscriptionEndsAt
- ) {
- return (
- <p>
- Your trial will end on {formatDate(organization.subscriptionEndsAt)}
- </p>
- );
+ if (!meta.statusLine) {
+ return null;
}
- return null;
+ return (
+ <p
+ className={
+ meta.statusLine.tone === 'destructive' ? 'text-destructive' : undefined
+ }
+ >
+ {meta.statusLine.text}
+ </p>
+ );
};
useEffect(() => {
@@ -138,10 +107,12 @@ export default function Billing({ organization }: Props) {
}
});
- return (
- <div className="grid grid-cols-1 gap-8 md:grid-cols-2">
- <div className="col gap-8">
- {currentProduct && currentPrice ? (
+ // Active subscribers manage an existing plan: current-plan card + usage on the
+ // left, FAQ on the right. Plan changes go through the modal.
+ if (currentProduct && currentPrice) {
+ return (
+ <div className="grid grid-cols-1 gap-8 md:grid-cols-2">
+ <div className="col gap-8">
<Widget className="w-full">
<WidgetHead className="flex items-center justify-between gap-4">
<div className="title flex-1 truncate">{currentProduct.name}</div>
@@ -219,72 +190,64 @@ export default function Billing({ organization }: Props) {
</div>
</WidgetBody>
</Widget>
- ) : (
- <Widget className="w-full">
- <WidgetHead className="flex items-center justify-between">
- <div className="flex-1 font-bold text-lg">
- {organization.isTrial
- ? 'Get started'
- : 'No active subscription'}
- </div>
- <div className="text-muted-foreground">
- {organization.isTrial ? '30 days free trial' : ''}
- </div>
- </WidgetHead>
- <WidgetBody>
- {organization.isTrial && organization.subscriptionEndsAt ? (
- <p>
- Your trial will end on{' '}
- {formatDate(organization.subscriptionEndsAt)} (
- {differenceInDays(
- organization.subscriptionEndsAt,
- new Date()
- ) + 1}{' '}
- days left)
- </p>
- ) : (
- <p>
- Your trial has expired. Please upgrade your account to
- continue using Openpanel.
- </p>
- )}
- <div className="col mt-4">
- <div className="mb-2 font-semibold">
- {number.format(organization.subscriptionPeriodEventsCount)} /{' '}
- {number.format(
- Number(organization.subscriptionPeriodEventsLimit)
- )}
- </div>
- <Progress
- size="sm"
- value={
- (organization.subscriptionPeriodEventsCount /
- Number(organization.subscriptionPeriodEventsLimit)) *
- 100
- }
- />
- <div className="row mt-4 justify-end">
- <Button
- onClick={() =>
- pushModal('SelectBillingPlan', {
- organization,
- currentProduct,
- })
- }
- size="sm"
- >
- Upgrade
- </Button>
- </div>
- </div>
- </WidgetBody>
- </Widget>
- )}
- <BillingUsage organization={organization} />
+ <BillingUsage organization={organization} />
+ </div>
+
+ <BillingFaq />
</div>
+ );
+ }
+
+ // Trial / expired / canceled / unpaid: there's no plan to manage yet, so the
+ // plan picker is the focus. A slim status strip replaces the old tall card
+ // (which showed a meaningless "0 / 0" bar during trials).
+ const daysLeft = organization.subscriptionEndsAt
+ ? differenceInDays(organization.subscriptionEndsAt, new Date()) + 1
+ : null;
- <BillingFaq />
+ return (
+ <div className="col gap-8">
+ <Widget className="w-full">
+ <WidgetBody className="col gap-2">
+ <div className="row items-center gap-2">
+ <Badge variant={organization.isTrial ? 'secondary' : 'destructive'}>
+ {organization.isTrial ? 'Free trial' : 'No active plan'}
+ </Badge>
+ {organization.isTrial && daysLeft !== null && (
+ <span className="font-semibold">{daysLeft} days left</span>
+ )}
+ </div>
+ {organization.isTrial && organization.subscriptionEndsAt ? (
+ <p className="text-muted-foreground">
+ Your trial ends on {formatDate(organization.subscriptionEndsAt)}.
+ When it ends, your dashboards pause until you choose a plan — your
+ data keeps flowing in.
+ </p>
+ ) : (
+ renderStatus()
+ )}
+ </WidgetBody>
+ </Widget>
+
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
+ <Widget className="w-full self-start">
+ <WidgetHead>
+ <div className="title">Choose a plan</div>
+ </WidgetHead>
+ <WidgetBody className="col gap-4">
+ <BillingPlanPicker
+ currentProduct={currentProduct}
+ organization={organization}
+ />
+ </WidgetBody>
+ </Widget>
+
+ <div className="col gap-8">
+ <BillingUsage organization={organization} />
+ <BillingFaq />
+ </div>
+ </div>
</div>
);
}
diff --git a/apps/start/src/components/sidebar-organization-menu.tsx b/apps/start/src/components/sidebar-organization-menu.tsx
index d66910b3d..964b5f6ae 100644
--- a/apps/start/src/components/sidebar-organization-menu.tsx
+++ b/apps/start/src/components/sidebar-organization-menu.tsx
@@ -18,6 +18,7 @@ import {
DropdownMenuTrigger,
} from './ui/dropdown-menu';
import { useAppContext } from '@/hooks/use-app-context';
+import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';
import { useOrganizationAccess } from '@/hooks/use-organization-access';
import { pushModal } from '@/modals';
import type { RouterOutputs } from '@/trpc/client';
@@ -68,10 +69,21 @@ export default function SidebarOrganizationMenu({
>
<CreditCardIcon size={20} />
<div className="flex-1">Billing</div>
- {organization?.isTrial && <Badge>Trial</Badge>}
- {organization?.isExpired && <Badge>Expired</Badge>}
- {organization?.isWillBeCanceled && <Badge>Canceled</Badge>}
- {organization?.isCanceled && <Badge>Canceled</Badge>}
+ {(() => {
+ if (!organization) {
+ return null;
+ }
+ const badge = getSubscriptionStateMeta(
+ organization.subscriptionState,
+ {
+ endsAt: organization.subscriptionEndsAt,
+ canceledAt: organization.subscriptionCanceledAt,
+ }
+ ).badge;
+ return badge ? (
+ <Badge variant={badge.variant}>{badge.label}</Badge>
+ ) : null;
+ })()}
</Link>
)}
{isAdmin && (
diff --git a/apps/start/src/modals/select-billing-plan.tsx b/apps/start/src/modals/select-billing-plan.tsx
index 25d2cbe31..7ed8d93cd 100644
--- a/apps/start/src/modals/select-billing-plan.tsx
+++ b/apps/start/src/modals/select-billing-plan.tsx
@@ -1,309 +1,26 @@
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Progress } from '@/components/ui/progress';
-import { useNumber } from '@/hooks/use-numer-formatter';
-import { useTRPC } from '@/integrations/trpc/react';
-import { cn } from '@/utils/cn';
-import { op } from '@/utils/op';
import type { IServiceOrganization } from '@openpanel/db';
import type { IPolarProduct } from '@openpanel/payments';
-import { current } from '@reduxjs/toolkit';
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { CheckIcon, ShuffleIcon } from 'lucide-react';
-import { Fragment, useEffect, useState } from 'react';
-import { toast } from 'sonner';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
+import BillingPlanPicker from '@/components/organization/billing-plan-picker';
interface Props {
organization: IServiceOrganization;
currentProduct: IPolarProduct | null;
}
-const getPrice = (product: IPolarProduct) => {
- return product.prices[0] && 'priceAmount' in product.prices[0]
- ? product.prices[0].priceAmount / 100
- : 0;
-};
-
export default function SelectBillingPlan({
organization,
currentProduct,
}: Props) {
- const number = useNumber();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const productsQuery = useQuery(
- trpc.subscription.products.queryOptions({
- organizationId: organization.id,
- }),
- );
- const [recurringInterval, setRecurringInterval] = useState<'year' | 'month'>(
- (organization.subscriptionInterval as 'year' | 'month') || 'month',
- );
- const [selectedProductId, setSelectedProductId] = useState<string | null>(
- organization.subscriptionProductId || null,
- );
- const products = productsQuery.data || [];
- const selectedProduct = products.find(
- (product) => product.id === selectedProductId,
- );
-
- const checkoutMutation = useMutation(
- trpc.subscription.checkout.mutationOptions({
- onSuccess(data) {
- if (data?.url) {
- window.location.href = data.url;
- } else {
- 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',
- });
- popModal();
- }
- },
- onError(error) {
- 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',
- });
- popModal();
- },
- onError(error) {
- toast.error(error.message);
- },
- }),
- );
-
- const handleCheckout = () => {
- if (!selectedProduct) return;
- op.track('subscription_checkout_started', {
- organizationId: organization.id,
- limit: selectedProduct.metadata.eventsLimit,
- price: getPrice(selectedProduct),
- });
- checkoutMutation.mutate({
- organizationId: organization.id,
- productPriceId: selectedProduct.prices[0].id,
- productId: selectedProduct.id,
- });
- };
-
- const handleCancelSubscription = () => {
- if (!selectedProduct) return;
- op.track('subscription_canceled', {
- organizationId: organization.id,
- limit: selectedProduct.metadata.eventsLimit,
- price: getPrice(selectedProduct),
- });
- cancelSubscription.mutate({
- organizationId: organization.id,
- });
- };
-
- const renderAction = () => {
- if (!selectedProduct) {
- return null;
- }
-
- const isCurrentProduct = selectedProduct.id === currentProduct?.id;
-
- if (isCurrentProduct && organization.isActive) {
- return (
- <Button
- className="w-full mt-4"
- variant="destructive"
- size="lg"
- onClick={handleCancelSubscription}
- >
- Cancel subscription
- </Button>
- );
- }
-
- const payLabel = (() => {
- if (
- organization.isCanceled ||
- organization.isWillBeCanceled ||
- organization.isExpired
- ) {
- return isCurrentProduct
- ? 'Reactivate subscription'
- : 'Change subscription';
- }
-
- if (currentProduct) {
- return 'Change subscription';
- }
-
- return 'Pay with Polar';
- })();
-
- return (
- <button
- type="button"
- className="w-full mt-4 rounded-lg overflow-hidden hover:translate-y-[-1px] transition-all group"
- onClick={handleCheckout}
- >
- {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">
- <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',
- )}
- >
- <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">
- <svg
- className="size-6"
- width="300"
- height="300"
- viewBox="0 0 300 300"
- fill="none"
- 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"
- />
- </g>
- <defs>
- <clipPath id="clip0_1_4">
- <rect width="300" height="300" fill="white" />
- </clipPath>
- </defs>
- </svg>
- <span className="font-semibold">{payLabel}</span>
- </div>
- </button>
- );
- };
-
return (
<ModalContent className="!flex !flex-col !overflow-hidden">
<ModalHeader title="Select a billing plan" />
- <div className="col gap-4 shrink-0">
- {currentProduct && (
- <div className="font-medium">
- Your current usage is{' '}
- {number.format(organization.subscriptionPeriodEventsCount)} out of{' '}
- {number.format(Number(currentProduct?.metadata.eventsLimit))}{' '}
- events.{' '}
- <span className="text-muted-foreground">
- You cannot downgrade if your usage exceeds the limit of the new
- plan.
- </span>
- </div>
- )}
- <div className="row items-center justify-between gap-2 -mb-2">
- <div className="font-medium">
- {recurringInterval === 'year' ? (
- 'Switch to monthly'
- ) : (
- <>
- Switch to yearly and get{' '}
- <span className="underline text-emerald-500">
- 2 months for free
- </span>
- </>
- )}
- </div>
-
- <Button
- variant="outline"
- onClick={() =>
- setRecurringInterval((p) => (p === 'year' ? 'month' : 'year'))
- }
- >
- {recurringInterval === 'year' ? 'Monthly' : 'Yearly'}
- <ShuffleIcon className="size-4 ml-2" />
- </Button>
- </div>
- </div>
- <div className="col divide-y divide-border border rounded-lg overflow-y-auto min-h-0">
- {products
- .filter((product) =>
- product.prices.some((p) => p.amountType !== 'free'),
- )
- .filter((product) => product.metadata.eventsLimit)
- .filter((product) => product.recurringInterval === recurringInterval)
- .map((product) => {
- const price = getPrice(product);
-
- const limit = product.metadata.eventsLimit
- ? Number(product.metadata.eventsLimit)
- : 0;
-
- const isProductDisabled =
- (limit > 0 &&
- organization.subscriptionPeriodEventsCount >= limit) ||
- !!product.disabled;
-
- return (
- <button
- key={product.id}
- type="button"
- disabled={isProductDisabled}
- className={cn(
- 'row justify-between p-4 py-3 hover:bg-def-100 shrink-0',
- currentProduct?.id === product.id &&
- selectedProductId !== product.id &&
- 'text-muted-foreground line-through',
- isProductDisabled && 'opacity-50 !cursor-not-allowed',
- )}
- onClick={() => setSelectedProductId(product.id)}
- >
- <span className={'font-medium'}>{product.name}</span>
- <div className="row items-center gap-2">
- <span className="font-bold">{number.currency(price)}</span>
- {selectedProductId === product.id && (
- <div className="size-4 center-center rounded-full bg-emerald-600 text-primary-foreground">
- <CheckIcon className="size-2" />
- </div>
- )}
- </div>
- </button>
- );
- })}
- </div>
- <div className="shrink-0">{renderAction()}</div>
+ <BillingPlanPicker
+ currentProduct={currentProduct}
+ onComplete={popModal}
+ organization={organization}
+ />
</ModalContent>
);
}
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.tsx
index 8e28d7bb9..252fbfca1 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.tsx
@@ -1,8 +1,10 @@
import BillingPrompt from '@/components/organization/billing-prompt';
import { useProjectDocumentTitle } from '@/hooks/use-project-document-title';
import { useTRPC } from '@/integrations/trpc/react';
+import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';
import { PAGE_TITLES, createProjectTitle } from '@/utils/title';
import { FREE_PRODUCT_IDS } from '@openpanel/payments';
+import { subscriptionBlocksDashboard } from '@openpanel/payments/subscription-state';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Outlet, createFileRoute } from '@tanstack/react-router';
@@ -53,16 +55,16 @@ function ProjectDashboard() {
return <BillingPrompt organization={organization} type={'freePlan'} />;
}
- if (organization.isExpired) {
+ if (subscriptionBlocksDashboard(organization.subscriptionState)) {
+ const { blockType } = getSubscriptionStateMeta(
+ organization.subscriptionState,
+ {
+ endsAt: organization.subscriptionEndsAt,
+ canceledAt: organization.subscriptionCanceledAt,
+ }
+ );
return (
- <BillingPrompt
- organization={organization}
- type={
- organization.subscriptionStatus === 'trialing'
- ? 'trialEnded'
- : 'expired'
- }
- />
+ <BillingPrompt organization={organization} type={blockType ?? 'expired'} />
);
}
diff --git a/apps/start/src/routes/_app.$organizationId.tsx b/apps/start/src/routes/_app.$organizationId.tsx
index 4afd1c77c..b5b57ce61 100644
--- a/apps/start/src/routes/_app.$organizationId.tsx
+++ b/apps/start/src/routes/_app.$organizationId.tsx
@@ -5,12 +5,15 @@ import SupporterPrompt from '@/components/organization/supporter-prompt';
import { LinkButton } from '@/components/ui/button';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
+import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';
+import { subscriptionBlocksDashboard } from '@openpanel/payments/subscription-state';
import { useSuspenseQuery } from '@tanstack/react-query';
import {
Outlet,
createFileRoute,
notFound,
useLocation,
+ useMatches,
} from '@tanstack/react-router';
import { format } from 'date-fns';
import { Building2Icon } from 'lucide-react';
@@ -116,42 +119,30 @@ function Component() {
}),
);
+ const stateMeta = getSubscriptionStateMeta(organization.subscriptionState, {
+ endsAt: organization.subscriptionEndsAt,
+ canceledAt: organization.subscriptionCanceledAt,
+ });
+
+ // Project routes show the full-screen BillingPrompt for blocking states;
+ // don't stack the (sometimes contradicting) banner on top. Org-level pages
+ // have no prompt, so the banner still shows there.
+ const isProjectRoute = useMatches({
+ select: (matches) =>
+ matches.some(
+ (match) => match.routeId === '/_app/$organizationId/$projectId',
+ ),
+ });
+ const hideBannerForPrompt =
+ isProjectRoute &&
+ subscriptionBlocksDashboard(organization.subscriptionState);
+
return (
<>
- {organization.subscriptionEndsAt && organization.isTrial && (
- <Alert
- title="Free trial"
- description={`Your organization is on a free trial. It ends on ${format(organization.subscriptionEndsAt, 'PPP')}`}
- >
- <LinkButton
- to="/$organizationId/billing"
- params={{
- organizationId: organizationId,
- }}
- >
- Upgrade from $2.5/month
- </LinkButton>
- </Alert>
- )}
- {organization.subscriptionEndsAt && organization.isWillBeCanceled && (
- <Alert
- title="Subscription will be canceled"
- description={`You have canceled your subscription. You can reactivate it by choosing a new plan below. It'll expire on ${format(organization.subscriptionEndsAt, 'PPP')}`}
- >
- <LinkButton
- to="/$organizationId/billing"
- params={{
- organizationId: organizationId,
- }}
- >
- Reactivate
- </LinkButton>
- </Alert>
- )}
- {organization.subscriptionCanceledAt && organization.isCanceled && (
+ {stateMeta.banner && !hideBannerForPrompt && (
<Alert
- title="Subscription canceled"
- description={`Your subscription was canceled on ${format(organization.subscriptionCanceledAt, 'PPP')}`}
+ title={stateMeta.banner.title}
+ description={stateMeta.banner.description}
>
<LinkButton
to="/$organizationId/billing"
@@ -159,7 +150,7 @@ function Component() {
organizationId: organizationId,
}}
>
- Reactivate
+ {stateMeta.banner.cta}
</LinkButton>
</Alert>
)}
diff --git a/apps/worker/src/boot-workers.ts b/apps/worker/src/boot-workers.ts
index ec1631ac4..3ca6b7ef3 100644
--- a/apps/worker/src/boot-workers.ts
+++ b/apps/worker/src/boot-workers.ts
@@ -10,7 +10,6 @@ import {
importQueue,
insightsQueue,
isKafkaConfigured,
- miscQueue,
notificationQueue,
queueLogger,
sessionsQueue,
@@ -29,7 +28,6 @@ import {
import { gscJob } from './jobs/gsc';
import { importJob } from './jobs/import';
import { insightsProjectJob } from './jobs/insights';
-import { miscJob } from './jobs/misc';
import { notificationJob } from './jobs/notification';
import { sessionsJob } from './jobs/sessions';
import { eventsGroupJobDuration } from './metrics';
@@ -44,7 +42,7 @@ const workerOptions: WorkerOptions = {
connection: getRedisQueue(),
};
-type QueueName = string; // Can be: events, events_N (where N is 0 to shards-1), sessions, cron, notification, misc
+type QueueName = string; // Can be: events, events_N (where N is 0 to shards-1), sessions, cron, notification
/**
* Parses the ENABLED_QUEUES environment variable and returns an array of queue names to start.
@@ -53,7 +51,7 @@ type QueueName = string; // Can be: events, events_N (where N is 0 to shards-1),
* Supported queue names:
* - events - All event shards (events_0, events_1, ..., events_N)
* - events_N - Individual event shard (where N is 0 to EVENTS_GROUP_QUEUES_SHARDS-1)
- * - sessions, cron, notification, misc
+ * - sessions, cron, notification
*/
function getEnabledQueues(): QueueName[] {
const enabledQueuesEnv = process.env.ENABLED_QUEUES?.trim();
@@ -69,7 +67,6 @@ function getEnabledQueues(): QueueName[] {
'sessions',
'cron',
'notification',
- 'misc',
'import',
'insights',
'gsc',
@@ -230,17 +227,6 @@ export function bootWorkers() {
logger.info({ concurrency }, 'Started worker for notification');
}
- // Start misc worker
- if (enabledQueues.includes('misc')) {
- const concurrency = getConcurrencyFor('misc');
- const miscWorker = new Worker(miscQueue.name, miscJob, {
- ...workerOptions,
- concurrency,
- });
- workers.push(miscWorker);
- logger.info({ concurrency }, 'Started worker for misc');
- }
-
// Start import worker
if (enabledQueues.includes('import')) {
const concurrency = getConcurrencyFor('import');
diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts
index 622434d44..0bfbc4856 100644
--- a/apps/worker/src/index.ts
+++ b/apps/worker/src/index.ts
@@ -10,7 +10,6 @@ import {
gscQueue,
importQueue,
insightsQueue,
- miscQueue,
notificationQueue,
sessionsQueue,
} from '@openpanel/queue';
@@ -58,7 +57,6 @@ async function start() {
new BullMQAdapter(sessionsQueue),
new BullMQAdapter(cronQueue),
new BullMQAdapter(notificationQueue),
- new BullMQAdapter(miscQueue),
new BullMQAdapter(importQueue),
new BullMQAdapter(insightsQueue),
new BullMQAdapter(gscQueue),
diff --git a/apps/worker/src/jobs/cron.onboarding.test.ts b/apps/worker/src/jobs/cron.onboarding.test.ts
new file mode 100644
index 000000000..dc12c3e54
--- /dev/null
+++ b/apps/worker/src/jobs/cron.onboarding.test.ts
@@ -0,0 +1,177 @@
+// Onboarding email cron: the sequential drip driven by the `org.onboarding`
+// pointer. db and email are mocked; we assert template selection, day gating,
+// early completion on active subs, and usage personalization.
+
+import { subDays } from 'date-fns';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { onboardingJob } from './cron.onboarding';
+
+const { dbMock, getOrganizationEventsCountMock, sendEmailMock } = vi.hoisted(
+ () => ({
+ dbMock: {
+ organization: {
+ findMany: vi.fn(),
+ update: vi.fn().mockResolvedValue({}),
+ },
+ },
+ getOrganizationEventsCountMock: vi.fn(),
+ sendEmailMock: vi.fn().mockResolvedValue({}),
+ }),
+);
+
+vi.mock('@openpanel/db', () => ({
+ db: dbMock,
+ getOrganizationEventsCount: getOrganizationEventsCountMock,
+}));
+
+vi.mock('@openpanel/email', () => ({
+ sendEmail: sendEmailMock,
+}));
+
+const org = (overrides: Record<string, unknown> = {}) => ({
+ id: 'org-1',
+ name: 'Acme',
+ createdAt: new Date(),
+ onboarding: null,
+ subscriptionStatus: 'trialing',
+ subscriptionEndsAt: new Date('2026-06-16T12:00:00Z'),
+ createdBy: {
+ id: 'user-1',
+ email: '[email protected]',
+ firstName: 'Alex',
+ deletedAt: null,
+ },
+ projects: [{ id: 'proj-1' }],
+ ...overrides,
+});
+
+const job = {} as Parameters<typeof onboardingJob>[0];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv('SELF_HOSTED', 'false');
+ dbMock.organization.update.mockResolvedValue({});
+ sendEmailMock.mockResolvedValue({});
+ getOrganizationEventsCountMock.mockResolvedValue(0);
+});
+
+describe('onboardingJob', () => {
+ it('sends the welcome email on day 0 with hasData from clickhouse', async () => {
+ getOrganizationEventsCountMock.mockResolvedValue(123);
+ dbMock.organization.findMany.mockResolvedValue([org()]);
+
+ const result = await onboardingJob(job);
+
+ expect(result).toMatchObject({ emailsSent: 1 });
+ expect(sendEmailMock).toHaveBeenCalledWith('onboarding-welcome', {
+ data: expect.objectContaining({
+ firstName: 'Alex',
+ hasData: true,
+ }),
+ });
+ expect(getOrganizationEventsCountMock).toHaveBeenCalledWith(['proj-1']);
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { onboarding: 'onboarding-welcome' },
+ });
+ });
+
+ it('does not fetch usage for orgs that are gated on days', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-welcome',
+ createdAt: subDays(new Date(), 1), // next email is day 2
+ }),
+ ]);
+
+ const result = await onboardingJob(job);
+
+ expect(result).toMatchObject({ emailsSent: 0, orgsSkipped: 1 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ expect(getOrganizationEventsCountMock).not.toHaveBeenCalled();
+ });
+
+ it('sends the no-data branch of what-to-track on day 2', async () => {
+ getOrganizationEventsCountMock.mockResolvedValue(0);
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-welcome',
+ createdAt: subDays(new Date(), 2),
+ }),
+ ]);
+
+ await onboardingJob(job);
+
+ expect(sendEmailMock).toHaveBeenCalledWith('onboarding-what-to-track', {
+ data: expect.objectContaining({ hasData: false, eventsCount: 0 }),
+ });
+ });
+
+ it('completes onboarding when the org subscribed before the trial emails', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-feature-request',
+ createdAt: subDays(new Date(), 27),
+ subscriptionStatus: 'active',
+ }),
+ ]);
+
+ const result = await onboardingJob(job);
+
+ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { onboarding: 'completed' },
+ });
+ });
+
+ it('populates recommendedPlan and trial stats in the trial-ending email', async () => {
+ // Regression: recommendedPlan used to read subscriptionPeriodEventsCount,
+ // which is always 0 for trial orgs (no Polar billing period).
+ getOrganizationEventsCountMock.mockResolvedValue(84_211);
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-feature-request',
+ createdAt: subDays(new Date(), 27),
+ }),
+ ]);
+
+ await onboardingJob(job);
+
+ expect(sendEmailMock).toHaveBeenCalledWith('onboarding-trial-ending', {
+ data: expect.objectContaining({
+ hasData: true,
+ eventsCount: 84_211,
+ trialEndDate: 'June 16',
+ // Compact-number casing (100K vs 100k) is ICU-version dependent and
+ // differs between macOS and Linux/CI, so match case-insensitively.
+ recommendedPlan: expect.stringMatching(
+ /100k events per month for \$20\.00/i
+ ),
+ }),
+ });
+ // Memoized — one query even though both data and recommendedPlan use it.
+ expect(getOrganizationEventsCountMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks onboarding completed once every email has been sent', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-trial-ended',
+ createdAt: subDays(new Date(), 31),
+ }),
+ ]);
+
+ const result = await onboardingJob(job);
+
+ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { onboarding: 'completed' },
+ });
+ });
+});
diff --git a/apps/worker/src/jobs/cron.onboarding.ts b/apps/worker/src/jobs/cron.onboarding.ts
index 9afac69d3..13678a92a 100644
--- a/apps/worker/src/jobs/cron.onboarding.ts
+++ b/apps/worker/src/jobs/cron.onboarding.ts
@@ -1,7 +1,7 @@
import type { Job } from 'bullmq';
-import { differenceInDays } from 'date-fns';
+import { differenceInDays, format } from 'date-fns';
-import { db } from '@openpanel/db';
+import { db, getOrganizationEventsCount } from '@openpanel/db';
import {
type EmailData,
type EmailTemplate,
@@ -23,6 +23,11 @@ const orgQuery = {
deletedAt: true,
},
},
+ projects: {
+ select: {
+ id: true,
+ },
+ },
},
} as const;
@@ -30,16 +35,23 @@ type OrgWithCreator = Awaited<
ReturnType<typeof db.organization.findMany<typeof orgQuery>>
>[number];
+type OnboardingUsage = {
+ eventsCount: number;
+ hasData: boolean;
+};
+
type OnboardingContext = {
org: OrgWithCreator;
user: NonNullable<OrgWithCreator['createdBy']>;
+ // Lazy + memoized: only emails past the day gate pay for the ClickHouse count.
+ getUsage: () => Promise<OnboardingUsage>;
};
type OnboardingEmail<T extends EmailTemplate = EmailTemplate> = {
day: number;
template: T;
shouldSend?: (ctx: OnboardingContext) => Promise<boolean | 'complete'>;
- data: (ctx: OnboardingContext) => EmailData<T>;
+ data: (ctx: OnboardingContext) => EmailData<T> | Promise<EmailData<T>>;
};
// Helper to create type-safe email entries with correlated template/data types
@@ -47,18 +59,36 @@ function email<T extends EmailTemplate>(config: OnboardingEmail<T>) {
return config;
}
+function createUsageGetter(org: OrgWithCreator) {
+ let promise: Promise<OnboardingUsage> | null = null;
+ return () => {
+ promise ??= getOrganizationEventsCount(
+ org.projects.map((project) => project.id),
+ ).then((eventsCount) => ({
+ eventsCount,
+ hasData: eventsCount > 0,
+ }));
+ return promise;
+ };
+}
+
const getters = {
firstName: (ctx: OnboardingContext) => ctx.user.firstName || undefined,
- organizationName: (ctx: OnboardingContext) => ctx.org.name,
dashboardUrl: (ctx: OnboardingContext) => {
return `${process.env.DASHBOARD_URL}/${ctx.org.id}`;
},
billingUrl: (ctx: OnboardingContext) => {
return `${process.env.DASHBOARD_URL}/${ctx.org.id}/billing`;
},
- recommendedPlan: (ctx: OnboardingContext) => {
+ trialEndDate: (ctx: OnboardingContext) => {
+ return ctx.org.subscriptionEndsAt
+ ? format(ctx.org.subscriptionEndsAt, 'MMMM d')
+ : undefined;
+ },
+ recommendedPlan: async (ctx: OnboardingContext) => {
+ const { eventsCount } = await ctx.getUsage();
return getRecommendedPlan(
- ctx.org.subscriptionPeriodEventsCount,
+ eventsCount,
(plan) =>
`${plan.formattedEvents} events per month for ${plan.formattedPrice}`,
);
@@ -70,31 +100,43 @@ const ONBOARDING_EMAILS = [
email({
day: 0,
template: 'onboarding-welcome',
- data: (ctx) => ({
+ data: async (ctx) => ({
firstName: getters.firstName(ctx),
dashboardUrl: getters.dashboardUrl(ctx),
+ hasData: (await ctx.getUsage()).hasData,
}),
}),
email({
day: 2,
template: 'onboarding-what-to-track',
- data: (ctx) => ({
- firstName: getters.firstName(ctx),
- }),
+ data: async (ctx) => {
+ const usage = await ctx.getUsage();
+ return {
+ firstName: getters.firstName(ctx),
+ hasData: usage.hasData,
+ eventsCount: usage.eventsCount,
+ };
+ },
}),
email({
day: 6,
template: 'onboarding-dashboards',
- data: (ctx) => ({
- firstName: getters.firstName(ctx),
- dashboardUrl: getters.dashboardUrl(ctx),
- }),
+ data: async (ctx) => {
+ const usage = await ctx.getUsage();
+ return {
+ firstName: getters.firstName(ctx),
+ dashboardUrl: getters.dashboardUrl(ctx),
+ hasData: usage.hasData,
+ eventsCount: usage.eventsCount,
+ };
+ },
}),
email({
day: 14,
template: 'onboarding-feature-request',
- data: (ctx) => ({
+ data: async (ctx) => ({
firstName: getters.firstName(ctx),
+ hasData: (await ctx.getUsage()).hasData,
}),
}),
email({
@@ -106,12 +148,15 @@ const ONBOARDING_EMAILS = [
}
return true;
},
- data: (ctx) => {
+ data: async (ctx) => {
+ const usage = await ctx.getUsage();
return {
firstName: getters.firstName(ctx),
- organizationName: getters.organizationName(ctx),
billingUrl: getters.billingUrl(ctx),
- recommendedPlan: getters.recommendedPlan(ctx),
+ recommendedPlan: await getters.recommendedPlan(ctx),
+ trialEndDate: getters.trialEndDate(ctx),
+ hasData: usage.hasData,
+ eventsCount: usage.eventsCount,
};
},
}),
@@ -124,11 +169,14 @@ const ONBOARDING_EMAILS = [
}
return true;
},
- data: (ctx) => {
+ data: async (ctx) => {
+ const usage = await ctx.getUsage();
return {
firstName: getters.firstName(ctx),
billingUrl: getters.billingUrl(ctx),
- recommendedPlan: getters.recommendedPlan(ctx),
+ recommendedPlan: await getters.recommendedPlan(ctx),
+ hasData: usage.hasData,
+ eventsCount: usage.eventsCount,
};
},
}),
@@ -167,6 +215,11 @@ export async function onboardingJob(job: Job<CronQueuePayload>) {
}
const user = org.createdBy;
+ const ctx: OnboardingContext = {
+ org,
+ user,
+ getUsage: createUsageGetter(org),
+ };
const daysSinceOrgCreation = differenceInDays(new Date(), org.createdAt);
// Find the next email to send
@@ -211,7 +264,7 @@ export async function onboardingJob(job: Job<CronQueuePayload>) {
// Check shouldSend callback if defined
if (nextEmail.shouldSend) {
- const result = await nextEmail.shouldSend({ org, user });
+ const result = await nextEmail.shouldSend(ctx);
if (result === 'complete') {
await db.organization.update({
@@ -232,7 +285,7 @@ export async function onboardingJob(job: Job<CronQueuePayload>) {
}
try {
- const emailData = nextEmail.data({ org, user });
+ const emailData = await nextEmail.data(ctx);
await sendEmail(nextEmail.template, {
to: user.email,
diff --git a/apps/worker/src/jobs/misc.trail-ending-soon.ts b/apps/worker/src/jobs/misc.trail-ending-soon.ts
deleted file mode 100644
index db52489ac..000000000
--- a/apps/worker/src/jobs/misc.trail-ending-soon.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { db } from '@openpanel/db';
-import { sendEmail } from '@openpanel/email';
-import type { MiscQueuePayloadTrialEndingSoon } from '@openpanel/queue';
-import type { Job } from 'bullmq';
-
-export async function trialEndingSoonJob(
- job: Job<MiscQueuePayloadTrialEndingSoon>,
-) {
- const { organizationId } = job.data.payload;
-
- const organization = await db.organization.findUnique({
- where: {
- id: organizationId,
- },
- include: {
- createdBy: {
- select: {
- email: true,
- },
- },
- projects: {
- select: {
- id: true,
- },
- },
- },
- });
-
- if (!organization) {
- return;
- }
-
- const project = organization.projects[0];
-
- if (!organization.createdBy?.email) {
- return;
- }
-
- if (!project) {
- return;
- }
-
- return sendEmail('trial-ending-soon', {
- to: organization.createdBy?.email,
- data: {
- organizationName: organization.name,
- url: `https://dashboard.openpanel.dev/${organization.id}/billing`,
- },
- });
-}
diff --git a/apps/worker/src/jobs/misc.ts b/apps/worker/src/jobs/misc.ts
deleted file mode 100644
index 9b143a141..000000000
--- a/apps/worker/src/jobs/misc.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Job } from 'bullmq';
-
-import type { MiscQueuePayloadTrialEndingSoon } from '@openpanel/queue';
-
-import { trialEndingSoonJob } from './misc.trail-ending-soon';
-
-export async function miscJob(job: Job<MiscQueuePayloadTrialEndingSoon>) {
- switch (job.data.type) {
- case 'trialEndingSoon': {
- return await trialEndingSoonJob(job);
- }
- }
-}
diff --git a/packages/db/package.json b/packages/db/package.json
index abce690f7..3ae01edcb 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -19,6 +19,7 @@
"@openpanel/constants": "workspace:*",
"@openpanel/json": "workspace:*",
"@openpanel/logger": "workspace:*",
+ "@openpanel/payments": "workspace:*",
"@openpanel/queue": "workspace:^",
"@openpanel/redis": "workspace:*",
"@openpanel/validation": "workspace:*",
diff --git a/packages/db/scripts/set-subscription-state.ts b/packages/db/scripts/set-subscription-state.ts
new file mode 100644
index 000000000..d7d8e8444
--- /dev/null
+++ b/packages/db/scripts/set-subscription-state.ts
@@ -0,0 +1,126 @@
+/**
+ * Dev helper: force an organization into any subscription state so you can
+ * eyeball every billing scenario in the dashboard.
+ *
+ * pnpm dotenv -e .env -- tsx packages/db/scripts/set-subscription-state.ts <state> [orgId]
+ *
+ * <state> is one of the SubscriptionState values (except self_hosted, which is
+ * env-driven). [orgId] defaults to "openpanel-dev".
+ *
+ * Note: the dashboard must run with SELF_HOSTED=false (or unset) to render
+ * billing — with SELF_HOSTED=true every org resolves to `self_hosted`.
+ */
+import { getSubscriptionState } from '@openpanel/payments/subscription-state';
+import { db } from '../src/prisma-client';
+
+const DAY = 1000 * 60 * 60 * 24;
+const future = () => new Date(Date.now() + 30 * DAY);
+const past = () => new Date(Date.now() - DAY);
+const monthAgo = () => new Date(Date.now() - 30 * DAY);
+
+type Recipe = {
+ subscriptionStatus: string | null;
+ subscriptionCanceledAt: Date | null;
+ subscriptionStartsAt: Date | null;
+ subscriptionEndsAt: Date | null;
+};
+
+const recipes: Record<string, () => Recipe> = {
+ trialing: () => ({
+ subscriptionStatus: null,
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: null,
+ subscriptionEndsAt: future(),
+ }),
+ trial_expired: () => ({
+ subscriptionStatus: null,
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: null,
+ subscriptionEndsAt: past(),
+ }),
+ active: () => ({
+ subscriptionStatus: 'active',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: new Date(),
+ subscriptionEndsAt: future(),
+ }),
+ canceling: () => ({
+ subscriptionStatus: 'active',
+ subscriptionCanceledAt: new Date(),
+ subscriptionStartsAt: new Date(),
+ subscriptionEndsAt: future(),
+ }),
+ canceled: () => ({
+ subscriptionStatus: 'canceled',
+ subscriptionCanceledAt: past(),
+ subscriptionStartsAt: monthAgo(),
+ subscriptionEndsAt: past(),
+ }),
+ past_due: () => ({
+ subscriptionStatus: 'past_due',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: monthAgo(),
+ subscriptionEndsAt: future(),
+ }),
+ unpaid: () => ({
+ subscriptionStatus: 'unpaid',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: monthAgo(),
+ subscriptionEndsAt: future(),
+ }),
+ incomplete: () => ({
+ subscriptionStatus: 'incomplete',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: new Date(),
+ subscriptionEndsAt: future(),
+ }),
+ expired: () => ({
+ subscriptionStatus: 'active',
+ subscriptionCanceledAt: null,
+ subscriptionStartsAt: monthAgo(),
+ subscriptionEndsAt: past(),
+ }),
+};
+
+async function main() {
+ const state = process.argv[2];
+ const orgId = process.argv[3] ?? 'openpanel-dev';
+
+ if (!state || !recipes[state]) {
+ console.error(
+ `Usage: set-subscription-state <state> [orgId]\n\nStates: ${Object.keys(recipes).join(', ')}`
+ );
+ process.exitCode = 1;
+ return;
+ }
+
+ const recipe = recipes[state]();
+ await db.organization.update({ where: { id: orgId }, data: recipe });
+
+ // Compute the resolved state ignoring SELF_HOSTED so the printout reflects
+ // what the dashboard shows when billing is enabled.
+ delete process.env.SELF_HOSTED;
+ const resolved = getSubscriptionState(recipe);
+
+ console.log(`Set ${orgId} -> requested "${state}", resolves to "${resolved}"`);
+ console.table({
+ subscriptionStatus: recipe.subscriptionStatus,
+ subscriptionCanceledAt: recipe.subscriptionCanceledAt?.toISOString() ?? null,
+ subscriptionStartsAt: recipe.subscriptionStartsAt?.toISOString() ?? null,
+ subscriptionEndsAt: recipe.subscriptionEndsAt?.toISOString() ?? null,
+ });
+ if (resolved !== state) {
+ console.warn(
+ `Heads up: resolves to "${resolved}", not "${state}" (status + dates combination).`
+ );
+ }
+}
+
+main()
+ .catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ })
+ .finally(async () => {
+ await db.$disconnect();
+ });
diff --git a/packages/db/src/prisma-client.ts b/packages/db/src/prisma-client.ts
index 2cf1ca567..534b3bb67 100644
--- a/packages/db/src/prisma-client.ts
+++ b/packages/db/src/prisma-client.ts
@@ -1,26 +1,13 @@
-import { type Organization, PrismaClient } from './generated/prisma/client';
+import { getSubscriptionState } from '@openpanel/payments/subscription-state';
+import { PrismaClient } from './generated/prisma/client';
export * from './generated/prisma/client';
-const isWillBeCanceled = (
- organization: Pick<
- Organization,
- 'subscriptionStatus' | 'subscriptionCanceledAt' | 'subscriptionEndsAt'
- >
-) =>
- organization.subscriptionStatus === 'active' &&
- organization.subscriptionCanceledAt &&
- organization.subscriptionEndsAt;
-
-const isCanceled = (
- organization: Pick<
- Organization,
- 'subscriptionStatus' | 'subscriptionCanceledAt'
- >
-) =>
- organization.subscriptionStatus === 'canceled' &&
- organization.subscriptionCanceledAt &&
- organization.subscriptionCanceledAt < new Date();
+const subscriptionStateNeeds = {
+ subscriptionStatus: true,
+ subscriptionCanceledAt: true,
+ subscriptionEndsAt: true,
+} as const;
const getPrismaClient = () => {
const prisma = new PrismaClient({
@@ -28,6 +15,12 @@ const getPrismaClient = () => {
}).$extends({
result: {
organization: {
+ subscriptionState: {
+ needs: subscriptionStateNeeds,
+ compute(org) {
+ return getSubscriptionState(org);
+ },
+ },
subscriptionStatus: {
needs: { subscriptionStatus: true, subscriptionCanceledAt: true },
compute(org) {
@@ -39,19 +32,16 @@ const getPrismaClient = () => {
},
},
hasSubscription: {
- needs: { subscriptionStatus: true, subscriptionEndsAt: true },
+ needs: subscriptionStateNeeds,
compute(org) {
- if (process.env.SELF_HOSTED === 'true') {
- return false;
- }
-
- if (
- [null, 'canceled', 'trialing'].includes(org.subscriptionStatus)
- ) {
- return false;
- }
-
- return true;
+ const state = getSubscriptionState(org);
+ return (
+ state === 'active' ||
+ state === 'canceling' ||
+ state === 'past_due' ||
+ state === 'unpaid' ||
+ state === 'incomplete'
+ );
},
},
slug: {
@@ -89,83 +79,35 @@ const getPrismaClient = () => {
},
},
isActive: {
- needs: {
- subscriptionStatus: true,
- subscriptionEndsAt: true,
- subscriptionCanceledAt: true,
- },
+ needs: subscriptionStateNeeds,
compute(org) {
- if (process.env.SELF_HOSTED === 'true') {
- return true;
- }
-
- return (
- org.subscriptionStatus === 'active' &&
- org.subscriptionEndsAt &&
- org.subscriptionEndsAt > new Date() &&
- !isCanceled(org) &&
- !isWillBeCanceled(org)
- );
+ const state = getSubscriptionState(org);
+ return state === 'active' || state === 'self_hosted';
},
},
isTrial: {
- needs: { subscriptionStatus: true, subscriptionEndsAt: true },
+ needs: subscriptionStateNeeds,
compute(org) {
- const isSubscriptionInFuture =
- org.subscriptionEndsAt && org.subscriptionEndsAt > new Date();
- return (
- (org.subscriptionStatus === 'trialing' ||
- org.subscriptionStatus === null) &&
- isSubscriptionInFuture
- );
+ return getSubscriptionState(org) === 'trialing';
},
},
isCanceled: {
- needs: { subscriptionStatus: true, subscriptionCanceledAt: true },
+ needs: subscriptionStateNeeds,
compute(org) {
- if (process.env.SELF_HOSTED === 'true') {
- return false;
- }
-
- return isCanceled(org);
+ return getSubscriptionState(org) === 'canceled';
},
},
isWillBeCanceled: {
- needs: {
- subscriptionStatus: true,
- subscriptionCanceledAt: true,
- subscriptionEndsAt: true,
- },
+ needs: subscriptionStateNeeds,
compute(org) {
- if (process.env.SELF_HOSTED === 'true') {
- return false;
- }
-
- return isWillBeCanceled(org);
+ return getSubscriptionState(org) === 'canceling';
},
},
isExpired: {
- needs: {
- subscriptionEndsAt: true,
- subscriptionStatus: true,
- subscriptionCanceledAt: true,
- },
+ needs: subscriptionStateNeeds,
compute(org) {
- if (process.env.SELF_HOSTED === 'true') {
- return false;
- }
-
- if (isCanceled(org)) {
- return false;
- }
-
- if (isWillBeCanceled(org)) {
- return false;
- }
-
- return (
- org.subscriptionEndsAt && org.subscriptionEndsAt < new Date()
- );
+ const state = getSubscriptionState(org);
+ return state === 'expired' || state === 'trial_expired';
},
},
isExceeded: {
diff --git a/packages/db/src/services/organization.service.ts b/packages/db/src/services/organization.service.ts
index b0fdef5a3..7c1f4a303 100644
--- a/packages/db/src/services/organization.service.ts
+++ b/packages/db/src/services/organization.service.ts
@@ -218,14 +218,17 @@ export async function connectUserToOrganization({
export async function getOrganizationBillingEventsCount(
organization: IServiceOrganization & { projects: IServiceProject[] }
) {
- // Dont count events if the organization has no subscription
- // Since we only use this for billing purposes
- if (
- !(
- organization.subscriptionCurrentPeriodStart &&
- organization.subscriptionCurrentPeriodEnd
- )
- ) {
+ // Trials have no Polar billing period; fall back to the trial window
+ // (creation → trial end). Status stays 'trialing' even once expired.
+ const isTrialStatus = organization.subscriptionStatus === 'trialing';
+ const periodStart =
+ organization.subscriptionCurrentPeriodStart ??
+ (isTrialStatus ? organization.createdAt : null);
+ const periodEnd =
+ organization.subscriptionCurrentPeriodEnd ??
+ (isTrialStatus ? organization.subscriptionEndsAt : null);
+
+ if (!(periodStart && periodEnd) || organization.projects.length === 0) {
return 0;
}
@@ -233,13 +236,31 @@ export async function getOrganizationBillingEventsCount(
sb.select.count = 'COUNT(*) AS count';
sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;
- sb.where.createdAt = `created_at BETWEEN ${sqlstring.escape(formatClickhouseDate(organization.subscriptionCurrentPeriodStart))} AND ${sqlstring.escape(formatClickhouseDate(organization.subscriptionCurrentPeriodEnd))}`;
+ sb.where.createdAt = `created_at BETWEEN ${sqlstring.escape(formatClickhouseDate(periodStart))} AND ${sqlstring.escape(formatClickhouseDate(periodEnd))}`;
sb.where.names = `name NOT IN ('session_start', 'session_end')`;
const res = await chQuery<{ count: number }>(getSql());
return res[0]?.count;
}
+// Lifetime event count for a set of projects (excluding session bookkeeping
+// events). The onboarding emails use this instead of subscriptionPeriodEventsCount,
+// which only refreshes when sessions end.
+export async function getOrganizationEventsCount(projectIds: string[]) {
+ if (projectIds.length === 0) {
+ return 0;
+ }
+
+ const { sb, getSql } = createSqlBuilder();
+
+ sb.select.count = 'COUNT(*) AS count';
+ sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;
+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;
+
+ const res = await chQuery<{ count: number }>(getSql());
+ return res[0]?.count ?? 0;
+}
+
export async function getOrganizationBillingEventsCountSerie(
organization: IServiceOrganization & { projects: { id: string }[] },
{
diff --git a/packages/email/src/emails/index.tsx b/packages/email/src/emails/index.tsx
index a5d435591..34fec96ff 100644
--- a/packages/email/src/emails/index.tsx
+++ b/packages/email/src/emails/index.tsx
@@ -19,7 +19,6 @@ import OnboardingWelcome, { zOnboardingWelcome } from './onboarding-welcome';
import OnboardingWhatToTrack, {
zOnboardingWhatToTrack,
} from './onboarding-what-to-track';
-import TrailEndingSoon, { zTrailEndingSoon } from './trial-ending-soon';
export const templates = {
invite: {
@@ -34,43 +33,42 @@ export const templates = {
Component: EmailResetPassword,
schema: zEmailResetPassword,
},
- 'trial-ending-soon': {
- subject: (data: z.infer<typeof zTrailEndingSoon>) =>
- 'Your trial is ending soon',
- Component: TrailEndingSoon,
- schema: zTrailEndingSoon,
- },
'onboarding-welcome': {
- subject: () => "You're in",
+ subject: () => 'Welcome to OpenPanel',
Component: OnboardingWelcome,
schema: zOnboardingWelcome,
category: 'onboarding' as const,
},
'onboarding-what-to-track': {
- subject: () => "What's actually worth tracking",
+ subject: (data: z.infer<typeof zOnboardingWhatToTrack>) =>
+ data.hasData ? 'What to track first' : 'Stuck on the install?',
Component: OnboardingWhatToTrack,
schema: zOnboardingWhatToTrack,
category: 'onboarding' as const,
},
'onboarding-dashboards': {
- subject: () => 'The part most people skip',
+ subject: (data: z.infer<typeof zOnboardingDashboards>) =>
+ data.hasData ? 'Your first dashboard' : 'A week in, no data yet',
Component: OnboardingDashboards,
schema: zOnboardingDashboards,
category: 'onboarding' as const,
},
'onboarding-feature-request': {
- subject: () => 'One provider to rule them all',
+ subject: () => 'Anything missing?',
Component: OnboardingFeatureRequest,
schema: zOnboardingFeatureRequest,
category: 'onboarding' as const,
},
'onboarding-trial-ending': {
- subject: () => 'Your trial ends in a few days',
+ subject: (data: z.infer<typeof zOnboardingTrialEnding>) =>
+ data.trialEndDate
+ ? `Your OpenPanel trial ends ${data.trialEndDate}`
+ : 'Your OpenPanel trial ends soon',
Component: OnboardingTrialEnding,
schema: zOnboardingTrialEnding,
},
'onboarding-trial-ended': {
- subject: () => 'Your trial has ended',
+ subject: () => 'Your trial ended, dashboard is locked',
Component: OnboardingTrialEnded,
schema: zOnboardingTrialEnded,
},
diff --git a/packages/email/src/emails/onboarding-dashboards.tsx b/packages/email/src/emails/onboarding-dashboards.tsx
index 02ae98a48..c4d0bf539 100644
--- a/packages/email/src/emails/onboarding-dashboards.tsx
+++ b/packages/email/src/emails/onboarding-dashboards.tsx
@@ -7,13 +7,20 @@ import { List } from '../components/list';
export const zOnboardingDashboards = z.object({
firstName: z.string().optional(),
dashboardUrl: z.string(),
+ hasData: z.boolean().default(false),
+ eventsCount: z.number().optional(),
});
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
export type Props = z.infer<typeof zOnboardingDashboards>;
export default OnboardingDashboards;
export function OnboardingDashboards({
firstName,
dashboardUrl = 'https://dashboard.openpanel.dev',
+ hasData = false,
+ eventsCount,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
const newUrl = new URL(dashboardUrl);
@@ -21,34 +28,61 @@ export function OnboardingDashboards({
newUrl.searchParams.set('utm_medium', 'email');
newUrl.searchParams.set('utm_campaign', 'onboarding-dashboards');
+ if (!hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ It's been a week and your project hasn't received any events, so the
+ dashboard advice I'd normally send wouldn't help you yet.
+ </Text>
+ <Text>
+ If you still want to try OpenPanel, the install is the only thing in
+ the way:{' '}
+ <Link
+ href={'https://openpanel.dev/docs/get-started/install-openpanel'}
+ >
+ install guide
+ </Link>
+ .
+ </Text>
+ <Text>
+ If something about the product put you off, I'd like to know what.
+ One line is enough.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
<Text>
- Tracking events is the easy part. The value comes from actually looking
- at them.
+ {eventsCount
+ ? `You've tracked ${formatEvents(eventsCount)} events so far. The next step is making them useful.`
+ : 'Your events are coming in. The next step is making them useful.'}
</Text>
<Text>
- If you haven't yet, try building a simple dashboard. Pick one thing you
- care about and visualize it. Could be:
+ Raw events don't tell you much on their own. A dashboard with two or
+ three reports does:
</Text>
<List
items={[
- 'How many people sign up and then actually do something',
- 'Where users drop off in a flow (funnel)',
- 'Which pages lead to conversions (entry page → CTA)',
+ 'a funnel for your main flow',
+ 'a conversion trend over time',
+ 'where your visitors come from',
]}
/>
<Text>
- This is usually when people go from "I have analytics" to "I understand
- what's happening." It's a different feeling.
+ Takes about ten minutes:{' '}
+ <Link href={newUrl.toString()}>build a dashboard</Link>.
</Text>
- <Text>Takes maybe 10 minutes to set up. Worth it.</Text>
<Text>
- Best regards,
- <br />
- Carl
+ Once it exists you'll actually open it. That's the difference between
+ having analytics and using them.
</Text>
+ <Text>Carl</Text>
<span style={{ margin: '0 -20px', display: 'block' }}>
<img
src="https://openpanel.dev/_next/image?url=%2Fscreenshots%2Fdashboard-dark.webp&w=3840&q=75"
@@ -63,3 +97,10 @@ export function OnboardingDashboards({
</Layout>
);
}
+
+OnboardingDashboards.PreviewProps = {
+ firstName: 'Alex',
+ dashboardUrl: 'https://dashboard.openpanel.dev/org-id',
+ hasData: true,
+ eventsCount: 48211,
+};
diff --git a/packages/email/src/emails/onboarding-feature-request.tsx b/packages/email/src/emails/onboarding-feature-request.tsx
index 6cc10c20c..fbca2ef7d 100644
--- a/packages/email/src/emails/onboarding-feature-request.tsx
+++ b/packages/email/src/emails/onboarding-feature-request.tsx
@@ -5,38 +5,43 @@ import { Layout } from '../components/layout';
export const zOnboardingFeatureRequest = z.object({
firstName: z.string().optional(),
+ hasData: z.boolean().default(true),
});
export type Props = z.infer<typeof zOnboardingFeatureRequest>;
export default OnboardingFeatureRequest;
export function OnboardingFeatureRequest({
firstName,
+ hasData = true,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
<Text>
- OpenPanel aims to be the one stop shop for all your analytics needs.
+ You're halfway through your trial, so a quick question: is there
+ anything you expected OpenPanel to do that it doesn't?
</Text>
<Text>
- We have already in a very short time become one of the most popular
- open-source analytics platforms out there and we're working hard to add
- more features to make it the best analytics platform.
- </Text>
- <Text>
- Do you feel like you're missing a feature that's important to you? If
- that's the case, please reply here or go to our feedback board and add
- your request there.
- </Text>
- <Text>
- <Link href={'https://feedback.openpanel.dev'}>Feedback board</Link>
- </Text>
- <Text>
- Best regards,
- <br />
- Carl
+ Just reply to this email. If you'd rather post publicly, the feedback
+ board is at{' '}
+ <Link href={'https://feedback.openpanel.dev'}>
+ feedback.openpanel.dev
+ </Link>
+ .
</Text>
+ {!hasData && (
+ <Text>
+ And if you never got around to installing the tracking, no hard
+ feelings, but I'd like to know what got in the way.
+ </Text>
+ )}
+ <Text>Carl</Text>
</Layout>
);
}
+
+OnboardingFeatureRequest.PreviewProps = {
+ firstName: 'Alex',
+ hasData: true,
+};
diff --git a/packages/email/src/emails/onboarding-trial-ended.tsx b/packages/email/src/emails/onboarding-trial-ended.tsx
index 14be5b802..399277fc5 100644
--- a/packages/email/src/emails/onboarding-trial-ended.tsx
+++ b/packages/email/src/emails/onboarding-trial-ended.tsx
@@ -8,14 +8,21 @@ export const zOnboardingTrialEnded = z.object({
firstName: z.string().optional(),
billingUrl: z.string(),
recommendedPlan: z.string().optional(),
+ hasData: z.boolean().default(true),
+ eventsCount: z.number().optional(),
});
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
export type Props = z.infer<typeof zOnboardingTrialEnded>;
export default OnboardingTrialEnded;
export function OnboardingTrialEnded({
firstName,
billingUrl = 'https://dashboard.openpanel.dev',
recommendedPlan,
+ hasData = true,
+ eventsCount,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
const newUrl = new URL(billingUrl);
@@ -23,34 +30,61 @@ export function OnboardingTrialEnded({
newUrl.searchParams.set('utm_medium', 'email');
newUrl.searchParams.set('utm_campaign', 'onboarding-trial-ended');
+ if (!hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ Your trial ended today. No events ever came in, so nothing is lost.
+ The empty workspace will be cleaned up and that's the end of it.
+ </Text>
+ <Text>
+ If you want to give OpenPanel another go some day, it'll be here. And
+ if you remember what made you bounce, I'd like to hear it. One line
+ is fine.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>Your OpenPanel trial has ended.</Text>
+ <Text>Your trial ended today, so your dashboard is locked.</Text>
<Text>
- Your tracking is still running in the background, but you won't be able
- to see any new data until you upgrade. All your dashboards, reports, and
- event history are still there waiting for you.
+ Your data isn't gone.
+ {eventsCount
+ ? ` The ${formatEvents(eventsCount)} events you tracked are still stored, and incoming events are still accepted for now.`
+ : ' Everything you tracked is still stored, and incoming events are still accepted for now.'}{' '}
+ Upgrade and everything picks up where it left off.
</Text>
<Text>
- Important: If you don't upgrade within 30 days, your workspace and
- projects will be permanently deleted.
+ {recommendedPlan
+ ? `Based on your volume: ${recommendedPlan}.`
+ : 'Plans start at $2.50 a month.'}
</Text>
<Text>
- To keep your data and continue using OpenPanel, upgrade to a paid plan.{' '}
- {recommendedPlan
- ? `Based on your usage we recommend upgrading to the ${recommendedPlan}`
- : 'Plans start at $2.50/month'}
- .
+ <Button href={newUrl.toString()}>Upgrade</Button>
</Text>
<Text>
- If you have any questions or something's holding you back, just reply to
- this email.
+ If you don't upgrade, the workspace is eventually removed along with
+ its data. I'm saying that plainly so it's not a surprise, not to
+ pressure you.
</Text>
<Text>
- <Button href={newUrl.toString()}>Upgrade Now</Button>
+ If OpenPanel wasn't right for you, a one-line reply saying why helps me
+ more than you'd think.
</Text>
<Text>Carl</Text>
</Layout>
);
}
+
+OnboardingTrialEnded.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ recommendedPlan: '100K events per month for $20.00',
+ hasData: true,
+ eventsCount: 84211,
+};
diff --git a/packages/email/src/emails/onboarding-trial-ending.tsx b/packages/email/src/emails/onboarding-trial-ending.tsx
index 236d3c883..fb88787f7 100644
--- a/packages/email/src/emails/onboarding-trial-ending.tsx
+++ b/packages/email/src/emails/onboarding-trial-ending.tsx
@@ -1,4 +1,4 @@
-import { Text } from '@react-email/components';
+import { Link, Text } from '@react-email/components';
import React from 'react';
import { z } from 'zod';
import { Button } from '../components/button';
@@ -6,18 +6,25 @@ import { Layout } from '../components/layout';
export const zOnboardingTrialEnding = z.object({
firstName: z.string().optional(),
- organizationName: z.string(),
billingUrl: z.string(),
recommendedPlan: z.string().optional(),
+ trialEndDate: z.string().optional(),
+ hasData: z.boolean().default(true),
+ eventsCount: z.number().optional(),
});
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
export type Props = z.infer<typeof zOnboardingTrialEnding>;
export default OnboardingTrialEnding;
export function OnboardingTrialEnding({
firstName,
- organizationName = 'your organization',
billingUrl = 'https://dashboard.openpanel.dev',
recommendedPlan,
+ trialEndDate,
+ hasData = true,
+ eventsCount,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
const newUrl = new URL(billingUrl);
@@ -25,33 +32,69 @@ export function OnboardingTrialEnding({
newUrl.searchParams.set('utm_medium', 'email');
newUrl.searchParams.set('utm_campaign', 'onboarding-trial-ending');
+ const endsOn = trialEndDate ? `on ${trialEndDate}` : 'in a few days';
+
+ if (!hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ Your trial ends {endsOn}, and since your project never received any
+ events, there's nothing here for you to lose.
+ </Text>
+ <Text>
+ If the timing was just off, you can install now and use the last few
+ days to see if it's useful:{' '}
+ <Link
+ href={'https://openpanel.dev/docs/get-started/install-openpanel'}
+ >
+ install guide
+ </Link>
+ .
+ </Text>
+ <Text>
+ If you tried and something didn't work, reply and I'll help you sort
+ it out before the trial runs out.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>Quick heads up: your OpenPanel trial ends soon.</Text>
<Text>
- Your tracking will keep working, but you won't be able to see new data
- until you upgrade. Everything you've built so far (dashboards, reports,
- event history) stays intact.
+ Your trial ends {endsOn}.
+ {eventsCount
+ ? ` Here's where you stand: ${formatEvents(eventsCount)} events tracked during the trial.`
+ : ''}
</Text>
<Text>
- To continue using OpenPanel, you'll need to upgrade to a paid plan.{' '}
{recommendedPlan
- ? `Based on your usage we recommend upgrading to the ${recommendedPlan} plan`
- : 'Plans start at $2.50/month'}
- .
+ ? `At that volume, the plan that fits is ${recommendedPlan}.`
+ : 'Plans start at $2.50 a month.'}{' '}
+ If you upgrade, nothing changes: same dashboards, same data. If you
+ don't, your dashboard locks when the trial ends, and eventually the
+ workspace is removed.
</Text>
<Text>
- If something's holding you back, I'd like to hear about it. Just reply.
+ <Button href={newUrl.toString()}>Upgrade</Button>
</Text>
<Text>
- Your project will receive events for the next 30 days, if you haven't
- upgraded by then we'll remove your workspace and projects.
- </Text>
- <Text>
- <Button href={newUrl.toString()}>Upgrade Now</Button>
+ If something is holding you back, reply and tell me. I'd rather fix the
+ reason than send you another reminder.
</Text>
<Text>Carl</Text>
</Layout>
);
}
+
+OnboardingTrialEnding.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ recommendedPlan: '100K events per month for $20.00',
+ trialEndDate: 'June 16',
+ hasData: true,
+ eventsCount: 84211,
+};
diff --git a/packages/email/src/emails/onboarding-welcome.tsx b/packages/email/src/emails/onboarding-welcome.tsx
index b2faf278e..35f4f6e08 100644
--- a/packages/email/src/emails/onboarding-welcome.tsx
+++ b/packages/email/src/emails/onboarding-welcome.tsx
@@ -1,4 +1,4 @@
-import { Heading, Link, Text } from '@react-email/components';
+import { Link, Text } from '@react-email/components';
import React from 'react';
import { z } from 'zod';
import { Layout } from '../components/layout';
@@ -7,49 +7,67 @@ import { List } from '../components/list';
export const zOnboardingWelcome = z.object({
firstName: z.string().optional(),
dashboardUrl: z.string(),
+ hasData: z.boolean().default(false),
});
export type Props = z.infer<typeof zOnboardingWelcome>;
export default OnboardingWelcome;
export function OnboardingWelcome({
firstName,
+ dashboardUrl = 'https://dashboard.openpanel.dev',
+ hasData = false,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>Thanks for trying OpenPanel.</Text>
+ <Text>Carl here. I build OpenPanel. Thanks for signing up.</Text>
<Text>
- We built OpenPanel because most analytics tools are either too
- expensive, too complicated, or both. OpenPanel is different.
- </Text>
- <Text>
- We hope you find OpenPanel useful and if you have any questions,
- regarding tracking or how to import your existing events, just reach
- out. We're here to help.
- </Text>
- <Text>To get started, you can:</Text>
- <List
- items={[
- <Link
- key=""
- href={'https://openpanel.dev/docs/get-started/install-openpanel'}
- >
- Install tracking script
- </Link>,
- <Link
- key=""
- href={'https://openpanel.dev/docs/get-started/track-events'}
- >
- Start tracking your events
- </Link>,
- ]}
- />
- <Text>
- Best regards,
- <br />
- Carl
+ Your trial runs for 30 days with everything included. No card needed
+ until you decide to stay.
</Text>
+ {hasData ? (
+ <>
+ <Text>
+ Events are already coming in, so you're past the hard part. Have a
+ look around your dashboard and reply if anything looks off.
+ </Text>
+ <Text>
+ <Link href={dashboardUrl}>Open your dashboard</Link>
+ </Text>
+ </>
+ ) : (
+ <>
+ <Text>
+ First step is getting data in. The install usually takes a few
+ minutes:
+ </Text>
+ <List
+ items={[
+ <Link
+ key="install"
+ href={'https://openpanel.dev/docs/get-started/install-openpanel'}
+ >
+ Install the tracking script
+ </Link>,
+ <Link
+ key="track"
+ href={'https://openpanel.dev/docs/get-started/track-events'}
+ >
+ Track custom events
+ </Link>,
+ ]}
+ />
+ <Text>If you get stuck, just reply to this email.</Text>
+ </>
+ )}
+ <Text>Carl</Text>
</Layout>
);
}
+
+OnboardingWelcome.PreviewProps = {
+ firstName: 'Alex',
+ dashboardUrl: 'https://dashboard.openpanel.dev/org-id',
+ hasData: false,
+};
diff --git a/packages/email/src/emails/onboarding-what-to-track.tsx b/packages/email/src/emails/onboarding-what-to-track.tsx
index ce3f8ecba..be1c6893a 100644
--- a/packages/email/src/emails/onboarding-what-to-track.tsx
+++ b/packages/email/src/emails/onboarding-what-to-track.tsx
@@ -1,46 +1,78 @@
-import { Text } from '@react-email/components';
+import { Link, Text } from '@react-email/components';
import React from 'react';
import { z } from 'zod';
import { Layout } from '../components/layout';
-import { List } from '../components/list';
export const zOnboardingWhatToTrack = z.object({
firstName: z.string().optional(),
+ hasData: z.boolean().default(false),
+ eventsCount: z.number().optional(),
});
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
export type Props = z.infer<typeof zOnboardingWhatToTrack>;
export default OnboardingWhatToTrack;
export function OnboardingWhatToTrack({
firstName,
+ hasData = false,
+ eventsCount,
unsubscribeUrl,
}: Props & { unsubscribeUrl?: string }) {
return (
<Layout unsubscribeUrl={unsubscribeUrl}>
<Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>
- Tracking can be overwhelming at first, and that's why its important to
- focus on what's matters. For most products, that's something like:
- </Text>
- <List
- items={[
- 'Find good funnels to track (onboarding or checkout)',
- 'Conversions (how many clicks your hero CTA)',
- 'What did the user do after clicking the CTA',
- ]}
- />
- <Text>
- Start small and incrementally add more events as you go is usually the
- best approach.
- </Text>
- <Text>
- If you're not sure whether something's worth tracking, or have any
- questions, just reply here.
- </Text>
- <Text>
- Best regards,
- <br />
- Carl
- </Text>
+ {hasData ? (
+ <>
+ <Text>
+ Your tracking is live
+ {eventsCount ? ` (${formatEvents(eventsCount)} events so far)` : ''}
+ , so here's the advice I give everyone next.
+ </Text>
+ <Text>
+ Don't try to track everything. Pick the one flow that decides
+ whether your product works (signup, checkout, whatever it is) and
+ set up a funnel for it. Two or three custom events is enough.
+ </Text>
+ <Text>
+ Pageviews tell you people came. The funnel tells you whether they
+ did the thing you built the product for.
+ </Text>
+ <Text>
+ Not sure what's worth tracking for your product? Reply with what
+ you're building and I'll give you a concrete suggestion.
+ </Text>
+ </>
+ ) : (
+ <>
+ <Text>
+ You created your OpenPanel account two days ago, but no events have
+ come in yet.
+ </Text>
+ <Text>
+ Usually that means the install didn't happen, or something is
+ blocking the script. Both are quick to sort out:{' '}
+ <Link
+ href={'https://openpanel.dev/docs/get-started/install-openpanel'}
+ >
+ install guide
+ </Link>
+ .
+ </Text>
+ <Text>
+ If something in the docs didn't make sense, reply and tell me where
+ you got stuck. That helps me either way.
+ </Text>
+ </>
+ )}
+ <Text>Carl</Text>
</Layout>
);
}
+
+OnboardingWhatToTrack.PreviewProps = {
+ firstName: 'Alex',
+ hasData: true,
+ eventsCount: 12544,
+};
diff --git a/packages/email/src/emails/trial-ending-soon.tsx b/packages/email/src/emails/trial-ending-soon.tsx
deleted file mode 100644
index bf6e7034a..000000000
--- a/packages/email/src/emails/trial-ending-soon.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { Button, Hr, Link, Text } from '@react-email/components';
-import React from 'react';
-import { z } from 'zod';
-import { Layout } from '../components/layout';
-
-export const zTrailEndingSoon = z.object({
- url: z.string(),
- organizationName: z.string(),
-});
-
-export type Props = z.infer<typeof zTrailEndingSoon>;
-export default TrailEndingSoon;
-export function TrailEndingSoon({
- organizationName = 'Acme Co',
- url = 'https://openpanel.dev',
- unsubscribeUrl,
-}: Props & { unsubscribeUrl?: string }) {
- const newUrl = new URL(url);
- newUrl.searchParams.set('utm_source', 'email');
- newUrl.searchParams.set('utm_medium', 'email');
- newUrl.searchParams.set('utm_campaign', 'trial-ending-soon');
- return (
- <Layout>
- <Text>Your trial period is ending soon for {organizationName}!</Text>
- <Text>
- When your trial ends, you'll still receive incoming events but you won't
- be able to see them in the dashboard until you upgrade.
- </Text>
- <Text>
- <Link href={newUrl.toString()}>Upgrade to a paid plan</Link>
- </Text>
- <Hr />
- <Text style={{ fontWeight: 'bold' }}>
- Discover what you can do with OpenPanel:
- </Text>
- <Text>
- 🎯 <strong>Create Custom Funnels</strong> - Track user progression
- through your key conversion paths and identify where users drop off
- </Text>
- <Text>
- 📈 <strong>User Retention Analysis</strong> - Understand how well you're
- keeping users engaged over time with beautiful retention graphs
- </Text>
- <Text>
- 🗺️ <strong>User Journey Mapping</strong> - Follow individual user paths
- through your application to understand their behavior and optimize their
- experience
- </Text>
- <Text>
- 🔬 <strong>A/B Testing Analysis</strong> - Measure the impact of your
- product changes with detailed conversion metrics and statistical
- significance
- </Text>
- <Text>
- 📊 <strong>Custom Event Tracking</strong> - Track any user interaction
- that matters to your business with our flexible event system
- </Text>
- <Text>
- <Button
- href={newUrl.toString()}
- style={{
- backgroundColor: '#0070f3',
- color: 'white',
- padding: '12px 20px',
- borderRadius: '5px',
- textDecoration: 'none',
- }}
- >
- Upgrade Now to Unlock All Features
- </Button>
- </Text>
- </Layout>
- );
-}
diff --git a/packages/payments/package.json b/packages/payments/package.json
index 3a5a6dd72..21da6b5c9 100644
--- a/packages/payments/package.json
+++ b/packages/payments/package.json
@@ -5,13 +5,16 @@
"main": "index.ts",
"exports": {
".": "./index.ts",
- "./prices": "./src/prices.ts"
+ "./prices": "./src/prices.ts",
+ "./subscription-state": "./src/subscription-state.ts",
+ "./subscription-state-meta": "./src/subscription-state-meta.ts"
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "@polar-sh/sdk": "^0.47.0"
+ "@polar-sh/sdk": "^0.48.1",
+ "date-fns": "^3.3.1"
},
"devDependencies": {
"@openpanel/db": "workspace:*",
diff --git a/packages/payments/src/polar.ts b/packages/payments/src/polar.ts
index 872edea79..da77ecc5d 100644
--- a/packages/payments/src/polar.ts
+++ b/packages/payments/src/polar.ts
@@ -110,6 +110,7 @@ export function changeSubscription(subscriptionId: string, productId: string) {
id: subscriptionId,
subscriptionUpdate: {
productId,
+ prorationBehavior: 'invoice',
},
});
}
diff --git a/packages/payments/src/subscription-state-meta.ts b/packages/payments/src/subscription-state-meta.ts
new file mode 100644
index 000000000..632715ada
--- /dev/null
+++ b/packages/payments/src/subscription-state-meta.ts
@@ -0,0 +1,203 @@
+import { format } from 'date-fns';
+import type { SubscriptionState } from './subscription-state.js';
+
+type BadgeVariant =
+ | 'default'
+ | 'secondary'
+ | 'success'
+ | 'warning'
+ | 'destructive';
+type Tone = 'default' | 'warning' | 'destructive';
+
+export type SubscriptionStateMeta = {
+ /** Sidebar badge, or null when nothing should be shown. */
+ badge: { label: string; variant: BadgeVariant } | null;
+ /** App-level banner, or null when no banner should show for this state. */
+ banner: {
+ title: string;
+ description: string;
+ cta: string;
+ tone: Tone;
+ } | null;
+ /** 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;
+};
+
+const fmt = (date: Date | null | undefined) =>
+ date ? format(date, 'PPP') : null;
+
+/**
+ * Single source of truth for how every subscription state is presented across
+ * the dashboard (billing page status line, app banner, sidebar badge, and the
+ * blocking BillingPrompt). All lifecycle dates come from `subscriptionEndsAt`.
+ */
+export function getSubscriptionStateMeta(
+ state: SubscriptionState,
+ opts: { endsAt?: Date | null; canceledAt?: Date | null }
+): SubscriptionStateMeta {
+ const endsAt = fmt(opts.endsAt);
+ const canceledAt = fmt(opts.canceledAt);
+
+ switch (state) {
+ case 'self_hosted':
+ case 'active':
+ return {
+ badge: null,
+ banner: null,
+ statusLine: endsAt
+ ? { text: `Your subscription renews on ${endsAt}`, tone: 'default' }
+ : null,
+ blockType: null,
+ };
+
+ case 'trialing':
+ return {
+ badge: { label: 'Trial', variant: 'secondary' },
+ banner: {
+ title: 'Free trial',
+ description: endsAt
+ ? `Your organization is on a free trial. It ends on ${endsAt}.`
+ : 'Your organization is on a free trial.',
+ cta: 'Upgrade from $2.5/month',
+ tone: 'default',
+ },
+ statusLine: endsAt
+ ? { text: `Your trial ends on ${endsAt}`, tone: 'default' }
+ : null,
+ blockType: null,
+ };
+
+ case 'trial_expired':
+ return {
+ badge: { label: 'Trial ended', variant: 'destructive' },
+ banner: {
+ title: 'Trial ended',
+ description:
+ 'Your free trial has ended. Upgrade to keep using OpenPanel.',
+ cta: 'Upgrade',
+ tone: 'destructive',
+ },
+ statusLine: { text: 'Your free trial has ended.', tone: 'destructive' },
+ blockType: 'trialEnded',
+ };
+
+ case 'canceling':
+ return {
+ badge: { label: 'Canceling', variant: 'warning' },
+ banner: {
+ title: 'Subscription will be canceled',
+ description: endsAt
+ ? `You have canceled your subscription. It will be canceled on ${endsAt} — reactivate it to keep your access.`
+ : 'You have canceled your subscription. Reactivate it to keep your access.',
+ cta: 'Reactivate',
+ tone: 'warning',
+ },
+ statusLine: endsAt
+ ? {
+ text: `Your subscription will be canceled on ${endsAt}`,
+ tone: 'destructive',
+ }
+ : null,
+ blockType: null,
+ };
+
+ case 'canceled':
+ return {
+ badge: { label: 'Canceled', variant: 'destructive' },
+ banner: {
+ title: 'Subscription canceled',
+ description: canceledAt
+ ? `Your subscription was canceled on ${canceledAt}. Choose a plan to regain access.`
+ : 'Your subscription was canceled. Choose a plan to regain access.',
+ cta: 'Choose a plan',
+ tone: 'destructive',
+ },
+ statusLine: {
+ text: canceledAt
+ ? `Your subscription was canceled on ${canceledAt}`
+ : 'Your subscription was canceled',
+ tone: 'destructive',
+ },
+ blockType: 'expired',
+ };
+
+ case 'past_due':
+ return {
+ badge: { label: 'Past due', variant: 'warning' },
+ banner: {
+ title: 'Payment past due',
+ description:
+ 'Your last payment failed. Update your payment method to avoid losing access.',
+ cta: 'Update payment',
+ tone: 'warning',
+ },
+ statusLine: {
+ text: 'Your last payment failed — please update your payment method.',
+ tone: 'destructive',
+ },
+ blockType: null,
+ };
+
+ case 'unpaid':
+ return {
+ badge: { label: 'Unpaid', variant: 'destructive' },
+ banner: {
+ title: 'Subscription unpaid',
+ description:
+ 'Your subscription is unpaid. Update your payment method to restore access.',
+ cta: 'Update payment',
+ tone: 'destructive',
+ },
+ statusLine: {
+ text: 'Your subscription is unpaid.',
+ tone: 'destructive',
+ },
+ blockType: 'unpaid',
+ };
+
+ case 'incomplete':
+ return {
+ badge: { label: 'Incomplete', variant: 'warning' },
+ banner: {
+ title: 'Finish setting up your subscription',
+ description:
+ 'Your subscription setup is incomplete. Complete checkout to activate it.',
+ cta: 'Complete checkout',
+ tone: 'warning',
+ },
+ statusLine: {
+ text: 'Your subscription setup is incomplete.',
+ tone: 'destructive',
+ },
+ blockType: null,
+ };
+
+ case 'expired':
+ return {
+ badge: { label: 'Expired', variant: 'destructive' },
+ banner: {
+ title: 'Subscription expired',
+ description: endsAt
+ ? `Your subscription expired on ${endsAt}. Choose a plan to regain access.`
+ : 'Your subscription expired. Choose a plan to regain access.',
+ cta: 'Choose a plan',
+ tone: 'destructive',
+ },
+ statusLine: {
+ text: endsAt
+ ? `Your subscription expired on ${endsAt}`
+ : 'Your subscription expired',
+ tone: 'destructive',
+ },
+ blockType: 'expired',
+ };
+
+ default: {
+ // Exhaustiveness guard — every SubscriptionState must be handled above.
+ const _exhaustive: never = state;
+ return _exhaustive;
+ }
+ }
+}
diff --git a/packages/payments/src/subscription-state.test.ts b/packages/payments/src/subscription-state.test.ts
new file mode 100644
index 000000000..0c0e4d10d
--- /dev/null
+++ b/packages/payments/src/subscription-state.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ type SubscriptionState,
+ getSubscriptionState,
+ subscriptionBlocksDashboard,
+} from './subscription-state.js';
+
+const DAY = 1000 * 60 * 60 * 24;
+const future = new Date(Date.now() + 30 * DAY);
+const past = new Date(Date.now() - DAY);
+
+type Case = {
+ name: string;
+ status: string | null;
+ canceledAt: Date | null;
+ endsAt: Date | null;
+ expected: SubscriptionState;
+};
+
+describe('getSubscriptionState', () => {
+ const original = process.env.SELF_HOSTED;
+ // The function short-circuits when SELF_HOSTED==='true'; force it off so we
+ // exercise the real billing logic regardless of the dev's local env.
+ beforeEach(() => {
+ delete process.env.SELF_HOSTED;
+ });
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.SELF_HOSTED;
+ } else {
+ process.env.SELF_HOSTED = original;
+ }
+ });
+
+ const cases: Case[] = [
+ // No paid subscription (trial is our own concept, Polar status null)
+ { name: 'null status, ends in future', status: null, canceledAt: null, endsAt: future, expected: 'trialing' },
+ { name: 'null status, ended', status: null, canceledAt: null, endsAt: past, expected: 'trial_expired' },
+ { name: 'null status, no end date', status: null, canceledAt: null, endsAt: null, expected: 'trial_expired' },
+ { name: 'trialing status, ends in future', status: 'trialing', canceledAt: null, endsAt: future, expected: 'trialing' },
+ { name: 'trialing status, ended', status: 'trialing', canceledAt: null, endsAt: past, expected: 'trial_expired' },
+
+ // Active paid subscription
+ { name: 'active, renewing', status: 'active', canceledAt: null, endsAt: future, expected: 'active' },
+ { name: 'active, no end date', status: 'active', canceledAt: null, endsAt: null, expected: 'active' },
+ { name: 'active but period already passed', status: 'active', canceledAt: null, endsAt: past, expected: 'expired' },
+
+ // Cancel-at-period-end keeps status active while canceledAt is set
+ { name: 'active + canceledAt (canceling)', status: 'active', canceledAt: past, endsAt: future, expected: 'canceling' },
+ { name: 'canceledAt wins even if period passed', status: 'active', canceledAt: past, endsAt: past, expected: 'canceling' },
+
+ // Payment-problem states
+ { name: 'past_due', status: 'past_due', canceledAt: null, endsAt: future, expected: 'past_due' },
+ { name: 'unpaid', status: 'unpaid', canceledAt: null, endsAt: future, expected: 'unpaid' },
+ { name: 'incomplete', status: 'incomplete', canceledAt: null, endsAt: future, expected: 'incomplete' },
+ { name: 'incomplete_expired', status: 'incomplete_expired', canceledAt: null, endsAt: past, expected: 'expired' },
+
+ // Fully canceled / revoked
+ { name: 'canceled', status: 'canceled', canceledAt: past, endsAt: past, expected: 'canceled' },
+
+ // Unknown status falls back to expired (fail safe, never silently active)
+ { name: 'unknown status', status: 'something_new', canceledAt: null, endsAt: future, expected: 'expired' },
+ ];
+
+ for (const c of cases) {
+ it(`${c.name} -> ${c.expected}`, () => {
+ expect(
+ getSubscriptionState({
+ subscriptionStatus: c.status,
+ subscriptionCanceledAt: c.canceledAt,
+ subscriptionEndsAt: c.endsAt,
+ })
+ ).toBe(c.expected);
+ });
+ }
+
+ it('SELF_HOSTED=true short-circuits to self_hosted', () => {
+ process.env.SELF_HOSTED = 'true';
+ expect(
+ getSubscriptionState({
+ subscriptionStatus: 'canceled',
+ subscriptionCanceledAt: past,
+ subscriptionEndsAt: past,
+ })
+ ).toBe('self_hosted');
+ });
+});
+
+describe('subscriptionBlocksDashboard', () => {
+ const blocking: SubscriptionState[] = [
+ 'trial_expired',
+ 'expired',
+ 'unpaid',
+ 'canceled',
+ ];
+ const allowed: SubscriptionState[] = [
+ 'self_hosted',
+ 'trialing',
+ 'active',
+ 'canceling',
+ 'past_due',
+ 'incomplete',
+ ];
+
+ for (const state of blocking) {
+ it(`blocks ${state}`, () => {
+ expect(subscriptionBlocksDashboard(state)).toBe(true);
+ });
+ }
+ for (const state of allowed) {
+ it(`allows ${state}`, () => {
+ expect(subscriptionBlocksDashboard(state)).toBe(false);
+ });
+ }
+});
diff --git a/packages/payments/src/subscription-state.ts b/packages/payments/src/subscription-state.ts
new file mode 100644
index 000000000..f95943318
--- /dev/null
+++ b/packages/payments/src/subscription-state.ts
@@ -0,0 +1,82 @@
+/**
+ * Canonical subscription state for an organization. This is the single place
+ * the raw Polar status + cancellation/period fields are interpreted; every
+ * boolean flag and UI surface derives from it.
+ *
+ * Pure, dependency-free domain logic so both the database layer (Prisma
+ * computed fields) and the browser dashboard can consume it without coupling
+ * to either side.
+ */
+export type SubscriptionState =
+ | 'self_hosted' // SELF_HOSTED=true — billing not applicable
+ | 'trialing' // in the trial window, no paid subscription yet
+ | 'trial_expired' // trial window passed, no paid subscription
+ | 'active' // paid, renewing
+ | 'canceling' // active but scheduled to cancel at period end
+ | 'canceled' // fully canceled / revoked (access ended)
+ | 'past_due' // payment failed, in dunning (still has access)
+ | 'unpaid' // payment failed terminally
+ | 'incomplete' // initial checkout not completed
+ | 'expired'; // period ended without renewal (catch-all)
+
+export interface SubscriptionStateInput {
+ subscriptionStatus: string | null;
+ subscriptionCanceledAt: Date | null;
+ subscriptionEndsAt: Date | null;
+}
+
+export function getSubscriptionState(
+ org: SubscriptionStateInput
+): SubscriptionState {
+ if (process.env.SELF_HOSTED === 'true') {
+ return 'self_hosted';
+ }
+
+ const now = new Date();
+ const { subscriptionStatus, subscriptionCanceledAt, subscriptionEndsAt } = org;
+ const endsInFuture = Boolean(subscriptionEndsAt && subscriptionEndsAt > now);
+
+ switch (subscriptionStatus) {
+ case null:
+ case 'trialing':
+ return endsInFuture ? 'trialing' : 'trial_expired';
+ case 'active':
+ // Cancel-at-period-end keeps the Polar status as `active` while
+ // `canceledAt` is set; the subscription stays usable until it expires.
+ if (subscriptionCanceledAt) {
+ return 'canceling';
+ }
+ return subscriptionEndsAt && subscriptionEndsAt <= now
+ ? 'expired'
+ : 'active';
+ case 'past_due':
+ return 'past_due';
+ case 'unpaid':
+ return 'unpaid';
+ case 'incomplete':
+ return 'incomplete';
+ case 'incomplete_expired':
+ return 'expired';
+ case 'canceled':
+ return 'canceled';
+ default:
+ return 'expired';
+ }
+}
+
+/**
+ * Whether a given state should block access to the dashboard (and force the
+ * billing prompt). Payment-in-progress states keep access; terminal/expired
+ * states do not.
+ */
+export function subscriptionBlocksDashboard(state: SubscriptionState): boolean {
+ switch (state) {
+ case 'trial_expired':
+ case 'expired':
+ case 'unpaid':
+ case 'canceled':
+ return true;
+ default:
+ return false;
+ }
+}
diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.ts
index 9dfd096f4..f13a70d06 100644
--- a/packages/queue/src/queues.ts
+++ b/packages/queue/src/queues.ts
@@ -169,15 +169,6 @@ export type CronQueuePayload =
| CronQueuePayloadSessionReaper
| CronQueuePayloadSessionVacuum;
-export type MiscQueuePayloadTrialEndingSoon = {
- type: 'trialEndingSoon';
- payload: {
- organizationId: string;
- };
-};
-
-export type MiscQueuePayload = MiscQueuePayloadTrialEndingSoon;
-
export type CronQueueType = CronQueuePayload['type'];
const orderingDelayMs = Number.parseInt(
@@ -240,13 +231,6 @@ export const cronQueue = new Queue<CronQueuePayload>(getQueueName('cron'), {
},
});
-export const miscQueue = new Queue<MiscQueuePayload>(getQueueName('misc'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 10,
- },
-});
-
export type NotificationQueuePayload = {
type: 'sendNotification';
payload: {
diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.ts
index 6186013f7..893551ed9 100644
--- a/packages/trpc/src/routers/subscription.ts
+++ b/packages/trpc/src/routers/subscription.ts
@@ -58,29 +58,27 @@ export const subscriptionRouter = createTRPCRouter({
}),
]);
+ // 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.
+ // Reactivate first if it was scheduled to cancel, otherwise change the
+ // product on the existing subscription.
if (
organization.subscriptionId &&
organization.subscriptionStatus === 'active'
) {
- const existingProduct = organization.subscriptionProductId
- ? await getProduct(organization.subscriptionProductId)
- : null;
-
- // If the existing product is free, cancel the subscription and then jump to the checkout
- if (existingProduct?.prices.some((p) => p.amountType === 'free')) {
- await cancelSubscription(organization.subscriptionId);
- } else {
- if (organization.subscriptionCanceledAt) {
- await reactivateSubscription(organization.subscriptionId);
- return null;
- }
-
- await changeSubscription(
- organization.subscriptionId,
- input.productId,
- );
+ if (organization.subscriptionCanceledAt) {
+ await reactivateSubscription(organization.subscriptionId);
return null;
}
+
+ // Already on this product — nothing to change.
+ if (organization.subscriptionProductId === input.productId) {
+ return null;
+ }
+
+ await changeSubscription(organization.subscriptionId, input.productId);
+ return null;
}
const checkout = await createCheckout({
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a7e168cf0..02b77bd76 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1226,6 +1226,9 @@ importers:
'@openpanel/logger':
specifier: workspace:*
version: link:../logger
+ '@openpanel/payments':
+ specifier: workspace:*
+ version: link:../payments
'@openpanel/queue':
specifier: workspace:^
version: link:../queue
@@ -1539,8 +1542,11 @@ importers:
packages/payments:
dependencies:
'@polar-sh/sdk':
- specifier: ^0.47.0
- version: 0.47.0
+ specifier: ^0.48.1
+ version: 0.48.1
+ date-fns:
+ specifier: ^3.3.1
+ version: 3.3.1
devDependencies:
'@openpanel/db':
specifier: workspace:*
@@ -6859,8 +6865,8 @@ packages:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
- '@polar-sh/[email protected]':
- resolution: {integrity: sha512-tZEt8eLWsQVhmyfUQzXhnN84e5Cnu/JsYFnCci1ranWkIGveQc+wTiyzDCG9Tl1xiz1Y/ztPsAJ1fevj6ExdAA==}
+ '@polar-sh/[email protected]':
+ resolution: {integrity: sha512-FmU6eLJRXJ6Zau0IkqscfkFta8xxYbFV1VD9zzS2Ki2btCuFmUyPZOkHOXU77R892h2zyBegLnHS7jrOhMN1Sw==}
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
@@ -21102,7 +21108,7 @@ snapshots:
dependencies:
'@babel/template': 7.28.6
'@babel/traverse': 7.29.0
- '@babel/types': 7.29.0
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -22203,7 +22209,7 @@ snapshots:
'@babel/core': 7.28.3
'@babel/helper-module-transforms': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-validator-identifier': 7.28.5
+ '@babel/helper-validator-identifier': 7.29.7
'@babel/traverse': 7.29.0
transitivePeerDependencies:
- supports-color
@@ -22214,7 +22220,7 @@ snapshots:
'@babel/core': 7.28.5
'@babel/helper-module-transforms': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-validator-identifier': 7.28.5
+ '@babel/helper-validator-identifier': 7.29.7
'@babel/traverse': 7.29.0
transitivePeerDependencies:
- supports-color
@@ -22583,7 +22589,7 @@ snapshots:
'@babel/helper-module-imports': 7.28.6
'@babel/helper-plugin-utils': 7.28.6
'@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
- '@babel/types': 7.29.0
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -22594,7 +22600,7 @@ snapshots:
'@babel/helper-module-imports': 7.28.6
'@babel/helper-plugin-utils': 7.28.6
'@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
- '@babel/types': 7.29.0
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -23061,7 +23067,7 @@ snapshots:
dependencies:
'@babel/core': 7.28.3
'@babel/helper-plugin-utils': 7.28.6
- '@babel/types': 7.29.0
+ '@babel/types': 7.29.7
esutils: 2.0.3
optional: true
@@ -23069,7 +23075,7 @@ snapshots:
dependencies:
'@babel/core': 7.28.5
'@babel/helper-plugin-utils': 7.28.6
- '@babel/types': 7.29.0
+ '@babel/types': 7.29.7
esutils: 2.0.3
@@ -24238,8 +24244,8 @@ snapshots:
dependencies:
'@babel/core': 7.29.0
'@babel/generator': 7.29.1
- '@babel/parser': 7.29.2
- '@babel/types': 7.29.0
+ '@babel/parser': 7.29.7
+ '@babel/types': 7.29.7
'@expo/config': 8.5.4
'@expo/env': 0.2.3
'@expo/json-file': 8.3.3
@@ -26827,7 +26833,7 @@ snapshots:
optional: true
- '@polar-sh/[email protected]':
+ '@polar-sh/[email protected]':
dependencies:
standardwebhooks: 1.0.0
zod: 4.3.6