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

Kiran K03b1903ee968
diff --git a/apps/web/app/api/cron/import/rewardful/route.ts b/apps/web/app/api/cron/import/rewardful/route.ts
new file mode 100644
index 0000000000..7affafff07
--- /dev/null
+++ b/apps/web/app/api/cron/import/rewardful/route.ts
@@ -0,0 +1,45 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { prisma } from "@dub/prisma";
+import { RewardfulApi } from "app/api/programs/[programId]/rewardful/importer";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ programId: z.string(),
+ action: z.enum(["import-affiliates"]),
+});
+
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const { programId } = schema.parse(JSON.parse(rawBody));
+
+ await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const rewardfulApi = new RewardfulApi({
+ programId,
+ });
+
+ const affiliates = await rewardfulApi.listAffiliates();
+
+ console.log(affiliates);
+
+ return NextResponse.json({
+ programId,
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts b/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts
new file mode 100644
index 0000000000..f39135e025
--- /dev/null
+++ b/apps/web/app/api/programs/[programId]/rewardful/campaigns/route.ts
@@ -0,0 +1,25 @@
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { withWorkspace } from "@/lib/auth";
+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 }) => {
+ const { programId } = params;
+
+ await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ const rewardfulApi = new RewardfulApi({ programId });
+ const campaigns = await rewardfulApi.listCampaigns();
+
+ return NextResponse.json(campaigns);
+});
diff --git a/apps/web/app/api/programs/[programId]/rewardful/import/route.ts b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
new file mode 100644
index 0000000000..7718cc85ed
--- /dev/null
+++ b/apps/web/app/api/programs/[programId]/rewardful/import/route.ts
@@ -0,0 +1,31 @@
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { RewardfulImporter } from "../importer";
+
+const schema = z.object({
+ apiKey: z.string(),
+ campaignId: z.string(),
+});
+
+// POST /api/programs/[programId]/rewardful/import - import a rewardful program
+// This is entrypoint for the rewardful importer
+export const POST = withWorkspace(async ({ workspace, params, req }) => {
+ const { programId } = params;
+ const { apiKey, campaignId } = schema.parse(await parseRequestBody(req));
+
+ const program = await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ // Start a background job to import
+ await new RewardfulImporter(programId).start({
+ apiKey,
+ campaignId,
+ });
+
+ return NextResponse.json(program);
+});
diff --git a/apps/web/app/api/programs/[programId]/rewardful/importer.ts b/apps/web/app/api/programs/[programId]/rewardful/importer.ts
new file mode 100644
index 0000000000..bac043e548
--- /dev/null
+++ b/apps/web/app/api/programs/[programId]/rewardful/importer.ts
@@ -0,0 +1,170 @@
+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
new file mode 100644
index 0000000000..77dc6bfba2
--- /dev/null
+++ b/apps/web/app/api/rewardful/affiliates/route.ts
@@ -0,0 +1,18 @@
+import { NextResponse } from "next/server";
+
+export async function GET() {
+ return NextResponse.json([
+ {
+ id: "d0ed8392-8880-4f39-8715-60230f9eceab",
+ created_at: "2019-05-09T16:18:59.920Z",
+ updated_at: "2019-05-09T16:25:42.614Z",
+ first_name: "Adam",
+ last_name: "Jones",
+ email: "[email protected]",
+ state: "active",
+ visitors: 100,
+ leads: 42,
+ conversions: 18,
+ },
+ ]);
+}
diff --git a/apps/web/app/api/rewardful/campaigns/route.ts b/apps/web/app/api/rewardful/campaigns/route.ts
new file mode 100644
index 0000000000..22407903db
--- /dev/null
+++ b/apps/web/app/api/rewardful/campaigns/route.ts
@@ -0,0 +1,37 @@
+import { NextResponse } from "next/server";
+
+export async function GET() {
+ return NextResponse.json([
+ {
+ id: "ceaef6d9-767e-49aa-a6ab-46c02aa79604",
+ created_at: "2021-11-24T06:31:06.672Z",
+ updated_at: "2022-02-22T23:17:55.119Z",
+ name: "Best Friends of Rewardful",
+ url: "https://rewardful.com/",
+ private: false,
+ private_tokens: false,
+ commission_amount_cents: null,
+ commission_amount_currency: null,
+ minimum_payout_cents: 0,
+ max_commission_period_months: null,
+ max_commissions: null,
+ days_before_referrals_expire: 30,
+ days_until_commissions_are_due: 30,
+ affiliate_dashboard_text: "",
+ custom_reward_description: "",
+ welcome_text: "",
+ customers_visible_to_affiliates: false,
+ sale_description_visible_to_affiliates: true,
+ parameter_type: "query",
+ stripe_coupon_id: "jo45MTj3",
+ default: false,
+ reward_type: "percent",
+ commission_percent: 30.0,
+ minimum_payout_currency: "USD",
+ visitors: 150,
+ leads: 39,
+ conversions: 7,
+ affiliates: 12,
+ },
+ ]);
+}