The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
code improvements
Pedro Ladeira14cf9703ce8a
diff --git a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.tsindex 830335e019..ebd0f20dca 100644--- a/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts+++ b/apps/web/app/(ee)/api/customers/[id]/reattribute/route.ts@@ -1,8 +1,11 @@import { createId } from "@/lib/api/create-id";import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";import {+ CUSTOMER_EVENTS_LIMIT,computeConversionFlags,+ customerEventsExceedLimit,getCustomerReattributeEvents,+ isRetiredReattributeStub,recreateCustomerForReattribution,shouldRecreateCustomer,} from "@/lib/api/customers/reattribute-customer";@@ -20,6 +23,7 @@ import {CustomerEnrichedSchema,reattributeCustomerBodySchema,} from "@/lib/zod/schemas/customers";+import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";import { nanoid } from "@dub/utils";import { NextResponse } from "next/server";@@ -46,6 +50,14 @@ export const POST = withWorkspace(},);+ if (isRetiredReattributeStub(customer)) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "This customer was already reattributed. Use the new customer ID.",+ });+ }+if (customer.partnerId === partnerId && customer.linkId === linkId) {throw new DubApiError({code: "bad_request",@@ -53,12 +65,19 @@ export const POST = withWorkspace(});}- await getProgramEnrollmentOrThrow({+ const enrollment = await getProgramEnrollmentOrThrow({partnerId,programId,include: {},});+ if (INACTIVE_ENROLLMENT_STATUSES.includes(enrollment.status)) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: "This partner is not eligible to receive customers.",+ });+ }+const link = await prisma.link.findUnique({where: {id: linkId,@@ -87,10 +106,19 @@ export const POST = withWorkspace(}),]);+ if (customerEventsExceedLimit(events.length)) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `This customer has too many events to reattribute (limit ${CUSTOMER_EVENTS_LIMIT}).`,+ });+ }+if (!shouldRecreateCustomer({eventCount: events.length,commissionCount,+ clickId: customer.clickId,+ sales: customer.sales,})) {const updatedCustomer = await prisma.customer.update({@@ -152,7 +180,7 @@ export const POST = withWorkspace(decrementConversions,},options: {- deduplicationId: customer.id,+ deduplicationId: `${customer.id}:${newCustomerId}`,flowControl: {key: workspace.id,parallelism: 1,@@ -178,5 +206,6 @@ export const POST = withWorkspace({requiredPlan: ["business", "advanced", "enterprise"],requiredRoles: ["owner", "member"],+ requiredPermissions: ["commissions.write"],},);diff --git a/apps/web/lib/api/customers/reattribute-customer-utils.ts b/apps/web/lib/api/customers/reattribute-customer-utils.tsnew file mode 100644index 0000000000..99de4e913f--- /dev/null+++ b/apps/web/lib/api/customers/reattribute-customer-utils.ts@@ -0,0 +1,175 @@+export const CUSTOMER_EVENTS_LIMIT = 1000;++export 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;+};++export function isRetiredReattributeStub(customer: {+ externalId?: string | null;+ partnerId?: string | null;+ linkId?: string | null;+ programId?: string | null;+}) {+ return (+ Boolean(customer.externalId?.startsWith("dummy_")) &&+ customer.partnerId == null &&+ customer.linkId == null &&+ customer.programId == null+ );+}++export function customerEventsExceedLimit(eventCount: number) {+ return eventCount >= CUSTOMER_EVENTS_LIMIT;+}++export function shouldRecreateCustomer({+ eventCount,+ commissionCount,+ clickId,+ sales,+}: {+ eventCount: number;+ commissionCount: number;+ clickId?: string | null;+ sales?: number;+}) {+ return (+ eventCount > 0 ||+ commissionCount > 0 ||+ Boolean(clickId) ||+ (sales ?? 0) > 0+ );+}++export function selectEventsToReingest({+ oldEvents,+ newEvents,+}: {+ oldEvents: CustomerTBEvent[];+ newEvents: CustomerTBEvent[];+}) {+ const newHasClick = newEvents.some((event) => event.event === "click");+ const newHasLead = newEvents.some((event) => event.event === "lead");+ const newSaleInvoiceIds = new Set(+ newEvents+ .filter((event) => event.event === "sale" && event.invoice_id)+ .map((event) => event.invoice_id)+ .filter((invoiceId): invoiceId is string => Boolean(invoiceId)),+ );+ const newInvoicelessSaleTimestamps = new Set(+ newEvents+ .filter((event) => event.event === "sale" && !event.invoice_id)+ .map((event) => event.timestamp),+ );++ return {+ clickEvent: !newHasClick+ ? oldEvents.find((event) => event.event === "click") ?? null+ : null,+ leadEvent: !newHasLead+ ? oldEvents.find((event) => event.event === "lead") ?? null+ : null,+ saleEvents: oldEvents.filter((event) => {+ if (event.event !== "sale") {+ return false;+ }++ if (event.invoice_id) {+ return !newSaleInvoiceIds.has(event.invoice_id);+ }++ return !newInvoicelessSaleTimestamps.has(event.timestamp);+ }),+ };+}++export function selectPaidReplacementEvents({+ paidInvoiceIds,+ hasPaidLead,+ newEvents,+ existingNewCommissions,+}: {+ paidInvoiceIds: string[];+ hasPaidLead: boolean;+ newEvents: CustomerTBEvent[];+ existingNewCommissions: Array<{+ type: string;+ invoiceId: string | null;+ }>;+}) {+ const hasExistingLead = existingNewCommissions.some(+ (commission) => commission.type === "lead",+ );+ const existingInvoiceIds = new Set(+ existingNewCommissions+ .map((commission) => commission.invoiceId)+ .filter((invoiceId): invoiceId is string => Boolean(invoiceId)),+ );+ const paidInvoiceIdSet = new Set(paidInvoiceIds);++ return {+ leadEvent:+ hasPaidLead && !hasExistingLead+ ? newEvents.find((event) => event.event === "lead") ?? null+ : null,+ saleEvents: newEvents.filter(+ (event) =>+ event.event === "sale" &&+ Boolean(event.invoice_id) &&+ paidInvoiceIdSet.has(event.invoice_id!) &&+ !existingInvoiceIds.has(event.invoice_id!),+ ),+ };+}++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"),+ };+}diff --git a/apps/web/lib/api/customers/reattribute-customer.ts b/apps/web/lib/api/customers/reattribute-customer.tsindex b6adb0b22f..b0bb6850d6 100644--- a/apps/web/lib/api/customers/reattribute-customer.ts+++ b/apps/web/lib/api/customers/reattribute-customer.ts@@ -21,8 +21,30 @@ import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";import { nanoid } from "@dub/utils";import { Customer, Link } from "@prisma/client";import * as z from "zod/v4";+import {+ CUSTOMER_EVENTS_LIMIT,+ customerEventsExceedLimit,+ selectEventsToReingest,+ selectPaidReplacementEvents,+ summarizeCustomerEvents,+ type CustomerTBEvent,+ type ReattributeEventPlan,+} from "./reattribute-customer-utils";++export {+ CUSTOMER_EVENTS_LIMIT,+ customerEventsExceedLimit,+ isRetiredReattributeStub,+ selectEventsToReingest,+ selectPaidReplacementEvents,+ shouldRecreateCustomer,+ summarizeCustomerEvents,+} from "./reattribute-customer-utils";+export type {+ CustomerTBEvent,+ ReattributeEventPlan,+} from "./reattribute-customer-utils";-const CUSTOMER_EVENTS_LIMIT = 1000;const UNPAID_COMMISSION_STATUSES = ["pending", "hold", "processed"] as const;const STATS_LOCK_TTL_SECONDS = 60 * 60 * 24;@@ -34,32 +56,6 @@ 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,@@ -100,36 +96,6 @@ export async function getCustomerReattributeEvents(customerId: string) {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,@@ -195,12 +161,17 @@ export async function loadReattributeEventPlan({getCustomerReattributeEvents(newCustomerId),]);- const alreadyReingested = newEvents.length > 0;- const sourceEvents = alreadyReingested ? newEvents : oldEvents;+ if (customerEventsExceedLimit(oldEvents.length)) {+ throw new Error(+ `Customer ${oldCustomerId} has too many events to reattribute (limit ${CUSTOMER_EVENTS_LIMIT}).`,+ );+ }++ const sourceEvents = oldEvents.length > 0 ? oldEvents : newEvents;return {...summarizeCustomerEvents(sourceEvents),- alreadyReingested,+ alreadyReingested: newEvents.length > 0 && oldEvents.length === 0,};}@@ -222,15 +193,30 @@ export async function reingestCustomerEvents({getCustomerReattributeEvents(newCustomerId),]);- if (newEvents.length > 0) {- return { skipped: true, reason: "already-reingested" as const };+ if (customerEventsExceedLimit(oldEvents.length)) {+ throw new Error(+ `Customer ${oldCustomerId} has too many events to reattribute (limit ${CUSTOMER_EVENTS_LIMIT}).`,+ );}- 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 { clickEvent, leadEvent, saleEvents } = selectEventsToReingest({+ oldEvents,+ newEvents,+ });++ if (!clickEvent && !leadEvent && saleEvents.length === 0) {+ return {+ skipped: true,+ reason:+ oldEvents.length > 0+ ? ("already-reingested" as const)+ : ("no-events" as const),+ };+ }++ const sourceClickEvent =+ oldEvents.find((event) => event.event === "click") ??+ newEvents.find((event) => event.event === "click");const newClickAttributes = {click_id: newClickId,@@ -238,7 +224,7 @@ export async function reingestCustomerEvents({};const clickEventData = recordClickZodSchema.parse({- ...existingClickEvent,+ ...sourceClickEvent,...newClickAttributes,workspace_id: workspaceId,domain: link.domain,@@ -248,14 +234,14 @@ export async function reingestCustomerEvents({const eventsToRecord: Promise<unknown>[] = [];- if (existingClickEvent) {+ if (clickEvent) {eventsToRecord.push(recordClickZod(clickEventData));}- if (existingLeadEvent) {+ if (leadEvent) {const leadEventData = leadEventSchemaTBWithTimestamp.parse({...clickEventData,- ...existingLeadEvent,+ ...leadEvent,...newClickAttributes,event_id: nanoid(16),link_id: link.id,@@ -265,8 +251,8 @@ export async function reingestCustomerEvents({eventsToRecord.push(recordLeadWithTimestamp(leadEventData));}- if (existingSaleEvents.length > 0) {- const saleEventsData = existingSaleEvents.map((existingSaleEvent) =>+ if (saleEvents.length > 0) {+ const saleEventsData = saleEvents.map((existingSaleEvent) =>saleEventSchemaTBWithTimestamp.parse({...clickEventData,...existingSaleEvent,@@ -281,10 +267,6 @@ export async function reingestCustomerEvents({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");@@ -527,22 +509,6 @@ export async function createClawbackAndReplacementCommissions({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,@@ -567,11 +533,18 @@ export async function createClawbackAndReplacementCommissions({return { skipped: true, reason: "no-paid-earnings" as const };}- const paidEventIds = paidCommissions- .map((commission) => commission.eventId)- .filter((eventId): eventId is string => Boolean(eventId));+ const paidInvoiceIds = paidCommissions+ .map((commission) => commission.invoiceId)+ .filter((invoiceId): invoiceId is string => Boolean(invoiceId));+ const hasPaidLead = paidCommissions.some(+ (commission) => commission.type === "lead",+ );- if (paidEventIds.length > 0 || paidCommissions.some((c) => c.invoiceId)) {+ if (+ paidCommissions.some(+ (commission) => commission.eventId || commission.invoiceId,+ )+ ) {await prisma.commission.updateMany({where: {id: { in: paidCommissions.map((commission) => commission.id) },@@ -583,38 +556,59 @@ export async function createClawbackAndReplacementCommissions({});}- await queuePartnerCommissionCreation({- event: "custom",- partnerId: oldPartnerId,- programId,- customerId: oldCustomerId,- amount: -paidEarnings,- quantity: 1,- description: "tracking_error",- skipWorkflow: true,- });+ await runOnce({+ key: `reattribute-customer:${oldCustomerId}:clawback`,+ fn: async () => {+ const existingClawback = await prisma.commission.findFirst({+ where: {+ customerId: oldCustomerId,+ partnerId: oldPartnerId,+ programId,+ type: "custom",+ description: "tracking_error",+ earnings: { lt: 0 },+ },+ select: { id: true },+ });- const existingReplacement = await prisma.commission.findFirst({- where: {- customerId: newCustomerId,- partnerId: newPartnerId,- type: { in: ["lead", "sale"] },+ if (existingClawback) {+ return;+ }++ await queuePartnerCommissionCreation({+ event: "custom",+ partnerId: oldPartnerId,+ programId,+ customerId: oldCustomerId,+ amount: -paidEarnings,+ quantity: 1,+ description: "tracking_error",+ skipWorkflow: true,+ });},- select: { id: true },});- if (existingReplacement) {- await syncTotalCommissions({- partnerId: oldPartnerId,- programId,- });-- return { skipped: false, clawback: true, recreated: 0 };- }+ const [newEvents, existingNewCommissions] = await Promise.all([+ getCustomerReattributeEvents(newCustomerId),+ prisma.commission.findMany({+ where: {+ customerId: newCustomerId,+ partnerId: newPartnerId,+ type: { in: ["lead", "sale"] },+ },+ select: {+ type: true,+ invoiceId: true,+ },+ }),+ ]);- const newEvents = await getCustomerReattributeEvents(newCustomerId);- const leadEvent = newEvents.find((event) => event.event === "lead");- const saleEvents = newEvents.filter((event) => event.event === "sale");+ const { leadEvent, saleEvents } = selectPaidReplacementEvents({+ paidInvoiceIds,+ hasPaidLead,+ newEvents,+ existingNewCommissions,+ });if (leadEvent?.event_id) {await queuePartnerCommissionCreation({@@ -688,16 +682,6 @@ export async function deleteOldCustomerTinybirdEvents({});}-export function shouldRecreateCustomer({- eventCount,- commissionCount,-}: {- eventCount: number;- commissionCount: number;-}) {- return eventCount > 0 || commissionCount > 0;-}-export function computeConversionFlags({customer,newLinkId,diff --git a/apps/web/playwright/api/customers/customers-reattribute.spec.ts b/apps/web/playwright/api/customers/customers-reattribute.spec.tsindex 7de03e3790..5ec7ec73a1 100644--- a/apps/web/playwright/api/customers/customers-reattribute.spec.ts+++ b/apps/web/playwright/api/customers/customers-reattribute.spec.ts@@ -1,4 +1,6 @@+import { prisma } from "@/lib/prisma";import type { Customer, CustomerEnriched } from "@/lib/types";+import { nanoid } from "@dub/utils";import { expect } from "@playwright/test";import { apiError, randomCustomer } from "../../utils";import { test, type ApiClient } from "../fixtures";@@ -111,3 +113,84 @@ test("POST /customers/{id}/reattribute – unchanged partner and link", async ({await deletePartner(partnerId);}});++test("POST /customers/{id}/reattribute – retired stub", 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 { data: created } = await createCustomer(api);+ customerId = created.id;++ await prisma.customer.update({+ where: { id: created.id },+ data: {+ externalId: `dummy_${nanoid(32)}`,+ partnerId: null,+ linkId: null,+ programId: null,+ },+ });++ expect(+ await api.post(`/api/customers/${created.id}/reattribute`, {+ partnerId: partner.id,+ linkId: partner.links![0].id,+ }),+ ).toEqual(+ apiError({+ code: "bad_request",+ message:+ "This customer was already reattributed. Use the new customer ID.",+ }),+ );+ } finally {+ await deleteCustomer(api, customerId);+ await deletePartner(partnerId);+ }+});++test("POST /customers/{id}/reattribute – banned partner", 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 { status: banStatus } = await api.post("/api/partners/ban", {+ partnerId: partner.id,+ reason: "fraud",+ });+ expect(banStatus).toEqual(200);++ const { data: created } = await createCustomer(api);+ customerId = created.id;++ expect(+ await api.post(`/api/customers/${created.id}/reattribute`, {+ partnerId: partner.id,+ linkId: partner.links![0].id,+ }),+ ).toEqual(+ apiError({+ code: "unprocessable_entity",+ message: "This partner is not eligible to receive customers.",+ }),+ );+ } finally {+ await deleteCustomer(api, customerId);+ await deletePartner(partnerId);+ }+});diff --git a/apps/web/tests/customers/reattribute-customer.test.ts b/apps/web/tests/customers/reattribute-customer.test.tsnew file mode 100644index 0000000000..b6824f3839--- /dev/null+++ b/apps/web/tests/customers/reattribute-customer.test.ts@@ -0,0 +1,209 @@+import {+ CUSTOMER_EVENTS_LIMIT,+ customerEventsExceedLimit,+ isRetiredReattributeStub,+ selectEventsToReingest,+ selectPaidReplacementEvents,+ shouldRecreateCustomer,+ type CustomerTBEvent,+} from "@/lib/api/customers/reattribute-customer-utils";+import { describe, expect, it } from "vitest";++function event(+ overrides: Partial<CustomerTBEvent> & Pick<CustomerTBEvent, "event">,+): CustomerTBEvent {+ return {+ timestamp: "2026-01-01 00:00:00",+ ...overrides,+ };+}++describe("shouldRecreateCustomer", () => {+ it("keeps the fast path for a manual customer", () => {+ expect(+ shouldRecreateCustomer({+ eventCount: 0,+ commissionCount: 0,+ }),+ ).toBe(false);+ });++ it("recreates when Tinybird events or commissions exist", () => {+ expect(shouldRecreateCustomer({ eventCount: 1, commissionCount: 0 })).toBe(+ true,+ );+ expect(shouldRecreateCustomer({ eventCount: 0, commissionCount: 2 })).toBe(+ true,+ );+ });++ it("recreates when clickId or sales are present even if Tinybird is empty", () => {+ expect(+ shouldRecreateCustomer({+ eventCount: 0,+ commissionCount: 0,+ clickId: "clk_abc",+ }),+ ).toBe(true);+ expect(+ shouldRecreateCustomer({+ eventCount: 0,+ commissionCount: 0,+ sales: 3,+ }),+ ).toBe(true);+ });+});++describe("isRetiredReattributeStub", () => {+ it("detects a retired stub", () => {+ expect(+ isRetiredReattributeStub({+ externalId: "dummy_abcdefghijklmnopqrstuvwxyz012345",+ partnerId: null,+ linkId: null,+ programId: null,+ }),+ ).toBe(true);+ });++ it("does not treat a live customer as retired", () => {+ expect(+ isRetiredReattributeStub({+ externalId: "user_123",+ partnerId: "pn_1",+ linkId: "link_1",+ programId: "prog_1",+ }),+ ).toBe(false);+ });++ it("requires dummy_ plus cleared attribution fields", () => {+ expect(+ isRetiredReattributeStub({+ externalId: "dummy_abc",+ partnerId: "pn_1",+ linkId: null,+ programId: null,+ }),+ ).toBe(false);+ });+});++describe("customerEventsExceedLimit", () => {+ it("refuses a truncated event page", () => {+ expect(customerEventsExceedLimit(CUSTOMER_EVENTS_LIMIT)).toBe(true);+ expect(customerEventsExceedLimit(CUSTOMER_EVENTS_LIMIT - 1)).toBe(false);+ });+});++describe("selectEventsToReingest", () => {+ const oldEvents: CustomerTBEvent[] = [+ event({ event: "click", click_id: "old_click" }),+ event({ event: "lead", event_id: "lead_1" }),+ event({+ event: "sale",+ event_id: "sale_1",+ invoice_id: "inv_1",+ saleAmount: 1000,+ }),+ event({+ event: "sale",+ event_id: "sale_2",+ invoice_id: "inv_2",+ saleAmount: 2000,+ }),+ ];++ it("selects every old event when the new customer is empty", () => {+ const selected = selectEventsToReingest({+ oldEvents,+ newEvents: [],+ });++ expect(selected.clickEvent?.click_id).toBe("old_click");+ expect(selected.leadEvent?.event_id).toBe("lead_1");+ expect(selected.saleEvents.map((sale) => sale.invoice_id)).toEqual([+ "inv_1",+ "inv_2",+ ]);+ });++ it("skips types already present and only copies missing sales", () => {+ const selected = selectEventsToReingest({+ oldEvents,+ newEvents: [+ event({ event: "click", click_id: "new_click" }),+ event({ event: "lead", event_id: "new_lead" }),+ event({ event: "sale", invoice_id: "inv_1", saleAmount: 1000 }),+ ],+ });++ expect(selected.clickEvent).toBeNull();+ expect(selected.leadEvent).toBeNull();+ expect(selected.saleEvents.map((sale) => sale.invoice_id)).toEqual([+ "inv_2",+ ]);+ });+});++describe("selectPaidReplacementEvents", () => {+ const newEvents: CustomerTBEvent[] = [+ event({ event: "lead", event_id: "new_lead" }),+ event({+ event: "sale",+ event_id: "new_sale_paid",+ invoice_id: "inv_paid",+ saleAmount: 5000,+ }),+ event({+ event: "sale",+ event_id: "new_sale_unpaid",+ invoice_id: "inv_unpaid",+ saleAmount: 1500,+ }),+ ];++ it("recreates paid lead and paid sales even when unpaid rows already moved", () => {+ const selected = selectPaidReplacementEvents({+ paidInvoiceIds: ["inv_paid"],+ hasPaidLead: true,+ newEvents,+ existingNewCommissions: [{ type: "sale", invoiceId: "inv_unpaid" }],+ });++ expect(selected.leadEvent?.event_id).toBe("new_lead");+ expect(selected.saleEvents.map((sale) => sale.invoice_id)).toEqual([+ "inv_paid",+ ]);+ });++ it("does not recreate a paid lead that already exists on the new customer", () => {+ const selected = selectPaidReplacementEvents({+ paidInvoiceIds: ["inv_paid"],+ hasPaidLead: true,+ newEvents,+ existingNewCommissions: [+ { type: "lead", invoiceId: null },+ { type: "sale", invoiceId: "inv_unpaid" },+ ],+ });++ expect(selected.leadEvent).toBeNull();+ expect(selected.saleEvents.map((sale) => sale.invoice_id)).toEqual([+ "inv_paid",+ ]);+ });++ it("skips paid sales that already have a replacement invoice", () => {+ const selected = selectPaidReplacementEvents({+ paidInvoiceIds: ["inv_paid"],+ hasPaidLead: false,+ newEvents,+ existingNewCommissions: [{ type: "sale", invoiceId: "inv_paid" }],+ });++ expect(selected.leadEvent).toBeNull();+ expect(selected.saleEvents).toEqual([]);+ });+});diff --git a/apps/web/ui/partners/partner-link-selector.tsx b/apps/web/ui/partners/partner-link-selector.tsxindex 58a776a55b..9111e0aa98 100644--- a/apps/web/ui/partners/partner-link-selector.tsx+++ b/apps/web/ui/partners/partner-link-selector.tsx@@ -1,5 +1,6 @@import useLink from "@/lib/swr/use-link";import useLinks from "@/lib/swr/use-links";+import usePartner from "@/lib/swr/use-partner";import useProgram from "@/lib/swr/use-program";import { LinkProps } from "@/lib/types";import { Combobox, LinkLogo, Tooltip } from "@dub/ui";@@ -8,7 +9,12 @@ import { cn, getApexDomain, linkConstructor } from "@dub/utils";import { ReactNode, useEffect, useMemo, useState } from "react";import { useDebounce } from "use-debounce";-const getLinkOption = (link: LinkProps) => ({+type PartnerLinkOption = Pick<+ LinkProps,+ "id" | "domain" | "key" | "url" | "saleAmount"+>;++const getLinkOption = (link: PartnerLinkOption) => ({value: link.id,label: linkConstructor({ ...link, pretty: true }),icon: (@@ -44,8 +50,11 @@ export function PartnerLinkSelector({const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search, 500);const { program } = useProgram();+ const { partner, loading: partnerLoading } = usePartner({+ partnerId: partnerId ?? null,+ });- const { links, isValidating } = useLinks(+ const { links: workspaceLinks, isValidating } = useLinks({folderId: program?.defaultFolderId ?? undefined,domain: program?.domain ?? undefined,@@ -60,7 +69,26 @@ export function PartnerLinkSelector({},);- const { link: selectedLink } = useLink(selectedLinkId ?? "");+ // Partner referral links live on the enrollment. `/api/links` can return+ // none of them when folder/domain filters from the current page don't match.+ const links = partnerId+ ? partner+ ? partner.links ?? []+ : undefined+ : workspaceLinks;++ const { link: selectedLinkFromApi } = useLink(+ partnerId || !selectedLinkId ? "" : selectedLinkId,+ );++ const selectedLink = useMemo(() => {+ if (!selectedLinkId) return null;+ return (+ links?.find((link) => link.id === selectedLinkId) ??+ selectedLinkFromApi ??+ null+ );+ }, [links, selectedLinkFromApi, selectedLinkId]);const options = useMemo(() => links?.map((link) => getLinkOption(link)),@@ -85,9 +113,11 @@ export function PartnerLinkSelector({return getLinkOption(selectedLink);}, [selectedLink]);+ const isLoadingLinks = partnerId ? partnerLoading : isValidating;+const showLoadingPlaceholder =(selectedLinkId && !selectedLink) ||- (!selectedLinkId && isValidating && !links);+ (!selectedLinkId && isLoadingLinks && !links);return (<>@@ -122,7 +152,7 @@ export function PartnerLinkSelector({),disabledTooltip,}}- shouldFilter={false}+ shouldFilter={Boolean(partnerId)}onCreate={onCreate}createLabel={(search) =>`Create "${search.startsWith(program?.domain + "/") ? search : program?.domain + "/" + search}"`