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.

Unify Stripe `customer.created` and `customer.updated` sync (#4158)

Kiran K3698dd2d9e2a
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts
index 2b70848106..94999bd54d 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts
@@ -1,82 +1,7 @@
-import { prisma } from "@/lib/prisma";
import type Stripe from "stripe";
-import { createNewCustomer } from "./utils/create-new-customer";
+import { syncCustomer } from "./utils/sync-customer";
// Handle event "customer.created"
export async function customerCreated(event: Stripe.CustomerCreatedEvent) {
- const stripeCustomer = event.data.object;
- const stripeAccountId = event.account as string;
- const dubCustomerExternalId =
- stripeCustomer.metadata?.dubCustomerExternalId ||
- stripeCustomer.metadata?.dubCustomerId;
-
- if (!dubCustomerExternalId) {
- return {
- response:
- "External ID not found in Stripe customer metadata, skipping...",
- };
- }
-
- const workspace = await prisma.project.findUnique({
- where: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- id: true,
- },
- });
-
- if (!workspace) {
- return {
- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
- };
- }
-
- const workspaceId = workspace.id;
-
- // Check the customer is not already created
- const customer = await prisma.customer.findFirst({
- where: {
- OR: [
- {
- projectId: workspace.id,
- externalId: dubCustomerExternalId,
- },
- {
- stripeCustomerId: stripeCustomer.id,
- },
- ],
- },
- });
-
- if (customer) {
- // if customer exists (created via /track/lead)
- // update it with the Stripe customer ID (for future reference by invoice.paid)
- try {
- await prisma.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- externalId: dubCustomerExternalId,
- stripeCustomerId: stripeCustomer.id,
- projectConnectId: stripeAccountId,
- },
- });
-
- return {
- response: `Dub customer with ID ${customer.id} updated with Stripe customer ID ${stripeCustomer.id}`,
- workspaceId,
- };
- } catch (error) {
- console.error(error);
- return {
- response: `Error updating Dub customer with ID ${customer.id}: ${error}`,
- workspaceId,
- };
- }
- }
-
- // otherwise create a new customer
- return await createNewCustomer(event);
+ return await syncCustomer(event);
}
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts
index 817c64a22e..25256f9ebf 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts
@@ -1,81 +1,7 @@
-import { prisma } from "@/lib/prisma";
import type Stripe from "stripe";
-import { createNewCustomer } from "./utils/create-new-customer";
+import { syncCustomer } from "./utils/sync-customer";
// Handle event "customer.updated"
export async function customerUpdated(event: Stripe.CustomerUpdatedEvent) {
- const stripeCustomer = event.data.object;
- const stripeAccountId = event.account as string;
- const dubCustomerExternalId =
- stripeCustomer.metadata?.dubCustomerExternalId ||
- stripeCustomer.metadata?.dubCustomerId;
-
- if (!dubCustomerExternalId) {
- return {
- response:
- "External ID not found in Stripe customer metadata, skipping...",
- };
- }
-
- const workspace = await prisma.project.findUnique({
- where: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- id: true,
- },
- });
-
- if (!workspace) {
- return {
- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
- };
- }
-
- const workspaceId = workspace.id;
-
- const customer = await prisma.customer.findFirst({
- where: {
- OR: [
- {
- projectId: workspace.id,
- externalId: dubCustomerExternalId,
- },
- {
- stripeCustomerId: stripeCustomer.id,
- },
- ],
- },
- });
-
- if (customer) {
- try {
- await prisma.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- name: stripeCustomer.name,
- email: stripeCustomer.email,
- externalId: dubCustomerExternalId,
- stripeCustomerId: stripeCustomer.id,
- projectConnectId: stripeAccountId,
- },
- });
-
- return {
- response: `Dub customer with ID ${customer.id} updated.`,
- workspaceId,
- };
- } catch (error) {
- console.error(error);
- return {
- response: `Error updating Dub customer with ID ${customer.id}: ${error}`,
- workspaceId,
- };
- }
- }
-
- // otherwise create a new customer
- return await createNewCustomer(event);
+ return await syncCustomer(event);
}
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
deleted file mode 100644
index 888eb683c4..0000000000
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import { createId } from "@/lib/api/create-id";
-import { includeTags } from "@/lib/api/links/include-tags";
-import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
-import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
-import { generateRandomName } from "@/lib/names";
-import { constructWebhookPartner } from "@/lib/partners/constuct-webhook-partner";
-import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
-import { prisma } from "@/lib/prisma";
-import { getClickEvent, recordLead } from "@/lib/tinybird";
-import { redis } from "@/lib/upstash";
-import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
-import { transformLeadEventData } from "@/lib/webhook/transform";
-import { nanoid } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import type Stripe from "stripe";
-
-export async function createNewCustomer(event: Stripe.Event) {
- const stripeCustomer = event.data.object as Stripe.Customer;
- const stripeAccountId = event.account as string;
- const dubCustomerExternalId =
- stripeCustomer.metadata?.dubCustomerExternalId ||
- stripeCustomer.metadata?.dubCustomerId;
- const clickId = stripeCustomer.metadata?.dubClickId;
-
- // The client app should always send dubClickId (dub_id) via metadata
- if (!clickId) {
- return {
- response: "Click ID not found in Stripe customer metadata, skipping...",
- };
- }
-
- // Find click
- const clickData = await getClickEvent({ clickId });
- if (!clickData) {
- return {
- response: `Click event with ID ${clickId} not found, skipping...`,
- };
- }
-
- // Find link
- const linkId = clickData.link_id;
- const link = await prisma.link.findUnique({
- where: {
- id: linkId,
- },
- });
-
- if (!link || !link.projectId) {
- return {
- response: `Link with ID ${linkId} not found or does not have a project, skipping...`,
- workspaceId: link?.projectId ? link.projectId : undefined,
- };
- }
-
- // Create a customer
- const customer = await prisma.customer.create({
- data: {
- id: createId({ prefix: "cus_" }),
- name: stripeCustomer.name || stripeCustomer.email || generateRandomName(),
- email: stripeCustomer.email,
- stripeCustomerId: stripeCustomer.id,
- projectConnectId: stripeAccountId,
- externalId: dubCustomerExternalId,
- projectId: link.projectId,
- programId: link.programId,
- partnerId: link.partnerId,
- linkId,
- clickId,
- clickedAt: new Date(clickData.timestamp + "Z"),
- country: clickData.country,
- },
- });
-
- const eventName = "New customer";
-
- const leadData = {
- ...clickData,
- workspace_id: clickData.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id
- event_id: nanoid(16),
- event_name: eventName,
- customer_id: customer.id,
- };
-
- const [_lead, _leadCached, linkUpdated, workspace] = await Promise.all([
- // record lead event in Tinybird
- recordLead(leadData),
-
- // cache lead event in Redis because the ingested event is not available immediately on Tinybird
- redis.set(`leadCache:${customer.id}`, leadData, {
- ex: 60 * 5,
- }),
-
- // update link leads count + lastLeadAt date
- prisma.link.update({
- where: {
- id: linkId,
- },
- data: {
- leads: {
- increment: 1,
- },
- lastLeadAt: new Date(),
- },
- include: includeTags,
- }),
-
- // update workspace usage
- prisma.project.update({
- where: {
- id: customer.projectId,
- },
- data: {
- usage: {
- increment: 1,
- },
- },
- }),
- ]);
-
- if (link.programId && link.partnerId) {
- waitUntil(
- Promise.allSettled([
- executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
- identity: {
- workspaceId: workspace.id,
- programId: link.programId,
- partnerId: link.partnerId,
- },
- metrics: {
- current: {
- leads: 1,
- },
- },
- }),
-
- syncPartnerLinksStats({
- partnerId: link.partnerId,
- programId: link.programId,
- eventType: "lead",
- }),
- ]),
- );
- }
-
- waitUntil(
- (async () => {
- let webhookPartner:
- | ReturnType<typeof constructWebhookPartner>
- | undefined;
-
- if (link.programId && link.partnerId) {
- const programEnrollment = await prisma.programEnrollment.findUnique({
- where: {
- partnerId_programId: {
- partnerId: link.partnerId,
- programId: link.programId,
- },
- },
- include: {
- partner: true,
- links: true,
- },
- });
-
- webhookPartner = programEnrollment
- ? constructWebhookPartner(programEnrollment)
- : undefined;
- }
-
- await Promise.allSettled([
- sendWorkspaceWebhook({
- trigger: "lead.created",
- workspace,
- data: transformLeadEventData({
- ...clickData,
- eventName,
- link: linkUpdated,
- customer,
- partner: webhookPartner,
- metadata: null,
- }),
- }),
-
- ...(link.partnerId
- ? [
- sendPartnerPostback({
- partnerId: link.partnerId,
- event: "lead.created",
- data: {
- ...clickData,
- eventName,
- link: linkUpdated,
- customer,
- },
- }),
- ]
- : []),
- ]);
- })(),
- );
-
- return {
- response: `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`,
- workspaceId: workspace.id,
- };
-}
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
new file mode 100644
index 0000000000..968c5a3471
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
@@ -0,0 +1,336 @@
+import { createId } from "@/lib/api/create-id";
+import { getOrCreateCustomer } from "@/lib/api/customers/get-or-create-customer";
+import { includeTags } from "@/lib/api/links/include-tags";
+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
+import { generateRandomName } from "@/lib/names";
+import { constructWebhookPartner } from "@/lib/partners/constuct-webhook-partner";
+import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
+import { prisma } from "@/lib/prisma";
+import { getClickEvent, recordLead } from "@/lib/tinybird";
+import { redis } from "@/lib/upstash";
+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
+import { transformLeadEventData } from "@/lib/webhook/transform";
+import { nanoid, pick } from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import type Stripe from "stripe";
+
+type SyncCustomerResponse = {
+ response: string;
+ workspaceId?: string;
+};
+
+export async function syncCustomer(
+ event: Stripe.CustomerCreatedEvent | Stripe.CustomerUpdatedEvent,
+): Promise<SyncCustomerResponse> {
+ const stripeCustomer = event.data.object;
+ const stripeAccountId = event.account as string;
+ const dubCustomerExternalId =
+ stripeCustomer.metadata?.dubCustomerExternalId ||
+ stripeCustomer.metadata?.dubCustomerId;
+ const clickId = stripeCustomer.metadata?.dubClickId;
+
+ console.log(
+ "Stripe customer",
+ pick(stripeCustomer, ["id", "name", "metadata"]),
+ );
+
+ if (!dubCustomerExternalId) {
+ return {
+ response:
+ "External ID not found in Stripe customer metadata, skipping...",
+ };
+ }
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ stripeConnectId: stripeAccountId,
+ },
+ select: {
+ id: true,
+ webhookEnabled: true,
+ },
+ });
+
+ if (!workspace) {
+ return {
+ response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
+ };
+ }
+
+ const existingCustomer = await prisma.customer.findFirst({
+ where: {
+ OR: [
+ {
+ projectId: workspace.id,
+ externalId: dubCustomerExternalId,
+ },
+ {
+ stripeCustomerId: stripeCustomer.id,
+ },
+ ],
+ },
+ });
+
+ // Existing customer found, update it
+ if (existingCustomer) {
+ return updateStripeCustomer({
+ workspaceId: workspace.id,
+ customerId: existingCustomer.id,
+ data: {
+ stripeCustomerId: stripeCustomer.id,
+ projectConnectId: stripeAccountId,
+ externalId: dubCustomerExternalId,
+ // Only update name/email when Stripe provides non-empty values
+ ...(stripeCustomer.name && { name: stripeCustomer.name }),
+ ...(stripeCustomer.email && { email: stripeCustomer.email }),
+ },
+ });
+ }
+
+ // No existing customer found, see if we can create a new one
+
+ if (!clickId) {
+ return {
+ response: "Click ID not found in Stripe customer metadata, skipping...",
+ workspaceId: workspace.id,
+ };
+ }
+
+ const clickData = await getClickEvent({
+ clickId,
+ });
+
+ if (!clickData) {
+ return {
+ response: `Click event with ID ${clickId} not found, skipping...`,
+ workspaceId: workspace.id,
+ };
+ }
+
+ const linkId = clickData.link_id;
+
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ select: {
+ projectId: true,
+ programId: true,
+ partnerId: true,
+ },
+ });
+
+ if (!link || !link.projectId) {
+ return {
+ response: `Link with ID ${linkId} not found or does not have a project, skipping...`,
+ workspaceId: workspace.id,
+ };
+ }
+
+ if (link.projectId !== workspace.id) {
+ return {
+ response: `Link ${linkId} does not belong to workspace ${workspace.id}, skipping...`,
+ workspaceId: workspace.id,
+ };
+ }
+
+ const { customer, created } = await getOrCreateCustomer({
+ findMode: "first",
+ where: {
+ OR: [
+ {
+ projectId: workspace.id,
+ externalId: dubCustomerExternalId,
+ },
+ {
+ stripeCustomerId: stripeCustomer.id,
+ },
+ ],
+ },
+ create: {
+ id: createId({ prefix: "cus_" }),
+ name: stripeCustomer.name || stripeCustomer.email || generateRandomName(),
+ email: stripeCustomer.email,
+ stripeCustomerId: stripeCustomer.id,
+ projectConnectId: stripeAccountId,
+ externalId: dubCustomerExternalId,
+ projectId: workspace.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ linkId,
+ clickId,
+ clickedAt: new Date(clickData.timestamp + "Z"),
+ country: clickData.country,
+ },
+ });
+
+ // If the customer was not created, it means it already exists
+ // Eg: concurrently created by two different webhooks events
+ if (!created) {
+ return updateStripeCustomer({
+ workspaceId: workspace.id,
+ customerId: customer.id,
+ data: {
+ stripeCustomerId: stripeCustomer.id,
+ projectConnectId: stripeAccountId,
+ externalId: dubCustomerExternalId,
+ // Only update name/email when Stripe provides non-empty values
+ ...(stripeCustomer.name && { name: stripeCustomer.name }),
+ ...(stripeCustomer.email && { email: stripeCustomer.email }),
+ },
+ });
+ }
+
+ // Track lead event for the new customer
+ const eventName = "New customer";
+
+ const leadData = {
+ ...clickData,
+ workspace_id: workspace.id,
+ event_id: nanoid(16),
+ event_name: eventName,
+ customer_id: customer.id,
+ };
+
+ const [_lead, _leadCached, linkUpdated] = await Promise.all([
+ recordLead(leadData),
+
+ redis.set(`leadCache:${customer.id}`, leadData, {
+ ex: 60 * 5,
+ }),
+
+ prisma.link.update({
+ where: {
+ id: linkId,
+ },
+ data: {
+ leads: {
+ increment: 1,
+ },
+ lastLeadAt: new Date(),
+ },
+ include: includeTags,
+ }),
+
+ prisma.project.update({
+ where: {
+ id: customer.projectId,
+ },
+ data: {
+ usage: {
+ increment: 1,
+ },
+ },
+ }),
+ ]);
+
+ waitUntil(
+ (async () => {
+ let webhookPartner:
+ | ReturnType<typeof constructWebhookPartner>
+ | undefined;
+
+ if (link.programId && link.partnerId) {
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: link.partnerId,
+ programId: link.programId,
+ },
+ },
+ include: {
+ partner: true,
+ links: true,
+ },
+ });
+
+ webhookPartner = programEnrollment
+ ? constructWebhookPartner(programEnrollment)
+ : undefined;
+
+ await Promise.allSettled([
+ executeWorkflows({
+ trigger: "partnerMetricsUpdated",
+ reason: "lead",
+ identity: {
+ workspaceId: workspace.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ },
+ metrics: {
+ current: {
+ leads: 1,
+ },
+ },
+ }),
+
+ syncPartnerLinksStats({
+ partnerId: link.partnerId,
+ programId: link.programId,
+ eventType: "lead",
+ }),
+
+ sendPartnerPostback({
+ partnerId: link.partnerId,
+ event: "lead.created",
+ data: {
+ ...clickData,
+ eventName,
+ link: linkUpdated,
+ customer,
+ },
+ }),
+ ]);
+ }
+
+ await sendWorkspaceWebhook({
+ trigger: "lead.created",
+ workspace,
+ data: transformLeadEventData({
+ ...clickData,
+ eventName,
+ link: linkUpdated,
+ customer,
+ partner: webhookPartner,
+ metadata: null,
+ }),
+ });
+ })(),
+ );
+
+ return {
+ response: `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`,
+ workspaceId: workspace.id,
+ };
+}
+
+async function updateStripeCustomer({
+ customerId,
+ workspaceId,
+ data,
+}: {
+ customerId: string;
+ workspaceId: string;
+ data: Prisma.CustomerUncheckedUpdateInput;
+}): Promise<SyncCustomerResponse> {
+ try {
+ await prisma.customer.update({
+ where: {
+ id: customerId,
+ },
+ data,
+ });
+
+ return {
+ response: `Dub customer with ID ${customerId} updated.`,
+ workspaceId,
+ };
+ } catch (error) {
+ return {
+ response: `Error updating Dub customer with ID ${customerId}: ${error}`,
+ workspaceId,
+ };
+ }
+}
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
index 8a4d6e9e9e..7aed29a8b7 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -1,5 +1,5 @@
import { createId } from "@/lib/api/create-id";
-import { createOrGetCustomer } from "@/lib/api/customers/create-or-get-customer";
+import { getOrCreateCustomer } from "@/lib/api/customers/get-or-create-customer";
import { DubApiError } from "@/lib/api/errors";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
@@ -167,7 +167,7 @@ export const trackLead = async ({
};
if (!customer) {
- const { customer: createdOrFoundCustomer } = await createOrGetCustomer({
+ const { customer: existingOrNewCustomer } = await getOrCreateCustomer({
where: {
projectId_externalId: {
projectId: workspace.id,
@@ -191,7 +191,7 @@ export const trackLead = async ({
},
});
- customer = createdOrFoundCustomer;
+ customer = existingOrNewCustomer;
}
// if wait mode, record the lead event synchronously
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index a8396adec1..5fc2afb03c 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -1,6 +1,6 @@
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { createOrGetCustomer } from "@/lib/api/customers/create-or-get-customer";
+import { getOrCreateCustomer } from "@/lib/api/customers/get-or-create-customer";
import { DubApiError } from "@/lib/api/errors";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
@@ -184,8 +184,8 @@ export const trackSale = async ({
? `${R2_URL}/customers/${finalCustomerId}/avatar_${nanoid(7)}`
: customerAvatar;
- const { customer: createdOrFoundCustomer, created } =
- await createOrGetCustomer({
+ const { customer: existingOrNewCustomer, created } =
+ await getOrCreateCustomer({
where: {
projectId_externalId: {
projectId: workspace.id,
@@ -208,9 +208,9 @@ export const trackSale = async ({
});
if (created) {
- newCustomer = createdOrFoundCustomer;
+ newCustomer = existingOrNewCustomer;
} else {
- existingCustomer = createdOrFoundCustomer;
+ existingCustomer = existingOrNewCustomer;
}
// Persist customer avatar to R2 if it's not already stored
diff --git a/apps/web/lib/api/customers/create-or-get-customer.ts b/apps/web/lib/api/customers/create-or-get-customer.ts
deleted file mode 100644
index 60ee7be124..0000000000
--- a/apps/web/lib/api/customers/create-or-get-customer.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { Prisma } from "@prisma/client";
-
-/**
- * Race-safe customer create-or-get.
- *
- * Prisma's `customer.upsert()` can still throw P2002 under MySQL concurrency
- * (two requests miss the row, both attempt insert). This helper create-firsts
- * and on unique-constraint conflict falls back to find using `where`,
- * so concurrent track-lead / track-sale / etc. share one path instead of
- * failing the request.
- */
-export async function createOrGetCustomer({
- where,
- create,
-}: {
- where: Prisma.CustomerWhereUniqueInput;
- create: Prisma.CustomerUncheckedCreateInput;
-}) {
- try {
- const customer = await prisma.customer.create({
- data: create,
- });
-
- return {
- customer,
- created: true,
- };
- } catch (error) {
- if (
- error instanceof Prisma.PrismaClientKnownRequestError &&
- error.code === "P2002"
- ) {
- const customer = await prisma.customer.findUniqueOrThrow({
- where,
- });
-
- return {
- customer,
- created: false,
- };
- }
-
- throw error;
- }
-}
diff --git a/apps/web/lib/api/customers/get-or-create-customer.ts b/apps/web/lib/api/customers/get-or-create-customer.ts
new file mode 100644
index 0000000000..b8da8367b5
--- /dev/null
+++ b/apps/web/lib/api/customers/get-or-create-customer.ts
@@ -0,0 +1,74 @@
+import { prisma } from "@/lib/prisma";
+import { Prisma } from "@prisma/client";
+
+/**
+ * Race-safe customer get-or-create.
+ *
+ * Prisma's `customer.upsert()` can still throw P2002 under MySQL concurrency
+ * (two requests miss the row, both attempt insert). This helper finds first,
+ * creates if missing, and on unique-constraint conflict falls back to find
+ * using `where`, so concurrent track-lead / track-sale / etc. share one path
+ * instead of failing the request.
+ */
+export async function getOrCreateCustomer({
+ where,
+ create,
+ findMode = "unique",
+}: {
+ where: Prisma.CustomerWhereUniqueInput | Prisma.CustomerWhereInput;
+ create: Prisma.CustomerUncheckedCreateInput;
+ findMode?: "first" | "unique";
+}) {
+ const customer =
+ findMode === "first"
+ ? await prisma.customer.findFirst({
+ where: where as Prisma.CustomerWhereInput,
+ })
+ : await prisma.customer.findUnique({
+ where: where as Prisma.CustomerWhereUniqueInput,
+ });
+
+ if (customer) {
+ return {
+ customer,
+ created: false,
+ };
+ }
+
+ try {
+ const customer = await prisma.customer.create({
+ data: create,
+ });
+
+ return {
+ customer,
+ created: true,
+ };
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ console.info(
+ "[getOrCreateCustomer] Unique constraint conflict (P2002), falling back to find",
+ { target: error.meta?.target },
+ );
+
+ const customer =
+ findMode === "first"
+ ? await prisma.customer.findFirstOrThrow({
+ where: where as Prisma.CustomerWhereInput,
+ })
+ : await prisma.customer.findUniqueOrThrow({
+ where: where as Prisma.CustomerWhereUniqueInput,
+ });
+
+ return {
+ customer,
+ created: false,
+ };
+ }
+
+ throw error;
+ }
+}