The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add updateStripeCustomers functionality to PartnerStack import process
Kiran Kd60c05992bcf
diff --git a/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts b/apps/web/app/(ee)/api/cron/import/partnerstack/route.tsindex ab0dab99c5..ca23b0aa9d 100644--- a/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts+++ b/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts@@ -5,6 +5,7 @@ import { importCustomers } from "@/lib/partnerstack/import-customers";import { importLinks } from "@/lib/partnerstack/import-links";import { importPartners } from "@/lib/partnerstack/import-partners";import { partnerStackImportPayloadSchema } from "@/lib/partnerstack/schemas";+import { updateStripeCustomers } from "@/lib/partnerstack/update-stripe-customers";import { NextResponse } from "next/server";export const dynamic = "force-dynamic";@@ -33,6 +34,9 @@ export async function POST(req: Request) {case "import-commissions":await importCommissions(payload);break;+ case "update-stripe-customers":+ await updateStripeCustomers(payload);+ break;}return NextResponse.json("OK");diff --git a/apps/web/lib/partnerstack/api.ts b/apps/web/lib/partnerstack/api.tsindex 9926a6960a..780bb3d780 100644--- a/apps/web/lib/partnerstack/api.ts+++ b/apps/web/lib/partnerstack/api.ts@@ -1,15 +1,15 @@import {- partnerStackPartner,partnerStackCommission,partnerStackCustomer,partnerStackLink,+ partnerStackPartner,} from "./schemas";import {- PartnerStackPartner,PartnerStackCommission,PartnerStackCustomer,PartnerStackLink,PartnerStackListResponse,+ PartnerStackPartner,} from "./types";const PAGE_LIMIT = 100;diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.tsindex 0db4e3c87f..0af5d0d047 100644--- a/apps/web/lib/partnerstack/import-commissions.ts+++ b/apps/web/lib/partnerstack/import-commissions.ts@@ -1,12 +1,29 @@import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { CommissionStatus } from "@prisma/client";+import { createId } from "../api/create-id";+import { syncTotalCommissions } from "../api/partners/sync-total-commissions";+import { getLeadEvent, recordSaleWithTimestamp } from "../tinybird";+import { clickEventSchemaTB } from "../zod/schemas/clicks";import { PartnerStackApi } from "./api";import { MAX_BATCHES, partnerStackImporter } from "./importer";-import { PartnerStackImportPayload } from "./types";+import { PartnerStackCommission, PartnerStackImportPayload } from "./types";++const toDubStatus: Record<+ PartnerStackCommission["reward_status"],+ CommissionStatus+> = {+ hold: "pending",+ pending: "pending",+ approved: "processed",+ declined: "canceled",+ paid: "paid",+};export async function importCommissions(payload: PartnerStackImportPayload) {const { programId, startingAfter } = payload;- const program = await prisma.program.findUniqueOrThrow({+ const { workspaceId } = await prisma.program.findUniqueOrThrow({where: {id: programId,},@@ -15,9 +32,8 @@ export async function importCommissions(payload: PartnerStackImportPayload) {},});- const { publicKey, secretKey } = await partnerStackImporter.getCredentials(- program.workspaceId,- );+ const { publicKey, secretKey } =+ await partnerStackImporter.getCredentials(workspaceId);const partnerStackApi = new PartnerStackApi({publicKey,@@ -38,75 +54,210 @@ export async function importCommissions(payload: PartnerStackImportPayload) {break;}- const partners = await prisma.partner.findMany({- where: {- email: {- in: commissions.map(({ partner }) => partner.email),- },- },- select: {- id: true,- },- });-- const programEnrollments = await prisma.programEnrollment.findMany({- where: {- partnerId: {- in: partners.map((partner) => partner.id),- },- programId,- },- select: {- partner: {- select: {- id: true,- email: true,- },- },- links: {- select: {- id: true,- key: true,- domain: true,- url: true,- },- },- },- });-- const partnerEmailToLinks = new Map<- string,- (typeof programEnrollments)[0]["links"]- >();-- for (const { partner, links } of programEnrollments) {- if (!partner.email) {- continue;- }-- partnerEmailToLinks.set(partner.email, links);- }-await Promise.allSettled(- commissions.map(({ partner, ...customer }) =>- createCustomer({- workspace,- customer,- partner,- links: partnerEmailToLinks.get(partner.email) ?? [],+ commissions.map((commission) =>+ createCommission({+ workspaceId,+ programId,+ commission,}),),);- await new Promise((resolve) => setTimeout(resolve, 2000));+ await new Promise((resolve) => setTimeout(resolve, 1000));- processedBatches++;currentStartingAfter = commissions[commissions.length - 1].key;+ processedBatches++;+ }++ delete payload?.startingAfter;++ if (!hasMore) {+ await partnerStackImporter.deleteCredentials(workspaceId);}await partnerStackImporter.queue({...payload,...(hasMore && { startingAfter: currentStartingAfter }),- action: hasMore ? "import-customers" : "import-commissions",+ action: hasMore ? "import-commissions" : "update-stripe-customers",+ });+}++async function createCommission({+ workspaceId,+ programId,+ commission,+}: {+ workspaceId: string;+ programId: string;+ commission: PartnerStackCommission;+}) {+ if (!commission.transaction) {+ console.log(`Commission ${commission.key} has no transaction, skipping...`);+ return;+ }++ if (!commission.customer) {+ console.log(`Commission ${commission.key} has no customer, skipping...`);+ return;+ }++ const commissionFound = await prisma.commission.findUnique({+ where: {+ invoiceId_programId: {+ invoiceId: commission.key, // This is not the actual invoice ID, but we use this to deduplicate the commissions+ programId,+ },+ },+ });++ if (commissionFound) {+ console.log(`Commission ${commission.key} already exists, skipping...`);+ return;+ }++ const customer = await prisma.customer.findFirst({+ where: {+ projectId: workspaceId,+ email: commission.customer.email,+ },+ include: {+ link: true,+ },+ orderBy: {+ id: "asc",+ },+ });++ if (!customer) {+ console.log(+ `No customer found for customer email ${commission.customer.email}, skipping...`,+ );+ return;+ }++ // 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 PartnerStack, we use the referral's customer ID+ // and check for commissions that were created with the same amount and within a +-1 hour window+ const chargedAt = new Date(commission.created_at);+ const trackedCommission = await prisma.commission.findFirst({+ where: {+ programId,+ type: "sale",+ customer: {+ id: customer.id,+ },+ amount: commission.transaction.amount,+ createdAt: {+ gte: new Date(chargedAt.getTime() - 60 * 60 * 1000), // 1 hour before+ lte: new Date(chargedAt.getTime() + 60 * 60 * 1000), // 1 hour after+ },+ },+ });++ if (trackedCommission) {+ console.log(+ `Commission ${trackedCommission.id} was already recorded on Dub, skipping...`,+ );+ return;+ }++ if (!customer.linkId) {+ console.log(`No link found for customer ${customer.id}, skipping...`);+ return;+ }++ if (!customer.clickId) {+ console.log(`No click ID found for customer ${customer.id}, skipping...`);+ return;+ }++ if (!customer.link?.partnerId) {+ console.log(`No partner ID found for customer ${customer.id}, skipping...`);+ return;+ }++ const leadEvent = await getLeadEvent({+ customerId: customer.id,+ });++ if (!leadEvent || leadEvent.data.length === 0) {+ console.log(`No lead event found for customer ${customer.id}, skipping...`);+ return;+ }++ const clickData = clickEventSchemaTB+ .omit({ timestamp: true })+ .parse(leadEvent.data[0]);++ const eventId = nanoid(16);++ await Promise.all([+ prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ eventId,+ type: "sale",+ programId,+ partnerId: customer.link.partnerId,+ linkId: customer.linkId,+ customerId: customer.id,+ amount: commission.transaction.amount,+ earnings: commission.amount,+ currency: commission.transaction.currency,+ quantity: 1,+ status: toDubStatus[commission.reward_status],+ invoiceId: commission.key, // this is not the actual invoice ID, but we use this to deduplicate the sales+ createdAt: new Date(commission.created_at),+ },+ }),++ recordSaleWithTimestamp({+ ...clickData,+ event_id: eventId,+ event_name: "Invoice paid",+ amount: commission.transaction.amount,+ customer_id: customer.id,+ payment_processor: "stripe",+ currency: commission.transaction.currency,+ metadata: JSON.stringify(commission),+ timestamp: new Date(commission.created_at).toISOString(),+ }),++ // update link stats+ prisma.link.update({+ where: {+ id: customer.linkId,+ },+ data: {+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: commission.transaction.amount,+ },+ },+ }),++ // update customer stats+ prisma.customer.update({+ where: {+ id: customer.id,+ },+ data: {+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: commission.transaction.amount,+ },+ },+ }),+ ]);++ await syncTotalCommissions({+ partnerId: customer.link.partnerId,+ programId,});}diff --git a/apps/web/lib/partnerstack/schemas.ts b/apps/web/lib/partnerstack/schemas.tsindex 6b16f38168..ee1af4fae0 100644--- a/apps/web/lib/partnerstack/schemas.ts+++ b/apps/web/lib/partnerstack/schemas.ts@@ -5,6 +5,7 @@ export const partnerStackImportSteps = z.enum(["import-links","import-customers","import-commissions",+ "update-stripe-customers",]);export const partnerStackImportPayloadSchema = z.object({@@ -57,20 +58,19 @@ export const partnerStackCustomer = z.object({export const partnerStackCommission = z.object({key: z.string(),- amount_usd: z.number().describe("The amount of the reward in cents (USD)."),- approved: z.boolean(),- created_at: z.string(),- currency: z.string(),- customer: z.object({- email: z.string(),- external_key: z.string(),- }),- invoice: z.object({- key: z.string(),- }),- transaction: z.object({- amount: z.number().describe("The amount of the transaction."),- }),+ amount: z.number().describe("The amount of the reward in cents (USD)."),+ created_at: z.number(),+ customer: z+ .object({+ email: z.string(),+ external_key: z.string().nullable(),+ })+ .nullable(),+ transaction: z+ .object({+ amount: z.number().describe("The amount of the transaction."),+ currency: z.string(),+ })+ .nullable(),reward_status: z.enum(["hold", "pending", "approved", "declined", "paid"]),- test: z.boolean().describe("True if created by a test."),});diff --git a/apps/web/lib/partnerstack/update-stripe-customers.ts b/apps/web/lib/partnerstack/update-stripe-customers.tsnew file mode 100644index 0000000000..2eb575ff34--- /dev/null+++ b/apps/web/lib/partnerstack/update-stripe-customers.ts@@ -0,0 +1,176 @@+import { sendEmail } from "@dub/email";+import CampaignImported from "@dub/email/templates/campaign-imported";+import { prisma } from "@dub/prisma";+import { Customer, Project } from "@dub/prisma/client";+import { log } from "@dub/utils";+import { stripeAppClient } from "../stripe";+import { MAX_BATCHES, partnerStackImporter } from "./importer";+import { PartnerStackImportPayload } from "./types";++const CUSTOMERS_PER_BATCH = 20;++const stripe = stripeAppClient({+ ...(process.env.VERCEL_ENV && { livemode: true }),+});++// PartnerStack 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: PartnerStackImportPayload,+) {+ const { programId, userId, startingAfter } = payload;++ const { workspace, ...program } = await prisma.program.findUniqueOrThrow({+ where: {+ id: programId,+ },+ select: {+ name: true,+ 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;+ let currentStartingAfter = startingAfter;++ while (hasMore && processedBatches < MAX_BATCHES) {+ const customers = await prisma.customer.findMany({+ where: {+ projectId: workspace.id,+ stripeCustomerId: null,+ },+ select: {+ id: true,+ name: true,+ email: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ take: CUSTOMERS_PER_BATCH,+ skip: currentStartingAfter ? 1 : 0,+ ...(currentStartingAfter && {+ cursor: {+ id: currentStartingAfter,+ },+ }),+ });++ if (customers.length === 0) {+ hasMore = false;+ break;+ }++ await Promise.all(+ customers.map((customer) =>+ searchStripeAndUpdateCustomer({+ workspace,+ customer,+ }),+ ),+ );++ await new Promise((resolve) => setTimeout(resolve, 2000));++ processedBatches++;+ currentStartingAfter = customers[customers.length - 1].id;+ }++ if (hasMore) {+ await partnerStackImporter.queue({+ ...payload,+ startingAfter: currentStartingAfter,+ action: "update-stripe-customers",+ });+ return;+ }++ const workspaceUser = await prisma.projectUsers.findUniqueOrThrow({+ where: {+ userId_projectId: {+ userId,+ projectId: workspace.id,+ },+ },+ select: {+ user: {+ select: {+ email: true,+ },+ },+ },+ });++ if (workspaceUser && workspaceUser.user.email) {+ await sendEmail({+ email: workspaceUser.user.email,+ subject: "PartnerStack program imported",+ react: CampaignImported({+ email: workspaceUser.user.email,+ workspace,+ program,+ provider: "PartnerStack",+ }),+ });+ }+}++async function searchStripeAndUpdateCustomer({+ workspace,+ customer,+}: {+ workspace: Pick<Project, "id" | "slug" | "stripeConnectId">;+ customer: Pick<Customer, "id" | "email">;+}) {+ const stripeCustomers = await stripe.customers.search(+ {+ query: `email:'${customer.email}'`,+ },+ {+ stripeAccount: workspace.stripeConnectId!,+ },+ );++ if (stripeCustomers.data.length === 0) {+ console.error(`Stripe search returned no customer for ${customer.email}`);+ return null;+ }++ if (stripeCustomers.data.length > 1) {+ await log({+ message: `Stripe search returned multiple customers for ${customer.email} for workspace ${workspace.slug}`,+ type: "errors",+ });++ console.error(+ `Stripe search returned multiple customers for ${customer.email}`,+ );++ return null;+ }++ const stripeCustomer = stripeCustomers.data[0];++ await prisma.customer.update({+ where: {+ id: customer.id,+ },+ data: {+ stripeCustomerId: stripeCustomer.id,+ },+ });+}diff --git a/packages/email/src/templates/campaign-imported.tsx b/packages/email/src/templates/campaign-imported.tsxindex 2d08b75974..fc2496c3fc 100644--- a/packages/email/src/templates/campaign-imported.tsx+++ b/packages/email/src/templates/campaign-imported.tsx@@ -25,7 +25,7 @@ export default function CampaignImported({},}: {email: string;- provider: "Rewardful" | "Tolt";+ provider: "Rewardful" | "Tolt" | "PartnerStack";workspace: {slug: string;};