The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
restructure
Kiran Kc6c1645fc72c
diff --git a/apps/web/app/api/cron/import/rewardful/route.ts b/apps/web/app/api/cron/import/rewardful/route.tsindex 1500992f5e..88b4901707 100644--- a/apps/web/app/api/cron/import/rewardful/route.ts+++ b/apps/web/app/api/cron/import/rewardful/route.ts@@ -1,7 +1,6 @@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 { importAffiliates, importReferrals } from "@/lib/rewardful/importer";import { prisma } from "@dub/prisma";import { NextResponse } from "next/server";import { z } from "zod";@@ -23,32 +22,23 @@ export async function POST(req: Request) {const { programId, action, page } = schema.parse(JSON.parse(rawBody));- const { workspace, ...program } = await prisma.program.findUniqueOrThrow({- where: {- id: programId,- },- include: {- workspace: true,- },- });-- const rewardfulApi = new RewardfulApi({- programId,- });-- const importer = new RewardfulImporter({- programId,- });+ // const { workspace, ...program } = await prisma.program.findUniqueOrThrow({+ // where: {+ // id: programId,+ // },+ // include: {+ // workspace: true,+ // },+ // });- // Import affiliatesif (action === "import-affiliates") {- await importer.importAffiliates({- workspace,+ await importAffiliates({+ programId,page,});} else if (action === "import-referrals") {- await importer.importReferrals({- workspace,+ await importReferrals({+ programId,page,});}diff --git a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts b/apps/web/app/api/programs/[programId]/rewardful/import/route.tsindex 8f192e6cf0..4f4ed25268 100644--- a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts+++ b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts@@ -1,7 +1,7 @@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 { startRewardfulImport } from "@/lib/rewardful/importer";import { NextResponse } from "next/server";import { z } from "zod";@@ -22,9 +22,10 @@ export const POST = withWorkspace(async ({ workspace, params, req }) => {});// Start a background job to import- await new RewardfulImporter({ programId }).start({- apiKey,+ await startRewardfulImport({+ programId,campaignId,+ apiKey,});return NextResponse.json(program);diff --git a/apps/web/lib/rewardful/importer.ts b/apps/web/lib/rewardful/importer.tsindex cfe774bc11..89cfd54600 100644--- a/apps/web/lib/rewardful/importer.ts+++ b/apps/web/lib/rewardful/importer.ts@@ -13,283 +13,254 @@ import { RewardfulReferral } from "./types";const MAX_BATCHES = 5;const CACHE_EXPIRY = 60 * 60 * 24;-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: CACHE_EXPIRY,- },- );-- return this.queueNextImport({- programId: this.programId,- });- }-- async queueNextImport(body: {- programId: string;- action?: string;- page?: number;- }) {- return await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/rewardful`,- body,- });- }+export function createRewardfulApi(programId: string) {+ return new RewardfulApi({ programId });+}- // 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,- },- });+export async function startRewardfulImport({+ programId,+ apiKey,+ campaignId,+}: {+ programId: string;+ apiKey: string;+ campaignId: string;+}) {+ await redis.set(+ `rewardful:import:${programId}`,+ { apiKey, campaignId },+ { ex: CACHE_EXPIRY },+ );++ return queueNextImport({ 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++;- }+export async function queueNextImport(body: {+ programId: string;+ action?: string;+ page?: number;+}) {+ return await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/rewardful`,+ body,+ });+}- await this.queueNextImport({- action: hasMoreAffiliates- ? "import-affiliates"- : "import-affiliates-links",- programId: program.id,+// 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,});- 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 (affiliates.length === 0) {+ hasMoreAffiliates = false;+ break;+ }- if (referrals.length === 0) {- hasMoreReferrals = false;- break;- }+ const partners = affiliates+ .filter((affiliate) => affiliate.state === "active")+ .map((affiliate) => ({+ name: `${affiliate.first_name} ${affiliate.last_name}`,+ email: affiliate.email,+ }));+ if (partners.length > 0) {await Promise.all(- referrals.map((referral) =>- this.createReferral({- referral,- workspace,- program,+ 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",+ },+ },+ },}),),);-- // Wait 2 second before next API call- await new Promise((resolve) => setTimeout(resolve, 2000));- currentPage++;- processedBatches++;}- if (hasMoreReferrals) {- await this.queueNextImport({- action: "import-referrals",- programId: program.id,- page: currentPage,- });- }-- return {- lastProcessedPage: currentPage - 1,- };+ await new Promise((resolve) => setTimeout(resolve, 2000));+ currentPage++;+ processedBatches++;}- 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",- },+ await queueNextImport({+ action: hasMoreAffiliates ? "import-affiliates" : "import-affiliates-links",+ programId: program.id,+ page: currentPage,+ });++ return { lastProcessedPage: currentPage - 1 };+}++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 (!link) {- console.log("Link not found", referral.link.token);- return;+ if (referrals.length === 0) {+ hasMoreReferrals = false;+ break;}- 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",- }),- });+ await Promise.all(+ referrals.map((referral) =>+ createReferral({+ referral,+ workspace,+ program,+ }),+ ),+ );- // 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,- });+ await new Promise((resolve) => setTimeout(resolve, 2000));+ currentPage++;+ processedBatches++;+ }- const clickEvent = clickEventSchemaTB.parse({- ...clickData,- bot: 0,- qr: 0,+ if (hasMoreReferrals) {+ await queueNextImport({+ action: "import-referrals",+ programId: program.id,+ page: currentPage,});+ }+}- 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,- },- },- }),- ]);+// Create individual referral entries+export 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 } },+ }),+ ]);}