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 customer partner reattribution

Pedro Ladeira6b8454363b75
diff --git a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts
new file mode 100644
index 0000000000..830335e019
--- /dev/null
+++ b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts
@@ -0,0 +1,182 @@
+import { createId } from "@/lib/api/create-id";
+import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
+import {
+ computeConversionFlags,
+ getCustomerReattributeEvents,
+ recreateCustomerForReattribution,
+ shouldRecreateCustomer,
+} from "@/lib/api/customers/reattribute-customer";
+import { transformCustomer } from "@/lib/api/customers/transform-customer";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
+import { prisma } from "@/lib/prisma";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
+import {
+ CustomerEnrichedSchema,
+ reattributeCustomerBodySchema,
+} from "@/lib/zod/schemas/customers";
+import { nanoid } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// POST /api/customers/:id/reattribute – Reattribute a customer to a different partner
+export const POST = withWorkspace(
+ async ({ workspace, params, req }) => {
+ const { id } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+ const { partnerId, linkId, createClawback } =
+ reattributeCustomerBodySchema.parse(await parseRequestBody(req));
+
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.reattributeCustomer,
+ identifier: workspace.id,
+ });
+
+ const customer = await getCustomerOrThrow(
+ {
+ id,
+ workspaceId: workspace.id,
+ },
+ {
+ includeExpandedFields: true,
+ },
+ );
+
+ if (customer.partnerId === partnerId && customer.linkId === linkId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Customer is already attributed to this partner and link.",
+ });
+ }
+
+ await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {},
+ });
+
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ });
+
+ if (
+ !link ||
+ link.projectId !== workspace.id ||
+ link.programId !== programId ||
+ link.partnerId !== partnerId
+ ) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "The selected referral link does not belong to this partner in the program.",
+ });
+ }
+
+ const [events, commissionCount] = await Promise.all([
+ getCustomerReattributeEvents(customer.id),
+ prisma.commission.count({
+ where: {
+ customerId: customer.id,
+ },
+ }),
+ ]);
+
+ if (
+ !shouldRecreateCustomer({
+ eventCount: events.length,
+ commissionCount,
+ })
+ ) {
+ const updatedCustomer = await prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ partnerId: link.partnerId,
+ linkId: link.id,
+ programId: link.programId,
+ },
+ });
+
+ const enrichedCustomer = await getCustomerOrThrow(
+ {
+ id: updatedCustomer.id,
+ workspaceId: workspace.id,
+ },
+ {
+ includeExpandedFields: true,
+ },
+ );
+
+ return NextResponse.json(
+ CustomerEnrichedSchema.parse(transformCustomer(enrichedCustomer)),
+ );
+ }
+
+ const newCustomerId = createId({ prefix: "cus_" });
+ const newClickId = nanoid(16);
+ const { incrementConversions, decrementConversions } =
+ computeConversionFlags({
+ customer,
+ newLinkId: link.id,
+ });
+
+ await recreateCustomerForReattribution({
+ customer,
+ link,
+ newCustomerId,
+ newClickId,
+ });
+
+ await dispatchWorkflows({
+ name: "reattribute-customer-workflow",
+ payload: {
+ workspaceId: workspace.id,
+ programId,
+ oldCustomerId: customer.id,
+ newCustomerId,
+ oldLinkId: customer.linkId,
+ newLinkId: link.id,
+ oldPartnerId: customer.partnerId,
+ newPartnerId: partnerId,
+ oldClickId: customer.clickId,
+ newClickId,
+ createClawback,
+ incrementConversions,
+ decrementConversions,
+ },
+ options: {
+ deduplicationId: customer.id,
+ flowControl: {
+ key: workspace.id,
+ parallelism: 1,
+ },
+ label: customer.id,
+ },
+ });
+
+ const newCustomer = await getCustomerOrThrow(
+ {
+ id: newCustomerId,
+ workspaceId: workspace.id,
+ },
+ {
+ includeExpandedFields: true,
+ },
+ );
+
+ return NextResponse.json(
+ CustomerEnrichedSchema.parse(transformCustomer(newCustomer)),
+ );
+ },
+ {
+ requiredPlan: ["business", "advanced", "enterprise"],
+ requiredRoles: ["owner", "member"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts b/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts
new file mode 100644
index 0000000000..335f736631
--- /dev/null
+++ b/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts
@@ -0,0 +1,186 @@
+import {
+ createClawbackAndReplacementCommissions,
+ decrementOldLinkStats,
+ deleteOldCustomerTinybirdEvents,
+ incrementNewLinkStats,
+ loadReattributeEventPlan,
+ reingestCustomerEvents,
+ transferUnpaidCommissions,
+} from "@/lib/api/customers/reattribute-customer";
+import { logger } from "@/lib/axiom/server";
+import { prisma } from "@/lib/prisma";
+import { reattributeCustomerWorkflowSchema } from "@/lib/zod/schemas/customers";
+import { WorkflowRetryAfterError } from "@upstash/workflow";
+import { serve } from "@upstash/workflow/nextjs";
+import * as z from "zod/v4";
+import { logAndReturn } from "../../cron/utils";
+
+type Input = z.infer<typeof reattributeCustomerWorkflowSchema>;
+
+/**
+ * Reattribute Customer Workflow
+ *
+ * Moves a customer (and their events/commissions) from one partner link to another.
+ *
+ * 1. load-plan: inspect old/new Tinybird events
+ * 2. reingest-events: copy events onto the new customer + link
+ * 3. increment-new-link-stats
+ * 4. transfer-unpaid-commissions
+ * 5. optional-clawback
+ * 6. delete-old-events
+ * 7. decrement-old-link-stats
+ */
+
+// POST /api/workflows/reattribute-customer
+export const { POST } = serve<Input>(
+ async (context) => {
+ const input = context.requestPayload;
+
+ const plan = await context.run("load-plan", async () => {
+ return await loadReattributeEventPlan({
+ oldCustomerId: input.oldCustomerId,
+ newCustomerId: input.newCustomerId,
+ });
+ });
+
+ await context.run("reingest-events", async () => {
+ try {
+ const link = await prisma.link.findUniqueOrThrow({
+ where: { id: input.newLinkId },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ },
+ });
+
+ return logAndReturn(
+ await reingestCustomerEvents({
+ oldCustomerId: input.oldCustomerId,
+ newCustomerId: input.newCustomerId,
+ newClickId: input.newClickId,
+ link,
+ workspaceId: input.workspaceId,
+ }),
+ );
+ } catch (error) {
+ throw new WorkflowRetryAfterError(
+ error instanceof Error ? error.message : "Failed to re-ingest events",
+ "5s",
+ );
+ }
+ });
+
+ await context.run("increment-new-link-stats", async () => {
+ return logAndReturn(
+ await incrementNewLinkStats({
+ oldCustomerId: input.oldCustomerId,
+ newLinkId: input.newLinkId,
+ programId: input.programId,
+ partnerId: input.newPartnerId,
+ plan,
+ incrementConversions: input.incrementConversions,
+ }),
+ );
+ });
+
+ await context.run("transfer-unpaid-commissions", async () => {
+ return logAndReturn(
+ await transferUnpaidCommissions({
+ oldCustomerId: input.oldCustomerId,
+ newCustomerId: input.newCustomerId,
+ newPartnerId: input.newPartnerId,
+ newLinkId: input.newLinkId,
+ programId: input.programId,
+ oldPartnerId: input.oldPartnerId,
+ }),
+ );
+ });
+
+ if (input.createClawback) {
+ const newCustomer = await context.run(
+ "load-new-customer-country",
+ async () => {
+ return await prisma.customer.findUnique({
+ where: { id: input.newCustomerId },
+ select: { country: true },
+ });
+ },
+ );
+
+ await context.run("optional-clawback", async () => {
+ return logAndReturn(
+ await createClawbackAndReplacementCommissions({
+ oldCustomerId: input.oldCustomerId,
+ newCustomerId: input.newCustomerId,
+ oldPartnerId: input.oldPartnerId,
+ newPartnerId: input.newPartnerId,
+ newLinkId: input.newLinkId,
+ programId: input.programId,
+ customerCountry: newCustomer?.country ?? null,
+ }),
+ );
+ });
+ }
+
+ await context.run("delete-old-events", async () => {
+ try {
+ await deleteOldCustomerTinybirdEvents({
+ oldCustomerId: input.oldCustomerId,
+ oldClickId: input.oldClickId,
+ });
+
+ return logAndReturn({ deleted: true });
+ } catch (error) {
+ throw new WorkflowRetryAfterError(
+ error instanceof Error
+ ? error.message
+ : "Failed to delete old Tinybird events",
+ "10s",
+ );
+ }
+ });
+
+ await context.run("decrement-old-link-stats", async () => {
+ return logAndReturn(
+ await decrementOldLinkStats({
+ oldCustomerId: input.oldCustomerId,
+ oldLinkId: input.oldLinkId,
+ oldPartnerId: input.oldPartnerId,
+ programId: input.programId,
+ plan,
+ decrementConversions: input.decrementConversions,
+ }),
+ );
+ });
+ },
+ {
+ initialPayloadParser: (requestPayload) => {
+ const payload =
+ typeof requestPayload === "string"
+ ? JSON.parse(requestPayload)
+ : requestPayload;
+
+ return reattributeCustomerWorkflowSchema.parse(payload);
+ },
+ failureFunction: async ({
+ context,
+ failStatus,
+ failResponse,
+ failHeaders,
+ }) => {
+ logger.error("workflow.failed", {
+ service: "qstash",
+ event: "workflow.failed",
+ workflowType: "reattribute-customer",
+ workflowRunId: context.workflowRunId,
+ failStatus,
+ failResponse,
+ failHeaders,
+ });
+
+ await logger.flush();
+ },
+ },
+);
diff --git a/apps/web/lib/api/customers/reattribute-customer.ts b/apps/web/lib/api/customers/reattribute-customer.ts
new file mode 100644
index 0000000000..b6adb0b22f
--- /dev/null
+++ b/apps/web/lib/api/customers/reattribute-customer.ts
@@ -0,0 +1,716 @@
+import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
+import { reconcilePayoutAmounts } from "@/lib/api/commissions/reconcile-payout-amounts";
+import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-for-importer";
+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
+import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
+import { MUTABLE_PAYOUT_STATUSES } from "@/lib/constants/payouts";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
+import { retallyPayoutsAmount } from "@/lib/payouts/retally-payouts-amount";
+import { prisma } from "@/lib/prisma";
+import { deleteTinybirdCustomerEvents } from "@/lib/tinybird/delete-events";
+import { getCustomerEventsTB } from "@/lib/tinybird/get-customer-events-tb";
+import {
+ recordClickZod,
+ recordClickZodSchema,
+} from "@/lib/tinybird/record-click-zod";
+import { recordLeadWithTimestamp } from "@/lib/tinybird/record-lead";
+import { recordSaleWithTimestamp } from "@/lib/tinybird/record-sale";
+import { redis } from "@/lib/upstash";
+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
+import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
+import { nanoid } from "@dub/utils";
+import { Customer, Link } from "@prisma/client";
+import * as z from "zod/v4";
+
+const CUSTOMER_EVENTS_LIMIT = 1000;
+const UNPAID_COMMISSION_STATUSES = ["pending", "hold", "processed"] as const;
+const STATS_LOCK_TTL_SECONDS = 60 * 60 * 24;
+
+const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+type CustomerTBEvent = {
+ event: "click" | "lead" | "sale";
+ timestamp: string;
+ click_id?: string;
+ link_id?: string;
+ event_id?: string;
+ event_name?: string;
+ saleAmount?: number;
+ invoice_id?: string;
+ payment_processor?: string;
+ currency?: string;
+ [key: string]: unknown;
+};
+
+export type ReattributeEventPlan = {
+ hasClick: boolean;
+ hasLead: boolean;
+ leadCount: number;
+ saleCount: number;
+ saleAmount: number;
+ leadTimestamp: string | null;
+ saleTimestamp: string | null;
+ oldEventIds: string[];
+ alreadyReingested: boolean;
+};
+
+async function runOnce({ key, fn }: { key: string; fn: () => Promise<void> }) {
+ const acquired = await redis.set(key, "1", {
+ nx: true,
+ ex: STATS_LOCK_TTL_SECONDS,
+ });
+
+ if (acquired !== "OK") {
+ return false;
+ }
+
+ try {
+ await fn();
+ return true;
+ } catch (error) {
+ await redis.del(key);
+ throw error;
+ }
+}
+
+function parseCustomerEvents(data: unknown[]): CustomerTBEvent[] {
+ return data.filter(
+ (event): event is CustomerTBEvent =>
+ typeof event === "object" &&
+ event !== null &&
+ "event" in event &&
+ (event.event === "click" ||
+ event.event === "lead" ||
+ event.event === "sale"),
+ );
+}
+
+export async function getCustomerReattributeEvents(customerId: string) {
+ const { data } = await getCustomerEventsTB({
+ customerId,
+ limit: CUSTOMER_EVENTS_LIMIT,
+ });
+
+ return parseCustomerEvents(data ?? []);
+}
+
+export function summarizeCustomerEvents(
+ events: CustomerTBEvent[],
+): Omit<ReattributeEventPlan, "alreadyReingested"> {
+ const clickEvent = events.find((event) => event.event === "click");
+ const leadEvent = events.find((event) => event.event === "lead");
+ const saleEvents = events.filter((event) => event.event === "sale");
+
+ return {
+ hasClick: Boolean(clickEvent),
+ hasLead: Boolean(leadEvent),
+ leadCount: leadEvent ? 1 : 0,
+ saleCount: saleEvents.length,
+ saleAmount: saleEvents.reduce(
+ (sum, event) => sum + (event.saleAmount ?? 0),
+ 0,
+ ),
+ leadTimestamp: leadEvent?.timestamp ?? null,
+ saleTimestamp:
+ saleEvents.length > 0
+ ? saleEvents.reduce((latest, event) =>
+ event.timestamp > latest.timestamp ? event : latest,
+ ).timestamp
+ : null,
+ oldEventIds: [
+ leadEvent?.event_id,
+ ...saleEvents.map((event) => event.event_id),
+ ].filter((eventId): eventId is string => typeof eventId === "string"),
+ };
+}
+
+export async function recreateCustomerForReattribution({
+ customer,
+ link,
+ newCustomerId,
+ newClickId,
+}: {
+ customer: Customer;
+ link: Pick<Link, "id" | "programId" | "partnerId">;
+ newCustomerId: string;
+ newClickId: string;
+}) {
+ return await prisma.$transaction(async (tx) => {
+ await tx.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ name: customer.name ? `${customer.name} (old)` : undefined,
+ externalId: `dummy_${nanoid(32)}`,
+ stripeCustomerId: null,
+ linkId: null,
+ programId: null,
+ partnerId: null,
+ clickId: null,
+ },
+ });
+
+ return await tx.customer.create({
+ data: {
+ id: newCustomerId,
+ name: customer.name,
+ email: customer.email,
+ avatar: customer.avatar,
+ externalId: customer.externalId,
+ stripeCustomerId: customer.stripeCustomerId,
+ clickedAt: customer.clickedAt,
+ country: customer.country,
+ sales: customer.sales,
+ saleAmount: customer.saleAmount,
+ firstSaleAt: customer.firstSaleAt,
+ subscriptionCanceledAt: customer.subscriptionCanceledAt,
+ projectId: customer.projectId,
+ projectConnectId: customer.projectConnectId,
+ createdAt: customer.createdAt,
+ linkId: link.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ clickId: newClickId,
+ },
+ });
+ });
+}
+
+export async function loadReattributeEventPlan({
+ oldCustomerId,
+ newCustomerId,
+}: {
+ oldCustomerId: string;
+ newCustomerId: string;
+}): Promise<ReattributeEventPlan> {
+ const [oldEvents, newEvents] = await Promise.all([
+ getCustomerReattributeEvents(oldCustomerId),
+ getCustomerReattributeEvents(newCustomerId),
+ ]);
+
+ const alreadyReingested = newEvents.length > 0;
+ const sourceEvents = alreadyReingested ? newEvents : oldEvents;
+
+ return {
+ ...summarizeCustomerEvents(sourceEvents),
+ alreadyReingested,
+ };
+}
+
+export async function reingestCustomerEvents({
+ oldCustomerId,
+ newCustomerId,
+ newClickId,
+ link,
+ workspaceId,
+}: {
+ oldCustomerId: string;
+ newCustomerId: string;
+ newClickId: string;
+ link: Pick<Link, "id" | "domain" | "key" | "url">;
+ workspaceId: string;
+}) {
+ const [oldEvents, newEvents] = await Promise.all([
+ getCustomerReattributeEvents(oldCustomerId),
+ getCustomerReattributeEvents(newCustomerId),
+ ]);
+
+ if (newEvents.length > 0) {
+ return { skipped: true, reason: "already-reingested" as const };
+ }
+
+ const existingClickEvent = oldEvents.find((event) => event.event === "click");
+ const existingLeadEvent = oldEvents.find((event) => event.event === "lead");
+ const existingSaleEvents = oldEvents.filter(
+ (event) => event.event === "sale",
+ );
+
+ const newClickAttributes = {
+ click_id: newClickId,
+ link_id: link.id,
+ };
+
+ const clickEventData = recordClickZodSchema.parse({
+ ...existingClickEvent,
+ ...newClickAttributes,
+ workspace_id: workspaceId,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ });
+
+ const eventsToRecord: Promise<unknown>[] = [];
+
+ if (existingClickEvent) {
+ eventsToRecord.push(recordClickZod(clickEventData));
+ }
+
+ if (existingLeadEvent) {
+ const leadEventData = leadEventSchemaTBWithTimestamp.parse({
+ ...clickEventData,
+ ...existingLeadEvent,
+ ...newClickAttributes,
+ event_id: nanoid(16),
+ link_id: link.id,
+ customer_id: newCustomerId,
+ });
+
+ eventsToRecord.push(recordLeadWithTimestamp(leadEventData));
+ }
+
+ if (existingSaleEvents.length > 0) {
+ const saleEventsData = existingSaleEvents.map((existingSaleEvent) =>
+ saleEventSchemaTBWithTimestamp.parse({
+ ...clickEventData,
+ ...existingSaleEvent,
+ ...newClickAttributes,
+ event_id: nanoid(16),
+ link_id: link.id,
+ customer_id: newCustomerId,
+ amount: existingSaleEvent.saleAmount,
+ }),
+ );
+
+ eventsToRecord.push(recordSaleWithTimestamp(saleEventsData));
+ }
+
+ if (eventsToRecord.length === 0) {
+ return { skipped: true, reason: "no-events" as const };
+ }
+
+ const results = await Promise.allSettled(eventsToRecord);
+ const failed = results.filter((result) => result.status === "rejected");
+
+ if (failed.length > 0) {
+ throw new Error(
+ `Failed to re-ingest ${failed.length} Tinybird event batch(es) for customer ${newCustomerId}.`,
+ );
+ }
+
+ return { skipped: false, recorded: eventsToRecord.length };
+}
+
+export async function incrementNewLinkStats({
+ oldCustomerId,
+ newLinkId,
+ programId,
+ partnerId,
+ plan,
+ incrementConversions,
+}: {
+ oldCustomerId: string;
+ newLinkId: string;
+ programId: string;
+ partnerId: string;
+ plan: ReattributeEventPlan;
+ incrementConversions: boolean;
+}) {
+ const didUpdate = await runOnce({
+ key: `reattribute-customer:${oldCustomerId}:new-link-stats`,
+ fn: async () => {
+ const link = await prisma.link.findUniqueOrThrow({
+ where: { id: newLinkId },
+ select: {
+ id: true,
+ lastLeadAt: true,
+ lastConversionAt: true,
+ },
+ });
+
+ const leadEventTimestamp = plan.leadTimestamp
+ ? new Date(`${plan.leadTimestamp}Z`)
+ : new Date();
+ const saleEventTimestamp = plan.saleTimestamp
+ ? new Date(`${plan.saleTimestamp}Z`)
+ : new Date();
+
+ await prisma.link.update({
+ where: { id: newLinkId },
+ data: {
+ ...(plan.hasClick && {
+ clicks: { increment: 1 },
+ }),
+ ...(plan.hasLead && {
+ leads: { increment: plan.leadCount },
+ lastLeadAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastLeadAt,
+ newTimestamp: leadEventTimestamp,
+ }),
+ }),
+ ...(incrementConversions && {
+ conversions: { increment: 1 },
+ lastConversionAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastConversionAt,
+ newTimestamp: saleEventTimestamp,
+ }),
+ }),
+ ...(plan.saleCount > 0 && {
+ sales: { increment: plan.saleCount },
+ saleAmount: { increment: plan.saleAmount },
+ }),
+ },
+ });
+ },
+ });
+
+ if (didUpdate && (plan.hasLead || plan.saleCount > 0)) {
+ await syncPartnerLinksStats({
+ partnerId,
+ programId,
+ eventType: plan.saleCount > 0 ? "sale" : "lead",
+ });
+ }
+}
+
+export async function decrementOldLinkStats({
+ oldCustomerId,
+ oldLinkId,
+ oldPartnerId,
+ programId,
+ plan,
+ decrementConversions,
+}: {
+ oldCustomerId: string;
+ oldLinkId: string | null;
+ oldPartnerId: string | null;
+ programId: string;
+ plan: ReattributeEventPlan;
+ decrementConversions: boolean;
+}) {
+ if (!oldLinkId || !oldPartnerId) {
+ return;
+ }
+
+ const didUpdate = await runOnce({
+ key: `reattribute-customer:${oldCustomerId}:old-link-stats`,
+ fn: async () => {
+ await prisma.link.update({
+ where: { id: oldLinkId },
+ data: {
+ ...(plan.hasClick && {
+ clicks: { decrement: 1 },
+ }),
+ ...(plan.hasLead && {
+ leads: { decrement: plan.leadCount },
+ }),
+ ...(decrementConversions && {
+ conversions: { decrement: 1 },
+ }),
+ ...(plan.saleCount > 0 && {
+ sales: { decrement: plan.saleCount },
+ saleAmount: { decrement: plan.saleAmount },
+ }),
+ },
+ });
+ },
+ });
+
+ if (didUpdate && (plan.hasLead || plan.saleCount > 0)) {
+ await syncPartnerLinksStats({
+ partnerId: oldPartnerId,
+ programId,
+ eventType: plan.saleCount > 0 ? "sale" : "lead",
+ });
+ }
+}
+
+export async function transferUnpaidCommissions({
+ oldCustomerId,
+ newCustomerId,
+ newPartnerId,
+ newLinkId,
+ programId,
+ oldPartnerId,
+}: {
+ oldCustomerId: string;
+ newCustomerId: string;
+ newPartnerId: string;
+ newLinkId: string;
+ programId: string;
+ oldPartnerId: string | null;
+}) {
+ const unpaidCommissions = await prisma.commission.findMany({
+ where: {
+ customerId: oldCustomerId,
+ status: { in: [...UNPAID_COMMISSION_STATUSES] },
+ },
+ select: {
+ id: true,
+ payoutId: true,
+ payout: {
+ select: {
+ id: true,
+ status: true,
+ },
+ },
+ },
+ });
+
+ if (unpaidCommissions.length === 0) {
+ return { transferred: 0 };
+ }
+
+ const payoutIds = unpaidCommissions
+ .map((commission) => commission.payoutId)
+ .filter((payoutId): payoutId is string => Boolean(payoutId));
+
+ const mutablePayoutIds = unpaidCommissions
+ .filter(
+ (commission) =>
+ commission.payoutId &&
+ commission.payout &&
+ MUTABLE_PAYOUT_STATUSES.includes(commission.payout.status),
+ )
+ .map((commission) => commission.payoutId)
+ .filter((payoutId): payoutId is string => Boolean(payoutId));
+
+ const processedPayoutIds = payoutIds.filter(
+ (payoutId) => !mutablePayoutIds.includes(payoutId),
+ );
+
+ await prisma.commission.updateMany({
+ where: {
+ id: { in: unpaidCommissions.map((commission) => commission.id) },
+ },
+ data: {
+ customerId: newCustomerId,
+ partnerId: newPartnerId,
+ linkId: newLinkId,
+ payoutId: null,
+ },
+ });
+
+ await reconcilePayoutAmounts(mutablePayoutIds);
+ await retallyPayoutsAmount(processedPayoutIds);
+
+ await Promise.all([
+ syncTotalCommissions({
+ partnerId: newPartnerId,
+ programId,
+ }),
+ oldPartnerId
+ ? syncTotalCommissions({
+ partnerId: oldPartnerId,
+ programId,
+ })
+ : Promise.resolve(),
+ ]);
+
+ return { transferred: unpaidCommissions.length };
+}
+
+export async function createClawbackAndReplacementCommissions({
+ oldCustomerId,
+ newCustomerId,
+ oldPartnerId,
+ newPartnerId,
+ newLinkId,
+ programId,
+ customerCountry,
+}: {
+ oldCustomerId: string;
+ newCustomerId: string;
+ oldPartnerId: string | null;
+ newPartnerId: string;
+ newLinkId: string;
+ programId: string;
+ customerCountry: string | null;
+}) {
+ if (!oldPartnerId) {
+ return { skipped: true, reason: "no-old-partner" as const };
+ }
+
+ const existingClawback = await prisma.commission.findFirst({
+ where: {
+ customerId: oldCustomerId,
+ partnerId: oldPartnerId,
+ programId,
+ type: "custom",
+ description: "tracking_error",
+ earnings: { lt: 0 },
+ },
+ select: { id: true },
+ });
+
+ if (existingClawback) {
+ return { skipped: true, reason: "already-clawed-back" as const };
+ }
+
+ const paidCommissions = await prisma.commission.findMany({
+ where: {
+ customerId: oldCustomerId,
+ partnerId: oldPartnerId,
+ status: "paid",
+ },
+ select: {
+ id: true,
+ eventId: true,
+ invoiceId: true,
+ earnings: true,
+ type: true,
+ },
+ });
+
+ const paidEarnings = paidCommissions.reduce(
+ (sum, commission) => sum + commission.earnings,
+ 0,
+ );
+
+ if (paidEarnings <= 0) {
+ return { skipped: true, reason: "no-paid-earnings" as const };
+ }
+
+ const paidEventIds = paidCommissions
+ .map((commission) => commission.eventId)
+ .filter((eventId): eventId is string => Boolean(eventId));
+
+ if (paidEventIds.length > 0 || paidCommissions.some((c) => c.invoiceId)) {
+ await prisma.commission.updateMany({
+ where: {
+ id: { in: paidCommissions.map((commission) => commission.id) },
+ },
+ data: {
+ eventId: null,
+ invoiceId: null,
+ },
+ });
+ }
+
+ await queuePartnerCommissionCreation({
+ event: "custom",
+ partnerId: oldPartnerId,
+ programId,
+ customerId: oldCustomerId,
+ amount: -paidEarnings,
+ quantity: 1,
+ description: "tracking_error",
+ skipWorkflow: true,
+ });
+
+ const existingReplacement = await prisma.commission.findFirst({
+ where: {
+ customerId: newCustomerId,
+ partnerId: newPartnerId,
+ type: { in: ["lead", "sale"] },
+ },
+ select: { id: true },
+ });
+
+ if (existingReplacement) {
+ await syncTotalCommissions({
+ partnerId: oldPartnerId,
+ programId,
+ });
+
+ return { skipped: false, clawback: true, recreated: 0 };
+ }
+
+ const newEvents = await getCustomerReattributeEvents(newCustomerId);
+ const leadEvent = newEvents.find((event) => event.event === "lead");
+ const saleEvents = newEvents.filter((event) => event.event === "sale");
+
+ if (leadEvent?.event_id) {
+ await queuePartnerCommissionCreation({
+ event: "lead",
+ programId,
+ partnerId: newPartnerId,
+ linkId: newLinkId,
+ customerId: newCustomerId,
+ eventId: leadEvent.event_id,
+ quantity: 1,
+ createdAt: new Date(`${leadEvent.timestamp}Z`),
+ context: {
+ customer: { country: customerCountry },
+ },
+ skipWorkflow: true,
+ });
+ }
+
+ for (const saleEvent of saleEvents) {
+ if (!saleEvent.event_id) {
+ continue;
+ }
+
+ await queuePartnerCommissionCreation({
+ event: "sale",
+ programId,
+ partnerId: newPartnerId,
+ linkId: newLinkId,
+ customerId: newCustomerId,
+ eventId: saleEvent.event_id,
+ quantity: 1,
+ amount: saleEvent.saleAmount,
+ currency: saleEvent.currency,
+ invoiceId: saleEvent.invoice_id,
+ createdAt: new Date(`${saleEvent.timestamp}Z`),
+ context: {
+ customer: { country: customerCountry },
+ },
+ skipWorkflow: true,
+ });
+ }
+
+ await Promise.all([
+ syncTotalCommissions({
+ partnerId: oldPartnerId,
+ programId,
+ }),
+ syncTotalCommissions({
+ partnerId: newPartnerId,
+ programId,
+ }),
+ ]);
+
+ return {
+ skipped: false,
+ clawback: true,
+ recreated: (leadEvent ? 1 : 0) + saleEvents.length,
+ };
+}
+
+export async function deleteOldCustomerTinybirdEvents({
+ oldCustomerId,
+ oldClickId,
+}: {
+ oldCustomerId: string;
+ oldClickId: string | null;
+}) {
+ await deleteTinybirdCustomerEvents({
+ customerId: oldCustomerId,
+ clickId: oldClickId,
+ });
+}
+
+export function shouldRecreateCustomer({
+ eventCount,
+ commissionCount,
+}: {
+ eventCount: number;
+ commissionCount: number;
+}) {
+ return eventCount > 0 || commissionCount > 0;
+}
+
+export function computeConversionFlags({
+ customer,
+ newLinkId,
+}: {
+ customer: Pick<Customer, "sales" | "linkId">;
+ newLinkId: string;
+}) {
+ const incrementConversions =
+ customer.sales > 0 && isFirstConversion({ customer, linkId: newLinkId });
+ const decrementConversions = customer.sales > 0 && Boolean(customer.linkId);
+
+ return {
+ incrementConversions,
+ decrementConversions,
+ };
+}
diff --git a/apps/web/lib/jobs/send-workflows.ts b/apps/web/lib/jobs/send-workflows.ts
index b618d65feb..57374093fd 100644
--- a/apps/web/lib/jobs/send-workflows.ts
+++ b/apps/web/lib/jobs/send-workflows.ts
@@ -29,6 +29,7 @@ const workflowPathMap = {
"merge-partner-accounts-workflow": "/api/workflows/merge-partner-accounts",
"create-partner-commission-workflow":
"/api/workflows/create-partner-commission",
+ "reattribute-customer-workflow": "/api/workflows/reattribute-customer",
} as const;
for (const name of Object.keys(workflowPathMap)) {
diff --git a/apps/web/lib/tinybird/delete-events.ts b/apps/web/lib/tinybird/delete-events.ts
new file mode 100644
index 0000000000..03781d9648
--- /dev/null
+++ b/apps/web/lib/tinybird/delete-events.ts
@@ -0,0 +1,106 @@
+const TINYBIRD_ID_PATTERN = /^[a-zA-Z0-9_]+$/;
+
+function assertSafeTinybirdId(value: string, label: string) {
+ if (!TINYBIRD_ID_PATTERN.test(value)) {
+ throw new Error(`Invalid ${label} for Tinybird delete.`);
+ }
+}
+
+async function deleteDatasourceRows({
+ dataSource,
+ deleteCondition,
+}: {
+ dataSource: string;
+ deleteCondition: string;
+}) {
+ const baseUrl = process.env.TINYBIRD_API_URL;
+ const token = process.env.TINYBIRD_API_KEY;
+
+ if (!baseUrl || !token) {
+ throw new Error("Tinybird is not configured.");
+ }
+
+ const response = await fetch(
+ `${baseUrl}/v0/datasources/${dataSource}/delete`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: `delete_condition=${deleteCondition}`,
+ },
+ );
+
+ const payload = await response.json().catch(() => null);
+
+ if (!response.ok) {
+ throw new Error(
+ `Tinybird delete failed for ${dataSource}: ${JSON.stringify(payload)}`,
+ );
+ }
+
+ return payload;
+}
+
+export async function deleteTinybirdCustomerEvents({
+ customerId,
+ clickId,
+}: {
+ customerId: string;
+ clickId?: string | null;
+}) {
+ assertSafeTinybirdId(customerId, "customerId");
+
+ const customerCondition = `customer_id='${customerId}'`;
+
+ const deletions: Promise<unknown>[] = [
+ deleteDatasourceRows({
+ dataSource: "dub_lead_events",
+ deleteCondition: customerCondition,
+ }),
+ deleteDatasourceRows({
+ dataSource: "dub_lead_events_mv",
+ deleteCondition: customerCondition,
+ }),
+ deleteDatasourceRows({
+ dataSource: "dub_sale_events",
+ deleteCondition: customerCondition,
+ }),
+ deleteDatasourceRows({
+ dataSource: "dub_sale_events_mv",
+ deleteCondition: customerCondition,
+ }),
+ ];
+
+ if (clickId) {
+ assertSafeTinybirdId(clickId, "clickId");
+ const clickCondition = `click_id='${clickId}'`;
+
+ deletions.push(
+ deleteDatasourceRows({
+ dataSource: "dub_click_events",
+ deleteCondition: clickCondition,
+ }),
+ deleteDatasourceRows({
+ dataSource: "dub_click_events_mv",
+ deleteCondition: clickCondition,
+ }),
+ deleteDatasourceRows({
+ dataSource: "dub_click_events_id",
+ deleteCondition: clickCondition,
+ }),
+ );
+ }
+
+ const results = await Promise.allSettled(deletions);
+ const failed = results.filter((result) => result.status === "rejected");
+
+ if (failed.length > 0) {
+ throw new Error(
+ `Failed to delete ${failed.length} Tinybird datasource(s) for customer ${customerId}.`,
+ );
+ }
+
+ return results;
+}
diff --git a/apps/web/lib/tinybird/get-customer-events-tb.ts b/apps/web/lib/tinybird/get-customer-events-tb.ts
index 51eaf3ee35..f32ae487db 100644
--- a/apps/web/lib/tinybird/get-customer-events-tb.ts
+++ b/apps/web/lib/tinybird/get-customer-events-tb.ts
@@ -10,12 +10,15 @@ const pipe = tb.buildPipe({
export const getCustomerEventsTB = async ({
customerId,
linkIds,
+ limit,
}: {
customerId: string;
linkIds?: string[];
+ limit?: number;
}) => {
return await pipe({
customerId,
...(linkIds ? { linkIds } : {}),
+ ...(limit ? { limit } : {}),
});
};
diff --git a/apps/web/lib/tinybird/index.ts b/apps/web/lib/tinybird/index.ts
index fc7b91e1d9..a13734aa29 100644
--- a/apps/web/lib/tinybird/index.ts
+++ b/apps/web/lib/tinybird/index.ts
@@ -1,4 +1,5 @@
export * from "./client";
+export * from "./delete-events";
export * from "./get-click-event";
export * from "./get-lead-event";
export * from "./record-click";
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index 214373c1bd..bc7cec720b 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -109,4 +109,13 @@ export const RATELIMIT_POLICIES = {
window: "1 h",
keyPrefix: "rl:domains:forward-dns-instructions:target",
},
+
+ // One reattribution per workspace per minute
+ reattributeCustomer: {
+ attempts: 1,
+ window: "1 m",
+ keyPrefix: "rl:customers:reattribute",
+ message: ({ retryAfter }) =>
+ `Customer reattribution is limited to once per minute because it updates analytics. Try again in ${retryAfter}.`,
+ },
} as const satisfies Record<string, RatelimitPolicy>;
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 61d210a621..e26b20c85f 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -140,6 +140,36 @@ export const updateCustomerBodySchema = createCustomerBodySchema
),
});
+export const reattributeCustomerBodySchema = z.object({
+ partnerId: z.string().describe("The partner to attribute this customer to."),
+ linkId: z
+ .string()
+ .describe("The partner referral link to attribute this customer to."),
+ createClawback: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(
+ "If the previous partner was already paid, create a clawback for those earnings and recreate commissions for the new partner.",
+ ),
+});
+
+export const reattributeCustomerWorkflowSchema = z.object({
+ workspaceId: z.string(),
+ programId: z.string(),
+ oldCustomerId: z.string(),
+ newCustomerId: z.string(),
+ oldLinkId: z.string().nullable(),
+ newLinkId: z.string(),
+ oldPartnerId: z.string().nullable(),
+ newPartnerId: z.string(),
+ oldClickId: z.string().nullable(),
+ newClickId: z.string(),
+ createClawback: z.boolean(),
+ incrementConversions: z.boolean(),
+ decrementConversions: z.boolean(),
+});
+
// used in webhook responses + regular /customers endpoints (without expanded fields)
export const CustomerSchema = z.object({
id: z
diff --git a/apps/web/playwright/api/customers/customers-reattribute.spec.ts b/apps/web/playwright/api/customers/customers-reattribute.spec.ts
new file mode 100644
index 0000000000..7de03e3790
--- /dev/null
+++ b/apps/web/playwright/api/customers/customers-reattribute.spec.ts
@@ -0,0 +1,113 @@
+import type { Customer, CustomerEnriched } from "@/lib/types";
+import { expect } from "@playwright/test";
+import { apiError, randomCustomer } from "../../utils";
+import { test, type ApiClient } from "../fixtures";
+import { createPartner, deletePartner } from "../partners/helpers";
+
+async function createCustomer(
+ api: ApiClient,
+ overrides: Record<string, unknown> = {},
+) {
+ return api.post<Customer>("/api/customers", {
+ ...randomCustomer(),
+ ...overrides,
+ });
+}
+
+async function deleteCustomer(api: ApiClient, id: string | undefined) {
+ if (!id) return;
+ await api.delete(`/api/customers/${id}`);
+}
+
+test("POST /customers/{id}/reattribute – fast path", async ({ api }) => {
+ let customerId: string | undefined;
+ let partnerId: string | undefined;
+
+ try {
+ const { status: partnerStatus, data: partner } = await createPartner(api);
+ partnerId = partner.id;
+
+ expect(partnerStatus).toEqual(201);
+ expect(partner.links).not.toBeNull();
+ expect(partner.links!.length).toBeGreaterThan(0);
+
+ const targetLink = partner.links![0];
+ const { data: created } = await createCustomer(api);
+ customerId = created.id;
+
+ const { status, data } = await api.post<CustomerEnriched>(
+ `/api/customers/${created.id}/reattribute`,
+ {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ },
+ );
+
+ expect(status).toEqual(200);
+ expect(data.id).toEqual(created.id);
+ expect(data.partner?.id).toEqual(partner.id);
+ expect(data.link?.id).toEqual(targetLink.id);
+ } finally {
+ await deleteCustomer(api, customerId);
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /customers/{id}/reattribute – unknown customer", async ({ api }) => {
+ expect(
+ await api.post("/api/customers/cus_doesnotexist/reattribute", {
+ partnerId: "pn_doesnotexist",
+ linkId: "link_doesnotexist",
+ }),
+ ).toEqual(
+ apiError({
+ code: "not_found",
+ message:
+ "Customer not found. Make sure you're using the correct customer ID (e.g. `cus_3TagGjzRzmsFJdH8od2BNCsc`) or external ID (has to be prefixed with `ext_`).",
+ }),
+ );
+});
+
+test("POST /customers/{id}/reattribute – unchanged partner and link", async ({
+ api,
+}) => {
+ let customerId: string | undefined;
+ let partnerId: string | undefined;
+
+ try {
+ const { status: partnerStatus, data: partner } = await createPartner(api);
+ partnerId = partner.id;
+
+ expect(partnerStatus).toEqual(201);
+ expect(partner.links).not.toBeNull();
+ expect(partner.links!.length).toBeGreaterThan(0);
+
+ const targetLink = partner.links![0];
+ const { data: created } = await createCustomer(api);
+ customerId = created.id;
+
+ const { status: firstStatus } = await api.post<CustomerEnriched>(
+ `/api/customers/${created.id}/reattribute`,
+ {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ },
+ );
+ expect(firstStatus).toEqual(200);
+
+ expect(
+ await api.post(`/api/customers/${created.id}/reattribute`, {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ }),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message: "Customer is already attributed to this partner and link.",
+ }),
+ );
+ } finally {
+ await deleteCustomer(api, customerId);
+ await deletePartner(partnerId);
+ }
+});
diff --git a/apps/web/tests/workflows/reattribute-customer-workflow.test.ts b/apps/web/tests/workflows/reattribute-customer-workflow.test.ts
new file mode 100644
index 0000000000..990684e620
--- /dev/null
+++ b/apps/web/tests/workflows/reattribute-customer-workflow.test.ts
@@ -0,0 +1,254 @@
+import {
+ VITEST_POLL_INTERVAL_MS,
+ VITEST_TEST_TIMEOUT_MS,
+} from "@/lib/constants/misc";
+import {
+ CommissionResponse,
+ Customer,
+ CustomerEnriched,
+ EnrolledPartnerProps,
+} from "@/lib/types";
+import { sleep } from "@dub/utils";
+import { describe, expect, onTestFinished, test } from "vitest";
+
+import { randomCustomer, randomPartnerEmail } from "../utils/helpers";
+import { IntegrationHarness } from "../utils/integration";
+import { E2E_PARTNER_GROUP } from "../utils/resource";
+import { trackE2ELead } from "./utils/track-e2e-lead";
+import { verifyReattributeCompleted } from "./utils/verify-reattribute-completed";
+
+describe.sequential("Workflow - ReattributeCustomer", async () => {
+ const h = new IntegrationHarness();
+ const { http } = await h.init();
+
+ async function createEnrolledPartner(label: string) {
+ const { status, data: partner } = await http.post<EnrolledPartnerProps>({
+ path: "/partners",
+ body: {
+ name: `E2E Reattribute ${label}`,
+ email: randomPartnerEmail(),
+ groupId: E2E_PARTNER_GROUP.id,
+ },
+ });
+
+ expect(status).toEqual(201);
+ expect(partner.links).not.toBeNull();
+ expect(partner.links!.length).toBeGreaterThan(0);
+
+ return partner;
+ }
+
+ async function createManualCustomer() {
+ const body = {
+ ...randomCustomer(),
+ country: "US",
+ };
+
+ const { status, data: customer } = await http.post<Customer>({
+ path: "/customers",
+ body,
+ });
+
+ expect(status).toEqual(201);
+ return customer;
+ }
+
+ function cleanupCustomers(...ids: Array<string | undefined>) {
+ onTestFinished(async () => {
+ await Promise.all(
+ ids
+ .filter((id): id is string => Boolean(id))
+ .map((id) => h.deleteCustomer(id).catch(() => undefined)),
+ );
+ });
+ }
+
+ async function waitForCustomerByExternalId(externalId: string) {
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {
+ const { status, data: customers } = await http.get<CustomerEnriched[]>({
+ path: "/customers",
+ query: {
+ externalId,
+ includeExpandedFields: "true",
+ },
+ });
+
+ if (status === 200 && customers.length > 0) {
+ return customers[0];
+ }
+
+ await sleep(VITEST_POLL_INTERVAL_MS);
+ }
+
+ throw new Error(
+ `Customer with externalId ${externalId} was not found within ${VITEST_TEST_TIMEOUT_MS / 1000}s.`,
+ );
+ }
+
+ async function tryFindCommissions(
+ customerId: string,
+ maxWaitMs = 30_000,
+ ): Promise<CommissionResponse[]> {
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < maxWaitMs) {
+ const { status, data: commissions } = await http.get<
+ CommissionResponse[]
+ >({
+ path: "/commissions",
+ query: { customerId },
+ });
+
+ if (status === 200 && commissions.length > 0) {
+ return commissions;
+ }
+
+ await sleep(VITEST_POLL_INTERVAL_MS);
+ }
+
+ return [];
+ }
+
+ test(
+ "Fast path reattributes a manual customer in place",
+ { timeout: VITEST_TEST_TIMEOUT_MS },
+ async () => {
+ const partner = await createEnrolledPartner("fast-path");
+ const targetLink = partner.links![0];
+ const customer = await createManualCustomer();
+ cleanupCustomers(customer.id);
+
+ const { status, data: reattributed } = await http.post<CustomerEnriched>({
+ path: `/customers/${customer.id}/reattribute`,
+ body: {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(reattributed.id).toEqual(customer.id);
+ expect(reattributed.partner?.id).toEqual(partner.id);
+ expect(reattributed.link?.id).toEqual(targetLink.id);
+
+ const { status: getStatus, data: fetched } =
+ await http.get<CustomerEnriched>({
+ path: `/customers/${customer.id}`,
+ query: { includeExpandedFields: "true" },
+ });
+
+ expect(getStatus).toEqual(200);
+ expect(fetched.id).toEqual(customer.id);
+ expect(fetched.partner?.id).toEqual(partner.id);
+ expect(fetched.link?.id).toEqual(targetLink.id);
+ },
+ );
+
+ test(
+ "Lead reattribute creates a new customer and moves attribution",
+ { timeout: VITEST_TEST_TIMEOUT_MS * 2 },
+ async () => {
+ const sourcePartner = await createEnrolledPartner("lead-source");
+ const targetPartner = await createEnrolledPartner("lead-target");
+ const sourceLink = sourcePartner.links![0];
+ const targetLink = targetPartner.links![0];
+
+ const { customerExternalId } = await trackE2ELead(http, sourceLink);
+ const sourceCustomer =
+ await waitForCustomerByExternalId(customerExternalId);
+ cleanupCustomers(sourceCustomer.id);
+
+ expect(sourceCustomer.partner?.id).toEqual(sourcePartner.id);
+ expect(sourceCustomer.link?.id).toEqual(sourceLink.id);
+
+ const existingCommissions = await tryFindCommissions(sourceCustomer.id);
+
+ const { status, data: reattributed } = await http.post<CustomerEnriched>({
+ path: `/customers/${sourceCustomer.id}/reattribute`,
+ body: {
+ partnerId: targetPartner.id,
+ linkId: targetLink.id,
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(reattributed.id).not.toEqual(sourceCustomer.id);
+ cleanupCustomers(reattributed.id);
+
+ await verifyReattributeCompleted({
+ http,
+ oldCustomerId: sourceCustomer.id,
+ newCustomerId: reattributed.id,
+ targetPartnerId: targetPartner.id,
+ targetLinkId: targetLink.id,
+ expectTransferredCommission: existingCommissions.length > 0,
+ });
+ },
+ );
+
+ test(
+ "Reattributing to the same partner and link is rejected",
+ { timeout: VITEST_TEST_TIMEOUT_MS },
+ async () => {
+ const partner = await createEnrolledPartner("noop");
+ const targetLink = partner.links![0];
+ const customer = await createManualCustomer();
+ cleanupCustomers(customer.id);
+
+ const { status: firstStatus } = await http.post<CustomerEnriched>({
+ path: `/customers/${customer.id}/reattribute`,
+ body: {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ },
+ });
+ expect(firstStatus).toEqual(200);
+
+ const { status, data } = await http.post({
+ path: `/customers/${customer.id}/reattribute`,
+ body: {
+ partnerId: partner.id,
+ linkId: targetLink.id,
+ },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ code: "bad_request",
+ message: "Customer is already attributed to this partner and link.",
+ },
+ });
+ },
+ );
+
+ test(
+ "Reattributing with a link that does not belong to the partner is rejected",
+ { timeout: VITEST_TEST_TIMEOUT_MS },
+ async () => {
+ const partner = await createEnrolledPartner("bad-link-partner");
+ const otherPartner = await createEnrolledPartner("bad-link-other");
+ const customer = await createManualCustomer();
+ cleanupCustomers(customer.id);
+
+ const { status, data } = await http.post({
+ path: `/customers/${customer.id}/reattribute`,
+ body: {
+ partnerId: partner.id,
+ linkId: otherPartner.links![0].id,
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(data).toMatchObject({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "The selected referral link does not belong to this partner in the program.",
+ },
+ });
+ },
+ );
+});
diff --git a/apps/web/tests/workflows/utils/track-e2e-lead.ts b/apps/web/tests/workflows/utils/track-e2e-lead.ts
index 1452fb5ece..88c02555dc 100644
--- a/apps/web/tests/workflows/utils/track-e2e-lead.ts
+++ b/apps/web/tests/workflows/utils/track-e2e-lead.ts
@@ -4,7 +4,16 @@ import { E2E_TRACK_CLICK_HEADERS } from "../../utils/resource";
export async function trackE2ELead(
http: any,
partnerLink: { domain: string; key: string },
+ overrides?: {
+ customerExternalId?: string;
+ customerEmail?: string;
+ },
) {
+ const customerExternalId =
+ overrides?.customerExternalId ?? `e2e-customer-${Date.now()}`;
+ const customerEmail =
+ overrides?.customerEmail ?? `${customerExternalId}@example.com`;
+
const { status: clickStatus, data: clickData } = await http.post({
path: "/track/click",
headers: E2E_TRACK_CLICK_HEADERS,
@@ -22,10 +31,16 @@ export async function trackE2ELead(
body: {
clickId: clickData.clickId,
eventName: `Signup-${Date.now()}`,
- customerExternalId: `e2e-customer-${Date.now()}`,
- customerEmail: `[email protected]`,
+ customerExternalId,
+ customerEmail,
},
});
expect(leadStatus).toEqual(200);
+
+ return {
+ customerExternalId,
+ customerEmail,
+ clickId: clickData.clickId as string,
+ };
}
diff --git a/apps/web/tests/workflows/utils/verify-reattribute-completed.ts b/apps/web/tests/workflows/utils/verify-reattribute-completed.ts
new file mode 100644
index 0000000000..98ba787a51
--- /dev/null
+++ b/apps/web/tests/workflows/utils/verify-reattribute-completed.ts
@@ -0,0 +1,102 @@
+import {
+ VITEST_POLL_INTERVAL_MS,
+ VITEST_TEST_TIMEOUT_MS,
+} from "@/lib/constants/misc";
+import { CommissionResponse, CustomerEnriched } from "@/lib/types";
+import { sleep } from "@dub/utils";
+import { expect } from "vitest";
+
+import { HttpClient } from "../../utils/http";
+
+interface VerifyReattributeCompletedProps {
+ http: HttpClient;
+ oldCustomerId: string;
+ newCustomerId: string;
+ targetPartnerId: string;
+ targetLinkId: string;
+ expectTransferredCommission?: boolean;
+}
+
+/**
+ * Polls until the reattribute-customer workflow has finished:
+ * - the new customer is attributed to the target partner/link
+ * - the old customer remains as a retired stub
+ * - optional: an unpaid commission moved to the new customer
+ */
+export const verifyReattributeCompleted = async ({
+ http,
+ oldCustomerId,
+ newCustomerId,
+ targetPartnerId,
+ targetLinkId,
+ expectTransferredCommission = false,
+}: VerifyReattributeCompletedProps) => {
+ const startTime = Date.now();
+
+ let lastNewPartnerId: string | undefined;
+ let lastNewLinkId: string | undefined;
+ let lastOldName: string | undefined;
+
+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {
+ const [newRes, oldRes, commissionsRes] = await Promise.all([
+ http.get<CustomerEnriched>({
+ path: `/customers/${newCustomerId}`,
+ query: { includeExpandedFields: "true" },
+ }),
+ http.get<CustomerEnriched>({
+ path: `/customers/${oldCustomerId}`,
+ query: { includeExpandedFields: "true" },
+ }),
+ expectTransferredCommission
+ ? http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: { customerId: newCustomerId },
+ })
+ : Promise.resolve({ status: 200, data: [] as CommissionResponse[] }),
+ ]);
+
+ lastNewPartnerId =
+ newRes.status === 200 ? newRes.data.partner?.id : undefined;
+ lastNewLinkId = newRes.status === 200 ? newRes.data.link?.id : undefined;
+ lastOldName =
+ oldRes.status === 200 ? oldRes.data.name ?? undefined : undefined;
+
+ const newAttributed =
+ newRes.status === 200 &&
+ lastNewPartnerId === targetPartnerId &&
+ lastNewLinkId === targetLinkId;
+
+ const oldStubbed =
+ oldRes.status === 200 &&
+ Boolean(oldRes.data.name?.endsWith(" (old)")) &&
+ !oldRes.data.partner &&
+ oldRes.data.stripeCustomerId == null;
+
+ const commissionMoved =
+ !expectTransferredCommission ||
+ (commissionsRes.status === 200 &&
+ commissionsRes.data.some(
+ (commission) =>
+ commission.customer?.id === newCustomerId &&
+ commission.partner?.id === targetPartnerId,
+ ));
+
+ if (newAttributed && oldStubbed && commissionMoved) {
+ expect(lastNewPartnerId).toBe(targetPartnerId);
+ expect(lastNewLinkId).toBe(targetLinkId);
+ expect(oldRes.data.name).toMatch(/ \(old\)$/);
+ return {
+ newCustomer: newRes.data,
+ oldCustomer: oldRes.data,
+ };
+ }
+
+ await sleep(VITEST_POLL_INTERVAL_MS);
+ }
+
+ throw new Error(
+ `Reattribution did not complete within ${VITEST_TEST_TIMEOUT_MS / 1000}s. ` +
+ `newCustomerId: ${newCustomerId} (partner: ${lastNewPartnerId}, link: ${lastNewLinkId}), ` +
+ `oldCustomerId: ${oldCustomerId} (name: ${lastOldName}).`,
+ );
+};
diff --git a/apps/web/ui/customers/customer-details-column.tsx b/apps/web/ui/customers/customer-details-column.tsx
index 3183f17dcf..2bc55c4790 100644
--- a/apps/web/ui/customers/customer-details-column.tsx
+++ b/apps/web/ui/customers/customer-details-column.tsx
@@ -22,10 +22,11 @@ import {
getPrettyUrl,
} from "@dub/utils";
import { Pencil } from "lucide-react";
-import { useParams } from "next/navigation";
+import { useParams, usePathname, useRouter } from "next/navigation";
import { Fragment, HTMLProps, useMemo } from "react";
import { DeviceIcon } from "../analytics/device-icon";
import { useEditCustomerModal } from "../modals/edit-customer-modal";
+import { useReattributeCustomerModal } from "../modals/reattribute-customer-modal";
import { ConditionalLink } from "../shared/conditional-link";
import { CustomerAvatar } from "./customer-avatar";
@@ -42,8 +43,12 @@ export function CustomerDetailsColumn({
}) {
const { programSlug } = useParams<{ programSlug: string }>();
const { product } = useCurrentProduct();
+ const pathname = usePathname();
+ const router = useRouter();
const { EditCustomerModal, openEditCustomerModal } = useEditCustomerModal();
+ const { ReattributeCustomerModal, openReattributeCustomerModal } =
+ useReattributeCustomerModal();
const basicFields = [
customer?.email
@@ -130,9 +135,12 @@ export function CustomerDetailsColumn({
})).filter(({ value }) => value);
}, [click?.url]);
+ const showReferralCard = Boolean(workspaceSlug || link || !customer);
+
return (
<>
<EditCustomerModal />
+ <ReattributeCustomerModal />
<div className="grid grid-cols-1 gap-6 overflow-hidden whitespace-nowrap text-sm text-neutral-900">
<div className="border-border-subtle flex flex-col divide-y divide-neutral-200 rounded-xl border bg-white">
<div className="p-4">
@@ -317,11 +325,35 @@ export function CustomerDetailsColumn({
</div>
</div>
- {(link || !customer) && (
+ {showReferralCard && (
<div className="border-border-subtle rounded-lg border p-4">
- <h2 className="text-content-emphasis mb-2.5 text-sm font-semibold">
- Referral {partner ? "partner" : "link"}
- </h2>
+ <div className="mb-2.5 flex items-center justify-between gap-2">
+ <h2 className="text-content-emphasis text-sm font-semibold">
+ Referral {partner || !link ? "partner" : "link"}
+ </h2>
+ {customer && workspaceSlug && (
+ <Button
+ variant="secondary"
+ icon={<Pencil className="size-3.5" />}
+ text={partner ? "Edit" : "Assign"}
+ className="h-7 w-fit rounded-lg px-2"
+ onClick={() =>
+ openReattributeCustomerModal(customer, {
+ onSuccess: (updatedCustomer) => {
+ if (
+ updatedCustomer.id !== customer.id &&
+ pathname.includes(customer.id)
+ ) {
+ router.push(
+ pathname.replace(customer.id, updatedCustomer.id),
+ );
+ }
+ },
+ })
+ }
+ />
+ )}
+ </div>
{partner && (
<div className="mb-4 flex items-center gap-2">
@@ -340,6 +372,12 @@ export function CustomerDetailsColumn({
</div>
)}
+ {!partner && customer && workspaceSlug && (
+ <p className="mb-4 text-xs text-neutral-500">
+ No partner assigned
+ </p>
+ )}
+
<div className="flex flex-col gap-2 text-xs">
{partner && <DetailHeading>Referral link</DetailHeading>}
{!customer || isCustomerActivityLoading ? (
@@ -361,7 +399,7 @@ export function CustomerDetailsColumn({
{getPrettyUrl(link.shortLink)}
</ConditionalLink>
</div>
- ) : (
+ ) : customer && workspaceSlug ? null : (
<span>-</span>
)}
</div>
diff --git a/apps/web/ui/modals/reattribute-customer-modal.tsx b/apps/web/ui/modals/reattribute-customer-modal.tsx
new file mode 100644
index 0000000000..542655c7e9
--- /dev/null
+++ b/apps/web/ui/modals/reattribute-customer-modal.tsx
@@ -0,0 +1,249 @@
+"use client";
+
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { CommissionsCount, CustomerEnriched, CustomerProps } from "@/lib/types";
+import { PartnerLinkSelector } from "@/ui/partners/partner-link-selector";
+import { PartnerSelector } from "@/ui/partners/partner-selector";
+import { Button, Checkbox, Modal } from "@dub/ui";
+import { currencyFormatter, fetcher } from "@dub/utils";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+type FormData = {
+ partnerId: string | null;
+ linkId: string | null;
+ createClawback: boolean;
+};
+
+type ReattributeCustomerModalProps = {
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
+ customer: Pick<CustomerEnriched, "id" | "partner" | "link">;
+ onSuccess?: (customer: CustomerProps) => void;
+};
+
+function ReattributeCustomerModal({
+ showModal,
+ setShowModal,
+ customer,
+ onSuccess,
+}: ReattributeCustomerModalProps) {
+ const { id: workspaceId } = useWorkspace();
+ const { makeRequest, isSubmitting } = useApiMutation<CustomerProps>();
+
+ const {
+ watch,
+ setValue,
+ handleSubmit,
+ reset,
+ formState: { isDirty },
+ } = useForm<FormData>({
+ defaultValues: {
+ partnerId: customer.partner?.id ?? null,
+ linkId: customer.link?.id ?? null,
+ createClawback: false,
+ },
+ });
+
+ const [partnerId, linkId, createClawback] = watch([
+ "partnerId",
+ "linkId",
+ "createClawback",
+ ]);
+
+ useEffect(() => {
+ if (showModal) {
+ reset({
+ partnerId: customer.partner?.id ?? null,
+ linkId: customer.link?.id ?? null,
+ createClawback: false,
+ });
+ }
+ }, [showModal, customer, reset]);
+
+ const { data: commissionsCount } = useSWR<CommissionsCount>(
+ workspaceId && customer.id && showModal
+ ? `/api/commissions/count?${new URLSearchParams({
+ customerId: customer.id,
+ workspaceId,
+ interval: "all",
+ })}`
+ : null,
+ fetcher,
+ );
+
+ const paidEarnings = commissionsCount?.paid?.earnings ?? 0;
+ const showClawback = paidEarnings > 0;
+ const isUnchanged =
+ partnerId === (customer.partner?.id ?? null) &&
+ linkId === (customer.link?.id ?? null);
+
+ const onSubmit = async (data: FormData) => {
+ if (!data.partnerId || !data.linkId) {
+ return;
+ }
+
+ await makeRequest(`/api/customers/${customer.id}/reattribute`, {
+ method: "POST",
+ body: {
+ partnerId: data.partnerId,
+ linkId: data.linkId,
+ createClawback: data.createClawback,
+ },
+ onSuccess: async (updatedCustomer) => {
+ toast.success("Customer reattributed. Analytics will update shortly.");
+ setShowModal(false);
+ await Promise.all([
+ mutatePrefix("/api/customers"),
+ mutatePrefix("/api/commissions"),
+ ]);
+ onSuccess?.(updatedCustomer);
+ },
+ });
+ };
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="sm:max-w-md"
+ >
+ <form
+ className="px-5 py-4"
+ onSubmit={(e) => {
+ e.stopPropagation();
+ handleSubmit(onSubmit)(e);
+ }}
+ >
+ <h3 className="text-lg font-medium">Assign to partner</h3>
+ <p className="mt-1 text-sm text-neutral-500">
+ Move this customer to a different partner. Unpaid commissions will
+ transfer automatically.
+ </p>
+
+ <div className="mt-6 flex flex-col gap-2">
+ <span className="block text-sm font-medium text-neutral-900">
+ Partner
+ </span>
+ <PartnerSelector
+ selectedPartnerId={partnerId}
+ setSelectedPartnerId={(id) => {
+ setValue("partnerId", id, { shouldDirty: true });
+ setValue("linkId", null, { shouldDirty: true });
+ }}
+ />
+ </div>
+
+ <div className="mt-4 flex flex-col gap-2">
+ <span className="block text-sm font-medium text-neutral-900">
+ Referral link
+ </span>
+ <PartnerLinkSelector
+ selectedLinkId={linkId}
+ partnerId={partnerId}
+ showDestinationUrl={false}
+ setSelectedLinkId={(id) =>
+ setValue("linkId", id, { shouldDirty: true })
+ }
+ disabledTooltip={
+ !partnerId
+ ? "You need to select a partner first before you can select a link"
+ : undefined
+ }
+ />
+ </div>
+
+ {showClawback && (
+ <label className="mt-5 flex items-start gap-2.5 rounded-lg border border-neutral-200 bg-neutral-50 p-3">
+ <Checkbox
+ checked={createClawback}
+ onCheckedChange={(checked) =>
+ setValue("createClawback", checked === true, {
+ shouldDirty: true,
+ })
+ }
+ className="mt-0.5"
+ />
+ <span className="text-sm text-neutral-700">
+ Create a clawback for{" "}
+ <span className="font-medium text-neutral-900">
+ {currencyFormatter(paidEarnings)}
+ </span>{" "}
+ already paid to the previous partner.
+ </span>
+ </label>
+ )}
+
+ <div className="mt-6 flex items-center justify-end gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-9 w-fit"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Save"
+ className="h-9 w-fit"
+ loading={isSubmitting}
+ disabled={!isDirty || isUnchanged || !partnerId || !linkId}
+ />
+ </div>
+ </form>
+ </Modal>
+ );
+}
+
+export function useReattributeCustomerModal() {
+ const [customer, setCustomer] = useState<CustomerEnriched | null>(null);
+ const [onSuccess, setOnSuccess] = useState<
+ ((customer: CustomerProps) => void) | undefined
+ >();
+
+ const openReattributeCustomerModal = useCallback(
+ (
+ nextCustomer: CustomerEnriched,
+ options?: { onSuccess?: (customer: CustomerProps) => void },
+ ) => {
+ setCustomer(nextCustomer);
+ setOnSuccess(() => options?.onSuccess);
+ },
+ [],
+ );
+
+ const ReattributeCustomerModalCallback = useCallback(() => {
+ if (!customer) {
+ return null;
+ }
+
+ return (
+ <ReattributeCustomerModal
+ customer={customer}
+ showModal
+ setShowModal={(show) => {
+ if (!show) {
+ setCustomer(null);
+ setOnSuccess(undefined);
+ }
+ }}
+ onSuccess={onSuccess}
+ />
+ );
+ }, [customer, onSuccess]);
+
+ return useMemo(
+ () => ({
+ openReattributeCustomerModal,
+ ReattributeCustomerModal: ReattributeCustomerModalCallback,
+ isReattributeCustomerModalOpen: customer !== null,
+ }),
+ [openReattributeCustomerModal, ReattributeCustomerModalCallback, customer],
+ );
+}