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.

Implement customer import functionality in PartnerStack API and update related schemas

Kiran K7113d82cbebd
diff --git a/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts b/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts
index 63730e65bf..2c2b084caf 100644
--- a/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts
+++ b/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts
@@ -1,10 +1,10 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { importAffiliates } from "@/lib/partnerstack/import-affiliates";
+import { importCustomers } from "@/lib/partnerstack/import-customers";
import { importLinks } from "@/lib/partnerstack/import-links";
import { partnerStackImportPayloadSchema } from "@/lib/partnerstack/schemas";
import { importCommissions } from "@/lib/tolt/import-commissions";
-import { importReferrals } from "@/lib/tolt/import-referrals";
import { updateStripeCustomers } from "@/lib/tolt/update-stripe-customers";
import { NextResponse } from "next/server";
@@ -28,8 +28,8 @@ export async function POST(req: Request) {
case "import-links":
await importLinks(payload);
break;
- case "import-referrals":
- await importReferrals(payload);
+ case "import-customers":
+ await importCustomers(payload);
break;
case "import-commissions":
await importCommissions(payload);
diff --git a/apps/web/lib/partnerstack/api.ts b/apps/web/lib/partnerstack/api.ts
index a0b9f2822f..91e4c29b98 100644
--- a/apps/web/lib/partnerstack/api.ts
+++ b/apps/web/lib/partnerstack/api.ts
@@ -1,6 +1,11 @@
-import { partnerStackAffiliate, partnerStackLink } from "./schemas";
+import {
+ partnerStackAffiliate,
+ partnerStackCustomer,
+ partnerStackLink,
+} from "./schemas";
import {
PartnerStackAffiliate,
+ PartnerStackCustomer,
PartnerStackLink,
PartnerStackListResponse,
} from "./types";
@@ -69,4 +74,21 @@ export class PartnerStackApi {
return partnerStackLink.array().parse(items);
}
+
+ async listCustomers({ startingAfter }: { startingAfter?: string }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ if (startingAfter) {
+ searchParams.append("starting_after", startingAfter);
+ }
+
+ const {
+ data: { items },
+ } = await this.fetch<PartnerStackListResponse<PartnerStackCustomer>>(
+ `/customers?${searchParams.toString()}`,
+ );
+
+ return partnerStackCustomer.array().parse(items);
+ }
}
diff --git a/apps/web/lib/partnerstack/import-customers.ts b/apps/web/lib/partnerstack/import-customers.ts
new file mode 100644
index 0000000000..b496530235
--- /dev/null
+++ b/apps/web/lib/partnerstack/import-customers.ts
@@ -0,0 +1,233 @@
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { Link, Project } from "@prisma/client";
+import { createId } from "../api/create-id";
+import { recordClick, recordLeadWithTimestamp } from "../tinybird";
+import { clickEventSchemaTB } from "../zod/schemas/clicks";
+import { PartnerStackApi } from "./api";
+import { MAX_BATCHES, partnerStackImporter } from "./importer";
+import {
+ PartnerStackAffiliate,
+ PartnerStackCustomer,
+ PartnerStackImportPayload,
+} from "./types";
+
+export async function importCustomers(payload: PartnerStackImportPayload) {
+ const { programId, startingAfter } = payload;
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ workspaceId: true,
+ },
+ });
+
+ const { token } = await partnerStackImporter.getCredentials(
+ program.workspaceId,
+ );
+
+ const partnerStackApi = new PartnerStackApi({
+ token,
+ });
+
+ let hasMore = true;
+ let processedBatches = 0;
+ let currentStartingAfter = startingAfter;
+
+ while (hasMore && processedBatches < MAX_BATCHES) {
+ const customers = await partnerStackApi.listCustomers({
+ startingAfter,
+ });
+
+ if (customers.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const partners = await prisma.partner.findMany({
+ where: {
+ email: {
+ in: customers.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(
+ customers.map(({ partner, ...customer }) =>
+ createCustomer({
+ workspace,
+ customer,
+ partner,
+ links: partnerEmailToLinks.get(partner.email) ?? [],
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ processedBatches++;
+ currentStartingAfter = customers[customers.length - 1].key;
+ }
+
+ await partnerStackImporter.queue({
+ ...payload,
+ ...(hasMore && { startingAfter: currentStartingAfter }),
+ action: hasMore ? "import-customers" : "import-commissions",
+ });
+}
+
+async function createCustomer({
+ customer,
+ workspace,
+ links,
+ partner,
+}: {
+ customer: PartnerStackCustomer;
+ partner: PartnerStackAffiliate;
+ workspace: Pick<Project, "id" | "stripeConnectId">;
+ links: Pick<Link, "id" | "key" | "domain" | "url">[];
+}) {
+ if (links.length === 0) {
+ console.log("Link not found for referral, skipping...", {
+ customerEmail: customer.email,
+ partnerEmail: partner.email,
+ });
+ return;
+ }
+
+ const customerFound = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: customer.customer_id,
+ },
+ },
+ });
+
+ if (customerFound) {
+ console.log(
+ `A customer already exists with customer_id ${customer.customer_id}`,
+ );
+ return;
+ }
+
+ const link = links[0];
+
+ const dummyRequest = new Request(link.url, {
+ headers: new Headers({
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ "x-forwarded-for": "127.0.0.1",
+ "x-vercel-ip-country": "US",
+ "x-vercel-ip-country-region": "CA",
+ "x-vercel-ip-continent": "NA",
+ }),
+ });
+
+ const clickData = await recordClick({
+ req: dummyRequest,
+ linkId: link.id,
+ clickId: nanoid(16),
+ url: link.url,
+ domain: link.domain,
+ key: link.key,
+ workspaceId: workspace.id,
+ skipRatelimit: true,
+ timestamp: new Date(customer.created_at).toISOString(),
+ });
+
+ const clickEvent = clickEventSchemaTB.parse({
+ ...clickData,
+ bot: 0,
+ qr: 0,
+ });
+
+ const customerId = createId({ prefix: "cus_" });
+
+ try {
+ await prisma.customer.create({
+ data: {
+ id: customerId,
+ name:
+ // if name is null/undefined or starts with cus_, use email as name
+ !customer.name || customer.name.startsWith("cus_")
+ ? customer.email
+ : customer.name,
+ email: customer.email,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ clickId: clickEvent.click_id,
+ linkId: link.id,
+ country: clickEvent.country,
+ clickedAt: new Date(customer.created_at),
+ createdAt: new Date(customer.created_at),
+ externalId: customer.customer_id,
+ },
+ });
+
+ await Promise.all([
+ recordLeadWithTimestamp({
+ ...clickEvent,
+ event_id: nanoid(16),
+ event_name: "Sign up",
+ customer_id: customerId,
+ timestamp: new Date(customer.created_at).toISOString(),
+ }),
+
+ prisma.link.update({
+ where: {
+ id: link.id,
+ },
+ data: {
+ leads: {
+ increment: 1,
+ },
+ },
+ }),
+ ]);
+ } catch (error) {
+ console.error("Error creating customer", customer, error);
+ }
+}
diff --git a/apps/web/lib/partnerstack/import-referrals.ts b/apps/web/lib/partnerstack/import-referrals.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/apps/web/lib/partnerstack/schemas.ts b/apps/web/lib/partnerstack/schemas.ts
index 501e6ff047..d7069ee02d 100644
--- a/apps/web/lib/partnerstack/schemas.ts
+++ b/apps/web/lib/partnerstack/schemas.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
export const partnerStackImportSteps = z.enum([
"import-affiliates",
"import-links",
- "import-referrals",
+ "import-customers",
"import-commissions",
"update-stripe-customers",
]);
@@ -30,3 +30,16 @@ export const partnerStackLink = z.object({
dest: z.string(),
url: z.string(),
});
+
+export const partnerStackCustomer = z.object({
+ key: z.string(),
+ customer_key: z.string().describe("External ID."),
+ name: z.string(),
+ email: z.string(),
+ provider_key: z
+ .string()
+ .describe("A unique identifier given by a payment provider."),
+ test: z.boolean().describe("True if created by a test partner."),
+ created_at: z.number(),
+ updated_at: z.number(),
+});
diff --git a/apps/web/lib/partnerstack/types.ts b/apps/web/lib/partnerstack/types.ts
index 67a8e8f56f..edcbbafe8a 100644
--- a/apps/web/lib/partnerstack/types.ts
+++ b/apps/web/lib/partnerstack/types.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import {
partnerStackAffiliate,
+ partnerStackCustomer,
partnerStackImportPayloadSchema,
partnerStackLink,
} from "./schemas";
@@ -22,3 +23,5 @@ export type PartnerStackImportPayload = z.infer<
export type PartnerStackAffiliate = z.infer<typeof partnerStackAffiliate>;
export type PartnerStackLink = z.infer<typeof partnerStackLink>;
+
+export type PartnerStackCustomer = z.infer<typeof partnerStackCustomer>;