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.

Update error messages for customer external ID validation and implement trackSale function for sale event processing. Refactor sale tracking logic in Singular integration to enhance clarity and maintainability.

Kiran Kcda2537aa29a
diff --git a/apps/web/app/(ee)/api/track/lead/route.ts b/apps/web/app/(ee)/api/track/lead/route.ts
index 384774b867..d0b32aee64 100644
--- a/apps/web/app/(ee)/api/track/lead/route.ts
+++ b/apps/web/app/(ee)/api/track/lead/route.ts
@@ -37,7 +37,7 @@ export const POST = withWorkspace(
if (!customerExternalId) {
throw new DubApiError({
code: "bad_request",
- message: "externalId is required",
+ message: "customerExternalId is required",
});
}
diff --git a/apps/web/app/(ee)/api/track/sale/route.ts b/apps/web/app/(ee)/api/track/sale/route.ts
index 02602deb05..da5d814e6f 100644
--- a/apps/web/app/(ee)/api/track/sale/route.ts
+++ b/apps/web/app/(ee)/api/track/sale/route.ts
@@ -1,24 +1,8 @@
-import { convertCurrency } from "@/lib/analytics/convert-currency";
+import { trackSale } from "@/lib/api/conversions/track-sale";
import { DubApiError } from "@/lib/api/errors";
-import { includeTags } from "@/lib/api/links/include-tags";
-import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
-import { getLeadEvent, recordSale } from "@/lib/tinybird";
-import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
-import { LeadEventTB } from "@/lib/types";
-import { redis } from "@/lib/upstash";
-import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
-import { transformSaleEventData } from "@/lib/webhook/transform";
-import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
-import {
- trackSaleRequestSchema,
- trackSaleResponseSchema,
-} from "@/lib/zod/schemas/sales";
-import { prisma } from "@dub/prisma";
-import { nanoid } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
+import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -47,231 +31,29 @@ export const POST = withWorkspace(
})
.parse(body);
- if (invoiceId) {
- // Skip if invoice id is already processed
- const ok = await redis.set(`dub_sale_events:invoiceId:${invoiceId}`, 1, {
- ex: 60 * 60 * 24 * 7,
- nx: true,
- });
-
- if (!ok) {
- return NextResponse.json({
- eventName,
- customer: null,
- sale: null,
- });
- }
- }
-
const customerExternalId = newExternalId || oldExternalId || oldCustomerId;
if (!customerExternalId) {
throw new DubApiError({
code: "bad_request",
- message: "externalId is required",
- });
- }
-
- // Find customer
- const customer = await prisma.customer.findUnique({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId: customerExternalId,
- },
- },
- });
-
- if (!customer) {
- waitUntil(
- logConversionEvent({
- workspace_id: workspace.id,
- path: "/track/sale",
- body: JSON.stringify(body),
- error: `Customer not found for externalId: ${customerExternalId}`,
- }),
- );
-
- return NextResponse.json({
- eventName,
- customer: null,
- sale: null,
+ message: "customerExternalId is required",
});
}
- // Find lead event
- const leadEvent = await getLeadEvent({
- customerId: customer.id,
- eventName: leadEventName,
- });
-
- let leadEventData: LeadEventTB | null = null;
-
- if (!leadEvent || leadEvent.data.length === 0) {
- // Check cache to see if the lead event exists
- // if leadEventName is provided, we only check for that specific event
- // otherwise, we check for all cached lead events for that customer
-
- const cachedLeadEvent = await redis.get<LeadEventTB>(
- `leadCache:${customer.id}${leadEventName ? `:${leadEventName.toLowerCase().replace(" ", "-")}` : ""}`,
- );
-
- if (!cachedLeadEvent) {
- throw new DubApiError({
- code: "not_found",
- message: `Lead event not found for externalId: ${customerExternalId} and eventName: ${leadEventName}`,
- });
- }
-
- leadEventData = cachedLeadEvent;
- } else {
- leadEventData = leadEvent.data[0];
- }
-
- const clickData = clickEventSchemaTB
- .omit({ timestamp: true })
- .parse(leadEventData);
-
- // if currency is not USD, convert it to USD based on the current FX rate
- // TODO: allow custom "defaultCurrency" on workspace table in the future
- if (currency !== "usd") {
- const { currency: convertedCurrency, amount: convertedAmount } =
- await convertCurrency({ currency, amount });
-
- currency = convertedCurrency;
- amount = convertedAmount;
- }
-
- const eventId = nanoid(16);
-
- const saleData = {
- ...clickData,
- event_id: eventId,
- event_name: eventName,
- customer_id: customer.id,
- payment_processor: paymentProcessor,
+ const response = await trackSale({
+ customerExternalId,
amount,
currency,
- invoice_id: invoiceId || "",
- metadata: metadata ? JSON.stringify(metadata) : "",
- };
-
- waitUntil(
- (async () => {
- const [_sale, link] = await Promise.all([
- recordSale(saleData),
-
- // update link sales count
- prisma.link.update({
- where: {
- id: clickData.link_id,
- },
- data: {
- sales: {
- increment: 1,
- },
- saleAmount: {
- increment: amount,
- },
- },
- include: includeTags,
- }),
- // update workspace sales usage
- prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- usage: {
- increment: 1,
- },
- },
- }),
- // update customer sales count
- prisma.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- sales: {
- increment: 1,
- },
- saleAmount: {
- increment: amount,
- },
- },
- }),
-
- logConversionEvent({
- workspace_id: workspace.id,
- link_id: clickData.link_id,
- path: "/track/sale",
- body: JSON.stringify(body),
- }),
- ]);
-
- // for program links
- if (link.programId && link.partnerId) {
- const commission = await createPartnerCommission({
- event: "sale",
- programId: link.programId,
- partnerId: link.partnerId,
- linkId: link.id,
- eventId,
- customerId: customer.id,
- amount: saleData.amount,
- quantity: 1,
- invoiceId,
- currency,
- });
-
- if (commission) {
- waitUntil(
- notifyPartnerSale({
- link,
- commission,
- }),
- );
- }
- }
-
- // Send workspace webhook
- const sale = transformSaleEventData({
- ...saleData,
- clickedAt: customer.clickedAt || customer.createdAt,
- link,
- customer,
- });
-
- await sendWorkspaceWebhook({
- trigger: "sale.created",
- data: sale,
- workspace,
- });
- })(),
- );
-
- const sale = trackSaleResponseSchema.parse({
eventName,
- customer,
- sale: {
- amount,
- currency,
- invoiceId,
- paymentProcessor,
- metadata,
- },
- });
-
- return NextResponse.json({
- ...sale,
- // for backwards compatibility – will remove soon
- amount,
- currency,
- invoiceId,
paymentProcessor,
+ invoiceId,
+ leadEventName,
metadata,
+ 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
index 2208849c59..218f5fac6f 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -35,7 +35,7 @@ export const trackLead = async ({
customerAvatar,
metadata,
mode,
- rawBody, // log this in TinyBird
+ rawBody,
workspace,
}: TrackLeadParams) => {
const stringifiedEventName = eventName.toLowerCase().replace(" ", "-");
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index e69de29bb2..00b7d02cd6 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -0,0 +1,260 @@
+import { convertCurrency } from "@/lib/analytics/convert-currency";
+import { DubApiError } from "@/lib/api/errors";
+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 { getLeadEvent, recordSale } from "@/lib/tinybird";
+import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
+import { LeadEventTB, WorkspaceProps } from "@/lib/types";
+import { redis } from "@/lib/upstash";
+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
+import { transformSaleEventData } from "@/lib/webhook/transform";
+import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
+import {
+ trackSaleRequestSchema,
+ trackSaleResponseSchema,
+} from "@/lib/zod/schemas/sales";
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { z } from "zod";
+
+type TrackSaleParams = z.input<typeof trackSaleRequestSchema> & {
+ rawBody: any;
+ workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
+};
+
+export const trackSale = async ({
+ customerExternalId,
+ amount,
+ currency = "usd",
+ eventName,
+ paymentProcessor,
+ invoiceId,
+ leadEventName,
+ metadata,
+ rawBody,
+ workspace,
+}: TrackSaleParams) => {
+ if (invoiceId) {
+ // Skip if invoice id is already processed
+ const ok = await redis.set(`dub_sale_events:invoiceId:${invoiceId}`, 1, {
+ ex: 60 * 60 * 24 * 7,
+ nx: true,
+ });
+
+ if (!ok) {
+ return {
+ eventName,
+ customer: null,
+ sale: null,
+ };
+ }
+ }
+
+ // Find customer
+ const customer = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ if (!customer) {
+ waitUntil(
+ logConversionEvent({
+ workspace_id: workspace.id,
+ path: "/track/sale",
+ body: JSON.stringify(rawBody),
+ error: `Customer not found for externalId: ${customerExternalId}`,
+ }),
+ );
+
+ return {
+ eventName,
+ customer: null,
+ sale: null,
+ };
+ }
+
+ // Find lead event
+ const leadEvent = await getLeadEvent({
+ customerId: customer.id,
+ eventName: leadEventName,
+ });
+
+ let leadEventData: LeadEventTB | null = null;
+
+ if (!leadEvent || leadEvent.data.length === 0) {
+ // Check cache to see if the lead event exists
+ // if leadEventName is provided, we only check for that specific event
+ // otherwise, we check for all cached lead events for that customer
+
+ const cachedLeadEvent = await redis.get<LeadEventTB>(
+ `leadCache:${customer.id}${leadEventName ? `:${leadEventName.toLowerCase().replace(" ", "-")}` : ""}`,
+ );
+
+ if (!cachedLeadEvent) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Lead event not found for externalId: ${customerExternalId} and eventName: ${leadEventName}`,
+ });
+ }
+
+ leadEventData = cachedLeadEvent;
+ } else {
+ leadEventData = leadEvent.data[0];
+ }
+
+ const clickData = clickEventSchemaTB
+ .omit({ timestamp: true })
+ .parse(leadEventData);
+
+ // if currency is not USD, convert it to USD based on the current FX rate
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ if (currency !== "usd") {
+ const { currency: convertedCurrency, amount: convertedAmount } =
+ await convertCurrency({
+ currency,
+ amount,
+ });
+
+ currency = convertedCurrency;
+ amount = convertedAmount;
+ }
+
+ const eventId = nanoid(16);
+
+ const saleData = {
+ ...clickData,
+ event_id: eventId,
+ event_name: eventName,
+ customer_id: customer.id,
+ payment_processor: paymentProcessor,
+ amount,
+ currency,
+ invoice_id: invoiceId || "",
+ metadata: metadata ? JSON.stringify(metadata) : "",
+ };
+
+ waitUntil(
+ (async () => {
+ const [_sale, link] = await Promise.all([
+ recordSale(saleData),
+
+ // update link sales count
+ prisma.link.update({
+ where: {
+ id: clickData.link_id,
+ },
+ data: {
+ sales: {
+ increment: 1,
+ },
+ saleAmount: {
+ increment: amount,
+ },
+ },
+ include: includeTags,
+ }),
+
+ // update workspace sales usage
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage: {
+ increment: 1,
+ },
+ },
+ }),
+
+ // update customer sales count
+ prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ sales: {
+ increment: 1,
+ },
+ saleAmount: {
+ increment: amount,
+ },
+ },
+ }),
+
+ logConversionEvent({
+ workspace_id: workspace.id,
+ link_id: clickData.link_id,
+ path: "/track/sale",
+ body: JSON.stringify(rawBody),
+ }),
+ ]);
+
+ // for program links
+ if (link.programId && link.partnerId) {
+ const commission = await createPartnerCommission({
+ event: "sale",
+ programId: link.programId,
+ partnerId: link.partnerId,
+ linkId: link.id,
+ eventId,
+ customerId: customer.id,
+ amount: saleData.amount,
+ quantity: 1,
+ invoiceId,
+ currency,
+ });
+
+ if (commission) {
+ waitUntil(
+ notifyPartnerSale({
+ link,
+ commission,
+ }),
+ );
+ }
+ }
+
+ // Send workspace webhook
+ const sale = transformSaleEventData({
+ ...saleData,
+ clickedAt: customer.clickedAt || customer.createdAt,
+ link,
+ customer,
+ });
+
+ await sendWorkspaceWebhook({
+ trigger: "sale.created",
+ data: sale,
+ workspace,
+ });
+ })(),
+ );
+
+ const sale = trackSaleResponseSchema.parse({
+ eventName,
+ customer,
+ sale: {
+ amount,
+ currency,
+ invoiceId,
+ paymentProcessor,
+ metadata,
+ },
+ });
+
+ return {
+ ...sale,
+ // for backwards compatibility – will remove soon
+ amount,
+ currency,
+ invoiceId,
+ paymentProcessor,
+ metadata,
+ };
+};
diff --git a/apps/web/lib/integrations/singular/track-sale.ts b/apps/web/lib/integrations/singular/track-sale.ts
index ff19f02ad3..e7e78e3e92 100644
--- a/apps/web/lib/integrations/singular/track-sale.ts
+++ b/apps/web/lib/integrations/singular/track-sale.ts
@@ -1,8 +1,30 @@
+import { trackSale } from "@/lib/api/conversions/track-sale";
+import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";
+import { prisma } from "@dub/prisma";
import { z } from "zod";
const singularRevenueEventSchema = z.object({
event_name: z.string().min(1),
revenue: z.number(),
+ 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: trackSaleRequestSchema.shape.customerExternalId,
+ amount: trackSaleRequestSchema.shape.amount,
+ currency: trackSaleRequestSchema.shape.currency,
+ payment_processor: trackSaleRequestSchema.shape.paymentProcessor,
+ invoice_id: trackSaleRequestSchema.shape.invoiceId,
+ lead_event_name: trackSaleRequestSchema.shape.leadEventName,
+ }),
+ ),
});
export const trackSingularSaleEvent = async (
@@ -10,6 +32,42 @@ export const trackSingularSaleEvent = async (
) => {
console.log("[Singular] Revenue event received", searchParams);
- const { event_name: eventName, revenue } =
- singularRevenueEventSchema.parse(searchParams);
+ const {
+ revenue,
+ event_name: eventName,
+ event_attributes: {
+ customer_external_id: customerExternalId,
+ amount,
+ currency,
+ payment_processor: paymentProcessor,
+ invoice_id: invoiceId,
+ lead_event_name: leadEventName,
+ },
+ } = singularRevenueEventSchema.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 trackSale({
+ customerExternalId,
+ amount,
+ currency,
+ eventName,
+ paymentProcessor,
+ invoiceId,
+ leadEventName,
+ workspace,
+ rawBody: searchParams,
+ });
};