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.

wip tolt importer

Kiran K8bf851b403b4
diff --git a/apps/web/app/(ee)/api/cron/import/tolt/route.ts b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
new file mode 100644
index 0000000000..04c1609a2b
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
@@ -0,0 +1,42 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { importAffiliates } from "@/lib/tolt/import-affiliates";
+import { importSteps } from "@/lib/tolt/importer";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ action: importSteps,
+ programId: z.string(),
+ startingAfter: z.string().optional(),
+});
+
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+
+ await verifyQstashSignature({
+ req,
+ rawBody,
+ });
+
+ const { programId, action, startingAfter } = schema.parse(
+ JSON.parse(rawBody),
+ );
+
+ switch (action) {
+ case "import-affiliates":
+ await importAffiliates({
+ programId,
+ startingAfter,
+ });
+ break;
+ }
+
+ return NextResponse.json("OK");
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/lib/tolt/api.ts b/apps/web/lib/tolt/api.ts
new file mode 100644
index 0000000000..be52f1bb21
--- /dev/null
+++ b/apps/web/lib/tolt/api.ts
@@ -0,0 +1,114 @@
+import { DubApiError } from "@/lib/api/errors";
+import {
+ RewardfulCommission,
+ RewardfulReferral,
+ ToltAffiliate,
+ ToltLink,
+ ToltListResponse,
+} from "./types";
+
+const PAGE_LIMIT = 100;
+
+class ToltApiError extends DubApiError {
+ constructor(message: string) {
+ super({
+ code: "bad_request",
+ message: `[Tolt API] ${message}`,
+ });
+ }
+}
+
+export class ToltApi {
+ private readonly baseUrl = "https://api.tolt.com/v1";
+ private readonly token: string;
+
+ constructor({ token }: { token: string }) {
+ this.token = token;
+ }
+
+ private async fetch<T>(url: string): Promise<T> {
+ const response = await fetch(url, {
+ headers: {
+ Authorization: `Bearer ${this.token}`,
+ },
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ console.log("Tolt API Error:", error);
+ throw new ToltApiError(error);
+ }
+
+ const data = await response.json();
+
+ console.debug("Tolt API Response:", {
+ url,
+ data: JSON.stringify(data, null, 2),
+ });
+
+ return data as T;
+ }
+
+ async listAffiliates({
+ programId,
+ startingAfter,
+ }: {
+ programId: string;
+ startingAfter?: string;
+ }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("program_id", programId);
+ searchParams.append("starting_after", startingAfter || "");
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ return await this.fetch<ToltListResponse<ToltAffiliate>>(
+ `${this.baseUrl}/partners?${searchParams.toString()}`,
+ );
+ }
+
+ async listLinks({
+ programId,
+ partnerId,
+ }: {
+ programId: string;
+ partnerId: string;
+ }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("program_id", programId);
+ searchParams.append("partner_id", partnerId);
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ return await this.fetch<ToltListResponse<ToltLink>>(
+ `${this.baseUrl}/links?${searchParams.toString()}`,
+ );
+ }
+
+ async listReferrals({ page = 1 }: { page?: number }) {
+ 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("limit", PAGE_LIMIT.toString());
+
+ const { data } = await this.fetch<{ data: RewardfulReferral[] }>(
+ `${this.baseUrl}/referrals?${searchParams.toString()}`,
+ );
+
+ return data;
+ }
+
+ async listCommissions({ page = 1 }: { page?: number }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("expand[]", "sale");
+ searchParams.append("expand[]", "campaign");
+ searchParams.append("page", page.toString());
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ const { data } = await this.fetch<{ data: RewardfulCommission[] }>(
+ `${this.baseUrl}/commissions?${searchParams.toString()}`,
+ );
+
+ return data;
+ }
+}
diff --git a/apps/web/lib/tolt/import-affiliates.ts b/apps/web/lib/tolt/import-affiliates.ts
new file mode 100644
index 0000000000..5a653bb82e
--- /dev/null
+++ b/apps/web/lib/tolt/import-affiliates.ts
@@ -0,0 +1,166 @@
+import { prisma } from "@dub/prisma";
+import { Program } from "@dub/prisma/client";
+import { nanoid } from "@dub/utils";
+import { createId } from "../api/create-id";
+import { bulkCreateLinks } from "../api/links";
+import { ToltApi } from "./api";
+import { MAX_BATCHES, toltImporter } from "./importer";
+import { ToltAffiliate } from "./types";
+
+export async function importAffiliates({
+ programId,
+ rewardId,
+ startingAfter,
+}: {
+ programId: string;
+ rewardId?: string; // not using this for now
+ startingAfter?: string;
+}) {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ const { userId, token } = await toltImporter.getCredentials(
+ program.workspaceId,
+ );
+
+ const toltApi = new ToltApi({ token });
+
+ let hasMoreAffiliates = true;
+ let processedBatches = 0;
+
+ // const reward = await prisma.reward.findUniqueOrThrow({
+ // where: {
+ // id: rewardId,
+ // },
+ // select: {
+ // id: true,
+ // event: true,
+ // },
+ // });
+
+ while (hasMoreAffiliates && processedBatches < MAX_BATCHES) {
+ const { data: affiliates, has_more } = await toltApi.listAffiliates({
+ programId,
+ startingAfter,
+ });
+
+ hasMoreAffiliates = has_more;
+
+ if (affiliates.length === 0) {
+ console.log("No more affiliates to import.");
+ break;
+ }
+
+ const activeAffiliates = affiliates.filter(
+ ({ status }) => status === "active",
+ );
+
+ if (activeAffiliates.length > 0) {
+ await Promise.all(
+ activeAffiliates.map((affiliate) =>
+ createPartnerAndLinks({
+ program,
+ affiliate,
+ userId,
+ toltApi,
+ }),
+ ),
+ );
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ processedBatches++;
+ }
+
+ const action = hasMoreAffiliates ? "import-affiliates" : "import-referrals";
+
+ await toltImporter.queue({
+ programId: program.id,
+ action,
+ ...(hasMoreAffiliates && { startingAfter }),
+ });
+}
+
+// Create partner and their links
+async function createPartnerAndLinks({
+ program,
+ affiliate,
+ userId,
+ toltApi,
+}: {
+ program: Program;
+ affiliate: ToltAffiliate;
+ userId: string;
+ toltApi: ToltApi;
+}) {
+ const partner = await prisma.partner.upsert({
+ where: {
+ email: affiliate.email,
+ },
+ create: {
+ id: createId({ prefix: "pn_" }),
+ name: `${affiliate.first_name} ${affiliate.last_name}`,
+ email: affiliate.email,
+ companyName: affiliate.company_name,
+ country: affiliate.country_code,
+ },
+ update: {},
+ });
+
+ const programEnrollment = await prisma.programEnrollment.upsert({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.id,
+ programId: program.id,
+ },
+ },
+ create: {
+ programId: program.id,
+ partnerId: partner.id,
+ status: "approved",
+ },
+ update: {
+ status: "approved",
+ },
+ include: {
+ links: true,
+ },
+ });
+
+ if (!program.domain || !program.url) {
+ console.error("Program domain or url not found", program.id);
+ return;
+ }
+
+ if (programEnrollment.links.length > 0) {
+ console.log("Partner already has links", partner.id);
+ return;
+ }
+
+ const { data: links } = await toltApi.listLinks({
+ programId: program.id,
+ partnerId: partner.id,
+ });
+
+ if (links.length === 0) {
+ console.log("No links found for partner", partner.id);
+ return;
+ }
+
+ await bulkCreateLinks({
+ links: links.map((link) => ({
+ domain: program.domain!,
+ key: link.value || nanoid(),
+ url: program.url!,
+ trackConversion: true,
+ programId: program.id,
+ partnerId: partner.id,
+ folderId: program.defaultFolderId,
+ projectId: program.workspaceId,
+ userId,
+ })),
+ });
+}
diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/lib/tolt/import-customers.ts b/apps/web/lib/tolt/import-customers.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/lib/tolt/import-links.ts b/apps/web/lib/tolt/import-links.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/lib/tolt/importer.ts b/apps/web/lib/tolt/importer.ts
new file mode 100644
index 0000000000..f26bf8f064
--- /dev/null
+++ b/apps/web/lib/tolt/importer.ts
@@ -0,0 +1,53 @@
+import { qstash } from "@/lib/cron";
+import { redis } from "@/lib/upstash";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { z } from "zod";
+import { ToltConfig } from "./types";
+
+export const MAX_BATCHES = 5;
+export const CACHE_EXPIRY = 60 * 60 * 24;
+export const CACHE_KEY_PREFIX = "tolt:import";
+
+export const importSteps = z.enum([
+ "import-affiliates",
+ "import-links",
+ "import-referrals",
+ "import-commissions",
+]);
+
+class ToltImporter {
+ async setCredentials(workspaceId: string, payload: ToltConfig) {
+ await redis.set(`${CACHE_KEY_PREFIX}:${workspaceId}`, payload, {
+ ex: CACHE_EXPIRY,
+ });
+ }
+
+ async getCredentials(workspaceId: string) {
+ const config = await redis.get<ToltConfig>(
+ `${CACHE_KEY_PREFIX}:${workspaceId}`,
+ );
+
+ if (!config) {
+ throw new Error("Tolt configuration not found.");
+ }
+
+ return config;
+ }
+
+ async deleteCredentials(workspaceId: string) {
+ return await redis.del(`${CACHE_KEY_PREFIX}:${workspaceId}`);
+ }
+
+ async queue(body: {
+ programId: string;
+ action?: z.infer<typeof importSteps>;
+ startingAfter?: string;
+ }) {
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/tolt`,
+ body,
+ });
+ }
+}
+
+export const toltImporter = new ToltImporter();
diff --git a/apps/web/lib/tolt/types.ts b/apps/web/lib/tolt/types.ts
new file mode 100644
index 0000000000..161c4e94a2
--- /dev/null
+++ b/apps/web/lib/tolt/types.ts
@@ -0,0 +1,122 @@
+export interface ToltConfig {
+ token: string;
+ userId: string;
+ programId: string;
+}
+
+export interface RewardfulCampaign {
+ id: string;
+ name: string;
+ url: string;
+ affiliates: number;
+ commission_amount_cents: number;
+ minimum_payout_cents: number;
+ max_commission_period_months: number;
+ days_until_commissions_are_due: number;
+ reward_type: "amount" | "percent";
+ commission_percent: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ToltListResponse<T> {
+ success: true;
+ has_more: boolean;
+ total_count: number;
+ data: T[];
+}
+
+export interface ToltProgram {
+ id: string;
+ name: string;
+ subdomain: string;
+}
+
+export interface ToltGroup {
+ id: string;
+ name: string;
+}
+
+export interface ToltAffiliate {
+ id: string;
+ group_id: string;
+ first_name: string;
+ last_name: string;
+ email: string;
+ company_name: string;
+ country_code: string;
+ status: "active" | "inactive";
+}
+
+export interface ToltLink {
+ id: string;
+ value: string;
+ partner_id: string;
+}
+
+export interface RewardfulCustomer {
+ id: string;
+ name: string;
+ email: string;
+ platform: string;
+}
+
+export interface RewardfulAffiliate {
+ id: string;
+ first_name: string;
+ last_name: string;
+ email: string;
+ state: string;
+ visitors: number;
+ leads: number;
+ conversions: number;
+ created_at: string;
+ updated_at: string;
+ links: ToltLink[];
+ campaign?: RewardfulCampaign;
+}
+
+export interface RewardfulReferral {
+ id: string;
+ link: ToltLink;
+ customer: RewardfulCustomer;
+ affiliate: RewardfulAffiliate;
+ created_at: string;
+ became_lead_at: string;
+ became_conversion_at: string;
+ expires_at: string;
+ updated_at: string;
+ conversion_state: string;
+ stripe_customer_id: string;
+}
+
+export interface RewardfulCommissionSale {
+ id: string;
+ currency: string;
+ charged_at: string;
+ stripe_account_id: string;
+ stripe_charge_id: string;
+ invoiced_at: string;
+ created_at: string;
+ updated_at: string;
+ charge_amount_cents: number;
+ refund_amount_cents: number;
+ tax_amount_cents: number;
+ sale_amount_cents: number;
+ referral: RewardfulReferral;
+ affiliate: RewardfulAffiliate;
+}
+
+export interface RewardfulCommission {
+ id: string;
+ created_at: string;
+ updated_at: string;
+ amount: number;
+ currency: string;
+ state: "pending" | "due" | "paid" | "voided";
+ due_at: string;
+ paid_at: string | null;
+ voided_at: string | null;
+ campaign: RewardfulCampaign;
+ sale: RewardfulCommissionSale;
+}