The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fix import-partners
Kiran Kf18fd9ea2e1b
diff --git a/apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts b/apps/web/app/(ee)/api/cron/import/firstpromoter/route.tsindex 82ac0bb6c8..f087945895 100644--- a/apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts+++ b/apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts@@ -24,9 +24,9 @@ export async function POST(req: Request) {case "import-campaigns":await importCampaigns(payload);break;- // case "import-partners":- // await importPartners(payload);- // break;+ case "import-partners":+ await importPartners(payload);+ break;// case "import-customers":// await importCustomers(payload);// break;diff --git a/apps/web/lib/firstpromoter/api.ts b/apps/web/lib/firstpromoter/api.tsindex 3ab818e509..de9a37dbfa 100644--- a/apps/web/lib/firstpromoter/api.ts+++ b/apps/web/lib/firstpromoter/api.ts@@ -1,3 +1,4 @@+import { z } from "zod";import { partnerStackLink } from "../partnerstack/schemas";import { PAGE_LIMIT } from "./importer";import {@@ -60,16 +61,13 @@ export class FirstPromoterApi {return firstPromoterCampaignSchema.array().parse(campaigns);}- async listPartners({- campaignId,- page,- }: {- campaignId: string;- page?: number;- }) {+ async listPartners({ page }: { page?: number }) {const filters = {- campaign_id: campaignId,archived: false,+ state: "accepted",+ referrals_count: {+ from: 1,+ },};const params: Record<string, string> = {@@ -80,9 +78,15 @@ export class FirstPromoterApi {const searchParams = new URLSearchParams(params);- const partners = await this.fetch(`/promoters?${searchParams.toString()}`);+ const response = await this.fetch(`/promoters?${searchParams.toString()}`);++ const { data: partners } = z+ .object({+ data: firstPromoterPartnerSchema.array(),+ })+ .parse(response);- return firstPromoterPartnerSchema.array().parse(partners);+ return partners;}// TODO:diff --git a/apps/web/lib/firstpromoter/import-partners.ts b/apps/web/lib/firstpromoter/import-partners.tsindex f380993322..7e86958db8 100644--- a/apps/web/lib/firstpromoter/import-partners.ts+++ b/apps/web/lib/firstpromoter/import-partners.ts@@ -3,36 +3,29 @@ import { PartnerGroup, Program } from "@dub/prisma/client";import { nanoid } from "@dub/utils";import { createId } from "../api/create-id";import { bulkCreateLinks } from "../api/links";-import { logImportError } from "../tinybird/log-import-error";import { DEFAULT_PARTNER_GROUP } from "../zod/schemas/groups";import { FirstPromoterApi } from "./api";import { firstPromoterImporter, MAX_BATCHES } from "./importer";import { FirstPromoterImportPayload, FirstPromoterPartner } from "./types";export async function importPartners(payload: FirstPromoterImportPayload) {- const { importId, userId, programId, groupId, campaignId, page = 1 } = payload;+ const { userId, programId, page = 1 } = payload;const program = await prisma.program.findUniqueOrThrow({where: {id: programId,},include: {- groups: {- // if groupId is provided, use it, otherwise use the default group- where: {- ...(groupId- ? {- id: groupId,- }- : {- slug: DEFAULT_PARTNER_GROUP.slug,- }),- },- },+ groups: true,},});- const group = program.groups[0];+ const { groups } = program;++ // Default group will always be created in the program creation+ const defaultGroup = groups.find(+ (group) => group.slug === DEFAULT_PARTNER_GROUP.slug,+ )!;const credentials = await firstPromoterImporter.getCredentials(program.workspaceId,@@ -44,16 +37,8 @@ export async function importPartners(payload: FirstPromoterImportPayload) {let processedBatches = 0;let currentPage = page;- const commonImportLogInputs = {- workspace_id: program.workspaceId,- import_id: importId,- source: "firstpromoter",- entity: "partner",- } as const;-while (hasMore && processedBatches < MAX_BATCHES) {const affiliates = await firstPromoterApi.listPartners({- campaignId,page: currentPage,});@@ -62,41 +47,27 @@ export async function importPartners(payload: FirstPromoterImportPayload) {break;}- const activeAffiliates: typeof affiliates = [];- const notImportedAffiliates: typeof affiliates = [];-- for (const affiliate of affiliates) {- if (- affiliate.state === "accepted" &&- affiliate.stats.referrals_count > 0- ) {- activeAffiliates.push(affiliate);- } else {- notImportedAffiliates.push(affiliate);- }- }+ const campaignMap = Object.fromEntries(+ groups.map((group) => [group.name, group]),+ );- if (activeAffiliates.length > 0) {+ if (affiliates.length > 0) {await Promise.all(- activeAffiliates.map((affiliate) =>- createPartnerAndLinks({+ affiliates.map((affiliate) => {+ const promoterCampaigns = affiliate.promoter_campaigns;++ const group =+ promoterCampaigns.length > 0+ ? campaignMap[promoterCampaigns[0].campaign.name] ?? defaultGroup+ : defaultGroup;++ return createPartnerAndLinks({program,affiliate,- userId,group,- }),- ),- );- }-- if (notImportedAffiliates.length > 0) {- await logImportError(- notImportedAffiliates.map((affiliate) => ({- ...commonImportLogInputs,- entity_id: affiliate.id,- code: "INACTIVE_PARTNER",- message: `Partner ${affiliate.email} not imported because it is not active or has no leads.`,- })),+ userId,+ });+ }),);}@@ -104,12 +75,9 @@ export async function importPartners(payload: FirstPromoterImportPayload) {processedBatches++;}- const action = hasMore ? "import-partners" : "import-customers";-await firstPromoterImporter.queue({...payload,- action,- ...(action === "import-partners" && groupId && { groupId }),+ action: hasMore ? "import-partners" : "import-customers",page: hasMore ? currentPage : undefined,});}@@ -118,16 +86,13 @@ export async function importPartners(payload: FirstPromoterImportPayload) {async function createPartnerAndLinks({program,affiliate,- userId,group,+ userId,}: {program: Program;affiliate: FirstPromoterPartner;+ group: PartnerGroup;userId: string;- group: Pick<- PartnerGroup,- "id" | "clickRewardId" | "leadRewardId" | "saleRewardId" | "discountId"- >;}) {const partner = await prisma.partner.upsert({where: {@@ -137,6 +102,21 @@ async function createPartnerAndLinks({id: createId({ prefix: "pn_" }),name: affiliate.name,email: affiliate.email,+ image: affiliate.profile.avatar,+ description: affiliate.profile.description,+ country: affiliate.profile.country,+ website: affiliate.profile.website,+ youtube: affiliate.profile.youtube_url,+ twitter: affiliate.profile.twitter_url,+ linkedin: affiliate.profile.linkedin_url,+ instagram: affiliate.profile.instagram_url,+ tiktok: affiliate.profile.tiktok_url,+ companyName: affiliate.profile.company_name,+ invoiceSettings: {+ ...(affiliate.profile.address && {+ address: affiliate.profile.address,+ }),+ },},update: {},});@@ -177,17 +157,19 @@ async function createPartnerAndLinks({return;}+ const links = affiliate.promoter_campaigns.map((campaign) => ({+ key: campaign.ref_token || nanoid(),+ domain: program.domain!,+ url: program.url!,+ programId: program.id,+ projectId: program.workspaceId,+ folderId: program.defaultFolderId,+ partnerId: partner.id,+ trackConversion: true,+ userId,+ }));+await bulkCreateLinks({- links: affiliate.links.map((link) => ({- domain: program.domain!,- key: link.token || nanoid(),- url: program.url!,- trackConversion: true,- programId: program.id,- partnerId: partner.id,- folderId: program.defaultFolderId,- userId,- projectId: program.workspaceId,- })),+ links,});}diff --git a/apps/web/lib/firstpromoter/importer.ts b/apps/web/lib/firstpromoter/importer.tsindex e414318a9b..a13af41c2a 100644--- a/apps/web/lib/firstpromoter/importer.ts+++ b/apps/web/lib/firstpromoter/importer.ts@@ -4,7 +4,7 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { FirstPromoterCredentials, FirstPromoterImportPayload } from "./types";export const PAGE_LIMIT = 10;-export const MAX_BATCHES = 1;+export const MAX_BATCHES = 2;export const CACHE_EXPIRY = 60 * 60 * 24;export const CACHE_KEY_PREFIX = "firstpromoter:import";diff --git a/apps/web/lib/firstpromoter/schemas.ts b/apps/web/lib/firstpromoter/schemas.tsindex bfd3c75fb0..636c9d0874 100644--- a/apps/web/lib/firstpromoter/schemas.ts+++ b/apps/web/lib/firstpromoter/schemas.ts@@ -29,40 +29,64 @@ export const firstPromoterCampaignSchema = z.object({});export const firstPromoterPartnerSchema = z.object({- id: z.string(),+ id: z.number(),email: z.string(),name: z.string(),- cust_id: z.string().nullable(),- state: z.enum([- "pending",- "accepted",- "rejected",- "blocked",- "inactive",- "not_set",- ]),profile: z.object({- id: z.string(),- first_name: z.string(),- last_name: z.string(),- website: z.string().nullable(),- company_name: z.string().nullable(),- company_number: z.string().nullable(),- vat_id: z.string().nullable(),- country: z.string().nullable(),- address: z.string().nullable(),- avatar: z.string().nullable(),- description: z.string().nullable(),- youtube_url: z.string().nullable(),- twitter_url: z.string().nullable(),- linkedin_url: z.string().nullable(),- instagram_url: z.string().nullable(),- tiktok_url: z.string().nullable(),- joined_at: z.string(),- }),- stats: z.object({- referrals_count: z.number(),+ id: z.number(),+ website: z+ .string()+ .nullable()+ .transform((val) => val || null),+ company_name: z+ .string()+ .nullable()+ .transform((val) => val || null),+ country: z+ .string()+ .nullable()+ .transform((val) => val || null),+ address: z+ .string()+ .nullable()+ .transform((val) => val || null),+ avatar: z+ .string()+ .nullable()+ .transform((val) => val || null),+ description: z+ .string()+ .nullable()+ .transform((val) => val || null),+ youtube_url: z+ .string()+ .nullable()+ .transform((val) => val || null),+ twitter_url: z+ .string()+ .nullable()+ .transform((val) => val || null),+ linkedin_url: z+ .string()+ .nullable()+ .transform((val) => val || null),+ instagram_url: z+ .string()+ .nullable()+ .transform((val) => val || null),+ tiktok_url: z+ .string()+ .nullable()+ .transform((val) => val || null),}),+ promoter_campaigns: z.array(+ z.object({+ campaign: z.object({+ name: z.string(),+ }),+ ref_token: z.string().nullable(),+ }),+ ),});export const firstPromoterCustomerSchema = z.object({