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.

feat: Add Rewardful import functionality for affiliates and referrals

Kiran Kf8c89630805c
diff --git a/apps/web/app/api/cron/import/rewardful/import-affiliate.ts b/apps/web/app/api/cron/import/rewardful/import-affiliate.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/app/api/cron/import/rewardful/route.ts b/apps/web/app/api/cron/import/rewardful/route.ts
index 7affafff07..1500992f5e 100644
--- a/apps/web/app/api/cron/import/rewardful/route.ts
+++ b/apps/web/app/api/cron/import/rewardful/route.ts
@@ -1,7 +1,8 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { RewardfulApi } from "@/lib/rewardful/api";
+import { RewardfulImporter } from "@/lib/rewardful/importer";
import { prisma } from "@dub/prisma";
-import { RewardfulApi } from "app/api/programs/[programId]/rewardful/importer";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -9,7 +10,10 @@ export const dynamic = "force-dynamic";
const schema = z.object({
programId: z.string(),
- action: z.enum(["import-affiliates"]),
+ action: z
+ .enum(["import-affiliates", "import-referrals"])
+ .default("import-referrals"),
+ page: z.number().optional().default(1),
});
export async function POST(req: Request) {
@@ -17,14 +21,14 @@ export async function POST(req: Request) {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const { programId } = schema.parse(JSON.parse(rawBody));
+ const { programId, action, page } = schema.parse(JSON.parse(rawBody));
- await prisma.program.findUniqueOrThrow({
+ const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
},
- select: {
- id: true,
+ include: {
+ workspace: true,
},
});
@@ -32,9 +36,22 @@ export async function POST(req: Request) {
programId,
});
- const affiliates = await rewardfulApi.listAffiliates();
+ const importer = new RewardfulImporter({
+ programId,
+ });
- console.log(affiliates);
+ // Import affiliates
+ if (action === "import-affiliates") {
+ await importer.importAffiliates({
+ workspace,
+ page,
+ });
+ } else if (action === "import-referrals") {
+ await importer.importReferrals({
+ workspace,
+ page,
+ });
+ }
return NextResponse.json({
programId,
diff --git a/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts b/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts
index f39135e025..85e66d13a3 100644
--- a/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts
+++ b/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts
@@ -1,13 +1,7 @@
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { withWorkspace } from "@/lib/auth";
+import { RewardfulApi } from "@/lib/rewardful/api";
import { NextResponse } from "next/server";
-import { z } from "zod";
-import { RewardfulApi } from "../importer";
-
-const schema = z.object({
- apiKey: z.string(),
- campaignId: z.string(),
-});
// GET /api/programs/[programId]/rewardful/campaigns - list rewardful campaigns
export const GET = withWorkspace(async ({ workspace, params }) => {
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 7718cc85ed..8f192e6cf0 100644
--- a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
+++ b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
@@ -1,9 +1,9 @@
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { RewardfulImporter } from "@/lib/rewardful/importer";
import { NextResponse } from "next/server";
import { z } from "zod";
-import { RewardfulImporter } from "../importer";
const schema = z.object({
apiKey: z.string(),
@@ -22,7 +22,7 @@ export const POST = withWorkspace(async ({ workspace, params, req }) => {
});
// Start a background job to import
- await new RewardfulImporter(programId).start({
+ await new RewardfulImporter({ programId }).start({
apiKey,
campaignId,
});
diff --git a/apps/web/app/api/programs/[programId]/rewardful/importer.ts b/apps/web/app/api/programs/[programId]/rewardful/importer.ts
deleted file mode 100644
index bac043e548..0000000000
--- a/apps/web/app/api/programs/[programId]/rewardful/importer.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { DubApiError } from "@/lib/api/errors";
-import { qstash } from "@/lib/cron";
-import { redis } from "@/lib/upstash";
-import { prisma } from "@dub/prisma";
-
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export class RewardfulImporter {
- constructor(private readonly programId: string) {
- //
- }
-
- // Start a background job to import the program
- async start({ apiKey, campaignId }: { apiKey: string; campaignId: string }) {
- await redis.set(
- `rewardful:import:${this.programId}`,
- {
- apiKey,
- campaignId,
- },
- {
- ex: 60 * 60 * 24,
- },
- );
-
- return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/rewardful`,
- body: {
- programId: this.programId,
- },
- });
- }
-
- // Import the program
- async import() {
- const apiKey = await redis.get(`rewardful:import:${this.programId}`);
-
- if (!apiKey) {
- throw new Error("Rewardful API key not found.", {
- cause: {
- programId: this.programId,
- },
- });
- }
-
- const program = await prisma.program.findUnique({
- where: { id: this.programId },
- });
- }
-}
-
-export class RewardfulApi {
- private readonly programId: string; // Dub program id
- // private readonly baseUrl = "https://api.getrewardful.com/v1";
- private readonly baseUrl = "http://api.localhost:8888/api/rewardful";
-
- constructor({ programId }: { programId: string }) {
- this.programId = programId;
- }
-
- private async fetchApiKey() {
- const apiKey = await redis.get(`rewardful:import:${this.programId}`);
-
- if (!apiKey) {
- throw new Error("Rewardful API key not found.", {
- cause: {
- programId: this.programId,
- },
- });
- }
-
- return apiKey;
- }
-
- private async getAuthHeader() {
- const apiKey = await this.fetchApiKey();
-
- return {
- Authorization: `Basic ${Buffer.from(`${apiKey}:`).toString("base64")}`,
- };
- }
-
- // List all campaigns
- async listCampaigns() {
- const response = await fetch(`${this.baseUrl}/campaigns`, {
- headers: await this.getAuthHeader(),
- });
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new RewardfulApiError(data.error);
- }
-
- console.debug("listCampaigns", data);
-
- return data as Campaign[];
- }
-
- // Retrieve campaign
- async retrieveCampaign(campaignId: string) {
- const response = await fetch(`${this.baseUrl}/campaigns/${campaignId}`, {
- headers: await this.getAuthHeader(),
- });
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new RewardfulApiError(data.error);
- }
-
- console.debug("retrieveCampaign", data);
-
- return data as Campaign;
- }
-
- // List all affiliates
- async listAffiliates() {
- const response = await fetch(`${this.baseUrl}/affiliates`, {
- headers: await this.getAuthHeader(),
- });
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new RewardfulApiError(data.error);
- }
-
- console.debug("listAffiliates", data);
-
- return data as Affiliate[];
- }
-}
-
-interface Campaign {
- id: string;
- name: string;
- affiliates: number;
- created_at: string;
- updated_at: string;
-}
-
-interface Affiliate {
- id: string;
- first_name: string;
- last_name: string;
- email: string;
- state: string;
- visitors: number;
- leads: number;
- conversions: number;
- created_at: string;
- updated_at: string;
-}
-
-class RewardfulApiError extends DubApiError {
- constructor(message: string) {
- super({
- code: "bad_request",
- message: `[Rewardful API] ${message}`,
- });
- }
-}
-
-// - List all campaigns + ask the user to choose one to import. Retrieve it and set their reward types
-// - Importing affiliates + their links (we can expand the links prop)
-// - Importing referrals
-// - creating a customer + lead on Dub, plus a dummy click event
-// - connect the referral to the affiliate
-// - Nice to have: Import affiliate coupons (and create a Discount on Dub)
diff --git a/apps/web/app/api/rewardful/affiliates/route.ts b/apps/web/app/api/rewardful/affiliates/route.ts
index 77dc6bfba2..90a4ad7e55 100644
--- a/apps/web/app/api/rewardful/affiliates/route.ts
+++ b/apps/web/app/api/rewardful/affiliates/route.ts
@@ -1,11 +1,15 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
-export async function GET() {
- return NextResponse.json([
+export async function GET(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const page = parseInt(searchParams.get("page") || "1");
+ const limit = parseInt(searchParams.get("limit") || "10");
+
+ const affiliates = [
{
id: "d0ed8392-8880-4f39-8715-60230f9eceab",
- created_at: "2019-05-09T16:18:59.920Z",
- updated_at: "2019-05-09T16:25:42.614Z",
+ created_at: "2023-05-09T16:18:59.920Z",
+ updated_at: "2023-05-09T16:25:42.614Z",
first_name: "Adam",
last_name: "Jones",
@@ -13,6 +17,220 @@ export async function GET() {
visitors: 100,
leads: 42,
conversions: 18,
+ links: [
+ {
+ id: "eb844960-6c42-4a3b-8009-f588a42d8506",
+ url: "http://www.example.com/?via=adam",
+ token: "adam",
+ visitors: 100,
+ leads: 42,
+ conversions: 18,
+ },
+ ],
+ },
+ {
+ id: "f7c91234-5678-4a3b-9012-34567890abcd",
+ created_at: "2023-06-15T10:30:00.000Z",
+ updated_at: "2023-06-15T10:35:00.000Z",
+ first_name: "Sarah",
+ last_name: "Smith",
+ email: "[email protected]",
+ state: "active",
+ visitors: 250,
+ leads: 85,
+ conversions: 30,
+ links: [
+ {
+ id: "cd123456-7890-4def-b123-456789abcdef",
+ url: "http://www.example.com/?via=sarah",
+ token: "sarah",
+ visitors: 250,
+ leads: 85,
+ conversions: 30,
+ },
+ ],
+ },
+ {
+ id: "a1b2c3d4-5678-4e5f-6g7h-8i9j0k1l2m3n",
+ created_at: "2023-07-20T14:45:00.000Z",
+ updated_at: "2023-07-20T14:50:00.000Z",
+ first_name: "Michael",
+ last_name: "Brown",
+ email: "[email protected]",
+ state: "inactive",
+ visitors: 150,
+ leads: 35,
+ conversions: 12,
+ links: [
+ {
+ id: "ef123456-7890-4abc-def1-23456789abcd",
+ url: "http://www.example.com/?via=michael",
+ token: "michael",
+ visitors: 150,
+ leads: 35,
+ conversions: 12,
+ },
+ ],
+ },
+ {
+ id: "b2c3d4e5-6f7g-8h9i-j0k1-l2m3n4o5p6q7",
+ created_at: "2023-08-05T09:15:00.000Z",
+ updated_at: "2023-08-05T09:20:00.000Z",
+ first_name: "Emily",
+ last_name: "Davis",
+ email: "[email protected]",
+ state: "active",
+ visitors: 300,
+ leads: 120,
+ conversions: 45,
+ links: [
+ {
+ id: "gh123456-7890-4ijk-lmno-pqrstuvwxyz1",
+ url: "http://www.example.com/?via=emily",
+ token: "emily",
+ visitors: 300,
+ leads: 120,
+ conversions: 45,
+ },
+ ],
+ },
+ {
+ id: "c3d4e5f6-7g8h-9i0j-k1l2-m3n4o5p6q7r8",
+ created_at: "2023-09-10T11:20:00.000Z",
+ updated_at: "2023-09-10T11:25:00.000Z",
+ first_name: "David",
+ last_name: "Wilson",
+ email: "[email protected]",
+ state: "active",
+ visitors: 180,
+ leads: 60,
+ conversions: 25,
+ links: [
+ {
+ id: "ij123456-7890-4klm-nopq-rstuvwxyz123",
+ url: "http://www.example.com/?via=david",
+ token: "david",
+ visitors: 180,
+ leads: 60,
+ conversions: 25,
+ },
+ ],
+ },
+ {
+ id: "d4e5f6g7-8h9i-0j1k-l2m3-n4o5p6q7r8s9",
+ created_at: "2023-10-15T13:40:00.000Z",
+ updated_at: "2023-10-15T13:45:00.000Z",
+ first_name: "Lisa",
+ last_name: "Taylor",
+ email: "[email protected]",
+ state: "active",
+ visitors: 220,
+ leads: 75,
+ conversions: 28,
+ links: [
+ {
+ id: "kl123456-7890-4mno-pqrs-tuvwxyz12345",
+ url: "http://www.example.com/?via=lisa",
+ token: "lisa",
+ visitors: 220,
+ leads: 75,
+ conversions: 28,
+ },
+ ],
+ },
+ {
+ id: "e5f6g7h8-9i0j-1k2l-m3n4-o5p6q7r8s9t0",
+ created_at: "2023-11-20T15:55:00.000Z",
+ updated_at: "2023-11-20T16:00:00.000Z",
+ first_name: "James",
+ last_name: "Anderson",
+ email: "[email protected]",
+ state: "inactive",
+ visitors: 90,
+ leads: 20,
+ conversions: 8,
+ links: [
+ {
+ id: "mn123456-7890-4opq-rstu-vwxyz123456",
+ url: "http://www.example.com/?via=james",
+ token: "james",
+ visitors: 90,
+ leads: 20,
+ conversions: 8,
+ },
+ ],
+ },
+ {
+ id: "f6g7h8i9-0j1k-2l3m-n4o5-p6q7r8s9t0u1",
+ created_at: "2023-12-25T08:10:00.000Z",
+ updated_at: "2023-12-25T08:15:00.000Z",
+ first_name: "Emma",
+ last_name: "Martinez",
+ email: "[email protected]",
+ state: "active",
+ visitors: 280,
+ leads: 95,
+ conversions: 40,
+ links: [
+ {
+ id: "op123456-7890-4qrs-tuv-wxyz1234567",
+ url: "http://www.example.com/?via=emma",
+ token: "emma",
+ visitors: 280,
+ leads: 95,
+ conversions: 40,
+ },
+ ],
+ },
+ {
+ id: "g7h8i9j0-1k2l-3m4n-o5p6-q7r8s9t0u1v2",
+ created_at: "2024-01-05T12:30:00.000Z",
+ updated_at: "2024-01-05T12:35:00.000Z",
+ first_name: "Robert",
+ last_name: "Garcia",
+ email: "[email protected]",
+ state: "active",
+ visitors: 160,
+ leads: 55,
+ conversions: 22,
+ links: [
+ {
+ id: "qr123456-7890-4stu-vwxy-z123456789",
+ url: "http://www.example.com/?via=robert",
+ token: "robert",
+ visitors: 160,
+ leads: 55,
+ conversions: 22,
+ },
+ ],
},
- ]);
+ {
+ id: "h8i9j0k1-2l3m-4n5o-p6q7-r8s9t0u1v2w3",
+ created_at: "2024-02-10T16:50:00.000Z",
+ updated_at: "2024-02-10T16:55:00.000Z",
+ first_name: "Olivia",
+ last_name: "Lee",
+ email: "[email protected]",
+ state: "active",
+ visitors: 200,
+ leads: 70,
+ conversions: 32,
+ links: [
+ {
+ id: "st123456-7890-4uvw-xyz1-234567890ab",
+ url: "http://www.example.com/?via=olivia",
+ token: "olivia",
+ visitors: 200,
+ leads: 70,
+ conversions: 32,
+ },
+ ],
+ },
+ ];
+
+ const startIndex = (page - 1) * limit;
+ const endIndex = startIndex + limit;
+ const paginatedAffiliates = affiliates.slice(startIndex, endIndex);
+
+ return NextResponse.json(paginatedAffiliates);
}
diff --git a/apps/web/app/api/rewardful/referrals/route.ts b/apps/web/app/api/rewardful/referrals/route.ts
new file mode 100644
index 0000000000..eb2e9695d3
--- /dev/null
+++ b/apps/web/app/api/rewardful/referrals/route.ts
@@ -0,0 +1,98 @@
+import { NextRequest, NextResponse } from "next/server";
+
+export async function GET(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const page = parseInt(searchParams.get("page") || "1");
+ const limit = parseInt(searchParams.get("limit") || "10");
+
+ const referrals = Array.from({ length: 10 }, (_, i) => ({
+ id: `e523da29-6157-4aac-b4b5-05b3b7b14fb${i}`,
+ link: {
+ id: `32a19d65-2b68-434d-a401-e72ca7f24d8${i}`,
+ url: `http://www.example.com/?via=ref${i}`,
+ leads: 3 + i,
+ token: `ref${i}`,
+ visitors: 5 + i,
+ conversions: 2 + i,
+ },
+ visits: 30 + i * 5,
+ customer: {
+ id: `cus_ABC${123 + i}`,
+ name: [
+ `John Doe`,
+ `Jane Smith`,
+ `Bob Johnson`,
+ `Alice Brown`,
+ `Charlie Wilson`,
+ `Diana Prince`,
+ `Bruce Wayne`,
+ `Clark Kent`,
+ `Peter Parker`,
+ `Tony Stark`,
+ ][i],
+ email: `user${i}@example.com`,
+ platform: "stripe",
+ },
+ affiliate: {
+ id: `dc939584-a94a-4bdf-b8f4-8d255aae72${i}c`,
+ email: `affiliate${i}@example.com`,
+ leads: 3 + i,
+ campaign: {
+ id: `ae37c8ce-f82b-4e1b-9653-b802ae459a${i}2`,
+ name: `Campaign ${i + 1}`,
+ created_at: `2020-04-${20 + i}T00:24:08.199Z`,
+ updated_at: `2020-04-${20 + i}T00:24:08.199Z`,
+ },
+ visitors: 5 + i,
+ last_name: [
+ `Smith`,
+ `Johnson`,
+ `Williams`,
+ `Brown`,
+ `Jones`,
+ `Garcia`,
+ `Miller`,
+ `Davis`,
+ `Rodriguez`,
+ `Martinez`,
+ ][i],
+ created_at: `2020-04-${20 + i}T00:24:08.334Z`,
+ first_name: [
+ `James`,
+ `Mary`,
+ `Robert`,
+ `Patricia`,
+ `Michael`,
+ `Linda`,
+ `William`,
+ `Elizabeth`,
+ `David`,
+ `Barbara`,
+ ][i],
+ updated_at: `2020-05-${i + 1}T19:39:03.028Z`,
+ conversions: 2 + i,
+ confirmed_at: `2020-04-${20 + i}T00:24:08.331Z`,
+ paypal_email: null,
+ sign_in_count: i,
+ stripe_account_id: null,
+ unconfirmed_email: null,
+ stripe_customer_id: null,
+ 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`,
+ expires_at: `2020-06-${20 + i}T00:34:28.448Z`,
+ updated_at: `2020-04-${20 + i}T00:38:28.448Z`,
+ deactivated_at: null,
+ conversion_state: "conversion",
+ stripe_account_id: `acct_ABC${123 + i}`,
+ stripe_customer_id: `cus_ABC${123 + i}`,
+ }));
+
+ const startIndex = (page - 1) * limit;
+ const endIndex = startIndex + limit;
+
+ return NextResponse.json(referrals.slice(startIndex, endIndex));
+}
diff --git a/apps/web/lib/rewardful/api.ts b/apps/web/lib/rewardful/api.ts
new file mode 100644
index 0000000000..e5467786fd
--- /dev/null
+++ b/apps/web/lib/rewardful/api.ts
@@ -0,0 +1,91 @@
+import { DubApiError } from "@/lib/api/errors";
+import { redis } from "@/lib/upstash";
+import { Campaign, RewardfulAffiliate, RewardfulReferral } from "./types";
+
+class RewardfulApiError extends DubApiError {
+ constructor(message: string) {
+ super({
+ code: "bad_request",
+ message: `[Rewardful API] ${message}`,
+ });
+ }
+}
+
+export class RewardfulApi {
+ private readonly programId: string; // Dub program id
+ // private readonly baseUrl = "https://api.getrewardful.com/v1";
+ private readonly baseUrl = "http://api.localhost:8888/api/rewardful";
+
+ constructor({ programId }: { programId: string }) {
+ this.programId = programId;
+ }
+
+ private async fetchApiKey() {
+ const apiKey = await redis.get(`rewardful:import:${this.programId}`);
+
+ if (!apiKey) {
+ throw new Error("Rewardful API key not found.", {
+ cause: {
+ programId: this.programId,
+ },
+ });
+ }
+
+ return apiKey;
+ }
+
+ private async getAuthHeader() {
+ const apiKey = await this.fetchApiKey();
+
+ return {
+ Authorization: `Basic ${Buffer.from(`${apiKey}:`).toString("base64")}`,
+ };
+ }
+
+ private async fetch<T>(url: string): Promise<T> {
+ const response = await fetch(url, {
+ headers: await this.getAuthHeader(),
+ });
+
+ const data = await response.json();
+
+ console.debug("Rewardful API Response:", { url, data });
+
+ if (!response.ok) {
+ throw new RewardfulApiError(data.error);
+ }
+
+ return data as T;
+ }
+
+ // List all campaigns
+ async listCampaigns() {
+ return this.fetch<Campaign[]>(`${this.baseUrl}/campaigns`);
+ }
+
+ // Retrieve campaign
+ async retrieveCampaign(campaignId: string) {
+ return this.fetch<Campaign>(`${this.baseUrl}/campaigns/${campaignId}`);
+ }
+
+ // List all affiliates
+ async listAffiliates({ page = 1 }: { page?: number }) {
+ return this.fetch<RewardfulAffiliate[]>(
+ `${this.baseUrl}/affiliates?expand[]=links&page=${page}&limit=100`,
+ );
+ }
+
+ // List all referrals
+ 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", "1");
+
+ return this.fetch<RewardfulReferral[]>(
+ `${this.baseUrl}/referrals?${searchParams.toString()}`,
+ );
+ }
+}
diff --git a/apps/web/lib/rewardful/importer.ts b/apps/web/lib/rewardful/importer.ts
new file mode 100644
index 0000000000..cf2c5f826b
--- /dev/null
+++ b/apps/web/lib/rewardful/importer.ts
@@ -0,0 +1,296 @@
+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 { createId } from "../api/utils";
+import { recordClick } from "../tinybird/record-click";
+import { recordLead } from "../tinybird/record-lead";
+import { clickEventSchemaTB } from "../zod/schemas/clicks";
+import { RewardfulApi } from "./api";
+import { RewardfulReferral } from "./types";
+
+const MAX_BATCHES = 5;
+
+export class RewardfulImporter {
+ private readonly programId: string;
+ private readonly rewardfulApi: RewardfulApi;
+
+ constructor({ programId }: { programId: string }) {
+ this.programId = programId;
+ this.rewardfulApi = new RewardfulApi({ programId });
+ }
+
+ async start({ apiKey, campaignId }: { apiKey: string; campaignId: string }) {
+ await redis.set(
+ `rewardful:import:${this.programId}`,
+ {
+ apiKey,
+ campaignId,
+ },
+ {
+ ex: 60 * 60 * 24,
+ },
+ );
+
+ return this.scheduleNextRun({
+ programId: this.programId,
+ action: "import",
+ });
+ }
+
+ async scheduleNextRun(body: {
+ programId: string;
+ action: string;
+ page?: number;
+ }) {
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/rewardful`,
+ body,
+ delay: 2000,
+ });
+ }
+
+ // Import affiliates and create the partner entries
+ async importAffiliates({
+ workspace,
+ page,
+ }: {
+ workspace: Project;
+ page: number;
+ }) {
+ let currentPage = page;
+ let hasMoreAffiliates = true;
+ let processedBatches = 0;
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: this.programId,
+ },
+ });
+
+ while (hasMoreAffiliates && processedBatches < MAX_BATCHES) {
+ const affiliates = await this.rewardfulApi.listAffiliates({
+ page: currentPage,
+ });
+
+ if (affiliates.length === 0) {
+ hasMoreAffiliates = false;
+ break;
+ }
+
+ const partners = affiliates
+ .filter((affiliate) => affiliate.state === "active")
+ .map((affiliate) => {
+ return {
+ name: `${affiliate.first_name} ${affiliate.last_name}`,
+ email: affiliate.email,
+ };
+ });
+
+ if (partners.length > 0) {
+ await Promise.all(
+ partners.map((partner) =>
+ prisma.partner.create({
+ data: {
+ id: createId({ prefix: "pn_" }),
+ name: partner.name,
+ email: partner.email,
+ showOnLeaderboard: false,
+ programs: {
+ create: {
+ programId: program.id,
+ status: "approved",
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ // TODO:
+ // Make sure the program and domain exists before starting the import
+ // Import links
+ }
+
+ // Wait 2 second before next API call
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ currentPage++;
+ processedBatches++;
+ }
+
+ await this.scheduleNextRun({
+ action: hasMoreAffiliates
+ ? "import-affiliates"
+ : "import-affiliates-links",
+ programId: program.id,
+ page: currentPage,
+ });
+
+ return {
+ lastProcessedPage: currentPage - 1,
+ };
+ }
+
+ // Import referrals and create the click, lead, and customer entries
+ async importReferrals({
+ workspace,
+ page,
+ }: {
+ workspace: Project;
+ page: number;
+ }) {
+ let currentPage = page;
+ let hasMoreReferrals = true;
+ let processedBatches = 0;
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: this.programId,
+ },
+ });
+
+ while (hasMoreReferrals && processedBatches < MAX_BATCHES) {
+ const referrals = await this.rewardfulApi.listReferrals({
+ page: currentPage,
+ });
+
+ if (referrals.length === 0) {
+ hasMoreReferrals = false;
+ break;
+ }
+
+ await Promise.all(
+ referrals.map((referral) =>
+ this.createReferral({
+ referral,
+ workspace,
+ program,
+ }),
+ ),
+ );
+
+ // Wait 2 second before next API call
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ currentPage++;
+ processedBatches++;
+ }
+
+ if (hasMoreReferrals) {
+ await this.scheduleNextRun({
+ action: "import-referrals",
+ programId: program.id,
+ page: currentPage,
+ });
+ }
+
+ return {
+ lastProcessedPage: currentPage - 1,
+ };
+ }
+
+ async createReferral({
+ referral,
+ workspace,
+ program,
+ }: {
+ referral: RewardfulReferral;
+ workspace: Project;
+ program: Program;
+ }) {
+ const link = await prisma.link.findFirst({
+ where: {
+ programId: program.id,
+ domain: program.domain!,
+ key: referral.link.token,
+ // id: "link_0ntBrVm4VqPSpcLaLTbNAV5y",
+ },
+ });
+
+ 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",
+ }),
+ });
+
+ // record click
+ 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([
+ // create customer
+ 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,
+ },
+ }),
+
+ // record lead
+ recordLead({
+ ...clickEvent,
+ event_id: nanoid(16),
+ event_name: "Sign up",
+ customer_id: customerId,
+ }),
+
+ // update link leads count
+ prisma.link.update({
+ where: {
+ id: link.id,
+ },
+ data: {
+ leads: {
+ increment: 1,
+ },
+ },
+ }),
+
+ // update workspace usage
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage: {
+ increment: 1,
+ },
+ },
+ }),
+ ]);
+ }
+}
diff --git a/apps/web/lib/rewardful/types.ts b/apps/web/lib/rewardful/types.ts
new file mode 100644
index 0000000000..69423d0d8b
--- /dev/null
+++ b/apps/web/lib/rewardful/types.ts
@@ -0,0 +1,51 @@
+export interface RewardfulLink {
+ id: string;
+ url: string;
+ token: string;
+ visitors: number;
+ leads: number;
+ conversions: number;
+}
+
+export interface RewardfulCustomer {
+ id: string;
+ name: string;
+ email: string;
+ platform: string;
+}
+
+export interface Campaign {
+ id: string;
+ name: string;
+ affiliates: number;
+ created_at: string;
+ updated_at: 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: RewardfulLink[];
+}
+
+export interface RewardfulReferral {
+ id: string;
+ link: RewardfulLink;
+ 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;
+}
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index eb80b9433a..5f3bb9c59d 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -32,6 +32,7 @@ export async function recordClick({
webhookIds,
skipRatelimit,
workspaceId,
+ timestamp,
}: {
req: Request;
linkId: string;
@@ -40,6 +41,7 @@ export async function recordClick({
webhookIds?: string[];
skipRatelimit?: boolean;
workspaceId: string | undefined;
+ timestamp?: string;
}) {
const searchParams = new URL(req.url).searchParams;
@@ -94,7 +96,7 @@ export async function recordClick({
const finalUrl = url ? getFinalUrlForRecordClick({ req, url }) : "";
const clickData = {
- timestamp: new Date(Date.now()).toISOString(),
+ timestamp: timestamp || new Date(Date.now()).toISOString(),
identity_hash,
click_id: clickId,
link_id: linkId,
@@ -181,6 +183,8 @@ export async function recordClick({
if (hasWebhooks && !hasExceededUsageLimit) {
await sendLinkClickWebhooks({ webhookIds, linkId, clickData });
}
+
+ return clickData;
}
async function sendLinkClickWebhooks({
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 535b97e2e2..a800340085 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -240,6 +240,7 @@ export const analyticsFilterTB = z
.string()
.optional()
.describe("The UTM tag to group by. Defaults to `utm_source`."),
+ customerId: z.string().optional(),
})
.merge(
analyticsQuerySchema.pick({
@@ -264,7 +265,6 @@ export const analyticsFilterTB = z
programId: true,
partnerId: true,
tenantId: true,
- customerId: true,
folderId: true,
}),
);