Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: More robust signup + billing event firing

Richie McIlroy637544eab2a9
diff --git a/apps/web/actions/analytics/track-user-signed-up.ts b/apps/web/actions/analytics/track-user-signed-up.ts
new file mode 100644
index 000000000..fd7cf6623
--- /dev/null
+++ b/apps/web/actions/analytics/track-user-signed-up.ts
@@ -0,0 +1,53 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { users } from "@cap/database/schema";
+import { sql } from "drizzle-orm";
+
+type UserPreferences = {
+ notifications?: {
+ pauseComments: boolean;
+ pauseReplies: boolean;
+ pauseViews: boolean;
+ pauseReactions: boolean;
+ };
+ trackedEvents?: {
+ user_signed_up?: boolean;
+ };
+} | null;
+
+export async function checkAndMarkUserSignedUpTracked(): Promise<{
+ shouldTrack: boolean;
+}> {
+ const currentUser = await getCurrentUser();
+ if (!currentUser) {
+ return { shouldTrack: false };
+ }
+
+ try {
+ const prefs = currentUser.preferences as UserPreferences;
+ const alreadyTracked = Boolean(prefs?.trackedEvents?.user_signed_up);
+
+ if (alreadyTracked) {
+ return { shouldTrack: false };
+ }
+
+ const result = await db()
+ .update(users)
+ .set({
+ preferences: sql`JSON_SET(COALESCE(${users.preferences}, JSON_OBJECT()), '$.trackedEvents.user_signed_up', true)`,
+ })
+ .where(
+ sql`(${users.id} = ${currentUser.id}) AND (${users.created_at} >= CURRENT_DATE()) AND (JSON_EXTRACT(${users.preferences}, '$.trackedEvents.user_signed_up') IS NULL OR JSON_EXTRACT(${users.preferences}, '$.trackedEvents.user_signed_up') = false)`,
+ );
+
+ if (result.rowsAffected && result.rowsAffected > 0) {
+ return { shouldTrack: true };
+ }
+
+ return { shouldTrack: false };
+ } catch {
+ return { shouldTrack: false };
+ }
+}
diff --git a/apps/web/actions/billing/track-meta-purchase.ts b/apps/web/actions/billing/track-meta-purchase.ts
new file mode 100644
index 000000000..c90db45c9
--- /dev/null
+++ b/apps/web/actions/billing/track-meta-purchase.ts
@@ -0,0 +1,124 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { users } from "@cap/database/schema";
+import { stripe } from "@cap/utils";
+import { eq } from "drizzle-orm";
+import type Stripe from "stripe";
+
+export async function getPurchaseForMeta({
+ sessionId,
+}: {
+ sessionId?: string | null;
+}): Promise<{
+ shouldTrack: boolean;
+ value?: number;
+ currency?: string;
+ eventId?: string;
+}> {
+ const user = await getCurrentUser();
+ if (!user) {
+ return { shouldTrack: false };
+ }
+
+ let subscriptionId: string | undefined;
+ let customerId: string | undefined;
+ let eventId: string | undefined;
+
+ try {
+ if (sessionId) {
+ const session = await stripe().checkout.sessions.retrieve(sessionId);
+ if (!session || session.mode !== "subscription") {
+ return { shouldTrack: false };
+ }
+
+ eventId = session.id;
+ customerId = (session.customer as string) || undefined;
+
+ if (
+ user.stripeCustomerId &&
+ customerId &&
+ user.stripeCustomerId !== customerId
+ ) {
+ return { shouldTrack: false };
+ }
+
+ if (!user.stripeCustomerId && customerId) {
+ const customer = await stripe().customers.retrieve(customerId);
+ let matches = false;
+ if (
+ "metadata" in customer &&
+ customer.metadata &&
+ (customer.metadata as Record<string, string | undefined>).userId ===
+ user.id
+ ) {
+ matches = true;
+ } else if (
+ "email" in customer &&
+ customer.email &&
+ customer.email === user.email
+ ) {
+ matches = true;
+ }
+ if (!matches) {
+ return { shouldTrack: false };
+ }
+ await db()
+ .update(users)
+ .set({ stripeCustomerId: customer.id })
+ .where(eq(users.id, user.id));
+ }
+
+ if (session.subscription) {
+ subscriptionId = String(session.subscription);
+ }
+ }
+
+ if (!subscriptionId) {
+ if (user.stripeSubscriptionId) {
+ subscriptionId = user.stripeSubscriptionId;
+ } else if (user.stripeCustomerId) {
+ const subs = await stripe().subscriptions.list({
+ customer: user.stripeCustomerId,
+ status: "all",
+ limit: 1,
+ });
+ if (subs.data[0]) subscriptionId = subs.data[0].id;
+ }
+ }
+
+ if (!subscriptionId) {
+ return { shouldTrack: false };
+ }
+
+ const subscription = await stripe().subscriptions.retrieve(subscriptionId);
+ const alreadyTracked =
+ (subscription.metadata &&
+ (subscription.metadata as Record<string, string | undefined>)
+ .meta_purchase_tracked === "true") ||
+ false;
+ if (alreadyTracked) {
+ return { shouldTrack: false };
+ }
+
+ const currency = subscription.items.data[0]?.price?.currency?.toUpperCase();
+ const amountCents = subscription.items.data.reduce((acc, item) => {
+ const unit = item.price?.unit_amount ?? 0;
+ const qty = item.quantity ?? 1;
+ return acc + unit * qty;
+ }, 0);
+ const value = amountCents / 100;
+
+ await stripe().subscriptions.update(subscription.id, {
+ metadata: {
+ ...(subscription.metadata || {}),
+ meta_purchase_tracked: "true",
+ } as Stripe.MetadataParam,
+ });
+
+ return { shouldTrack: true, value, currency, eventId };
+ } catch {
+ return { shouldTrack: false };
+ }
+}
diff --git a/apps/web/actions/videos/generate-ai-metadata.ts b/apps/web/actions/videos/generate-ai-metadata.ts
index a9b61bd13..7de6689d5 100644
--- a/apps/web/actions/videos/generate-ai-metadata.ts
+++ b/apps/web/actions/videos/generate-ai-metadata.ts
@@ -4,7 +4,7 @@ import { db } from "@cap/database";
import { s3Buckets, videos } from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { serverEnv } from "@cap/env";
-import { Video } from "@cap/web-domain";
+import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";
import { createBucketProvider } from "@/utils/s3";
diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.ts
index 83a6c0720..87b24caef 100644
--- a/apps/web/actions/videos/get-status.ts
+++ b/apps/web/actions/videos/get-status.ts
@@ -4,7 +4,7 @@ import { db } from "@cap/database";
import { users, videos } from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";
-import { Policy, Video } from "@cap/web-domain";
+import { Policy, type Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect, Exit } from "effect";
import * as EffectRuntime from "@/lib/server";
diff --git a/apps/web/app/Layout/MetaPixel.tsx b/apps/web/app/Layout/MetaPixel.tsx
index c0b64d55e..946378264 100644
--- a/apps/web/app/Layout/MetaPixel.tsx
+++ b/apps/web/app/Layout/MetaPixel.tsx
@@ -5,62 +5,86 @@ import Script from "next/script";
import { useId, useRef } from "react";
declare global {
- interface Window {
- fbq: (command: string, ...args: unknown[]) => void;
- _fbq: unknown;
- }
+ interface Window {
+ fbq: (command: string, ...args: unknown[]) => void;
+ _fbq: unknown;
+ }
}
export function MetaPixel() {
- const pixelInitialized = useRef(false);
- const pixelId = buildEnv.NEXT_PUBLIC_META_PIXEL_ID;
- const scriptId = useId();
+ const pixelInitialized = useRef(false);
+ const pixelId = buildEnv.NEXT_PUBLIC_META_PIXEL_ID;
+ const scriptId = useId();
- if (!pixelId) {
- return null;
- }
+ if (!pixelId) {
+ return null;
+ }
- return (
- <>
- <Script
- id={scriptId}
- strategy="afterInteractive"
- src="https://connect.facebook.net/en_US/fbevents.js"
- onLoad={() => {
- if (
- !pixelInitialized.current &&
- typeof window !== "undefined" &&
- window.fbq &&
- pixelId
- ) {
- window.fbq("init", pixelId);
- window.fbq("track", "PageView");
- pixelInitialized.current = true;
- }
- }}
- />
- <noscript>
- <img
- height="1"
- width="1"
- style={{ display: "none" }}
- src={`https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1`}
- alt=""
- />
- </noscript>
- </>
- );
+ if (typeof window !== "undefined" && !window.fbq) {
+ const w = window as unknown as Record<string, any>;
+ const n: any = (...args: unknown[]) => {
+ if (n.callMethod) {
+ n.callMethod.apply(n, args as any);
+ } else {
+ n.queue.push(args);
+ }
+ };
+ if (!w._fbq) w._fbq = n;
+ n.push = n;
+ n.loaded = true;
+ n.version = "2.0";
+ n.queue = [] as unknown[];
+ w.fbq = n as unknown;
+ }
+
+ return (
+ <>
+ <Script
+ id={scriptId}
+ strategy="afterInteractive"
+ src="https://connect.facebook.net/en_US/fbevents.js"
+ onLoad={() => {
+ if (
+ !pixelInitialized.current &&
+ typeof window !== "undefined" &&
+ window.fbq &&
+ pixelId
+ ) {
+ window.fbq("init", pixelId);
+ window.fbq("track", "PageView");
+ pixelInitialized.current = true;
+ }
+ }}
+ />
+ <noscript>
+ <img
+ height="1"
+ width="1"
+ style={{ display: "none" }}
+ src={`https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1`}
+ alt=""
+ />
+ </noscript>
+ </>
+ );
}
export function trackMetaEvent(
- eventName: string,
- parameters?: Record<string, unknown>
+ eventName: string,
+ parameters?: Record<string, unknown>,
+ options?: { eventId?: string },
) {
- if (typeof window !== "undefined" && window.fbq) {
- try {
- window.fbq("track", eventName, parameters);
- } catch (error) {
- console.error(`Error tracking Meta event ${eventName}:`, error);
- }
- }
+ if (typeof window !== "undefined" && window.fbq) {
+ try {
+ if (options?.eventId) {
+ window.fbq("track", eventName, parameters, {
+ eventID: options.eventId,
+ });
+ } else {
+ window.fbq("track", eventName, parameters);
+ }
+ } catch (error) {
+ console.error(`Error tracking Meta event ${eventName}:`, error);
+ }
+ }
}
diff --git a/apps/web/app/Layout/PosthogIdentify.tsx b/apps/web/app/Layout/PosthogIdentify.tsx
index 0997882e0..1eaad3994 100644
--- a/apps/web/app/Layout/PosthogIdentify.tsx
+++ b/apps/web/app/Layout/PosthogIdentify.tsx
@@ -1,6 +1,7 @@
"use client";
import { Suspense, use, useEffect } from "react";
+import { checkAndMarkUserSignedUpTracked } from "@/actions/analytics/track-user-signed-up";
import {
identifyUser,
initAnonymousUser,
@@ -24,17 +25,15 @@ function Inner() {
initAnonymousUser();
return;
} else {
- // Track if this is the first time a user is being identified
- const isNewUser = !localStorage.getItem("user_identified");
-
identifyUser(user.id);
- if (isNewUser) {
- localStorage.setItem("user_identified", "true");
- trackEvent("user_signed_up");
- }
-
- trackEvent("user_signed_in");
+ (async () => {
+ const { shouldTrack } = await checkAndMarkUserSignedUpTracked();
+ if (shouldTrack) {
+ trackEvent("user_signed_up");
+ }
+ trackEvent("user_signed_in");
+ })();
}
}, [user]);
diff --git a/apps/web/app/Layout/PurchaseTracker.tsx b/apps/web/app/Layout/PurchaseTracker.tsx
new file mode 100644
index 000000000..d15e3ed73
--- /dev/null
+++ b/apps/web/app/Layout/PurchaseTracker.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { useCallback, useEffect } from "react";
+import { getPurchaseForMeta } from "@/actions/billing/track-meta-purchase";
+import { trackMetaEvent } from "./MetaPixel";
+
+export function PurchaseTracker() {
+ const params = useSearchParams();
+ const router = useRouter();
+ const pathname = usePathname();
+
+ const shouldCheck = params.get("upgrade") === "true";
+ const sessionId = params.get("session_id");
+
+ const cleanUrl = useCallback(() => {
+ const next = new URLSearchParams(params.toString());
+ next.delete("upgrade");
+ next.delete("guest");
+ next.delete("session_id");
+ const query = next.toString();
+ router.replace(query ? `${pathname}?${query}` : pathname);
+ }, [params, pathname, router]);
+
+ useEffect(() => {
+ if (!shouldCheck) return;
+ let cancelled = false;
+ (async () => {
+ const result = await getPurchaseForMeta({ sessionId });
+ if (cancelled) return;
+ if (
+ result.shouldTrack &&
+ typeof result.value === "number" &&
+ result.currency
+ ) {
+ trackMetaEvent(
+ "Purchase",
+ { value: result.value, currency: result.currency },
+ { eventId: result.eventId },
+ );
+ }
+ cleanUrl();
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [shouldCheck, sessionId, cleanUrl]);
+
+ return null;
+}
diff --git a/apps/web/app/api/settings/billing/guest-checkout/route.ts b/apps/web/app/api/settings/billing/guest-checkout/route.ts
index e848d9e70..f940ec204 100644
--- a/apps/web/app/api/settings/billing/guest-checkout/route.ts
+++ b/apps/web/app/api/settings/billing/guest-checkout/route.ts
@@ -19,7 +19,7 @@ export async function POST(request: NextRequest) {
const checkoutSession = await stripe().checkout.sessions.create({
line_items: [{ price: priceId, quantity: quantity || 1 }],
mode: "subscription",
- success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&guest=true`,
+ success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&guest=true&session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${serverEnv().WEB_URL}/pricing`,
allow_promotion_codes: true,
metadata: {
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.ts
index 50a90e489..78f5d6bcb 100644
--- a/apps/web/app/api/settings/billing/subscribe/route.ts
+++ b/apps/web/app/api/settings/billing/subscribe/route.ts
@@ -66,7 +66,7 @@ export async function POST(request: NextRequest) {
customer: customerId as string,
line_items: [{ price: priceId, quantity: quantity }],
mode: "subscription",
- success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true`,
+ success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${serverEnv().WEB_URL}/pricing`,
allow_promotion_codes: true,
metadata: { platform: "web", dubCustomerId: user.id },
diff --git a/apps/web/app/api/video/ai/route.ts b/apps/web/app/api/video/ai/route.ts
index 915f10545..9639ef50e 100644
--- a/apps/web/app/api/video/ai/route.ts
+++ b/apps/web/app/api/video/ai/route.ts
@@ -2,7 +2,7 @@ import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { users, videos } from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
-import { Video } from "@cap/web-domain";
+import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import type { NextRequest } from "next/server";
import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
diff --git a/apps/web/app/api/video/transcribe/status/route.ts b/apps/web/app/api/video/transcribe/status/route.ts
index d56b65b94..33374a4f6 100644
--- a/apps/web/app/api/video/transcribe/status/route.ts
+++ b/apps/web/app/api/video/transcribe/status/route.ts
@@ -1,7 +1,7 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
-import { Video } from "@cap/web-domain";
+import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import type { NextRequest } from "next/server";
import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index b99fe63b2..9b3198486 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -267,8 +267,8 @@ export const POST = async (req: Request) => {
typeof session.metadata === "object" &&
session.metadata !== null &&
"platform" in session.metadata &&
- typeof (session.metadata as Record<string, unknown>).platform ===
- "string"
+ typeof (session.metadata as Record<string, unknown>)
+ .platform === "string"
? ((session.metadata as Record<string, unknown>)
.platform as string)
: "web",
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index 47b3f10ff..3582bbd4c 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -13,6 +13,7 @@ import { PublicEnvContext } from "@/utils/public-env";
import { AuthContextProvider } from "./Layout/AuthContext";
import { MetaPixel } from "./Layout/MetaPixel";
import { PosthogIdentify } from "./Layout/PosthogIdentify";
+import { PurchaseTracker } from "./Layout/PurchaseTracker";
import {
PostHogProvider,
ReactQueryProvider,
@@ -122,6 +123,7 @@ export default async function RootLayout({ children }: PropsWithChildren) {
<main className="w-full">{children}</main>
<PosthogIdentify />
<MetaPixel />
+ <PurchaseTracker />
</ReactQueryProvider>
</PublicEnvContext>
</SessionProvider>
diff --git a/apps/web/app/utils/analytics.ts b/apps/web/app/utils/analytics.ts
index a5b01d795..727cbaa84 100644
--- a/apps/web/app/utils/analytics.ts
+++ b/apps/web/app/utils/analytics.ts
@@ -43,10 +43,11 @@ export function trackEvent(
}
posthog.capture(eventName, { ...properties, platform: "web" });
-
+
const metaEventMap: Record<string, string> = {
- "purchase_completed": "Purchase",
- "subscription_purchased": "Purchase",
+ purchase_completed: "Purchase",
+ subscription_purchased: "Purchase",
+ user_signed_up: "CompleteRegistration",
};
const metaEventName = metaEventMap[eventName];
diff --git a/apps/web/lib/transcribe.ts b/apps/web/lib/transcribe.ts
index 45a04e678..138f819ae 100644
--- a/apps/web/lib/transcribe.ts
+++ b/apps/web/lib/transcribe.ts
@@ -1,7 +1,7 @@
import { db } from "@cap/database";
import { s3Buckets, videos } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { Video } from "@cap/web-domain";
+import type { Video } from "@cap/web-domain";
import { createClient } from "@deepgram/sdk";
import { eq } from "drizzle-orm";
import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 21afc96f2..8e6f908da 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -72,6 +72,12 @@ export const users = mysqlTable(
pauseViews: boolean;
pauseReactions: boolean;
};
+ // For analytics.
+ // Adding in preferences so we don't have to
+ // add a new column and can be dynamic going forward.
+ trackedEvents?: {
+ user_signed_up?: boolean;
+ };
} | null>()
.default(null),
activeOrganizationId: nanoId("activeOrganizationId"),
@@ -452,7 +458,7 @@ export const sessionsRelations = relations(sessions, ({ one }) => ({
export const verificationTokensRelations = relations(
verificationTokens,
- ({}) => ({
+ () => ({
// No relations defined
}),
);