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.

finalize backend changes (createManualCommissionAction)

Steven Tey4c8c719dc4fd
diff --git a/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts b/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts
index 7547339103..3d805d876f 100644
--- a/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts
+++ b/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts
@@ -1,14 +1,8 @@
import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
+import { getCustomerStripeInvoices } from "@/lib/api/customers/get-customer-stripe-invoices";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
-import { stripeAppClient } from "@/lib/stripe";
-import { StripeCustomerInvoiceSchema } from "@/lib/zod/schemas/customers";
import { NextResponse } from "next/server";
-
-const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { mode: "live" }),
-});
-
export const GET = withWorkspace(async ({ workspace, params }) => {
const { id: customerId } = params;
@@ -33,18 +27,10 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
});
}
- const { data } = await stripe.invoices.list(
- {
- customer: customer.stripeCustomerId,
- status: "paid",
- },
- {
- stripeAccount: workspace.stripeConnectId,
- },
- );
-
- const stripeCustomerInvoices =
- StripeCustomerInvoiceSchema.array().parse(data);
+ const stripeCustomerInvoices = await getCustomerStripeInvoices({
+ stripeCustomerId: customer.stripeCustomerId,
+ stripeConnectId: workspace.stripeConnectId,
+ });
return NextResponse.json(stripeCustomerInvoices);
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx
index 202d8dccc0..614804a6dd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx
@@ -577,7 +577,7 @@ function CreateCommissionSheetContent({
</div>
</div>
- {customerId && (
+ {customerId && commissionType === "sale" && (
<div>
<label htmlFor="eventSource">
<h2 className="text-sm font-medium text-neutral-900">
diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.ts
index 2b5ca0884e..d5cc6ab6f0 100644
--- a/apps/web/lib/actions/partners/create-manual-commission.ts
+++ b/apps/web/lib/actions/partners/create-manual-commission.ts
@@ -1,6 +1,7 @@
"use server";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
+import { getCustomerStripeInvoices } from "@/lib/api/customers/get-customer-stripe-invoices";
import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-for-importer";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -20,7 +21,7 @@ import { createCommissionSchema } from "@/lib/zod/schemas/commissions";
import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
import { prisma } from "@dub/prisma";
-import { nanoid } from "@dub/utils";
+import { nanoid, prettyPrint } from "@dub/utils";
import { COUNTRIES_TO_CONTINENTS } from "@dub/utils/src";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
@@ -67,10 +68,6 @@ export const createManualCommissionAction = authActionClient
productId,
} = parsedInput;
- // for useExistingEvents, we need to keep track of some stats so we can update later
- let totalSales = 0;
- let totalSaleAmount = 0;
-
const programId = getDefaultProgramIdOrThrow(workspace);
const [{ partner, links }, customer] = await Promise.all([
@@ -147,117 +144,123 @@ export const createManualCommissionAction = authActionClient
const tbEventsToRecord: Promise<any>[] = []; // a list of promises of events to record in Tinybird
const commissionsToCreate: CreatePartnerCommissionProps[] = [];
- // Track event timestamps for updating link stats
- let leadEventTimestamp: Date | null = null;
- let saleEventTimestamp: Date | null = null;
+ // keep track of click event to update customer later
+ let clickId: string | undefined = undefined;
+ let clickedAt: Date | undefined = undefined;
- // If we're using existing events (Stripe invoice for sale, or duplicate events for lead)
+ // keep track of link stats to update later
+ let totalSales = 0;
+ let totalSaleAmount = 0;
+ let lastLeadAt: Date | undefined = undefined;
+ let lastConversionAt: Date | undefined = undefined;
+
+ // If we're using existing events (Stripe invoice for sale)
if (useExistingEvents) {
- // Sale from selected Stripe invoice: create new events using invoice data
- if (commissionType === "sale" && invoiceId && saleAmount != null) {
- const finalLeadEventDate = saleEventDate ?? new Date();
- const clickId = nanoid(16);
- const clickTimestamp = new Date(
- finalLeadEventDate.getTime() - 5 * 60 * 1000,
+ if (!workspace.stripeConnectId) {
+ throw new Error(
+ "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",
);
+ }
- const generatedClickEvent = recordClickZodSchema.parse({
- timestamp: clickTimestamp.toISOString(),
- identity_hash: customer.externalId || customer.id,
- click_id: clickId,
- link_id: link.id,
- url: link.url,
- ip: "127.0.0.1",
- continent: customer.country
- ? COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()] || ""
- : "",
- });
+ if (!customer.stripeCustomerId) {
+ throw new Error(
+ `Customer ${customer.id} doesn't have a Stripe customer ID. Add one in the customer profile before proceeding.`,
+ );
+ }
+
+ const stripeCustomerInvoices = await getCustomerStripeInvoices({
+ stripeCustomerId: customer.stripeCustomerId,
+ stripeConnectId: workspace.stripeConnectId,
+ }).then(
+ (
+ invoices, // sort invoices by created date ascending
+ ) => invoices.sort((a, b) => a.created.getTime() - b.created.getTime()),
+ );
- tbEventsToRecord.push(recordClickZod(generatedClickEvent));
+ if (stripeCustomerInvoices.length === 0) {
+ throw new Error(
+ `No paid Stripe invoices found for customer ${customer.email} (${customer.stripeCustomerId}).`,
+ );
+ }
- const leadEventData = leadEventSchemaTBWithTimestamp.parse({
- ...generatedClickEvent,
- event_id: nanoid(16),
- event_name: leadEventName || "Sign up",
- customer_id: customer.id,
- timestamp: finalLeadEventDate.toISOString(),
- });
+ lastLeadAt = stripeCustomerInvoices[0].created;
+ lastConversionAt = stripeCustomerInvoices[0].created;
- tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));
+ clickId = nanoid(16);
+ clickedAt = new Date(lastLeadAt.getTime() - 5 * 60 * 1000);
- const saleEventData = saleEventSchemaTBWithTimestamp.parse({
+ const generatedClickEvent = recordClickZodSchema.parse({
+ timestamp: clickedAt.toISOString(),
+ identity_hash: customer.externalId || customer.id,
+ click_id: clickId,
+ link_id: link.id,
+ url: link.url,
+ ip: "127.0.0.1",
+ continent: customer.country
+ ? COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()] || ""
+ : "",
+ });
+
+ tbEventsToRecord.push(recordClickZod(generatedClickEvent));
+
+ const leadEventData = leadEventSchemaTBWithTimestamp.parse({
+ ...generatedClickEvent,
+ event_id: nanoid(16),
+ event_name: "Sign up",
+ customer_id: customer.id,
+ timestamp: lastLeadAt.toISOString(),
+ });
+
+ tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));
+
+ const saleEventData = stripeCustomerInvoices.map((invoice) =>
+ saleEventSchemaTBWithTimestamp.parse({
...generatedClickEvent,
event_id: nanoid(16),
- invoice_id: invoiceId,
+ invoice_id: invoice.id,
event_name: "Purchase",
- amount: saleAmount,
+ amount: invoice.amount_paid,
customer_id: customer.id,
payment_processor: "stripe",
currency: "usd",
- timestamp: new Date(saleEventDate ?? Date.now()).toISOString(),
- metadata: productId ? JSON.stringify({ productId }) : undefined,
- });
+ timestamp: invoice.created.toISOString(),
+ }),
+ );
- tbEventsToRecord.push(recordSaleWithTimestamp(saleEventData));
+ tbEventsToRecord.push(recordSaleWithTimestamp(saleEventData));
- commissionsToCreate.push({
+ commissionsToCreate.push(
+ ...saleEventData.map((saleEvent) => ({
event: "sale" as const,
programId,
partnerId,
linkId: link.id,
customerId: customer.id,
- eventId: saleEventData.event_id,
+ eventId: saleEvent.event_id,
quantity: 1,
- amount: saleEventData.amount,
- currency: saleEventData.currency,
- invoiceId: saleEventData.invoice_id,
- createdAt: new Date(saleEventData.timestamp),
+ amount: saleEvent.amount,
+ currency: saleEvent.currency,
+ invoiceId: saleEvent.invoice_id,
+ createdAt: new Date(saleEvent.timestamp),
user,
context: {
customer: { country: customer.country },
- sale: { productId },
},
- });
-
- saleEventTimestamp = new Date(saleEventData.timestamp);
- totalSales = 1;
- totalSaleAmount = saleAmount;
-
- await prisma.customer.update({
- where: { id: customer.id },
- data: {
- linkId: link.id,
- programId: link.programId,
- partnerId: link.partnerId,
- clickId,
- clickedAt: new Date(clickTimestamp),
- sales: { increment: 1 },
- saleAmount: { increment: saleAmount },
- firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
- },
- });
- } else if (commissionType === "lead") {
- if (!customer.linkId) {
- throw new Error(
- `No linkId found for existing customer ${customer.id}.`,
- );
- }
- // TODO: duplicate existing lead events under new link
- } else {
- throw new Error(
- "Select a Stripe invoice when using existing invoices for a sale commission.",
- );
- }
+ })),
+ );
+ totalSales = saleEventData.length;
+ totalSaleAmount = saleEventData.reduce(
+ (acc, saleEvent) => acc + saleEvent.amount,
+ 0,
+ );
} else {
const finalLeadEventDate = leadEventDate ?? saleEventDate ?? new Date();
- const clickId = nanoid(16);
- const clickTimestamp = new Date(
- finalLeadEventDate.getTime() - 5 * 60 * 1000,
- );
+ clickId = nanoid(16);
+ clickedAt = new Date(finalLeadEventDate.getTime() - 5 * 60 * 1000);
// Record click event
const generatedClickEvent = recordClickZodSchema.parse({
- timestamp: clickTimestamp.toISOString(),
+ timestamp: clickedAt.toISOString(),
identity_hash: customer.externalId || customer.id,
click_id: clickId,
link_id: link.id,
@@ -299,7 +302,7 @@ export const createManualCommissionAction = authActionClient
},
});
// Track the lead event timestamp for link stats update
- leadEventTimestamp = new Date(leadEventData.timestamp);
+ lastLeadAt = new Date(leadEventData.timestamp);
}
// Prepare sale event if requested
@@ -341,51 +344,28 @@ export const createManualCommissionAction = authActionClient
},
});
// Track the sale event timestamp for link stats update
- saleEventTimestamp = new Date(saleEventData.timestamp);
+ lastConversionAt = new Date(saleEventData.timestamp);
}
-
- const updatedCustomer = await prisma.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- linkId: link.id,
- programId: link.programId,
- partnerId: link.partnerId,
- clickId: clickId,
- clickedAt: new Date(clickTimestamp),
- ...(saleAmount && {
- sales: {
- increment: 1,
- },
- saleAmount: {
- increment: saleAmount,
- },
- firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
- }),
- },
- });
- console.log(
- "Updated customer to include link & sale attributes: ",
- updatedCustomer,
- );
}
}
- const res = await Promise.allSettled(tbEventsToRecord);
- console.log("recorded events in Tinybird: ", res);
+ // record events in Tinybird
+ const tbRes = await Promise.allSettled(tbEventsToRecord);
+ console.log("recorded events in Tinybird: ", prettyPrint(tbRes));
- waitUntil(
- (async () => {
- console.log("Commissions to create: ", commissionsToCreate);
+ // create partner commissions
+ await Promise.allSettled(
+ commissionsToCreate.map((commission) =>
+ createPartnerCommission(commission),
+ ),
+ );
- // create partner commissions
- await Promise.allSettled(
- commissionsToCreate.map((commission) =>
- createPartnerCommission(commission),
- ),
- );
+ console.log(
+ `Created ${commissionsToCreate.length} commissions: ${prettyPrint(commissionsToCreate)}`,
+ );
+ waitUntil(
+ (async () => {
const firstConversionFlag =
commissionType === "sale" &&
isFirstConversion({
@@ -393,41 +373,62 @@ export const createManualCommissionAction = authActionClient
linkId: link.id,
});
- await prisma.link.update({
- where: {
- id: link.id,
- },
- data: {
- // we'll always create click + lead events, so need to increment the stats
- clicks: {
- increment: 1,
- },
- leads: {
- increment: 1,
+ await Promise.allSettled([
+ prisma.link.update({
+ where: {
+ id: link.id,
},
- lastLeadAt: updateLinkStatsForImporter({
- currentTimestamp: link.lastLeadAt,
- newTimestamp: leadEventTimestamp || new Date(),
- }),
- ...(firstConversionFlag && {
- conversions: {
+ data: {
+ // we'll always create click + lead events, so need to increment the stats
+ clicks: {
+ increment: 1,
+ },
+ leads: {
increment: 1,
},
- lastConversionAt: updateLinkStatsForImporter({
- currentTimestamp: link.lastConversionAt,
- newTimestamp: saleEventTimestamp || new Date(),
+ lastLeadAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastLeadAt,
+ newTimestamp: lastLeadAt || new Date(),
}),
- }),
- ...(commissionType === "sale" && {
+ ...(firstConversionFlag && {
+ conversions: {
+ increment: 1,
+ },
+ lastConversionAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastConversionAt,
+ newTimestamp: lastConversionAt || new Date(),
+ }),
+ }),
+ ...(commissionType === "sale" && {
+ sales: {
+ increment: saleAmount ? 1 : totalSales,
+ },
+ saleAmount: {
+ increment: saleAmount ?? totalSaleAmount,
+ },
+ }),
+ },
+ }),
+ prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ linkId: link.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ clickId,
+ clickedAt,
sales: {
- increment: saleAmount ? 1 : totalSales,
+ increment: totalSales,
},
saleAmount: {
- increment: saleAmount ?? totalSaleAmount,
+ increment: totalSaleAmount,
},
- }),
- },
- });
+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
+ },
+ }),
+ ]);
// execute workflows
if (["lead", "sale"].includes(commissionType)) {
diff --git a/apps/web/lib/api/customers/get-customer-stripe-invoices.ts b/apps/web/lib/api/customers/get-customer-stripe-invoices.ts
new file mode 100644
index 0000000000..509a945f76
--- /dev/null
+++ b/apps/web/lib/api/customers/get-customer-stripe-invoices.ts
@@ -0,0 +1,29 @@
+import { stripeAppClient } from "@/lib/stripe";
+import { StripeCustomerInvoiceSchema } from "@/lib/zod/schemas/customers";
+
+const stripe = stripeAppClient({
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
+});
+
+export async function getCustomerStripeInvoices({
+ stripeCustomerId,
+ stripeConnectId,
+}: {
+ stripeCustomerId: string;
+ stripeConnectId: string;
+}) {
+ const { data } = await stripe.invoices.list(
+ {
+ customer: stripeCustomerId,
+ status: "paid",
+ },
+ {
+ stripeAccount: stripeConnectId,
+ },
+ );
+
+ const stripeCustomerInvoices =
+ StripeCustomerInvoiceSchema.array().parse(data);
+
+ return stripeCustomerInvoices;
+}
diff --git a/apps/web/scripts/programs/backfill-reuse-commission.ts b/apps/web/scripts/programs/backfill-reuse-commission.ts
new file mode 100644
index 0000000000..8a609bd14e
--- /dev/null
+++ b/apps/web/scripts/programs/backfill-reuse-commission.ts
@@ -0,0 +1,358 @@
+import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
+import { createId } from "@/lib/api/create-id";
+import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-for-importer";
+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
+import { qstash } from "@/lib/cron";
+import {
+ createPartnerCommission,
+ CreatePartnerCommissionProps,
+} from "@/lib/partners/create-partner-commission";
+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 { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
+import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK, nanoid, prettyPrint } from "@dub/utils";
+import "dotenv-flow/config";
+import * as z from "zod/v4";
+
+const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+// Script config – set these before running
+const COMMISSION_TYPE = "sale" as "lead" | "sale"; // "lead" or "sale"
+const PRODUCT_ID: string | undefined = undefined; // optional, for sale context
+
+async function main() {
+ const link = await prisma.link.findUniqueOrThrow({
+ where: {
+ id: "link_xxx",
+ },
+ });
+
+ const customer = await prisma.customer.findUniqueOrThrow({
+ where: {
+ id: "cus_xxx",
+ },
+ });
+
+ const programId = link.programId!;
+ const partnerId = link.partnerId!;
+ const workspaceId = customer.projectId;
+
+ const tbEventsToRecord: Promise<unknown>[] = [];
+ const commissionsToTransferEventIds: string[] = [];
+ const commissionsToCreate: CreatePartnerCommissionProps[] = [];
+ let leadEventTimestamp: Date | null = null;
+ let saleEventTimestamp: Date | null = null;
+ let totalSales = 0;
+ let totalSaleAmount = 0;
+ const user = undefined; // no auth user in script
+ const commissionType = COMMISSION_TYPE;
+ const productId = PRODUCT_ID;
+
+ if (!customer.linkId) {
+ throw new Error(`Customer ${customer.id} has no linkId.`);
+ }
+ // fetch existing customer events and duplicate them under the new customer.id
+ const existingCustomerEvents = await getCustomerEventsTB({
+ customerId: customer.id,
+ linkIds: [customer.linkId],
+ }).then((res) => res.data);
+
+ if (existingCustomerEvents.length === 0) {
+ throw new Error(`No existing events found for customer ${customer.id}.`);
+ }
+
+ const existingClickEvent = existingCustomerEvents.find(
+ (event) => event.event === "click",
+ );
+ console.log("Found existing click event: ", existingClickEvent);
+ const existingLeadEvent = existingCustomerEvents.find(
+ (event) => event.event === "lead",
+ );
+ console.log("Found existing lead event: ", existingLeadEvent);
+ const existingSaleEvents = existingCustomerEvents.filter(
+ (event) => event.event === "sale",
+ );
+ console.log("Found existing sale events: ", existingSaleEvents);
+
+ const newClickAttributes = {
+ click_id: nanoid(16), // create new clickId
+ link_id: link.id, // set to new link.id,
+ };
+ const clickEventData = recordClickZodSchema.parse({
+ ...existingClickEvent,
+ ...newClickAttributes,
+ });
+
+ console.log("Click event to record: ", clickEventData);
+ if (existingClickEvent) {
+ tbEventsToRecord.push(recordClickZod(clickEventData));
+ }
+
+ const duplicateCustomerId = createId({ prefix: "cus_" });
+
+ if (existingLeadEvent) {
+ const leadEventData = leadEventSchemaTBWithTimestamp.parse({
+ ...clickEventData,
+ ...existingLeadEvent,
+ ...newClickAttributes, // make sure new click attributes are not overridden by existing click attributes
+ event_id: nanoid(16), // create new event_id
+ link_id: link.id, // set to new link.id
+ customer_id: duplicateCustomerId, // set to new duplicateCustomerId
+ });
+ console.log("Lead event to record: ", leadEventData);
+ tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));
+
+ // Store the original lead eventId for nullification
+ commissionsToTransferEventIds.push(existingLeadEvent.event_id);
+
+ if (commissionType === "lead") {
+ // add the new lead event to the list of commissions to create
+ commissionsToCreate.push({
+ event: "lead" as const,
+ programId,
+ partnerId,
+ linkId: link.id,
+ customerId: duplicateCustomerId,
+ eventId: leadEventData.event_id,
+ quantity: 1,
+ createdAt: new Date(leadEventData.timestamp + "Z"), // add the "Z" to the timestamp to make it UTC
+ user,
+ context: {
+ customer: { country: customer.country },
+ },
+ });
+ // Track the lead event timestamp for link stats update
+ leadEventTimestamp = new Date(leadEventData.timestamp + "Z");
+ }
+ }
+
+ const recordSaleEvents =
+ commissionType === "sale" && existingSaleEvents.length > 0;
+
+ if (recordSaleEvents) {
+ if (existingSaleEvents.length > 5) {
+ throw new Error(
+ `You can only backfill up to 5 sale events. Found ${existingSaleEvents.length} existing sale events.`,
+ );
+ }
+
+ const saleEventsData = existingSaleEvents.map((existingSaleEvent) =>
+ saleEventSchemaTBWithTimestamp.parse({
+ ...clickEventData,
+ ...existingSaleEvent,
+ ...newClickAttributes, // make sure new click attributes are not overridden
+ event_id: nanoid(16), // create new event_id
+ link_id: link.id, // set to new link.id
+ customer_id: duplicateCustomerId, // set to new duplicateCustomerId
+ amount: existingSaleEvent.saleAmount, // change format returned by Tinybird
+ }),
+ );
+ console.log("Sale events to record: ", saleEventsData);
+ tbEventsToRecord.push(recordSaleWithTimestamp(saleEventsData));
+
+ // Store the original sale eventIds for nullification
+ commissionsToTransferEventIds.push(
+ ...existingSaleEvents.map(
+ (existingSaleEvent) => existingSaleEvent.event_id,
+ ),
+ );
+
+ if (commissionType === "sale") {
+ // add the new sale events to the list of commissions to create
+ commissionsToCreate.push(
+ ...saleEventsData.map((saleEventData) => ({
+ event: "sale" as const,
+ programId,
+ partnerId,
+ linkId: link.id,
+ customerId: duplicateCustomerId,
+ eventId: saleEventData.event_id,
+ quantity: 1,
+ amount: saleEventData.amount,
+ currency: saleEventData.currency,
+ invoiceId: saleEventData.invoice_id,
+ createdAt: new Date(saleEventData.timestamp + "Z"), // add the "Z" to the timestamp to make it UTC
+ user,
+ context: {
+ customer: {
+ country: customer.country,
+ },
+ sale: {
+ productId,
+ },
+ },
+ })),
+ );
+ // Track the latest sale event timestamp for link stats update
+ const latestSaleTimestamp = Math.max(
+ ...saleEventsData.map((data) =>
+ new Date(data.timestamp + "Z").getTime(),
+ ),
+ );
+ saleEventTimestamp = new Date(latestSaleTimestamp);
+ }
+ totalSales = existingSaleEvents.length;
+ totalSaleAmount = existingSaleEvents.reduce(
+ (acc, saleEvent) => acc + saleEvent.saleAmount,
+ 0,
+ );
+ }
+
+ const duplicatedCustomer = 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)}`, // generate random externalId
+ stripeCustomerId: null,
+ linkId: null,
+ programId: null,
+ partnerId: null,
+ clickId: null,
+ },
+ });
+
+ return await tx.customer.create({
+ data: {
+ ...customer,
+ id: duplicateCustomerId,
+ linkId: link.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ clickId: clickEventData.click_id,
+ clickedAt: new Date(clickEventData.timestamp),
+ country:
+ clickEventData.country === "Unknown" ? null : clickEventData.country,
+ ...(recordSaleEvents && {
+ sales: totalSales,
+ saleAmount: totalSaleAmount,
+ }),
+ },
+ });
+ });
+
+ console.log(
+ `Duplicated customer ${customer.id} to ${duplicatedCustomer.id}: `,
+ duplicatedCustomer,
+ );
+
+ // Record events in Tinybird
+ const tbRes = await Promise.allSettled(tbEventsToRecord);
+ console.log("Recorded events in Tinybird: ", tbRes);
+
+ const finalCommissionsToTransferEventIds =
+ commissionsToTransferEventIds.filter(
+ (eventId) => typeof eventId === "string",
+ );
+ console.log(
+ "Final commissions to transfer event ids: ",
+ finalCommissionsToTransferEventIds,
+ );
+
+ const firstConversionFlag =
+ commissionType === "sale" &&
+ isFirstConversion({
+ customer,
+ linkId: link.id,
+ });
+
+ // Update link stats and nullify old commissions
+ await Promise.all([
+ prisma.link.update({
+ where: { id: link.id },
+ data: {
+ clicks: { increment: 1 },
+ leads: { increment: 1 },
+ lastLeadAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastLeadAt,
+ newTimestamp: leadEventTimestamp || new Date(),
+ }),
+ ...(firstConversionFlag && {
+ conversions: { increment: 1 },
+ lastConversionAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastConversionAt,
+ newTimestamp: saleEventTimestamp || new Date(),
+ }),
+ }),
+ ...(commissionType === "sale" && {
+ sales: { increment: totalSales },
+ saleAmount: { increment: totalSaleAmount },
+ }),
+ },
+ }),
+ finalCommissionsToTransferEventIds.length > 0
+ ? prisma.commission.updateMany({
+ where: {
+ eventId: { in: finalCommissionsToTransferEventIds },
+ },
+ data: {
+ eventId: null,
+ invoiceId: null,
+ },
+ })
+ : Promise.resolve(),
+ ]);
+
+ console.log(
+ `Updated link${finalCommissionsToTransferEventIds.length > 0 ? " and nullified old commissions" : ""}`,
+ );
+
+ console.log("Commissions to create: ", commissionsToCreate);
+ await Promise.allSettled(
+ commissionsToCreate.map((commission) =>
+ createPartnerCommission({ ...commission, skipWorkflow: true }),
+ ),
+ );
+
+ if (["lead", "sale"].includes(commissionType)) {
+ await Promise.allSettled([
+ executeWorkflows({
+ trigger: "partnerMetricsUpdated",
+ reason: "commission",
+ identity: {
+ workspaceId,
+ programId,
+ partnerId,
+ },
+ metrics: {
+ current: {
+ leads: commissionType === "lead" ? 1 : 0,
+ saleAmount: totalSaleAmount,
+ conversions: firstConversionFlag ? 1 : 0,
+ },
+ },
+ }),
+ syncPartnerLinksStats({
+ partnerId,
+ programId,
+ eventType: commissionType as "lead" | "sale",
+ }),
+ ]);
+ }
+
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions`,
+ body: { programId },
+ });
+ console.log(
+ `Triggered aggregate due commissions cron job for program ${programId}: ${prettyPrint(qstashResponse)}`,
+ );
+}
+
+main();
diff --git a/apps/web/ui/modals/add-customer-modal.tsx b/apps/web/ui/modals/add-customer-modal.tsx
index c55b74be87..9ae459af7e 100644
--- a/apps/web/ui/modals/add-customer-modal.tsx
+++ b/apps/web/ui/modals/add-customer-modal.tsx
@@ -32,8 +32,6 @@ interface AddCustomerModalProps {
type FormData = z.infer<typeof createCustomerBodySchema>;
type StripeCustomer = z.infer<typeof StripeCustomerSchema>;
-const STRIPE_DASHBOARD_CUSTOMER_URL = "https://dashboard.stripe.com/customers";
-
function getCustomerInitials(customer: StripeCustomer): string {
const raw = customer.name || customer.email || customer.id;
const parts = raw
@@ -288,7 +286,7 @@ export const AddCustomerModal = ({
const displayName =
customer.name || customer.email || customer.id;
const initials = getCustomerInitials(customer);
- const stripeUrl = `${STRIPE_DASHBOARD_CUSTOMER_URL}/${customer.id}`;
+ const stripeUrl = `https://dashboard.stripe.com/customers/${customer.id}`;
return (
<li key={customer.id}>