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.

import links

Kiran K77997baccd74
diff --git a/apps/web/app/(ee)/api/cron/import/tolt/route.ts b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
index 58f32b7da6..a8c4bdc313 100644
--- a/apps/web/app/(ee)/api/cron/import/tolt/route.ts
+++ b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
@@ -1,6 +1,8 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { importAffiliates } from "@/lib/tolt/import-affiliates";
+import { importLinks } from "@/lib/tolt/import-links";
+import { importReferrals } from "@/lib/tolt/import-referrals";
import { importSteps } from "@/lib/tolt/importer";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -22,18 +24,17 @@ export async function POST(req: Request) {
rawBody,
});
- const { programId, action, startingAfter } = schema.parse(
- JSON.parse(rawBody),
- );
-
- console.log("Request body", { programId, action, startingAfter });
+ const { action, ...payload } = schema.parse(JSON.parse(rawBody));
switch (action) {
case "import-affiliates":
- await importAffiliates({
- programId,
- startingAfter,
- });
+ await importAffiliates(payload);
+ break;
+ case "import-links":
+ await importLinks(payload);
+ break;
+ case "import-referrals":
+ await importReferrals(payload);
break;
}
diff --git a/apps/web/lib/actions/partners/start-tolt-import.ts b/apps/web/lib/actions/partners/start-tolt-import.ts
index 205ca05c3f..05358084c7 100644
--- a/apps/web/lib/actions/partners/start-tolt-import.ts
+++ b/apps/web/lib/actions/partners/start-tolt-import.ts
@@ -30,6 +30,14 @@ export const startToltImportAction = authActionClient
throw new Error("Program URL is not set.");
}
+ const credentials = await toltImporter.getCredentials(workspace.id);
+
+ if (!credentials) {
+ throw new Error(
+ "Tolt credentials not found. Please restart the import process.",
+ );
+ }
+
await toltImporter.queue({
action: "import-affiliates",
programId,
diff --git a/apps/web/lib/tolt/api.ts b/apps/web/lib/tolt/api.ts
index f2f84040c8..a4d2069810 100644
--- a/apps/web/lib/tolt/api.ts
+++ b/apps/web/lib/tolt/api.ts
@@ -1,8 +1,11 @@
import { DubApiError } from "@/lib/api/errors";
-import { ToltAffiliateSchema, ToltProgramSchema } from "./schemas";
+import {
+ ToltAffiliateSchema,
+ ToltLinkSchema,
+ ToltProgramSchema,
+} from "./schemas";
import {
RewardfulCommission,
- RewardfulReferral,
ToltAffiliate,
ToltLink,
ToltListResponse,
@@ -61,16 +64,18 @@ export class ToltApi {
throw new Error("No partners found to import.");
}
- const firstPartner = partners[0];
+ const partner = partners[0];
- if (!firstPartner.program) {
+ if (!partner.program) {
throw new Error("No program found for the first partner.");
}
- return ToltProgramSchema.parse({
- ...firstPartner.program,
+ return {
+ ...ToltProgramSchema.parse({
+ ...partner.program,
+ }),
total_affiliates: total_count,
- });
+ };
}
async listAffiliates({
@@ -99,34 +104,50 @@ export class ToltApi {
async listLinks({
programId,
- partnerId,
+ startingAfter,
}: {
programId: string;
- partnerId: string;
+ startingAfter?: string;
}) {
const searchParams = new URLSearchParams();
searchParams.append("program_id", programId);
- searchParams.append("partner_id", partnerId);
+ searchParams.append("expand[]", "partner");
+ searchParams.append("starting_after", startingAfter || "");
searchParams.append("limit", PAGE_LIMIT.toString());
- return await this.fetch<ToltListResponse<ToltLink>>(
- `${this.baseUrl}/links?${searchParams.toString()}`,
- );
+ const { data, has_more, total_count } = await this.fetch<
+ ToltListResponse<ToltLink>
+ >(`${this.baseUrl}/links?${searchParams.toString()}`);
+
+ return {
+ has_more,
+ total_count,
+ data: ToltLinkSchema.array().parse(data),
+ };
}
- async listReferrals({ page = 1 }: { page?: number }) {
+ async listReferrals({
+ programId,
+ startingAfter,
+ }: {
+ programId: string;
+ startingAfter?: string;
+ }) {
const searchParams = new URLSearchParams();
- searchParams.append("expand[]", "affiliate");
- searchParams.append("conversion_state[]", "lead");
- searchParams.append("conversion_state[]", "conversion");
- searchParams.append("page", page.toString());
+ searchParams.append("program_id", programId);
+ searchParams.append("expand[]", "partner");
+ searchParams.append("starting_after", startingAfter || "");
searchParams.append("limit", PAGE_LIMIT.toString());
- const { data } = await this.fetch<{ data: RewardfulReferral[] }>(
- `${this.baseUrl}/referrals?${searchParams.toString()}`,
- );
+ const { data, has_more, total_count } = await this.fetch<
+ ToltListResponse<ToltLink>
+ >(`${this.baseUrl}/links?${searchParams.toString()}`);
- return data;
+ return {
+ has_more,
+ total_count,
+ data: ToltLinkSchema.array().parse(data),
+ };
}
async listCommissions({ page = 1 }: { page?: number }) {
diff --git a/apps/web/lib/tolt/import-customers.ts b/apps/web/lib/tolt/import-customers.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/apps/web/lib/tolt/import-links.ts b/apps/web/lib/tolt/import-links.ts
index e69de29bb2..1709096d7e 100644
--- a/apps/web/lib/tolt/import-links.ts
+++ b/apps/web/lib/tolt/import-links.ts
@@ -0,0 +1,89 @@
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { bulkCreateLinks } from "../api/links";
+import { ToltApi } from "./api";
+import { MAX_BATCHES, toltImporter } from "./importer";
+
+export async function importLinks({
+ programId,
+ startingAfter,
+}: {
+ programId: string;
+ startingAfter?: string;
+}) {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ const { token, toltProgramId, userId } = await toltImporter.getCredentials(
+ program.workspaceId,
+ );
+
+ const toltApi = new ToltApi({ token });
+
+ let hasMoreLinks = true;
+ let processedBatches = 0;
+
+ while (hasMoreLinks && processedBatches < MAX_BATCHES) {
+ const { data: links, has_more } = await toltApi.listLinks({
+ programId: toltProgramId,
+ startingAfter,
+ });
+
+ hasMoreLinks = has_more;
+
+ if (links.length === 0) {
+ console.log("No more links to import.");
+ break;
+ }
+
+ const partners = await prisma.partner.findMany({
+ where: {
+ email: {
+ in: links.map(({ partner }) => partner.email),
+ },
+ },
+ select: {
+ id: true,
+ email: true,
+ },
+ });
+
+ const partnerMap = new Map(partners.map(({ email, id }) => [email, id]));
+
+ const activeLinks = links.filter((link) =>
+ partnerMap.has(link.partner.email),
+ );
+
+ if (activeLinks.length === 0) {
+ console.log("No active links to import.");
+ break;
+ }
+
+ await bulkCreateLinks({
+ links: activeLinks.map((link) => ({
+ userId,
+ programId,
+ projectId: program.workspaceId,
+ partnerId: partnerMap.get(link.partner.email),
+ folderId: program.defaultFolderId,
+ domain: program.domain!,
+ key: link.value || nanoid(),
+ url: program.url!,
+ trackConversion: true,
+ })),
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ processedBatches++;
+ startingAfter = links[links.length - 1].id;
+ }
+
+ await toltImporter.queue({
+ programId,
+ action: hasMoreLinks ? "import-links" : "import-referrals",
+ ...(hasMoreLinks && { startingAfter }),
+ });
+}
diff --git a/apps/web/lib/tolt/schemas.ts b/apps/web/lib/tolt/schemas.ts
index 28bc9b81ef..a086cc5c5d 100644
--- a/apps/web/lib/tolt/schemas.ts
+++ b/apps/web/lib/tolt/schemas.ts
@@ -5,7 +5,6 @@ export const ToltProgramSchema = z.object({
name: z.string(),
subdomain: z.string(),
payout_term: z.string(),
- total_affiliates: z.number(), // custom property doesn't exist in the API response
});
export const ToltAffiliateSchema = z.object({
@@ -16,7 +15,12 @@ export const ToltAffiliateSchema = z.object({
company_name: z.string().nullable(),
country_code: z.string().nullable(),
status: z.enum(["active", "inactive"]).default("active"),
- program: ToltProgramSchema.omit({
- total_affiliates: true,
- }).optional(),
+ program: ToltProgramSchema.optional(),
+});
+
+export const ToltLinkSchema = z.object({
+ id: z.string(),
+ param: z.string(),
+ value: z.string(),
+ partner: ToltAffiliateSchema,
});
diff --git a/apps/web/lib/tolt/types.ts b/apps/web/lib/tolt/types.ts
index db1090d6e7..819b990d4c 100644
--- a/apps/web/lib/tolt/types.ts
+++ b/apps/web/lib/tolt/types.ts
@@ -1,5 +1,9 @@
import { z } from "zod";
-import { ToltAffiliateSchema, ToltProgramSchema } from "./schemas";
+import {
+ ToltAffiliateSchema,
+ ToltLinkSchema,
+ ToltProgramSchema,
+} from "./schemas";
export interface ToltConfig {
token: string;
@@ -7,14 +11,25 @@ export interface ToltConfig {
toltProgramId: string;
}
+export interface ToltListResponse<T> {
+ success: true;
+ has_more: boolean;
+ total_count: number;
+ data: T[];
+}
+
export interface ToltProgram extends z.infer<typeof ToltProgramSchema> {
- //
+ total_affiliates: number;
}
export interface ToltAffiliate extends z.infer<typeof ToltAffiliateSchema> {
//
}
+export interface ToltLink extends z.infer<typeof ToltLinkSchema> {
+ //
+}
+
export interface RewardfulCampaign {
id: string;
name: string;
@@ -30,24 +45,11 @@ export interface RewardfulCampaign {
updated_at: string;
}
-export interface ToltListResponse<T> {
- success: true;
- has_more: boolean;
- total_count: number;
- data: T[];
-}
-
export interface ToltGroup {
id: string;
name: string;
}
-export interface ToltLink {
- id: string;
- value: string;
- partner_id: string;
-}
-
export interface RewardfulCustomer {
id: string;
name: string;