The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Create commissions for uncommissioned events when reattributing customers (#4637)
Kiran K5f666abe1d07
diff --git a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.tsindex 5d74f7c5ed..3f842d24fa 100644--- a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts+++ b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts@@ -24,6 +24,7 @@ import {} from "@/lib/zod/schemas/customers";import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";import { ACME_WORKSPACE_ID, nanoid } from "@dub/utils";+import { Prisma } from "@prisma/client";import { NextResponse } from "next/server";// POST /api/customers/:id/reattribute – Reattribute a customer to a different partner@@ -41,15 +42,10 @@ export const POST = withWorkspace(});}- const customer = await getCustomerOrThrow(- {- id,- workspaceId: workspace.id,- },- {- includeExpandedFields: true,- },- );+ const customer = await getCustomerOrThrow({+ id,+ workspaceId: workspace.id,+ });if (isReattributedCustomerStub(customer)) {throw new DubApiError({@@ -82,6 +78,12 @@ export const POST = withWorkspace(where: {id: linkId,},+ select: {+ id: true,+ projectId: true,+ programId: true,+ partnerId: true,+ },});if (@@ -109,49 +111,68 @@ export const POST = withWorkspace(if (events.length >= CUSTOMER_REATTRIBUTION_EVENTS_LIMIT) {throw new DubApiError({code: "unprocessable_entity",- message: `This customer has too many events to reattribute (limit ${CUSTOMER_REATTRIBUTION_EVENTS_LIMIT}).`,+ message: `This customer has at least ${CUSTOMER_REATTRIBUTION_EVENTS_LIMIT} events, so their full history cannot be moved.`,});}- if (+ // No events, commissions, click, or sales to move, so update this customer in place.+ const hasNoHistory =events.length === 0 &&commissionCount === 0 &&!customer.clickId &&- customer.sales === 0- ) {- const updatedCustomer = await prisma.customer.update({- where: {- id: customer.id,- },- data: {- partnerId: link.partnerId,- linkId: link.id,- programId: link.programId,- },- include: {- link: {- include: {- linkReward: {- select: {- discount: true,+ customer.sales === 0;++ if (hasNoHistory) {+ const updatedCustomer = await prisma.customer+ .update({+ where: {+ id: customer.id,+ partnerId: customer.partnerId,+ linkId: customer.linkId,+ },+ data: {+ partnerId: link.partnerId,+ linkId: link.id,+ programId: link.programId,+ },+ include: {+ link: {+ include: {+ linkReward: {+ select: {+ discount: true,+ },},},},- },- programEnrollment: {- include: {- partner: true,- discount: true,+ programEnrollment: {+ include: {+ partner: true,+ discount: true,+ },},},- },- });+ })+ .catch((error) => {+ if (+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2025"+ ) {+ throw new DubApiError({+ code: "conflict",+ message: `Customer "${customer.id}" changed while being reattributed. Please try again.`,+ });+ }++ throw error;+ });return NextResponse.json(CustomerEnrichedSchema.parse(transformCustomer(updatedCustomer)),);}+ // Events, commissions, a click, or sales exist, so create a new customer and move the history.const newCustomerId = createId({ prefix: "cus_" });const newClickId = nanoid(16);const incrementConversions =diff --git a/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts b/apps/web/app/(ee)/api/workflows/reattribute-customer/route.tsindex 143ab44de1..e2eb265c04 100644--- a/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts+++ b/apps/web/app/(ee)/api/workflows/reattribute-customer/route.ts@@ -1,9 +1,11 @@import {applyClawbackAndReplacementCommissions,+ createMissingPartnerCommissions,decrementOldLinkStats,incrementNewLinkStats,loadClawbackPlan,loadReattributeEventPlan,+ ReattributeEventsNotReadyError,reingestCustomerEvents,transferUnpaidCommissions,} from "@/lib/api/customers/reattribute-customer";@@ -27,9 +29,10 @@ type Input = z.infer<typeof reattributeCustomerWorkflowSchema>;* 2. reingest-events: copy events onto the new customer + link* 3. increment-new-link-stats* 4. transfer-unpaid-commissions- * 5. load-clawback-plan + optional-clawback- * 6. delete-old-events- * 7. decrement-old-link-stats+ * 5. create-missing-commissions: commission lead/sale events only when neither customer has a lead or sale commission+ * 6. load-clawback-plan + optional-clawback+ * 7. delete-old-events+ * 8. decrement-old-link-stats*/// POST /api/workflows/reattribute-customer@@ -107,6 +110,27 @@ export const { POST } = serve<Input>();});+ await context.run("create-missing-commissions", async () => {+ try {+ const commissions = await createMissingPartnerCommissions({+ oldCustomerId: input.oldCustomerId,+ newCustomerId: input.newCustomerId,+ newPartnerId: input.newPartnerId,+ newLinkId: input.newLinkId,+ programId: input.programId,+ plan,+ });++ return logAndReturn(commissions);+ } catch (error) {+ if (error instanceof ReattributeEventsNotReadyError) {+ throw new WorkflowRetryAfterError(error.message, "10s");+ }++ throw error;+ }+ });+if (input.createClawback) {const newCustomer = await context.run("load-new-customer-country",diff --git a/apps/web/lib/api/customers/reattribute-customer.ts b/apps/web/lib/api/customers/reattribute-customer.tsindex 30a77b10ab..ef9de21d3d 100644--- a/apps/web/lib/api/customers/reattribute-customer.ts+++ b/apps/web/lib/api/customers/reattribute-customer.ts@@ -16,7 +16,7 @@ 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 { CommissionType, Customer, EventType, Link } from "@prisma/client";import * as z from "zod/v4";export const CUSTOMER_REATTRIBUTION_EVENTS_LIMIT = 500;@@ -813,6 +813,7 @@ export async function applyClawbackAndReplacementCommissions({},select: {type: true,+ eventId: true,invoiceId: true,},}),@@ -833,9 +834,11 @@ export async function applyClawbackAndReplacementCommissions({.map((commission) => commission.invoiceId).filter((invoiceId): invoiceId is string => Boolean(invoiceId)),);- const existingInvoicelessCount = existingNewCommissions.filter(- (commission) => commission.type === "sale" && !commission.invoiceId,- ).length;+ const existingEventIds = new Set(+ existingNewCommissions+ .map((commission) => commission.eventId)+ .filter((eventId): eventId is string => Boolean(eventId)),+ );const saleEvents = [...newEvents.filter(@@ -845,11 +848,12 @@ export async function applyClawbackAndReplacementCommissions({paidInvoiceIds.has(event.invoice_id) &&!existingInvoiceIds.has(event.invoice_id),),- ...newEvents- .filter((event) => event.event === "sale" && !event.invoice_id)- .slice(- 0,- Math.max(0, plan.paidInvoicelessCount - existingInvoicelessCount),+ ...sortEventsByTimestamp(+ newEvents.filter((event) => event.event === "sale" && !event.invoice_id),+ )+ .slice(0, plan.paidInvoicelessCount)+ .filter(+ (event) => !event.event_id || !existingEventIds.has(event.event_id),),];@@ -911,3 +915,252 @@ export async function applyClawbackAndReplacementCommissions({recreated: (leadEvent ? 1 : 0) + saleEvents.length,};}++export function sortEventsByTimestamp<+ T extends Pick<CustomerTBEvent, "timestamp">,+>(events: T[]) {+ return [...events].sort((a, b) => a.timestamp.localeCompare(b.timestamp));+}++// Finds lead and sale events that don't have a commission yet.+// Existing commissions are matched by event ID, then invoice ID, then+// (for sales without an invoice) one per sale, oldest first.+export function selectUncommissionedEvents<+ T extends Pick<CustomerTBEvent, "timestamp" | "event_id" | "invoice_id"> & {+ event: string;+ },+>({+ newEvents,+ existingCommissions,+}: {+ newEvents: T[];+ existingCommissions: {+ type: CommissionType;+ eventId: string | null;+ invoiceId: string | null;+ }[];+}) {+ const currentEventIds = new Set(newEvents.map((event) => event.event_id));+ const commissionedEventIds = new Set<string>();+ const priorInvoiceIds = new Set<string>();++ let hasPriorLead = false;+ // Counts the sale commissions that already exist from earlier history but have no invoice ID.+ let priorInvoicelessCount = 0;++ for (const commission of existingCommissions) {+ if (commission.eventId) {+ commissionedEventIds.add(commission.eventId);++ if (currentEventIds.has(commission.eventId)) {+ continue;+ }+ }++ if (commission.type === CommissionType.lead) {+ hasPriorLead = true;+ } else if (commission.type === CommissionType.sale) {+ if (commission.invoiceId) {+ priorInvoiceIds.add(commission.invoiceId);+ } else {+ priorInvoicelessCount++;+ }+ }+ }++ let leadEvent: T | null = null;+ const saleEvents: T[] = [];++ for (const event of sortEventsByTimestamp(newEvents)) {+ const isInvoicelessSale =+ event.event === EventType.sale && !event.invoice_id;++ // Sales without an invoice can't be matched to a commission by ID: the copied+ // events have new event IDs and there is no invoice ID to compare. Instead,+ // each prior invoiceless commission covers one invoiceless sale, oldest first,+ // and only the sales left over get a new commission. Clawback recreates paid+ // ones from the oldest sales too, so the two steps never pick the same sale.+ if (isInvoicelessSale && priorInvoicelessCount > 0) {+ priorInvoicelessCount--;+ continue;+ }++ if (!event.event_id || commissionedEventIds.has(event.event_id)) {+ continue;+ }++ if (event.event === EventType.lead) {+ if (!hasPriorLead && !leadEvent) {+ leadEvent = event;+ }+ } else if (event.event === EventType.sale) {+ if (isInvoicelessSale || !priorInvoiceIds.has(event.invoice_id!)) {+ saleEvents.push(event);+ }+ }+ }++ return {+ leadEvent,+ saleEvents,+ };+}++export class ReattributeEventsNotReadyError extends Error {}++// Creates commissions for lead/sale events that have none, when this customer+// has never had a lead or sale commission:+// - the customer came from a regular short link (no partner, so no commissions)+// - the old partner never earned a lead or sale commission+// - events were tracked before the old link was added to a program+//+// Any existing lead or sale commission means the reward engine already ran.+// Paid rows stay on the old customer, so replaying later uncommissioned sales+// would treat them as a new first sale for the new partner.+export async function createMissingPartnerCommissions({+ oldCustomerId,+ newCustomerId,+ newPartnerId,+ newLinkId,+ programId,+ plan,+}: {+ oldCustomerId: string;+ newCustomerId: string;+ newPartnerId: string;+ newLinkId: string;+ programId: string;+ plan: ReattributeEventPlan;+}) {+ const existingCommission = await prisma.commission.findFirst({+ where: {+ customerId: {+ in: [oldCustomerId, newCustomerId],+ },+ type: {+ in: [CommissionType.lead, CommissionType.sale],+ },+ },+ select: {+ id: true,+ },+ });++ if (existingCommission) {+ return {+ skipped: true,+ reason: "existing-commissions",+ created: 0,+ };+ }++ const [newEvents, existingCommissions, newCustomer] = await Promise.all([+ getCustomerReattributeEvents(newCustomerId),++ prisma.commission.findMany({+ where: {+ customerId: {+ in: [oldCustomerId, newCustomerId],+ },+ type: {+ in: [CommissionType.lead, CommissionType.sale],+ },+ },+ select: {+ type: true,+ eventId: true,+ invoiceId: true,+ },+ }),++ prisma.customer.findUnique({+ where: {+ id: newCustomerId,+ },+ select: {+ country: true,+ },+ }),+ ]);++ const newLeadCount = newEvents.filter(+ (e) => e.event === EventType.lead,+ ).length;++ const newSaleCount = newEvents.filter(+ (e) => e.event === EventType.sale,+ ).length;++ if (newLeadCount < plan.leadCount || newSaleCount < plan.saleCount) {+ throw new ReattributeEventsNotReadyError(+ `Re-ingested events for customer ${newCustomerId} are not queryable yet.`,+ );+ }++ const { leadEvent, saleEvents } = selectUncommissionedEvents({+ newEvents,+ existingCommissions,+ });++ if (!leadEvent && saleEvents.length === 0) {+ return {+ skipped: true,+ created: 0,+ };+ }++ let created = 0;++ await runOnce({+ key: `reattribute-customer:${oldCustomerId}:missing-commissions`,+ fn: async () => {+ const context = {+ customer: {+ country: newCustomer?.country ?? null,+ },+ };++ if (leadEvent?.event_id) {+ await queuePartnerCommissionCreation({+ event: CommissionType.lead,+ programId,+ partnerId: newPartnerId,+ linkId: newLinkId,+ customerId: newCustomerId,+ eventId: leadEvent.event_id,+ quantity: 1,+ createdAt: new Date(`${leadEvent.timestamp}Z`),+ context,+ skipWorkflow: true,+ });++ created++;+ }++ for (const saleEvent of saleEvents) {+ await queuePartnerCommissionCreation({+ event: CommissionType.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,+ skipWorkflow: true,+ });++ created++;+ }+ },+ });++ return {+ skipped: false,+ created,+ };+}diff --git a/apps/web/ui/modals/reattribute-customer-modal.tsx b/apps/web/ui/modals/reattribute-customer-modal.tsxindex d4ad479f7c..6d93224244 100644--- a/apps/web/ui/modals/reattribute-customer-modal.tsx+++ b/apps/web/ui/modals/reattribute-customer-modal.tsx@@ -205,25 +205,35 @@ function ReattributeCustomerModal({</div>{showClawback && (- <label className="flex items-start gap-2.5 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm">- <Checkbox- checked={createClawback}- onCheckedChange={(checked) =>- setValue("createClawback", checked === true, {- shouldDirty: true,- })- }- className="mt-0.5 data-[state=checked]:bg-black"- />- <span className="text-sm text-neutral-700">- Create a clawback for the{" "}- <span className="font-medium text-neutral-900">- {currencyFormatter(paidEarnings)}- </span>{" "}- in commissions that were already paid to the previous- partner.- </span>- </label>+ <div className="flex flex-col gap-3 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm">+ <label className="flex items-start gap-2.5">+ <Checkbox+ checked={createClawback}+ onCheckedChange={(checked) =>+ setValue("createClawback", checked === true, {+ shouldDirty: true,+ })+ }+ className="mt-0.5 data-[state=checked]:bg-black"+ />+ <span className="text-sm text-neutral-700">+ Create a clawback for the{" "}+ <span className="font-medium text-neutral-900">+ {currencyFormatter(paidEarnings)}+ </span>{" "}+ in commissions that were already paid to the previous+ partner.+ </span>+ </label>+ {!createClawback && (+ <p className="text-xs text-neutral-500">+ If left unchecked, Dub will skip creating duplicate+ commissions for the new partner, since those+ commissions have already been paid to the previous+ partner.+ </p>+ )}+ </div>)}</>)}