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.

Add tests for `/track/lead` and `/track/sale` endpoints

Kiran K09fab629d194
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 6b27e202aa..bee3fe5ad3 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -8,7 +8,10 @@ import { ratelimit } from "@/lib/upstash";
import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
-import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";
+import {
+ trackLeadRequestSchema,
+ trackLeadResponseSchema,
+} from "@/lib/zod/schemas/leads";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -74,9 +77,9 @@ export const POST = withWorkspaceEdge(
projectConnectId: workspace.stripeConnectId,
},
update: {
- name: finalCustomerName,
- email: customerEmail,
- avatar: customerAvatar,
+ ...(customerName ? { name: customerName } : undefined),
+ ...(customerEmail ? { email: customerEmail } : undefined),
+ ...(customerAvatar ? { avatar: customerAvatar } : undefined),
},
});
@@ -147,7 +150,7 @@ export const POST = withWorkspaceEdge(
})(),
);
- return NextResponse.json({
+ const lead = trackLeadResponseSchema.parse({
click: {
id: clickId,
},
@@ -157,6 +160,11 @@ export const POST = withWorkspaceEdge(
email: customer.email,
avatar: customer.avatar,
},
+ });
+
+ return NextResponse.json({
+ ...lead,
+
// for backwards compatibility – will remove soon
clickId,
customerId: customer.externalId,
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index a8c714f861..f77a213272 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -6,7 +6,10 @@ import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
-import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";
+import {
+ trackSaleRequestSchema,
+ trackSaleResponseSchema,
+} from "@/lib/zod/schemas/sales";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -49,7 +52,7 @@ export const POST = withWorkspaceEdge(
if (!leadEvent || leadEvent.data.length === 0) {
throw new DubApiError({
code: "not_found",
- message: `Lead event not found for customerId: ${customer.id}`,
+ message: `Lead event not found for customerId: ${externalId}`,
});
}
@@ -123,7 +126,7 @@ export const POST = withWorkspaceEdge(
})(),
);
- return NextResponse.json({
+ const sale = trackSaleResponseSchema.parse({
eventName,
customer: {
id: customer.externalId,
@@ -138,6 +141,11 @@ export const POST = withWorkspaceEdge(
paymentProcessor,
metadata,
},
+ });
+
+ return NextResponse.json({
+ ...sale,
+
// for backwards compatibility – will remove soon
customerId: externalId,
amount,
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index ec74bad187..c74fe8dc91 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -3,9 +3,12 @@ import { metaTagsSchema } from "@/lib/zod/schemas/metatags";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
import { Link, Project, Webhook } from "@prisma/client";
import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";
+import { trackCustomerResponseSchema } from "./zod/schemas/customers";
import { integrationSchema } from "./zod/schemas/integration";
+import { trackLeadResponseSchema } from "./zod/schemas/leads";
import { createLinkBodySchema } from "./zod/schemas/links";
import { createOAuthAppSchema, oAuthAppSchema } from "./zod/schemas/oauth";
+import { trackSaleResponseSchema } from "./zod/schemas/sales";
import { tokenSchema } from "./zod/schemas/token";
import {
createWebhookSchema,
@@ -258,3 +261,9 @@ export type WebhookCacheProps = Pick<
Webhook,
"id" | "url" | "secret" | "triggers"
>;
+
+export type TrackCustomerResponse = z.infer<typeof trackCustomerResponseSchema>;
+
+export type TrackLeadResponse = z.infer<typeof trackLeadResponseSchema>;
+
+export type TrackSaleResponse = z.infer<typeof trackSaleResponseSchema>;
diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.ts
index 35d6e9a523..c66c086655 100644
--- a/apps/web/lib/zod/schemas/leads.ts
+++ b/apps/web/lib/zod/schemas/leads.ts
@@ -55,9 +55,9 @@ export const trackLeadResponseSchema = z.object({
}),
customer: z.object({
id: z.string(),
- name: z.string(),
- email: z.string(),
- avatar: z.string(),
+ name: z.string().nullable(),
+ email: z.string().nullable(),
+ avatar: z.string().nullable(),
}),
});
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index 3401a9236e..83a8d487a0 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -50,16 +50,16 @@ export const trackSaleResponseSchema = z.object({
eventName: z.string(),
customer: z.object({
id: z.string(),
- name: z.string(),
- email: z.string(),
- avatar: z.string(),
+ name: z.string().nullable(),
+ email: z.string().nullable(),
+ avatar: z.string().nullable(),
}),
sale: z.object({
amount: z.number(),
currency: z.string(),
- invoiceId: z.string().nullable(),
paymentProcessor: z.string(),
- metadata: z.record(z.unknown()),
+ invoiceId: z.string().nullable(),
+ metadata: z.record(z.unknown()).nullable(),
}),
});
diff --git a/apps/web/tests/tracks/create-customer.test.ts b/apps/web/tests/tracks/create-customer.test.ts
deleted file mode 100644
index 77480c87a1..0000000000
--- a/apps/web/tests/tracks/create-customer.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { trackCustomerResponseSchema } from "@/lib/zod/schemas/customers";
-import { nanoid } from "@dub/utils";
-import { Tag } from "@prisma/client";
-import { describe, expect, test } from "vitest";
-import { IntegrationHarness } from "../utils/integration";
-
-describe.skip("POST /track/customer", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- test("with required params", async () => {
- const customer = {
- customerId: nanoid(16),
- };
-
- const response = await http.post<Tag>({
- path: "/track/customer",
- body: {
- customerId: customer.customerId,
- },
- });
-
- const parsed = trackCustomerResponseSchema.safeParse(response.data);
-
- expect(parsed.success).toBe(true);
- expect(response.status).toEqual(201);
- expect(response.data).toStrictEqual({
- customerId: customer.customerId,
- customerName: null,
- customerEmail: null,
- customerAvatar: null,
- });
- });
-
- test("with all params", async () => {
- const customer = {
- customerId: nanoid(16),
- customerName: "David",
- customerEmail: "[email protected]",
- customerAvatar: "https://example.com/david.jpeg",
- };
-
- const response = await http.post<Tag>({
- path: "/track/customer",
- body: customer,
- });
-
- const parsed = trackCustomerResponseSchema.safeParse(response.data);
-
- expect(parsed.success).toBe(true);
- expect(response.status).toEqual(201);
- expect(response.data).toStrictEqual(customer);
- });
-});
diff --git a/apps/web/tests/tracks/create-lead.test.ts b/apps/web/tests/tracks/create-lead.test.ts
deleted file mode 100644
index c7772eced6..0000000000
--- a/apps/web/tests/tracks/create-lead.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { trackLeadResponseSchema } from "@/lib/zod/schemas/leads";
-import { Tag } from "@prisma/client";
-import { describe, expect, test } from "vitest";
-import { IntegrationHarness } from "../utils/integration";
-
-const customer = {
- customerId: "david",
- customerName: "David",
- customerEmail: "[email protected]",
- customerAvatar: "https://example.com/david.jpeg",
- metadata: { plan: "enterprise" },
-};
-
-describe.skip("POST /track/lead", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
- const clickId = "uxdcuMfBa5Nqnbwk";
-
- test("with required params", async () => {
- const response = await http.post<Tag>({
- path: "/track/lead",
- body: {
- clickId,
- eventName: "Signup",
- customerId: customer.customerId,
- },
- });
-
- const parsed = trackLeadResponseSchema.safeParse(response.data);
-
- expect(parsed.success).toBe(true);
- expect(response.status).toEqual(200);
- expect(response.data).toStrictEqual({
- clickId,
- eventName: "Signup",
- customerId: customer.customerId,
- customerName: null,
- customerEmail: null,
- customerAvatar: null,
- metadata: null,
- });
- });
-
- test("with all params", async () => {
- const response = await http.post<Tag>({
- path: "/track/lead",
- body: {
- clickId,
- eventName: "Signup",
- ...customer,
- },
- });
-
- const parsed = trackLeadResponseSchema.safeParse(response.data);
-
- expect(parsed.success).toBe(true);
- expect(response.status).toEqual(200);
- expect(response.data).toStrictEqual({
- clickId,
- eventName: "Signup",
- ...customer,
- });
- });
-});
diff --git a/apps/web/tests/tracks/track-customer.test.ts b/apps/web/tests/tracks/track-customer.test.ts
new file mode 100644
index 0000000000..2223b0ed4f
--- /dev/null
+++ b/apps/web/tests/tracks/track-customer.test.ts
@@ -0,0 +1,49 @@
+import { TrackCustomerResponse } from "@/lib/types";
+import { randomCustomer } from "tests/utils/helpers";
+import { describe, expect, test } from "vitest";
+import { IntegrationHarness } from "../utils/integration";
+
+describe("POST /track/customer", async () => {
+ const h = new IntegrationHarness();
+ const { http } = await h.init();
+ const customer = randomCustomer();
+
+ test("create a new customer", async () => {
+ const response = await http.post<TrackCustomerResponse>({
+ path: "/track/customer",
+ body: {
+ customerId: customer.id, // We're only required params
+ },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.data).toStrictEqual({
+ customerId: customer.id,
+ customerName: expect.any(String),
+ customerEmail: null,
+ customerAvatar: null,
+ });
+ });
+
+ test("update an existing customer", async () => {
+ const updatedCustomer = {
+ customerName: "David",
+ customerEmail: "[email protected]",
+ customerAvatar: "https://example.com/david.png",
+ };
+
+ const response = await http.post<TrackCustomerResponse>({
+ path: "/track/customer",
+ body: {
+ customerId: customer.id,
+ ...updatedCustomer,
+ },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.data).toStrictEqual({
+ customerId: customer.id,
+ ...updatedCustomer,
+ });
+ });
+});
diff --git a/apps/web/tests/tracks/track-lead.test.ts b/apps/web/tests/tracks/track-lead.test.ts
new file mode 100644
index 0000000000..e981cbece6
--- /dev/null
+++ b/apps/web/tests/tracks/track-lead.test.ts
@@ -0,0 +1,63 @@
+import { TrackLeadResponse } from "@/lib/types";
+import { randomCustomer } from "tests/utils/helpers";
+import { describe, expect, test } from "vitest";
+import { IntegrationHarness } from "../utils/integration";
+
+describe("POST /track/lead", async () => {
+ const h = new IntegrationHarness();
+ const { http } = await h.init();
+ const customer = randomCustomer();
+ const clickId = "avYirXJbt3gGALMk"; // TODO: Replace this with a valid clickId
+
+ test("track a lead", async () => {
+ const response = await http.post<TrackLeadResponse>({
+ path: "/track/lead",
+ body: {
+ clickId,
+ eventName: "Signup",
+ customerId: customer.id,
+ customerName: customer.name,
+ customerEmail: customer.email,
+ customerAvatar: customer.avatar,
+ },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.data).toStrictEqual({
+ clickId,
+ customerId: customer.id,
+ customerName: customer.name,
+ customerEmail: customer.email,
+ customerAvatar: customer.avatar,
+ click: {
+ id: clickId,
+ },
+ customer: {
+ id: customer.id,
+ name: customer.name,
+ email: customer.email,
+ avatar: customer.avatar,
+ },
+ });
+ });
+
+ test("duplicate request with same customerId", async () => {
+ const response = await http.post<TrackLeadResponse>({
+ path: "/track/lead",
+ body: {
+ clickId,
+ eventName: "Signup",
+ customerId: customer.id,
+ },
+ });
+
+ expect(response.status).toEqual(429);
+ expect(response.data).toStrictEqual({
+ error: {
+ code: "rate_limit_exceeded",
+ doc_url: "https://dub.co/docs/api-reference/errors#rate-limit_exceeded",
+ message: `Rate limit exceeded for customer ${customer.id}: Signup`,
+ },
+ });
+ });
+});
diff --git a/apps/web/tests/tracks/track-sale.test.ts b/apps/web/tests/tracks/track-sale.test.ts
new file mode 100644
index 0000000000..46df94409c
--- /dev/null
+++ b/apps/web/tests/tracks/track-sale.test.ts
@@ -0,0 +1,67 @@
+import { TrackSaleResponse } from "@/lib/types";
+import { randomCustomer, randomId } from "tests/utils/helpers";
+import { expect, test } from "vitest";
+import { IntegrationHarness } from "../utils/integration";
+
+test("POST /track/sale", async () => {
+ const h = new IntegrationHarness();
+ const { http } = await h.init();
+ const customer = randomCustomer();
+ const clickId = "avYirXJbt3gGALMk"; // TODO: Replace this with a valid clickId
+
+ const sale = {
+ eventName: "Subscription",
+ amount: 100,
+ currency: "usd",
+ invoiceId: `INV_${randomId()}`,
+ paymentProcessor: "stripe",
+ };
+
+ await http.post({
+ path: "/track/lead",
+ body: {
+ clickId,
+ eventName: "Signup",
+ customerId: customer.id,
+ customerName: customer.name,
+ customerEmail: customer.email,
+ customerAvatar: customer.avatar,
+ },
+ });
+
+ // Add a delay to ensure the lead has been created
+ // TODO: Should fix this
+ await new Promise((resolve) => setTimeout(resolve, 5000));
+
+ const response = await http.post<TrackSaleResponse>({
+ path: "/track/sale",
+ body: {
+ customerId: customer.id,
+ ...sale,
+ },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.data).toStrictEqual({
+ eventName: sale.eventName,
+ customer: {
+ id: customer.id,
+ name: customer.name,
+ email: customer.email,
+ avatar: customer.avatar,
+ },
+ sale: {
+ amount: sale.amount,
+ currency: sale.currency,
+ paymentProcessor: sale.paymentProcessor,
+ invoiceId: sale.invoiceId,
+ metadata: null,
+ },
+ customerId: customer.id,
+ amount: sale.amount,
+ currency: sale.currency,
+ paymentProcessor: sale.paymentProcessor,
+ metadata: null,
+ invoiceId: sale.invoiceId,
+ });
+});
diff --git a/apps/web/tests/utils/helpers.ts b/apps/web/tests/utils/helpers.ts
index 6e782f940f..67fccc5b4a 100644
--- a/apps/web/tests/utils/helpers.ts
+++ b/apps/web/tests/utils/helpers.ts
@@ -1 +1,14 @@
export const randomId = () => Math.random().toString(36).substr(2, 9);
+
+// Generate random customer data
+export const randomCustomer = () => {
+ const customerId = randomId();
+
+ return {
+ id: customerId,
+ name: `name-${customerId}`,
+ email: `email-${customerId}@example.com`,
+ avatar: `https://example.com/avatar-${customerId}.png`,
+ metadata: { plan: "enterprise" },
+ };
+};