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.

return a conflict when a commission customer hits another unique key

Kiran K7a2d18a973d2
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index 3d87aa5920..6b301c3edc 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -22,12 +22,14 @@ import {
Customer,
Link,
Partner,
+ Prisma,
Project,
} from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { createId } from "../create-id";
import { getCustomerStripeInvoices } from "../customers/get-customer-stripe-invoices";
+import { getOrCreateCustomer } from "../customers/get-or-create-customer";
import { DubApiError } from "../errors";
import { updateLinkStatsForImporter } from "../links/update-link-stats-for-importer";
import { syncPartnerLinksStats } from "../partners/sync-partner-links-stats";
@@ -377,31 +379,17 @@ async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {
? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`
: avatar;
- targetCustomer = await prisma.customer.upsert({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId,
- },
- },
- create: {
+ targetCustomer = await createOrUpdateCustomer({
+ workspace,
+ linkId: targetLink.id,
+ customer: {
id: customerId,
name: finalCustomerName,
email,
avatar: finalCustomerAvatar,
externalId,
stripeCustomerId,
- linkId: targetLink.id,
- country,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- },
- update: {
- name: finalCustomerName,
- email,
- avatar: finalCustomerAvatar,
country,
- stripeCustomerId,
},
});
@@ -436,6 +424,89 @@ async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {
};
}
+/**
+ * Creates the customer by `(projectId, externalId)`, or updates it if it already exists.
+ *
+ * We avoid `prisma.customer.upsert()` here because `Customer` has two other
+ * unique keys besides `(projectId, externalId)`: `stripeCustomerId` (global) and
+ * `(projectConnectId, externalId)`. Upsert only handles conflicts on its `where`
+ * key, so a clash on either of the others throws an opaque
+ * "Unique constraint failed on the (not available)" error from MySQL.
+ *
+ * `getOrCreateCustomer` handles concurrent creates of the same customer. The
+ * remaining Prisma errors are mapped to a 409 conflict:
+ * - P2002: the update sets a `stripeCustomerId` already used by another customer.
+ * - P2025: the create hit one of the other unique keys, so the fallback lookup
+ * by `(projectId, externalId)` found nothing.
+ */
+async function createOrUpdateCustomer({
+ workspace,
+ linkId,
+ customer,
+}: {
+ workspace: Pick<Project, "id" | "stripeConnectId">;
+ linkId: string;
+ customer: Pick<
+ Prisma.CustomerUncheckedCreateInput,
+ "id" | "name" | "email" | "avatar" | "stripeCustomerId" | "country"
+ > & { externalId: string };
+}) {
+ const { id, name, email, avatar, externalId, stripeCustomerId, country } =
+ customer;
+
+ try {
+ const { customer: resolvedCustomer, created } = await getOrCreateCustomer({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId,
+ },
+ },
+ create: {
+ id,
+ name,
+ email,
+ avatar,
+ externalId,
+ stripeCustomerId,
+ linkId,
+ country,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ },
+ });
+
+ if (created) {
+ return resolvedCustomer;
+ }
+
+ return await prisma.customer.update({
+ where: {
+ id: resolvedCustomer.id,
+ },
+ data: {
+ name,
+ email,
+ avatar,
+ country,
+ stripeCustomerId,
+ },
+ });
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ (error.code === "P2002" || error.code === "P2025")
+ ) {
+ throw new DubApiError({
+ code: "conflict",
+ message: `A customer with external ID ${externalId} or Stripe customer ID ${stripeCustomerId} already exists.`,
+ });
+ }
+
+ throw error;
+ }
+}
+
async function recordEvents(args: RecordEventsArgs) {
const { type } = args;