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.

Enhance Rewardful import process with modular imports and improved error handling

Kiran Kfa87eab0974f
diff --git a/apps/web/app/api/cron/import/rewardful/route.ts b/apps/web/app/api/cron/import/rewardful/route.ts
index 6a18a929c9..78ee08166b 100644
--- a/apps/web/app/api/cron/import/rewardful/route.ts
+++ b/apps/web/app/api/cron/import/rewardful/route.ts
@@ -1,10 +1,8 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import {
- importAffiliates,
- importReferrals,
- ImportSteps,
-} from "@/lib/rewardful/importer";
+import { importAffiliates } from "@/lib/rewardful/import-affiliates";
+import { importReferrals } from "@/lib/rewardful/import-referrals";
+import { ImportSteps } from "@/lib/rewardful/importer";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -12,6 +10,7 @@ export const dynamic = "force-dynamic";
const schema = z.object({
programId: z.string(),
+ campaignId: z.string(),
action: ImportSteps.default("import-affiliates"),
page: z.number().optional().default(1),
});
@@ -21,23 +20,25 @@ export async function POST(req: Request) {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const { programId, action, page } = schema.parse(JSON.parse(rawBody));
+ const { programId, campaignId, action, page } = schema.parse(
+ JSON.parse(rawBody),
+ );
if (action === "import-affiliates") {
await importAffiliates({
programId,
+ campaignId,
page,
});
} else if (action === "import-referrals") {
await importReferrals({
programId,
+ campaignId,
page,
});
}
- return NextResponse.json({
- programId,
- });
+ return NextResponse.json("OK");
} catch (error) {
return handleAndReturnErrorResponse(error);
}
diff --git a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
index 0fc5b7a5d0..f9f03b7389 100644
--- a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
+++ b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
@@ -1,4 +1,3 @@
-import { DubApiError } from "@/lib/api/errors";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
@@ -25,14 +24,8 @@ export const POST = withWorkspace(
const { campaignId } = schema.parse(await parseRequestBody(req));
- const config = await fetchRewardfulConfig(programId);
-
- if (!config) {
- throw new DubApiError({
- code: "bad_request",
- message: "Rewardful token not found. Please try again.",
- });
- }
+ // check the Rewardful token exists before queueing the import
+ await fetchRewardfulConfig(programId);
await queueRewardfulImport({
programId,
diff --git a/apps/web/app/api/rewardful/referrals/route.ts b/apps/web/app/api/rewardful/referrals/route.ts
index eb2e9695d3..1eb5390f17 100644
--- a/apps/web/app/api/rewardful/referrals/route.ts
+++ b/apps/web/app/api/rewardful/referrals/route.ts
@@ -80,9 +80,9 @@ export async function GET(request: NextRequest) {
paypal_email_confirmed_at: null,
receive_new_commission_notifications: true,
},
- created_at: `2020-04-${20 + i}T00:34:28.448Z`,
- became_lead_at: `2020-04-${20 + i}T00:36:28.448Z`,
- became_conversion_at: `2020-04-${20 + i}T00:38:28.448Z`,
+ created_at: `2025-01-${20 + i}T00:34:28.448Z`,
+ became_lead_at: `2025-01-${20 + i}T00:36:28.448Z`,
+ became_conversion_at: `2025-01-${20 + i}T00:38:28.448Z`,
expires_at: `2020-06-${20 + i}T00:34:28.448Z`,
updated_at: `2020-04-${20 + i}T00:38:28.448Z`,
deactivated_at: null,
diff --git a/apps/web/lib/rewardful/api.ts b/apps/web/lib/rewardful/api.ts
index 9eacc98b97..d834787772 100644
--- a/apps/web/lib/rewardful/api.ts
+++ b/apps/web/lib/rewardful/api.ts
@@ -27,10 +27,6 @@ export class RewardfulApi {
private async getAuthHeader() {
const config = await fetchRewardfulConfig(this.programId);
- if (!config || !config.token) {
- throw new Error("Rewardful config not found.");
- }
-
return {
Authorization: `Basic ${Buffer.from(`${config.token}:`).toString("base64")}`,
};
diff --git a/apps/web/lib/rewardful/import-affiliates.ts b/apps/web/lib/rewardful/import-affiliates.ts
new file mode 100644
index 0000000000..487671e6e5
--- /dev/null
+++ b/apps/web/lib/rewardful/import-affiliates.ts
@@ -0,0 +1,145 @@
+import { prisma } from "@dub/prisma";
+import { Program, Project } from "@prisma/client";
+import { createLink } from "../api/links/create-link";
+import { processLink } from "../api/links/process-link";
+import { createId } from "../api/utils";
+import { WorkspaceProps } from "../types";
+import {
+ createRewardfulApi,
+ fetchRewardfulConfig,
+ MAX_BATCHES,
+ queueRewardfulImport,
+} from "./importer";
+import { RewardfulAffiliate } from "./types";
+
+// Import Rewardful affiliates
+export async function importAffiliates({
+ programId,
+ campaignId,
+ page,
+}: {
+ programId: string;
+ campaignId: string;
+ page: number;
+}) {
+ const rewardfulApi = createRewardfulApi(programId);
+
+ let currentPage = page;
+ let hasMoreAffiliates = true;
+ let processedBatches = 0;
+
+ const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ },
+ });
+
+ const { userId } = await fetchRewardfulConfig(program.id);
+
+ while (hasMoreAffiliates && processedBatches < MAX_BATCHES) {
+ const affiliates = await rewardfulApi.listAffiliates({
+ page: currentPage,
+ });
+
+ if (affiliates.length === 0) {
+ hasMoreAffiliates = false;
+ break;
+ }
+
+ const activeAffiliates = affiliates.filter(
+ (affiliate) => affiliate.state === "active",
+ );
+
+ if (activeAffiliates.length > 0) {
+ await Promise.all(
+ activeAffiliates.map((affiliate) =>
+ createPartnerAndLinks({
+ workspace,
+ program,
+ affiliate,
+ userId,
+ }),
+ ),
+ );
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ currentPage++;
+ processedBatches++;
+ }
+
+ await queueRewardfulImport({
+ programId: program.id,
+ campaignId,
+ action: hasMoreAffiliates ? "import-affiliates" : "import-referrals",
+ ...(hasMoreAffiliates ? { page: currentPage } : {}),
+ });
+}
+
+// Create partner and their links
+async function createPartnerAndLinks({
+ workspace,
+ program,
+ affiliate,
+ userId,
+}: {
+ workspace: Project;
+ program: Program;
+ affiliate: RewardfulAffiliate;
+ userId: string;
+}) {
+ const partner = await prisma.partner.create({
+ data: {
+ id: createId({ prefix: "pn_" }),
+ name: `${affiliate.first_name} ${affiliate.last_name}`,
+ email: affiliate.email,
+ bio: "Rewardful affiliate",
+ programs: {
+ create: {
+ programId: program.id,
+ status: "approved",
+ },
+ },
+ },
+ });
+
+ if (!program.domain || !program.url) {
+ console.error("Program domain or url not found", program.id);
+ return;
+ }
+
+ await Promise.all(
+ affiliate.links.map(async (link) => {
+ try {
+ const { link: newLink, error } = await processLink({
+ payload: {
+ url: link.url || program.url!,
+ key: link.token || undefined,
+ domain: program.domain!,
+ programId: program.id,
+ partnerId: partner.id,
+ trackConversion: true,
+ folderId: program.defaultFolderId,
+ },
+ userId,
+ skipProgramChecks: true,
+ workspace: workspace as WorkspaceProps,
+ });
+
+ if (error != null) {
+ console.error("Error creating link", error);
+ return;
+ }
+
+ const partnerLink = await createLink(newLink);
+
+ console.log("Partner link created", partnerLink);
+ } catch (error) {
+ console.error("Error processing link:", error);
+ }
+ }),
+ );
+}
diff --git a/apps/web/lib/rewardful/import-referrals.ts b/apps/web/lib/rewardful/import-referrals.ts
new file mode 100644
index 0000000000..aaafbfda96
--- /dev/null
+++ b/apps/web/lib/rewardful/import-referrals.ts
@@ -0,0 +1,160 @@
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { Program, Project } from "@prisma/client";
+import { createId } from "../api/utils";
+import { recordClick } from "../tinybird/record-click";
+import { recordLead } from "../tinybird/record-lead";
+import { clickEventSchemaTB } from "../zod/schemas/clicks";
+import {
+ createRewardfulApi,
+ MAX_BATCHES,
+ queueRewardfulImport,
+} from "./importer";
+import { RewardfulReferral } from "./types";
+
+export async function importReferrals({
+ programId,
+ campaignId,
+ page,
+}: {
+ programId: string;
+ campaignId: string;
+ page: number;
+}) {
+ let currentPage = page;
+ let hasMoreReferrals = true;
+ let processedBatches = 0;
+
+ const rewardfulApi = createRewardfulApi(programId);
+
+ const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ },
+ });
+
+ while (hasMoreReferrals && processedBatches < MAX_BATCHES) {
+ const referrals = await rewardfulApi.listReferrals({
+ page: currentPage,
+ });
+
+ if (referrals.length === 0) {
+ hasMoreReferrals = false;
+ break;
+ }
+
+ await Promise.all(
+ referrals.map((referral) =>
+ createReferral({
+ referral,
+ workspace,
+ program,
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ currentPage++;
+ processedBatches++;
+ }
+
+ if (hasMoreReferrals) {
+ await queueRewardfulImport({
+ programId: program.id,
+ campaignId,
+ action: "import-referrals",
+ page: currentPage,
+ });
+ }
+}
+
+// Create individual referral entries
+async function createReferral({
+ referral,
+ workspace,
+ program,
+}: {
+ referral: RewardfulReferral;
+ workspace: Project;
+ program: Program;
+}) {
+ const link = await prisma.link.findFirst({
+ where: {
+ key: referral.link.token,
+ domain: program.domain!,
+ programId: program.id,
+ },
+ });
+
+ if (!link) {
+ console.log("Link not found", referral.link.token);
+ return;
+ }
+
+ 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,
+ workspaceId: workspace.id,
+ timestamp: new Date(referral.created_at).toISOString(),
+ skipRatelimit: true,
+ });
+
+ const clickEvent = clickEventSchemaTB.parse({
+ ...clickData,
+ bot: 0,
+ qr: 0,
+ });
+
+ const customerId = createId({ prefix: "cus_" });
+
+ await Promise.all([
+ prisma.customer.create({
+ data: {
+ id: customerId,
+ name: referral.customer.name,
+ email: referral.customer.email,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ clickId: clickEvent.click_id,
+ linkId: link.id,
+ country: clickEvent.country,
+ clickedAt: new Date(referral.created_at),
+ createdAt: new Date(referral.became_lead_at),
+ externalId: referral.customer.id,
+ stripeCustomerId: referral.stripe_customer_id,
+ },
+ }),
+
+ recordLead({
+ ...clickEvent,
+ event_id: nanoid(16),
+ event_name: "Sign up",
+ customer_id: customerId,
+ }),
+
+ prisma.link.update({
+ where: { id: link.id },
+ data: { leads: { increment: 1 } },
+ }),
+
+ prisma.project.update({
+ where: { id: workspace.id },
+ data: { usage: { increment: 1 } },
+ }),
+ ]);
+}
diff --git a/apps/web/lib/rewardful/importer.ts b/apps/web/lib/rewardful/importer.ts
index be33d4f009..a3b740e6b1 100644
--- a/apps/web/lib/rewardful/importer.ts
+++ b/apps/web/lib/rewardful/importer.ts
@@ -1,33 +1,15 @@
import { qstash } from "@/lib/cron";
import { redis } from "@/lib/upstash";
-import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";
-import { Program, Project } from "@prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { z } from "zod";
-import { createLink } from "../api/links/create-link";
-import { processLink } from "../api/links/process-link";
-import { createId } from "../api/utils";
-import { recordClick } from "../tinybird/record-click";
-import { recordLead } from "../tinybird/record-lead";
-import { WorkspaceProps } from "../types";
-import { clickEventSchemaTB } from "../zod/schemas/clicks";
import { RewardfulApi } from "./api";
-import {
- RewardfulAffiliate,
- RewardfulConfig,
- RewardfulReferral,
-} from "./types";
-
-const MAX_BATCHES = 5;
-const CACHE_EXPIRY = 60 * 60 * 24;
-const CACHE_KEY_PREFIX = "rewardful:import";
+import { RewardfulConfig } from "./types";
+export const MAX_BATCHES = 5;
+export const CACHE_EXPIRY = 60 * 60 * 24;
+export const CACHE_KEY_PREFIX = "rewardful:import";
export const ImportSteps = z.enum(["import-affiliates", "import-referrals"]);
-export function createRewardfulApi(programId: string) {
- return new RewardfulApi({ programId });
-}
-
export async function setRewardfulConfig({
programId,
userId,
@@ -50,7 +32,15 @@ export async function setRewardfulConfig({
}
export async function fetchRewardfulConfig(programId: string) {
- return await redis.get<RewardfulConfig>(`${CACHE_KEY_PREFIX}:${programId}`);
+ const config = await redis.get<RewardfulConfig>(
+ `${CACHE_KEY_PREFIX}:${programId}`,
+ );
+
+ if (!config) {
+ throw new Error("Rewardful config not found.");
+ }
+
+ return config;
}
export async function queueRewardfulImport(body: {
@@ -65,275 +55,6 @@ export async function queueRewardfulImport(body: {
});
}
-// Import Rewardful affiliates
-export async function importAffiliates({
- programId,
- page,
-}: {
- programId: string;
- page: number;
-}) {
- const rewardfulApi = createRewardfulApi(programId);
-
- let currentPage = page;
- let hasMoreAffiliates = true;
- let processedBatches = 0;
-
- const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
- where: {
- id: programId,
- },
- include: {
- workspace: true,
- },
- });
-
- while (hasMoreAffiliates && processedBatches < MAX_BATCHES) {
- const affiliates = await rewardfulApi.listAffiliates({
- page: currentPage,
- });
-
- if (affiliates.length === 0) {
- hasMoreAffiliates = false;
- break;
- }
-
- const activeAffiliates = affiliates.filter(
- (affiliate) => affiliate.state === "active",
- );
-
- if (activeAffiliates.length > 0) {
- await Promise.all(
- activeAffiliates.map((affiliate) =>
- createPartnerAndLinks({
- workspace,
- program,
- affiliate,
- }),
- ),
- );
- }
-
- await new Promise((resolve) => setTimeout(resolve, 2000));
- currentPage++;
- processedBatches++;
- }
-
- await queueRewardfulImport({
- programId: program.id,
- action: hasMoreAffiliates ? "import-affiliates" : "import-referrals",
- ...(hasMoreAffiliates ? { page: currentPage } : {}),
- });
-
- return { lastProcessedPage: currentPage - 1 };
-}
-
-// Create partner and their links
-async function createPartnerAndLinks({
- workspace,
- program,
- affiliate,
-}: {
- workspace: Project;
- program: Program;
- affiliate: RewardfulAffiliate;
-}) {
- const partner = await prisma.partner.create({
- data: {
- id: createId({ prefix: "pn_" }),
- name: `${affiliate.first_name} ${affiliate.last_name}`,
- email: affiliate.email,
- bio: "Rewardful affiliate",
- programs: {
- create: {
- programId: program.id,
- status: "approved",
- },
- },
- },
- });
-
- if (!program.domain || !program.url) {
- console.error("Program domain or url not found", program.id);
- return;
- }
-
- const { userId } = await fetchRewardfulConfig(program.id);
-
- const links = affiliate.links;
-
- await Promise.all(
- links.map(async (link) => {
- try {
- const { link: newLink, error } = await processLink({
- payload: {
- url: link.url || program.url!,
- key: link.token || undefined,
- domain: program.domain!,
- programId: program.id,
- partnerId: partner.id,
- trackConversion: true,
- folderId: program.defaultFolderId,
- },
- userId,
- skipProgramChecks: true,
- workspace: workspace as WorkspaceProps,
- });
-
- if (error != null) {
- console.error("Error creating link", error);
- return;
- }
-
- const partnerLink = await createLink(newLink);
- console.log("Partner link created", partnerLink);
- } catch (error) {
- console.error("Error processing link:", error);
- }
- }),
- );
-}
-
-export async function importReferrals({
- programId,
- page,
-}: {
- programId: string;
- page: number;
-}) {
- let currentPage = page;
- let hasMoreReferrals = true;
- let processedBatches = 0;
- const rewardfulApi = createRewardfulApi(programId);
-
- const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
- where: {
- id: programId,
- },
- include: {
- workspace: true,
- },
- });
-
- while (hasMoreReferrals && processedBatches < MAX_BATCHES) {
- const referrals = await rewardfulApi.listReferrals({
- page: currentPage,
- });
-
- if (referrals.length === 0) {
- hasMoreReferrals = false;
- break;
- }
-
- await Promise.all(
- referrals.map((referral) =>
- createReferral({
- referral,
- workspace,
- program,
- }),
- ),
- );
-
- await new Promise((resolve) => setTimeout(resolve, 2000));
- currentPage++;
- processedBatches++;
- }
-
- if (hasMoreReferrals) {
- await queueRewardfulImport({
- action: "import-referrals",
- programId: program.id,
- page: currentPage,
- });
- }
-}
-
-// Create individual referral entries
-async function createReferral({
- referral,
- workspace,
- program,
-}: {
- referral: RewardfulReferral;
- workspace: Project;
- program: Program;
-}) {
- const link = await prisma.link.findFirst({
- where: {
- // id: "link_0ntBrVm4VqPSpcLaLTbNAV5y", // TODO: Update with proper query
- key: referral.link.token,
- domain: program.domain!,
- programId: program.id,
- },
- });
-
- if (!link) {
- console.log("Link not found", referral.link.token);
- return;
- }
-
- 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,
- workspaceId: workspace.id,
- timestamp: new Date(referral.created_at).toISOString(),
- skipRatelimit: true,
- });
-
- const clickEvent = clickEventSchemaTB.parse({
- ...clickData,
- bot: 0,
- qr: 0,
- });
-
- const customerId = createId({ prefix: "cus_" });
-
- await Promise.all([
- prisma.customer.create({
- data: {
- id: customerId,
- name: referral.customer.name,
- email: referral.customer.email,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- clickId: clickEvent.click_id,
- linkId: link.id,
- country: clickEvent.country,
- clickedAt: new Date(referral.created_at),
- createdAt: new Date(referral.became_lead_at),
- externalId: referral.customer.id,
- stripeCustomerId: referral.stripe_customer_id,
- },
- }),
-
- recordLead({
- ...clickEvent,
- event_id: nanoid(16),
- event_name: "Sign up",
- customer_id: customerId,
- }),
-
- prisma.link.update({
- where: { id: link.id },
- data: { leads: { increment: 1 } },
- }),
-
- prisma.project.update({
- where: { id: workspace.id },
- data: { usage: { increment: 1 } },
- }),
- ]);
+export function createRewardfulApi(programId: string) {
+ return new RewardfulApi({ programId });
}