Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Refactor Singular webhook integration: consolidate event tracking logic, remove deprecated functions, and enhance error handling. Introduce new trackLead and trackSale functions for improved event processing.

Kiran K8171c4514f5f
diff --git a/apps/web/app/(ee)/api/singular/webhook/route.ts b/apps/web/app/(ee)/api/singular/webhook/route.ts
index 6754bedfcc..13883f0764 100644
--- a/apps/web/app/(ee)/api/singular/webhook/route.ts
+++ b/apps/web/app/(ee)/api/singular/webhook/route.ts
@@ -1,61 +1,27 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { getClickEvent } from "@/lib/tinybird";
-import { ClickEventTB } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import { prisma } from "@dub/prisma";
+import { trackSingularLeadEvent } from "@/lib/integrations/singular/track-lead";
+import { trackSingularSaleEvent } from "@/lib/integrations/singular/track-sale";
import { getSearchParams } from "@dub/utils";
import { NextResponse } from "next/server";
-import { z } from "zod";
-import { trackSingularLeadEvent } from "./track-lead-event";
-import { trackSingularSaleEvent } from "./track-sale-event";
-
-const supportedEvents = [
- "sng_complete_registration",
- "sng_subscribe",
- "sng_ecommerce_purchase",
-];
const singularToDubEvent = {
sng_complete_registration: "lead",
sng_subscribe: "sale",
sng_ecommerce_purchase: "sale",
+ "Copy GAID": "lead", // Singular Device Assist
+ "copy IDFA": "lead", // Singular Device Assist
};
-const customEventSchema = z.object({
- dub_id: z.string().min(1),
- event_name: z.string(),
- event_date: z.string().nullable(),
- event_time: z.string().nullable(),
- install_date: z.string().nullable(),
- install_time: z.string().nullable(),
-});
-
-const saleEventSchema = customEventSchema.merge(
- z.object({
- revenue: z.number().nullable(),
- }),
-);
-
-const schema = z.discriminatedUnion("event_name", [
- customEventSchema,
- saleEventSchema,
-]);
+const supportedEvents = Object.keys(singularToDubEvent);
// GET /api/singular/webhook – listen to Postback events from Singular
export const GET = async (req: Request) => {
try {
const searchParams = getSearchParams(req.url);
- console.debug("Parameters", searchParams);
+ console.log("[Singular] Postback received", searchParams);
- const {
- dub_id: clickId,
- event_name: eventName,
- event_date: eventDate,
- event_time: eventTime,
- install_date: installDate,
- install_time: installTime,
- } = schema.parse(searchParams);
+ const { event_name: eventName } = searchParams;
if (!supportedEvents.includes(eventName)) {
throw new DubApiError({
@@ -64,77 +30,20 @@ export const GET = async (req: Request) => {
});
}
- // Find the click event
- let clickData: ClickEventTB | null = null;
- const clickEvent = await getClickEvent({
- clickId,
- });
-
- if (clickEvent && clickEvent.data && clickEvent.data.length > 0) {
- clickData = clickEvent.data[0];
- }
-
- if (!clickData) {
- const cachedClickData = await redis.get<ClickEventTB>(
- `clickIdCache:${clickId}`,
- );
-
- if (cachedClickData) {
- clickData = {
- ...cachedClickData,
- timestamp: cachedClickData.timestamp
- .replace("T", " ")
- .replace("Z", ""),
- qr: cachedClickData.qr ? 1 : 0,
- bot: cachedClickData.bot ? 1 : 0,
- };
- }
- }
-
- if (!clickData) {
- throw new DubApiError({
- code: "not_found",
- message: `Click event not found for clickId: ${clickId}`,
- });
- }
-
- // TODO:
- // How to skip already tracked events
- // How to identify the customer (do they pass the these info via)
-
- // Find the link associated with the click event
- const { link_id: linkId } = clickData;
-
- const link = await prisma.link.findUniqueOrThrow({
- where: {
- id: linkId,
- },
- });
-
- if (!link.projectId) {
- throw new DubApiError({
- code: "not_found",
- message: "Link does not belong to a workspace.",
- });
- }
-
const dubEvent = singularToDubEvent[eventName];
if (dubEvent === "lead") {
- await trackSingularLeadEvent({
- clickData,
- link,
- });
+ await trackSingularLeadEvent(searchParams);
} else if (dubEvent === "sale") {
- await trackSingularSaleEvent({
- clickData,
- link,
+ await trackSingularSaleEvent(searchParams);
+ } else {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Event ${eventName} is not supported by Singular <> Dub integration.`,
});
}
- return NextResponse.json({
- clickId,
- });
+ return NextResponse.json("OK");
} catch (error) {
return handleAndReturnErrorResponse(error);
}
diff --git a/apps/web/app/(ee)/api/singular/webhook/track-lead-event.ts b/apps/web/app/(ee)/api/singular/webhook/track-lead-event.ts
deleted file mode 100644
index 16b31a8602..0000000000
--- a/apps/web/app/(ee)/api/singular/webhook/track-lead-event.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { includeTags } from "@/lib/api/links/include-tags";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
-import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { ClickEventTB } from "@/lib/types";
-import { prisma } from "@dub/prisma";
-import { Link } from "@dub/prisma/client";
-import { nanoid } from "@dub/utils";
-
-export const trackSingularLeadEvent = async ({
- clickData,
- link,
-}: {
- clickData: ClickEventTB;
- link: Link;
-}) => {
- const eventQuantity = 1;
- const eventId = nanoid(16);
- const body = {};
- const customer = {
- id: "xxx",
- };
-
- // TODO:
- // Record lead
- // Send "lead.created" webhook
-
- await Promise.allSettled([
- prisma.link.update({
- where: {
- id: link.id,
- },
- data: {
- leads: {
- increment: eventQuantity,
- },
- },
- include: includeTags,
- }),
-
- prisma.project.update({
- where: {
- id: link.projectId!,
- },
- data: {
- usage: {
- increment: eventQuantity,
- },
- },
- }),
-
- logConversionEvent({
- workspace_id: link.projectId!,
- link_id: link.id,
- path: "/track/lead",
- body: JSON.stringify(body),
- }),
- ]);
-
- if (link.programId && link.partnerId && customer) {
- await createPartnerCommission({
- event: "lead",
- programId: link.programId,
- partnerId: link.partnerId,
- linkId: link.id,
- eventId,
- customerId: customer.id,
- quantity: eventQuantity,
- });
- }
-};
diff --git a/apps/web/app/(ee)/api/singular/webhook/track-sale-event.ts b/apps/web/app/(ee)/api/singular/webhook/track-sale-event.ts
deleted file mode 100644
index b0dd14d94b..0000000000
--- a/apps/web/app/(ee)/api/singular/webhook/track-sale-event.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { includeTags } from "@/lib/api/links/include-tags";
-import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
-import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { ClickEventTB } from "@/lib/types";
-import { prisma } from "@dub/prisma";
-import { Link } from "@dub/prisma/client";
-import { nanoid } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-
-export const trackSingularSaleEvent = async ({
- clickData,
- link,
-}: {
- clickData: ClickEventTB;
- link: Link;
-}) => {
- const eventQuantity = 1;
- const eventId = nanoid(16);
- const body = {};
- const customer = {
- id: "xxx",
- };
- const amount = 100;
-
- // TODO:
- // Record sale
- // Send "sale.created" webhook
- // Notify partner sale
-
- await Promise.allSettled([
- prisma.link.update({
- where: {
- id: link.id,
- },
- data: {
- sales: {
- increment: 1,
- },
- saleAmount: {
- increment: amount,
- },
- },
- include: includeTags,
- }),
-
- prisma.project.update({
- where: {
- id: link.projectId!,
- },
- data: {
- usage: {
- increment: 1,
- },
- },
- }),
-
- prisma.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- sales: {
- increment: 1,
- },
- saleAmount: {
- increment: amount,
- },
- },
- }),
-
- logConversionEvent({
- workspace_id: link.projectId!,
- link_id: link.id,
- path: "/track/sale",
- body: JSON.stringify(body),
- }),
- ]);
-
- if (link.programId && link.partnerId && customer) {
- const commission = await createPartnerCommission({
- event: "sale",
- programId: link.programId,
- partnerId: link.partnerId,
- linkId: link.id,
- eventId,
- customerId: customer.id,
- amount,
- quantity: 1,
- invoiceId: "xxx",
- currency: "usd",
- });
-
- if (commission) {
- waitUntil(
- notifyPartnerSale({
- link,
- commission,
- }),
- );
- }
- }
-};
diff --git a/apps/web/app/(ee)/api/track/lead/route.ts b/apps/web/app/(ee)/api/track/lead/route.ts
index bf2a9882f7..384774b867 100644
--- a/apps/web/app/(ee)/api/track/lead/route.ts
+++ b/apps/web/app/(ee)/api/track/lead/route.ts
@@ -1,25 +1,8 @@
-import { createId } from "@/lib/api/create-id";
+import { trackLead } from "@/lib/api/conversions/track-lead";
import { DubApiError } from "@/lib/api/errors";
-import { includeTags } from "@/lib/api/links/include-tags";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { generateRandomName } from "@/lib/names";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
-import { isStored, storage } from "@/lib/storage";
-import { getClickEvent, recordLead, recordLeadSync } from "@/lib/tinybird";
-import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { ClickEventTB } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
-import { transformLeadEventData } from "@/lib/webhook/transform";
-import {
- trackLeadRequestSchema,
- trackLeadResponseSchema,
-} from "@/lib/zod/schemas/leads";
-import { prisma } from "@dub/prisma";
-import { nanoid, R2_URL } from "@dub/utils";
-import { Customer } from "@prisma/client";
-import { waitUntil } from "@vercel/functions";
+import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -49,15 +32,7 @@ export const POST = withWorkspace(
})
.parse(body);
- const stringifiedEventName = eventName.toLowerCase().replace(" ", "-");
const customerExternalId = newExternalId || oldExternalId || oldCustomerId;
- const customerId = createId({ prefix: "cus_" });
- const finalCustomerName =
- customerName || customerEmail || generateRandomName();
- const finalCustomerAvatar =
- customerAvatar && !isStored(customerAvatar)
- ? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`
- : customerAvatar;
if (!customerExternalId) {
throw new DubApiError({
@@ -66,243 +41,21 @@ export const POST = withWorkspace(
});
}
- // deduplicate lead events – only record 1 unique event for the same customer and event name
- const ok = await redis.set(
- `trackLead:${workspace.id}:${customerExternalId}:${stringifiedEventName}`,
- {
- timestamp: Date.now(),
- clickId,
- eventName,
- customerExternalId,
- customerName,
- customerEmail,
- customerAvatar,
- },
- {
- ex: 60 * 60 * 24 * 7, // cache for 1 week
- nx: true,
- },
- );
-
- if (ok) {
- // Find click event
- let clickData: ClickEventTB | null = null;
- const clickEvent = await getClickEvent({ clickId });
-
- if (clickEvent && clickEvent.data && clickEvent.data.length > 0) {
- clickData = clickEvent.data[0];
- }
-
- if (!clickData) {
- const cachedClickData = await redis.get<ClickEventTB>(
- `clickIdCache:${clickId}`,
- );
-
- if (cachedClickData) {
- clickData = {
- ...cachedClickData,
- timestamp: cachedClickData.timestamp
- .replace("T", " ")
- .replace("Z", ""),
- qr: cachedClickData.qr ? 1 : 0,
- bot: cachedClickData.bot ? 1 : 0,
- };
- }
- }
-
- if (!clickData) {
- throw new DubApiError({
- code: "not_found",
- message: `Click event not found for clickId: ${clickId}`,
- });
- }
-
- const leadEventId = nanoid(16);
-
- // Create a function to handle customer upsert to avoid duplication
- const upsertCustomer = async () => {
- return prisma.customer.upsert({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId: customerExternalId,
- },
- },
- create: {
- id: customerId,
- name: finalCustomerName,
- email: customerEmail,
- avatar: finalCustomerAvatar,
- externalId: customerExternalId,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- clickId: clickData.click_id,
- linkId: clickData.link_id,
- country: clickData.country,
- clickedAt: new Date(clickData.timestamp + "Z"),
- },
- update: {}, // no updates needed if the customer exists
- });
- };
-
- // Create a function to prepare the lead event payload
- const createLeadEventPayload = (customerId: string) => {
- const basePayload = {
- ...clickData,
- event_id: leadEventId,
- event_name: eventName,
- customer_id: customerId,
- metadata: metadata ? JSON.stringify(metadata) : "",
- };
-
- return eventQuantity
- ? Array(eventQuantity)
- .fill(null)
- .map(() => ({
- ...basePayload,
- event_id: nanoid(16),
- }))
- : basePayload;
- };
-
- let customer: Customer | undefined;
-
- // Handle customer creation and lead recording based on mode
- if (mode === "wait") {
- // Execute customer creation synchronously
- customer = await upsertCustomer();
-
- const leadEventPayload = createLeadEventPayload(customer.id);
- const cacheLeadEventPayload = Array.isArray(leadEventPayload)
- ? leadEventPayload[0]
- : leadEventPayload;
-
- await Promise.all([
- // Use recordLeadSync which waits for the operation to complete
- recordLeadSync(leadEventPayload),
-
- // Cache the latest lead event for 5 minutes because the ingested event is not available immediately on Tinybird
- // we're setting two keys because we want to support the use case where the customer has multiple lead events
- redis.set(`leadCache:${customer.id}`, cacheLeadEventPayload, {
- ex: 60 * 5,
- }),
- redis.set(
- `leadCache:${customer.id}:${stringifiedEventName}`,
- cacheLeadEventPayload,
- {
- ex: 60 * 5,
- },
- ),
- ]);
- }
-
- waitUntil(
- (async () => {
- // For async mode, create customer in the background
- if (mode === "async") {
- customer = await upsertCustomer();
-
- // Use recordLead which doesn't wait
- await recordLead(createLeadEventPayload(customer.id));
- }
-
- // Always process link/project updates, partner rewards, and webhooks in the background
- const [link, _project] = await Promise.all([
- // update link leads count
- prisma.link.update({
- where: {
- id: clickData.link_id,
- },
- data: {
- leads: {
- increment: eventQuantity ?? 1,
- },
- },
- include: includeTags,
- }),
-
- // update workspace usage
- prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- usage: {
- increment: eventQuantity ?? 1,
- },
- },
- }),
-
- logConversionEvent({
- workspace_id: workspace.id,
- link_id: clickData.link_id,
- path: "/track/lead",
- body: JSON.stringify(body),
- }),
- ]);
-
- if (link.programId && link.partnerId && customer) {
- await createPartnerCommission({
- event: "lead",
- programId: link.programId,
- partnerId: link.partnerId,
- linkId: link.id,
- eventId: leadEventId,
- customerId: customer.id,
- quantity: eventQuantity ?? 1,
- });
- }
-
- if (
- customerAvatar &&
- !isStored(customerAvatar) &&
- finalCustomerAvatar
- ) {
- // persist customer avatar to R2
- await storage.upload(
- finalCustomerAvatar.replace(`${R2_URL}/`, ""),
- customerAvatar,
- {
- width: 128,
- height: 128,
- },
- );
- }
-
- await sendWorkspaceWebhook({
- trigger: "lead.created",
- data: transformLeadEventData({
- ...clickData,
- eventName,
- link,
- customer,
- }),
- workspace,
- });
- })(),
- );
- }
-
- const lead = trackLeadResponseSchema.parse({
- click: {
- id: clickId,
- },
- customer: {
- name: finalCustomerName,
- email: customerEmail,
- avatar: finalCustomerAvatar,
- externalId: customerExternalId,
- },
- });
-
- return NextResponse.json({
- ...lead,
- // for backwards compatibility – will remove soon
+ const response = await trackLead({
clickId,
- customerName: finalCustomerName,
- customerEmail: customerEmail,
- customerAvatar: finalCustomerAvatar,
+ eventName,
+ customerEmail,
+ customerAvatar,
+ customerExternalId,
+ customerName,
+ eventQuantity,
+ metadata,
+ mode,
+ workspace,
+ rawBody: body,
});
+
+ return NextResponse.json(response);
},
{
requiredPlan: [
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
new file mode 100644
index 0000000000..2208849c59
--- /dev/null
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -0,0 +1,288 @@
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { includeTags } from "@/lib/api/links/include-tags";
+import { generateRandomName } from "@/lib/names";
+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { isStored, storage } from "@/lib/storage";
+import { getClickEvent, recordLead, recordLeadSync } from "@/lib/tinybird";
+import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
+import { ClickEventTB, WorkspaceProps } from "@/lib/types";
+import { redis } from "@/lib/upstash";
+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
+import { transformLeadEventData } from "@/lib/webhook/transform";
+import {
+ trackLeadRequestSchema,
+ trackLeadResponseSchema,
+} from "@/lib/zod/schemas/leads";
+import { prisma } from "@dub/prisma";
+import { nanoid, R2_URL } from "@dub/utils";
+import { Customer } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { z } from "zod";
+
+type TrackLeadParams = z.input<typeof trackLeadRequestSchema> & {
+ rawBody: any;
+ workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
+};
+
+export const trackLead = async ({
+ clickId,
+ eventName,
+ eventQuantity,
+ customerExternalId,
+ customerName,
+ customerEmail,
+ customerAvatar,
+ metadata,
+ mode,
+ rawBody, // log this in TinyBird
+ workspace,
+}: TrackLeadParams) => {
+ const stringifiedEventName = eventName.toLowerCase().replace(" ", "-");
+
+ // deduplicate lead events – only record 1 unique event for the same customer and event name
+ const ok = await redis.set(
+ `trackLead:${workspace.id}:${customerExternalId}:${stringifiedEventName}`,
+ {
+ timestamp: Date.now(),
+ clickId,
+ eventName,
+ customerExternalId,
+ customerName,
+ customerEmail,
+ customerAvatar,
+ },
+ {
+ ex: 60 * 60 * 24 * 7, // cache for 1 week
+ nx: true,
+ },
+ );
+
+ const customerId = createId({ prefix: "cus_" });
+ const finalCustomerName =
+ customerName || customerEmail || generateRandomName();
+ const finalCustomerAvatar =
+ customerAvatar && !isStored(customerAvatar)
+ ? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`
+ : customerAvatar;
+
+ if (ok) {
+ // Find click event
+ let clickData: ClickEventTB | null = null;
+ const clickEvent = await getClickEvent({ clickId });
+
+ if (clickEvent && clickEvent.data && clickEvent.data.length > 0) {
+ clickData = clickEvent.data[0];
+ }
+
+ if (!clickData) {
+ const cachedClickData = await redis.get<ClickEventTB>(
+ `clickIdCache:${clickId}`,
+ );
+
+ if (cachedClickData) {
+ clickData = {
+ ...cachedClickData,
+ timestamp: cachedClickData.timestamp
+ .replace("T", " ")
+ .replace("Z", ""),
+ qr: cachedClickData.qr ? 1 : 0,
+ bot: cachedClickData.bot ? 1 : 0,
+ };
+ }
+ }
+
+ if (!clickData) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Click event not found for clickId: ${clickId}`,
+ });
+ }
+
+ const leadEventId = nanoid(16);
+
+ // Create a function to handle customer upsert to avoid duplication
+ const upsertCustomer = async () => {
+ return prisma.customer.upsert({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: customerExternalId,
+ },
+ },
+ create: {
+ id: customerId,
+ name: finalCustomerName,
+ email: customerEmail,
+ avatar: finalCustomerAvatar,
+ externalId: customerExternalId,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ clickId: clickData.click_id,
+ linkId: clickData.link_id,
+ country: clickData.country,
+ clickedAt: new Date(clickData.timestamp + "Z"),
+ },
+ update: {}, // no updates needed if the customer exists
+ });
+ };
+
+ // Create a function to prepare the lead event payload
+ const createLeadEventPayload = (customerId: string) => {
+ const basePayload = {
+ ...clickData,
+ event_id: leadEventId,
+ event_name: eventName,
+ customer_id: customerId,
+ metadata: metadata ? JSON.stringify(metadata) : "",
+ };
+
+ return eventQuantity
+ ? Array(eventQuantity)
+ .fill(null)
+ .map(() => ({
+ ...basePayload,
+ event_id: nanoid(16),
+ }))
+ : basePayload;
+ };
+
+ let customer: Customer | undefined;
+
+ // Handle customer creation and lead recording based on mode
+ if (mode === "wait") {
+ // Execute customer creation synchronously
+ customer = await upsertCustomer();
+
+ const leadEventPayload = createLeadEventPayload(customer.id);
+ const cacheLeadEventPayload = Array.isArray(leadEventPayload)
+ ? leadEventPayload[0]
+ : leadEventPayload;
+
+ await Promise.all([
+ // Use recordLeadSync which waits for the operation to complete
+ recordLeadSync(leadEventPayload),
+
+ // Cache the latest lead event for 5 minutes because the ingested event is not available immediately on Tinybird
+ // we're setting two keys because we want to support the use case where the customer has multiple lead events
+ redis.set(`leadCache:${customer.id}`, cacheLeadEventPayload, {
+ ex: 60 * 5,
+ }),
+ redis.set(
+ `leadCache:${customer.id}:${stringifiedEventName}`,
+ cacheLeadEventPayload,
+ {
+ ex: 60 * 5,
+ },
+ ),
+ ]);
+ }
+
+ waitUntil(
+ (async () => {
+ // For async mode, create customer in the background
+ if (mode === "async") {
+ customer = await upsertCustomer();
+
+ // Use recordLead which doesn't wait
+ await recordLead(createLeadEventPayload(customer.id));
+ }
+
+ // Always process link/project updates, partner rewards, and webhooks in the background
+ const [link, _project] = await Promise.all([
+ // update link leads count
+ prisma.link.update({
+ where: {
+ id: clickData.link_id,
+ },
+ data: {
+ leads: {
+ increment: eventQuantity ?? 1,
+ },
+ },
+ include: includeTags,
+ }),
+
+ // update workspace usage
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage: {
+ increment: eventQuantity ?? 1,
+ },
+ },
+ }),
+
+ logConversionEvent({
+ workspace_id: workspace.id,
+ link_id: clickData.link_id,
+ path: "/track/lead",
+ body: JSON.stringify(rawBody),
+ }),
+ ]);
+
+ if (link.programId && link.partnerId && customer) {
+ await createPartnerCommission({
+ event: "lead",
+ programId: link.programId,
+ partnerId: link.partnerId,
+ linkId: link.id,
+ eventId: leadEventId,
+ customerId: customer.id,
+ quantity: eventQuantity ?? 1,
+ });
+ }
+
+ if (
+ customerAvatar &&
+ !isStored(customerAvatar) &&
+ finalCustomerAvatar
+ ) {
+ // persist customer avatar to R2
+ await storage.upload(
+ finalCustomerAvatar.replace(`${R2_URL}/`, ""),
+ customerAvatar,
+ {
+ width: 128,
+ height: 128,
+ },
+ );
+ }
+
+ await sendWorkspaceWebhook({
+ trigger: "lead.created",
+ data: transformLeadEventData({
+ ...clickData,
+ eventName,
+ link,
+ customer,
+ }),
+ workspace,
+ });
+ })(),
+ );
+ }
+
+ const lead = trackLeadResponseSchema.parse({
+ click: {
+ id: clickId,
+ },
+ customer: {
+ name: finalCustomerName,
+ email: customerEmail,
+ avatar: finalCustomerAvatar,
+ externalId: customerExternalId,
+ },
+ });
+
+ return {
+ ...lead,
+ // for backwards compatibility – will remove soon
+ clickId,
+ customerName: finalCustomerName,
+ customerEmail: customerEmail,
+ customerAvatar: finalCustomerAvatar,
+ };
+};
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/lib/integrations/singular/track-lead.ts b/apps/web/lib/integrations/singular/track-lead.ts
new file mode 100644
index 0000000000..38c0f6a62a
--- /dev/null
+++ b/apps/web/lib/integrations/singular/track-lead.ts
@@ -0,0 +1,74 @@
+import { trackLead } from "@/lib/api/conversions/track-lead";
+import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+
+const singularLeadEventSchema = z.object({
+ dub_id: z.string().min(1),
+ event_name: z.string().min(1),
+ event_attributes: z
+ .string()
+ .transform((val) => {
+ try {
+ return JSON.parse(val);
+ } catch {
+ throw new Error("Invalid JSON in event_attributes");
+ }
+ })
+ .pipe(
+ z.object({
+ customer_external_id: trackLeadRequestSchema.shape.customerExternalId,
+ customer_name: trackLeadRequestSchema.shape.customerName,
+ customer_email: trackLeadRequestSchema.shape.customerEmail,
+ customer_avatar: trackLeadRequestSchema.shape.customerAvatar,
+ event_quantity: trackLeadRequestSchema.shape.eventQuantity,
+ mode: trackLeadRequestSchema.shape.mode,
+ }),
+ ),
+});
+
+export const trackSingularLeadEvent = async (
+ searchParams: Record<string, string>,
+) => {
+ console.log("[Singular] Lead event received", searchParams);
+
+ const {
+ dub_id: clickId,
+ event_name: eventName,
+ event_attributes: {
+ customer_external_id: customerExternalId,
+ customer_name: customerName,
+ customer_email: customerEmail,
+ customer_avatar: customerAvatar,
+ event_quantity: eventQuantity,
+ mode,
+ },
+ } = singularLeadEventSchema.parse(searchParams);
+
+ // TODO: Fix this
+ const workspaceId = "clrei1gld0002vs9mzn93p8ik";
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: workspaceId,
+ },
+ select: {
+ id: true,
+ stripeConnectId: true,
+ webhookEnabled: true,
+ },
+ });
+
+ return await trackLead({
+ clickId,
+ eventName,
+ customerEmail,
+ customerAvatar,
+ customerExternalId,
+ customerName,
+ eventQuantity,
+ mode,
+ workspace,
+ rawBody: searchParams,
+ });
+};
diff --git a/apps/web/lib/integrations/singular/track-sale.ts b/apps/web/lib/integrations/singular/track-sale.ts
new file mode 100644
index 0000000000..ff19f02ad3
--- /dev/null
+++ b/apps/web/lib/integrations/singular/track-sale.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+
+const singularRevenueEventSchema = z.object({
+ event_name: z.string().min(1),
+ revenue: z.number(),
+});
+
+export const trackSingularSaleEvent = async (
+ searchParams: Record<string, string>,
+) => {
+ console.log("[Singular] Revenue event received", searchParams);
+
+ const { event_name: eventName, revenue } =
+ singularRevenueEventSchema.parse(searchParams);
+};