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.

fix import-commissions

Kiran K643a8c28bcf8
diff --git a/apps/web/lib/firstpromoter/import-commissions.ts b/apps/web/lib/firstpromoter/import-commissions.ts
index dfa2787323..9f423e09a1 100644
--- a/apps/web/lib/firstpromoter/import-commissions.ts
+++ b/apps/web/lib/firstpromoter/import-commissions.ts
@@ -7,9 +7,9 @@ import { convertCurrencyWithFxRates } from "../analytics/convert-currency";
import { isFirstConversion } from "../analytics/is-first-conversion";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
+import { recordSaleWithTimestamp } from "../tinybird";
import { getLeadEvents } from "../tinybird/get-lead-events";
import { logImportError } from "../tinybird/log-import-error";
-import { recordSaleWithTimestamp } from "../tinybird/record-sale";
import { LeadEventTB } from "../types";
import { redis } from "../upstash";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
@@ -20,12 +20,12 @@ import { FirstPromoterCommission, FirstPromoterImportPayload } from "./types";
const toDubStatus: Record<FirstPromoterCommission["status"], CommissionStatus> =
{
pending: "pending",
- approved: "paid",
+ approved: "processed",
denied: "canceled",
};
export async function importCommissions(payload: FirstPromoterImportPayload) {
- const { importId, programId, userId, campaignId, page = 1 } = payload;
+ const { importId, programId, userId, page = 1 } = payload;
const program = await prisma.program.findUniqueOrThrow({
where: {
@@ -36,6 +36,7 @@ export async function importCommissions(payload: FirstPromoterImportPayload) {
const credentials = await firstPromoterImporter.getCredentials(
program.workspaceId,
);
+
const firstPromoterApi = new FirstPromoterApi(credentials);
const fxRates = await redis.hgetall<Record<string, string>>("fxRates:usd");
@@ -44,7 +45,7 @@ export async function importCommissions(payload: FirstPromoterImportPayload) {
let processedBatches = 0;
let currentPage = page;
- while (hasMore && processedBatches < MAX_BATCHES) {
+ while (processedBatches < MAX_BATCHES) {
const commissions = await firstPromoterApi.listCommissions({
page: currentPage,
});
@@ -75,16 +76,15 @@ export async function importCommissions(payload: FirstPromoterImportPayload) {
customerIds: customersData.map(({ id }) => id),
}).then((res) => res.data);
- await Promise.all(
+ await Promise.allSettled(
commissions.map((commission) =>
createCommission({
- commission,
program,
- campaignId,
+ commission,
fxRates,
- importId,
customersData,
customerLeadEvents,
+ importId,
}),
),
);
@@ -93,98 +93,93 @@ export async function importCommissions(payload: FirstPromoterImportPayload) {
processedBatches++;
}
- if (hasMore) {
- await firstPromoterImporter.queue({
- ...payload,
- action: "import-commissions",
- page: currentPage,
- });
-
- return;
- }
+ await firstPromoterImporter.queue({
+ ...payload,
+ action: hasMore ? "import-commissions" : "update-stripe-customers",
+ page: hasMore ? currentPage : undefined,
+ });
// Imports finished
- await firstPromoterImporter.deleteCredentials(program.workspaceId);
+ if (!hasMore) {
+ await firstPromoterImporter.deleteCredentials(program.workspaceId);
- const workspaceUser = await prisma.projectUsers.findUniqueOrThrow({
- where: {
- userId_projectId: {
- userId,
- projectId: program.workspaceId,
+ const workspaceUser = await prisma.projectUsers.findUniqueOrThrow({
+ where: {
+ userId_projectId: {
+ userId,
+ projectId: program.workspaceId,
+ },
},
- },
- include: {
- project: true,
- user: true,
- },
- });
+ include: {
+ project: true,
+ user: true,
+ },
+ });
- if (workspaceUser && workspaceUser.user.email) {
- await sendEmail({
- email: workspaceUser.user.email,
- subject: "FirstPromoter campaign imported",
- react: ProgramImported({
+ if (workspaceUser && workspaceUser.user.email) {
+ await sendEmail({
email: workspaceUser.user.email,
- workspace: workspaceUser.project,
- program,
- provider: "FirstPromoter",
- importId,
- }),
- });
+ subject: "FirstPromoter campaign imported",
+ react: ProgramImported({
+ email: workspaceUser.user.email,
+ workspace: workspaceUser.project,
+ program,
+ provider: "FirstPromoter",
+ importId,
+ }),
+ });
+ }
}
}
async function createCommission({
- commission,
program,
- campaignId,
+ commission,
fxRates,
- importId,
customersData,
customerLeadEvents,
+ importId,
}: {
- commission: FirstPromoterCommission;
program: Program;
- campaignId: string;
+ commission: FirstPromoterCommission;
fxRates: Record<string, string> | null;
- importId: string;
customersData: (Customer & { link: Link | null })[];
customerLeadEvents: LeadEventTB[];
+ importId: string;
}) {
const commonImportLogInputs = {
workspace_id: program.workspaceId,
import_id: importId,
source: "firstpromoter",
entity: "commission",
- entity_id: commission.id,
+ entity_id: `${commission.id}`,
} as const;
- if (commission.promoter_campaign.campaign.id !== campaignId) {
- console.log(
- `Affiliate ${commission.promoter_campaign.promoter.email} for commission ${commission.id}) not in campaign ${campaignId} (they're in ${commission.promoter_campaign.campaign.id}). Skipping...`,
- );
+ if (commission.is_self_referral) {
+ await logImportError({
+ ...commonImportLogInputs,
+ code: "SELF_REFERRAL",
+ message: `Self-referral commission ${commission.id}.`,
+ });
return;
}
- // if (
- // !sale.referral.stripe_customer_id ||
- // !sale.referral.stripe_customer_id.startsWith("cus_")
- // ) {
- // await logImportError({
- // ...commonImportLogInputs,
- // code: "STRIPE_CUSTOMER_NOT_FOUND",
- // message: `No Stripe customer ID provided for referral ${sale.referral.id}`,
- // });
+ if (commission.unit !== "cash") {
+ await logImportError({
+ ...commonImportLogInputs,
+ code: "NOT_SUPPORTED_UNIT",
+ message: `Invalid unit ${commission.unit} for commission ${commission.id}.`,
+ });
- // return;
- // }
+ return;
+ }
// Find the commission
const commissionFound = await prisma.commission.findUnique({
where: {
invoiceId_programId: {
- invoiceId: commission.id, // this is not the actual invoice ID, but we use this to deduplicate the sales
+ invoiceId: `${commission.id}`, // this is not the actual invoice ID, but we use this to deduplicate the sales
programId: program.id,
},
},
@@ -196,11 +191,11 @@ async function createCommission({
}
// Find the customer
- const customerFound = customersData.find(
+ const customer = customersData.find(
({ email }) => email === commission.referral?.email,
);
- if (!customerFound) {
+ if (!customer) {
await logImportError({
...commonImportLogInputs,
code: "CUSTOMER_NOT_FOUND",
@@ -212,10 +207,9 @@ async function createCommission({
// Sale amount (can potentially be null)
let saleAmount = Number(commission.original_sale_amount ?? 0);
-
const saleCurrency = commission.original_sale_currency ?? "usd";
- if (saleCurrency.toUpperCase() !== "USD" && fxRates) {
+ if (saleAmount > 0 && saleCurrency.toUpperCase() !== "USD" && fxRates) {
const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: saleCurrency,
amount: saleAmount,
@@ -228,16 +222,6 @@ async function createCommission({
// Earnings
let earnings = commission.amount;
- // if (earningsCurrency !== "USD" && fxRates) {
- // const { amount: convertedAmount } = convertCurrencyWithFxRates({
- // currency: earningsCurrency,
- // amount: earnings,
- // fxRates,
- // });
-
- // earnings = convertedAmount;
- // }
-
// here, we also check for commissions that have already been recorded on Dub
// e.g. during the transition period
// since we don't have the Stripe invoiceId from Rewardful, we use the referral's Stripe customer ID
@@ -250,7 +234,7 @@ async function createCommission({
gte: new Date(chargedAt.getTime() - 60 * 60 * 1000), // 1 hour before
lte: new Date(chargedAt.getTime() + 60 * 60 * 1000), // 1 hour after
},
- customerId: customerFound.id,
+ customerId: customer.id,
type: "sale",
amount: saleAmount,
},
@@ -264,73 +248,84 @@ async function createCommission({
return;
}
- if (!customerFound.linkId) {
+ if (!customer.linkId) {
await logImportError({
...commonImportLogInputs,
code: "LINK_NOT_FOUND",
- message: `No link found for customer ${customerFound.id}.`,
+ message: `No link found for customer ${customer.id}.`,
});
return;
}
- if (!customerFound.clickId) {
+ if (!customer.clickId) {
await logImportError({
...commonImportLogInputs,
code: "CLICK_NOT_FOUND",
- message: `No click ID found for customer ${customerFound.id}.`,
+ message: `No click ID found for customer ${customer.id}.`,
});
return;
}
- if (!customerFound.link?.partnerId) {
+ if (!customer.link?.partnerId) {
await logImportError({
...commonImportLogInputs,
code: "PARTNER_NOT_FOUND",
- message: `No partner ID found for customer ${customerFound.id}.`,
+ message: `No partner ID found for customer ${customer.id}.`,
});
return;
}
+ // Find the customer lead event
const leadEvent = customerLeadEvents.find(
- (event) => event.customer_id === customerFound.id,
+ (event) => event.customer_id === customer.id,
);
if (!leadEvent) {
+ console.log(`No lead event found for customer ${customer.id}.`);
await logImportError({
...commonImportLogInputs,
code: "LEAD_NOT_FOUND",
- message: `No lead event found for customer ${customerFound.id}.`,
+ message: `No lead event found for customer ${customer.id}.`,
});
return;
}
+ // Customer click event
const clickData = clickEventSchemaTB
.omit({ timestamp: true })
.parse(leadEvent);
const eventId = nanoid(16);
- await Promise.all([
+ // Decide the commission status
+ let status: CommissionStatus = toDubStatus[commission.status];
+
+ if (commission.is_paid) {
+ status = "paid";
+ }
+
+ await Promise.allSettled([
prisma.commission.create({
data: {
id: createId({ prefix: "cm_" }),
eventId,
- type: "sale",
+ type: commission.commission_type,
programId: program.id,
- partnerId: customerFound.link.partnerId,
- linkId: customerFound.linkId,
- customerId: customerFound.id,
+ partnerId: customer.link.partnerId,
+ linkId: customer.linkId,
+ customerId: customer.id,
amount: saleAmount,
earnings,
currency: "usd",
quantity: 1,
- status: toDubStatus[commission.status],
- invoiceId: commission.id, // this is not the actual invoice ID, but we use this to deduplicate the sales
+ status,
+ invoiceId: `${commission.id}`, // this is not the actual invoice ID, but we use this to deduplicate the sales
createdAt: new Date(commission.created_at),
+ description: commission.external_note || null,
},
}),
@@ -339,7 +334,7 @@ async function createCommission({
event_id: eventId,
event_name: "Invoice paid",
amount: saleAmount,
- customer_id: customerFound.id,
+ customer_id: customer.id,
payment_processor: "stripe",
currency: "usd",
metadata: JSON.stringify(commission.metadata),
@@ -349,12 +344,12 @@ async function createCommission({
// update link stats
prisma.link.update({
where: {
- id: customerFound.linkId,
+ id: customer.linkId,
},
data: {
...(isFirstConversion({
- customer: customerFound,
- linkId: customerFound.linkId,
+ customer: customer,
+ linkId: customer.linkId,
}) && {
conversions: {
increment: 1,
@@ -372,7 +367,7 @@ async function createCommission({
// update customer stats
prisma.customer.update({
where: {
- id: customerFound.id,
+ id: customer.id,
},
data: {
sales: {
@@ -386,7 +381,7 @@ async function createCommission({
]);
await syncTotalCommissions({
- partnerId: customerFound.link.partnerId,
+ partnerId: customer.link.partnerId,
programId: program.id,
});
}
diff --git a/apps/web/lib/firstpromoter/schemas.ts b/apps/web/lib/firstpromoter/schemas.ts
index 7674edd16f..6ec861ce55 100644
--- a/apps/web/lib/firstpromoter/schemas.ts
+++ b/apps/web/lib/firstpromoter/schemas.ts
@@ -18,7 +18,8 @@ export const firstPromoterImportPayloadSchema = z.object({
importId: z.string(),
userId: z.string(),
programId: z.string(),
- page: z.number().optional(),
+ page: z.number().optional().describe("FP pagination"),
+ startingAfter: z.string().optional().describe("Internal pagination"),
});
export const firstPromoterCampaignSchema = z.object({
diff --git a/apps/web/lib/firstpromoter/update-stripe-customers.ts b/apps/web/lib/firstpromoter/update-stripe-customers.ts
new file mode 100644
index 0000000000..0334021e2d
--- /dev/null
+++ b/apps/web/lib/firstpromoter/update-stripe-customers.ts
@@ -0,0 +1,171 @@
+import { prisma } from "@dub/prisma";
+import { Customer, Project } from "@dub/prisma/client";
+import Stripe from "stripe";
+import { stripeAppClient } from "../stripe";
+import { logImportError } from "../tinybird/log-import-error";
+import { firstPromoterImporter, MAX_BATCHES } from "./importer";
+import { FirstPromoterImportPayload } from "./types";
+
+const CUSTOMERS_PER_BATCH = 20;
+
+const stripe = stripeAppClient({
+ ...(process.env.VERCEL_ENV && { livemode: true }),
+});
+
+// FirstPromoter API doesn't return the Stripe customer ID,
+// so we'll search for Stripe customers by email and update the customer record with the Stripe customer ID, if found.
+export async function updateStripeCustomers(
+ payload: FirstPromoterImportPayload,
+) {
+ let { importId, programId, startingAfter } = payload;
+
+ const { workspace } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ workspace: {
+ select: {
+ id: true,
+ slug: true,
+ stripeConnectId: true,
+ },
+ },
+ },
+ });
+
+ if (!workspace.stripeConnectId) {
+ console.error(
+ `Workspace ${workspace.id} has no stripeConnectId. Skipping...`,
+ );
+ return;
+ }
+
+ let hasMore = true;
+ let processedBatches = 0;
+
+ while (processedBatches < MAX_BATCHES) {
+ const customers = await prisma.customer.findMany({
+ where: {
+ projectId: workspace.id,
+ stripeCustomerId: null,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ orderBy: {
+ id: "asc",
+ },
+ take: CUSTOMERS_PER_BATCH,
+ skip: startingAfter ? 1 : 0,
+ ...(startingAfter && {
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ });
+
+ if (customers.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ await Promise.allSettled(
+ customers.map((customer) =>
+ searchStripeAndUpdateCustomer({
+ workspace,
+ customer,
+ importId,
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ processedBatches++;
+ startingAfter = customers[customers.length - 1].id;
+ }
+
+ if (hasMore) {
+ return await firstPromoterImporter.queue({
+ ...payload,
+ startingAfter,
+ action: "update-stripe-customers",
+ });
+ }
+}
+
+async function searchStripeAndUpdateCustomer({
+ workspace,
+ customer,
+ importId,
+}: {
+ workspace: Pick<Project, "id" | "slug" | "stripeConnectId">;
+ customer: Pick<Customer, "id" | "email">;
+ importId: string;
+}) {
+ const commonImportLogInputs = {
+ workspace_id: workspace.id,
+ import_id: importId,
+ source: "firstpromoter",
+ entity: "customer",
+ entity_id: customer.id,
+ } as const;
+
+ const stripeCustomers = await stripe.customers.search(
+ {
+ query: `email:'${customer.email}'`,
+ },
+ {
+ stripeAccount: workspace.stripeConnectId!,
+ },
+ );
+
+ if (stripeCustomers.data.length === 0) {
+ await logImportError({
+ ...commonImportLogInputs,
+ code: "STRIPE_CUSTOMER_NOT_FOUND",
+ message: `Stripe search returned no customer for ${customer.email}`,
+ });
+
+ return null;
+ }
+
+ let stripeCustomer: Stripe.Customer;
+
+ if (stripeCustomers.data.length > 1) {
+ // look for the one with metadata.fp_uid set
+ const firstPromoterStripeCustomer = stripeCustomers.data.find(
+ ({ metadata }) => metadata.fp_uid,
+ );
+
+ if (firstPromoterStripeCustomer) {
+ stripeCustomer = firstPromoterStripeCustomer;
+ } else {
+ await logImportError({
+ ...commonImportLogInputs,
+ code: "STRIPE_CUSTOMER_NOT_FOUND",
+ message: `Stripe search returned multiple customers for ${customer.email} for workspace ${workspace.slug} and none had metadata.fp_uid set`,
+ });
+
+ return null;
+ }
+ } else {
+ stripeCustomer = stripeCustomers.data[0];
+ }
+
+ await prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ stripeCustomerId: stripeCustomer.id,
+ },
+ });
+
+ console.log(
+ `Updated customer ${customer.id} with Stripe customer ID ${stripeCustomer.id}`,
+ );
+}