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.

Add Rewardful commissions import functionality

Kiran K4b3b94dc8307
diff --git a/apps/web/app/api/cron/import/rewardful/route.ts b/apps/web/app/api/cron/import/rewardful/route.ts
index 31801f7e91..9a41a45187 100644
--- a/apps/web/app/api/cron/import/rewardful/route.ts
+++ b/apps/web/app/api/cron/import/rewardful/route.ts
@@ -2,6 +2,7 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { importAffiliates } from "@/lib/rewardful/import-affiliates";
import { importCampaign } from "@/lib/rewardful/import-campaign";
+import { importCommissions } from "@/lib/rewardful/import-commissions";
import { importReferrals } from "@/lib/rewardful/import-referrals";
import { importSteps } from "@/lib/rewardful/importer";
import { NextResponse } from "next/server";
@@ -44,6 +45,12 @@ export async function POST(req: Request) {
page,
});
break;
+ case "import-commissions":
+ await importCommissions({
+ programId,
+ page,
+ });
+ break;
}
return NextResponse.json("OK");
diff --git a/apps/web/app/api/mock/rewardful/commissions/route.ts b/apps/web/app/api/mock/rewardful/commissions/route.ts
index b186f2220b..4b376d8de3 100644
--- a/apps/web/app/api/mock/rewardful/commissions/route.ts
+++ b/apps/web/app/api/mock/rewardful/commissions/route.ts
@@ -16,7 +16,7 @@ export async function GET(request: NextRequest) {
paid_at: i % 3 === 1 ? `2020-09-${20 + i}T16:28:25.000Z` : null,
voided_at: i % 3 === 2 ? `2020-09-${21 + i}T16:28:25.000Z` : null,
campaign: {
- id: `c3482343-8680-40c5-af9a-9efa119713b${i}`,
+ id: "ceaef6d9-767e-49aa-a6ab-46c02aa79604",
created_at: `2020-05-22T02:55:19.802Z`,
updated_at: `2020-08-19T16:28:16.177Z`,
name: `Campaign ${i + 1}`,
diff --git a/apps/web/app/api/mock/rewardful/referrals/route.ts b/apps/web/app/api/mock/rewardful/referrals/route.ts
index 88ba211240..35196b86d7 100644
--- a/apps/web/app/api/mock/rewardful/referrals/route.ts
+++ b/apps/web/app/api/mock/rewardful/referrals/route.ts
@@ -38,7 +38,7 @@ export async function GET(request: NextRequest) {
email: `affiliate${i}@example.com`,
leads: 3 + i,
campaign: {
- id: `ae37c8ce-f82b-4e1b-9653-b802ae459a${i}2`,
+ id: "ceaef6d9-767e-49aa-a6ab-46c02aa79604",
name: `Campaign ${i + 1}`,
created_at: `2020-04-${20 + i}T00:24:08.199Z`,
updated_at: `2020-04-${20 + i}T00:24:08.199Z`,
diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.ts
index 038e35b9a8..b1881e4005 100644
--- a/apps/web/lib/rewardful/import-commissions.ts
+++ b/apps/web/lib/rewardful/import-commissions.ts
@@ -1,7 +1,11 @@
import { sendEmail } from "@dub/email";
import { CampaignImported } from "@dub/email/templates/campaign-imported";
import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
import { Program, Project } from "@prisma/client";
+import { getLeadEvent } from "../tinybird";
+import { recordSaleWithTimestamp } from "../tinybird/record-sale";
+import { clickEventSchemaTB } from "../zod/schemas/clicks";
import { RewardfulApi } from "./api";
import { MAX_BATCHES, rewardfulImporter } from "./importer";
import { RewardfulCommission } from "./types";
@@ -123,6 +127,9 @@ async function createCommission({
where: {
stripeCustomerId: sale.referral.stripe_customer_id,
},
+ include: {
+ link: true,
+ },
});
if (!customerFound) {
@@ -132,21 +139,78 @@ async function createCommission({
return;
}
+ if (
+ !customerFound.linkId ||
+ !customerFound.clickId ||
+ !customerFound.link?.partnerId
+ ) {
+ console.log(
+ `No link or click ID or partner ID found for customer ${customerFound.id}, skipping...`,
+ );
+ return;
+ }
+
+ const leadEvent = await getLeadEvent({
+ customerId: customerFound.id,
+ });
+
+ if (!leadEvent || leadEvent.data.length === 0) {
+ console.log(
+ `No lead event found for customer ${customerFound.id}, skipping...`,
+ );
+ return;
+ }
+
+ const clickData = clickEventSchemaTB
+ .omit({ timestamp: true })
+ .parse(leadEvent.data[0]);
+
+ const eventId = nanoid(16);
+
await Promise.all([
- // recordSaleWithTimestamp({
- // ...clickEvent,
- // event_id: nanoid(16),
- // event_name: "Sign up",
- // customer_id: customerId,
- // timestamp: new Date(referral.became_lead_at).toISOString(),
- // }),
- // prisma.link.update({
- // where: { id: link.id },
- // data: { leads: { increment: 1 } },
- // }),
- // prisma.project.update({
- // where: { id: workspace.id },
- // data: { usage: { increment: 1 } },
- // }),
+ prisma.commission.create({
+ data: {
+ eventId,
+ type: "sale",
+ programId: program.id,
+ partnerId: customerFound.link.partnerId,
+ linkId: customerFound.linkId,
+ customerId: customerFound.id,
+ amount: sale.sale_amount_cents,
+ currency: sale.currency.toLowerCase(),
+ quantity: 1,
+ status: "paid",
+ invoiceId: sale.id, // this is not the actual invoice ID
+ createdAt: new Date(sale.created_at),
+ },
+ }),
+
+ recordSaleWithTimestamp({
+ ...clickData,
+ event_id: eventId,
+ event_name: "Purchase",
+ amount: sale.sale_amount_cents,
+ customer_id: customerFound.id,
+ payment_processor: "stripe",
+ currency: sale.currency.toLowerCase(),
+ timestamp: new Date(sale.created_at).toISOString(),
+ metadata: JSON.stringify(commission),
+ }),
+
+ prisma.link.update({
+ where: { id: customerFound.linkId },
+ data: {
+ sales: { increment: 1 },
+ saleAmount: { increment: sale.sale_amount_cents },
+ },
+ }),
+
+ prisma.project.update({
+ where: { id: workspace.id },
+ data: {
+ usage: { increment: 1 },
+ salesUsage: { increment: sale.sale_amount_cents },
+ },
+ }),
]);
}
diff --git a/apps/web/lib/rewardful/import-referrals.ts b/apps/web/lib/rewardful/import-referrals.ts
index ffe44a8c9d..d6c4ea0e08 100644
--- a/apps/web/lib/rewardful/import-referrals.ts
+++ b/apps/web/lib/rewardful/import-referrals.ts
@@ -16,7 +16,7 @@ export async function importReferrals({
programId: string;
page: number;
}) {
- const { token, userId, campaignId } =
+ const { token, campaignId } =
await rewardfulImporter.getCredentials(programId);
const rewardfulApi = new RewardfulApi({ token });
@@ -67,6 +67,11 @@ export async function importReferrals({
page: currentPage,
});
}
+
+ await rewardfulImporter.queue({
+ programId: program.id,
+ action: "import-commissions",
+ });
}
// Create individual referral entries
diff --git a/apps/web/lib/rewardful/types.ts b/apps/web/lib/rewardful/types.ts
index 922ce29e3d..14f2604804 100644
--- a/apps/web/lib/rewardful/types.ts
+++ b/apps/web/lib/rewardful/types.ts
@@ -13,7 +13,6 @@ export interface RewardfulCampaign {
max_commission_period_months: number;
reward_type: "amount" | "percent";
commission_percent: number;
- // stripe_coupon_id: string;
created_at: string;
updated_at: string;
}