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.

Import Rewardful commissions

Steven Tey4f3ade481a76
diff --git a/apps/web/app/api/mock/rewardful/commissions/route.ts b/apps/web/app/api/mock/rewardful/commissions/route.ts
new file mode 100644
index 0000000000..b186f2220b
--- /dev/null
+++ b/apps/web/app/api/mock/rewardful/commissions/route.ts
@@ -0,0 +1,130 @@
+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 commissions = Array.from({ length: 10 }, (_, i) => ({
+ id: `39e68c88-d84a-4510-b3b4-43c75016a0${i}0`,
+ created_at: `2020-08-${19 + i}T16:28:31.164Z`,
+ updated_at: `2020-08-${19 + i}T16:28:31.164Z`,
+ amount: 3000 + i * 1000,
+ currency: "USD",
+ state: ["due", "paid", "voided"][i % 3],
+ due_at: `2020-09-${18 + i}T16:28:25.000Z`,
+ 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}`,
+ created_at: `2020-05-22T02:55:19.802Z`,
+ updated_at: `2020-08-19T16:28:16.177Z`,
+ name: `Campaign ${i + 1}`,
+ },
+ sale: {
+ id: `74e37d3b-03c5-4bfc-841c-a79d5799551${i}`,
+ currency: "USD",
+ charged_at: `2020-08-${19 + i}T16:28:25.000Z`,
+ stripe_account_id: `acct_ABC${123 + i}`,
+ stripe_charge_id: `ch_ABC${123 + i}`,
+ invoiced_at: `2020-08-${19 + i}T16:28:25.000Z`,
+ created_at: `2020-08-${19 + i}T16:28:31.102Z`,
+ updated_at: `2020-08-${19 + i}T16:28:31.102Z`,
+ charge_amount_cents: 10000 + i * 1000,
+ refund_amount_cents: 0,
+ tax_amount_cents: 0,
+ sale_amount_cents: 10000 + i * 1000,
+ referral: {
+ id: `d154e622-278a-4103-b191-5cbebae4047${i}`,
+ stripe_account_id: `acct_ABC${123 + i}`,
+ stripe_customer_id: `cus_ABC${123 + i}`,
+ conversion_state: "conversion",
+ deactivated_at: null,
+ expires_at: `2020-10-18T16:13:12.109Z`,
+ created_at: `2020-08-19T16:13:12.109Z`,
+ updated_at: `2020-08-19T16:28:31.166Z`,
+ customer: {
+ platform: "stripe",
+ id: `cus_ABC${123 + i}`,
+ name: [
+ "Freddie Mercury",
+ "David Bowie",
+ "Mick Jagger",
+ "Robert Plant",
+ "Roger Waters",
+ "Paul McCartney",
+ "John Lennon",
+ "George Harrison",
+ "Ringo Starr",
+ "Brian May",
+ ][i],
+ email: `rockstar${i}@example.com`,
+ },
+ visits: 2 + i,
+ link: {
+ id: `b759a9ed-ed63-499f-b621-0221f2712${i}86`,
+ url: `http://www.demo.com:8080/?via=ref${i}`,
+ token: `ref${i}`,
+ visitors: 197 + i,
+ leads: 196 + i,
+ conversions: 156 + i,
+ },
+ },
+ affiliate: {
+ id: `07d8acc5-c689-4b4a-bbab-f88a71ffc0${i}2`,
+ created_at: `2020-05-22T02:55:19.934Z`,
+ updated_at: `2020-08-19T16:28:31.168Z`,
+ first_name: [
+ "James",
+ "Felix",
+ "Eve",
+ "M",
+ "Q",
+ "Bill",
+ "Alec",
+ "Pierce",
+ "Timothy",
+ "Daniel",
+ ][i],
+ last_name: [
+ "Bond",
+ "Leiter",
+ "Moneypenny",
+ "Mansfield",
+ "Boothroyd",
+ "Tanner",
+ "Trevelyan",
+ "Brosnan",
+ "Dalton",
+ "Craig",
+ ][i],
+ email: `agent${i}@mi6.co.uk`,
+ paypal_email: "",
+ confirmed_at: `2020-07-09T03:53:06.760Z`,
+ paypal_email_confirmed_at: `2020-07-03T17:49:23.489Z`,
+ receive_new_commission_notifications: true,
+ sign_in_count: 1 + i,
+ unconfirmed_email: null,
+ stripe_customer_id: null,
+ stripe_account_id: null,
+ visitors: 197 + i,
+ leads: 196 + i,
+ conversions: 156 + i,
+ campaign: {
+ id: `c3482343-8680-40c5-af9a-9efa119713b${i}`,
+ created_at: `2020-05-22T02:55:19.802Z`,
+ updated_at: `2020-08-19T16:28:16.177Z`,
+ name: `Campaign ${i + 1}`,
+ },
+ },
+ },
+ }));
+
+ const startIndex = (page - 1) * limit;
+ const endIndex = startIndex + limit;
+ const slicedCommissions = commissions.slice(startIndex, endIndex);
+
+ return NextResponse.json({
+ data: slicedCommissions.length > 0 ? slicedCommissions : [],
+ });
+}
diff --git a/apps/web/lib/rewardful/api.ts b/apps/web/lib/rewardful/api.ts
index 3d9e25a95c..9c183c5e34 100644
--- a/apps/web/lib/rewardful/api.ts
+++ b/apps/web/lib/rewardful/api.ts
@@ -2,6 +2,7 @@ import { DubApiError } from "@/lib/api/errors";
import {
RewardfulAffiliate,
RewardfulCampaign,
+ RewardfulCommission,
RewardfulReferral,
} from "./types";
@@ -86,4 +87,18 @@ export class RewardfulApi {
return data;
}
+
+ async listCommissions({ page = 1 }: { page?: number }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("expand[]", "sale");
+ searchParams.append("expand[]", "campaign");
+ searchParams.append("page", page.toString());
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ const { data } = await this.fetch<{ data: RewardfulCommission[] }>(
+ `${this.baseUrl}/commissions?${searchParams.toString()}`,
+ );
+
+ return data;
+ }
}
diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.ts
new file mode 100644
index 0000000000..038e35b9a8
--- /dev/null
+++ b/apps/web/lib/rewardful/import-commissions.ts
@@ -0,0 +1,152 @@
+import { sendEmail } from "@dub/email";
+import { CampaignImported } from "@dub/email/templates/campaign-imported";
+import { prisma } from "@dub/prisma";
+import { Program, Project } from "@prisma/client";
+import { RewardfulApi } from "./api";
+import { MAX_BATCHES, rewardfulImporter } from "./importer";
+import { RewardfulCommission } from "./types";
+
+export async function importCommissions({
+ programId,
+ page,
+}: {
+ programId: string;
+ page: number;
+}) {
+ const { token, userId, campaignId } =
+ await rewardfulImporter.getCredentials(programId);
+
+ const rewardfulApi = new RewardfulApi({ token });
+
+ let currentPage = page;
+ let hasMoreCommissions = true;
+ let processedBatches = 0;
+
+ const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ },
+ });
+
+ while (hasMoreCommissions && processedBatches < MAX_BATCHES) {
+ const commissions = await rewardfulApi.listCommissions({
+ page: currentPage,
+ });
+
+ if (commissions.length === 0) {
+ hasMoreCommissions = false;
+ break;
+ }
+
+ await Promise.all(
+ commissions.map((commission) =>
+ createCommission({
+ commission,
+ workspace,
+ program,
+ campaignId,
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ currentPage++;
+ processedBatches++;
+ }
+
+ if (hasMoreCommissions) {
+ return await rewardfulImporter.queue({
+ programId: program.id,
+ action: "import-commissions",
+ page: currentPage,
+ });
+ }
+
+ // Imports finished
+ await rewardfulImporter.deleteCredentials(programId);
+
+ const { email } = await prisma.user.findUniqueOrThrow({
+ where: {
+ id: userId,
+ },
+ });
+
+ if (email) {
+ await sendEmail({
+ email,
+ subject: "Rewardful campaign imported",
+ react: CampaignImported({
+ email,
+ provider: "Rewardful",
+ workspace,
+ program,
+ }),
+ });
+ }
+}
+
+// Backfill historical commissions
+async function createCommission({
+ commission,
+ workspace,
+ program,
+ campaignId,
+}: {
+ commission: RewardfulCommission;
+ workspace: Project;
+ program: Program;
+ campaignId: string;
+}) {
+ if (commission.campaign.id !== campaignId) {
+ console.log(
+ `Commission ${commission.id} not in campaign ${campaignId} (they're in ${commission.campaign.id}). Skipping...`,
+ );
+ return;
+ }
+
+ const { sale } = commission;
+
+ if (
+ !sale.referral.stripe_customer_id ||
+ !sale.referral.stripe_customer_id.startsWith("cus_")
+ ) {
+ console.log(
+ `No Stripe customer ID provided for referral ${sale.referral.id}, skipping...`,
+ );
+ return;
+ }
+
+ const customerFound = await prisma.customer.findUnique({
+ where: {
+ stripeCustomerId: sale.referral.stripe_customer_id,
+ },
+ });
+
+ if (!customerFound) {
+ console.log(
+ `No customer found for Stripe customer ID ${sale.referral.stripe_customer_id}, skipping...`,
+ );
+ return;
+ }
+
+ 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 } },
+ // }),
+ ]);
+}
diff --git a/apps/web/lib/rewardful/import-referrals.ts b/apps/web/lib/rewardful/import-referrals.ts
index e8416a49d0..f33701a7df 100644
--- a/apps/web/lib/rewardful/import-referrals.ts
+++ b/apps/web/lib/rewardful/import-referrals.ts
@@ -1,5 +1,3 @@
-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";
@@ -69,28 +67,6 @@ export async function importReferrals({
page: currentPage,
});
}
-
- // Imports finished
- await rewardfulImporter.deleteCredentials(programId);
-
- const { email } = await prisma.user.findUniqueOrThrow({
- where: {
- id: userId,
- },
- });
-
- if (email) {
- await sendEmail({
- email,
- subject: "Rewardful campaign imported",
- react: CampaignImported({
- email,
- provider: "Rewardful",
- workspace,
- program,
- }),
- });
- }
}
// Create individual referral entries
diff --git a/apps/web/lib/rewardful/importer.ts b/apps/web/lib/rewardful/importer.ts
index c88a184811..7414d90345 100644
--- a/apps/web/lib/rewardful/importer.ts
+++ b/apps/web/lib/rewardful/importer.ts
@@ -12,6 +12,7 @@ export const importSteps = z.enum([
"import-campaign",
"import-affiliates",
"import-referrals",
+ "import-commissions",
]);
class RewardfulImporter {
diff --git a/apps/web/lib/rewardful/types.ts b/apps/web/lib/rewardful/types.ts
index bfa5c4c626..922ce29e3d 100644
--- a/apps/web/lib/rewardful/types.ts
+++ b/apps/web/lib/rewardful/types.ts
@@ -62,3 +62,34 @@ export interface RewardfulReferral {
conversion_state: string;
stripe_customer_id: string;
}
+
+export interface RewardfulCommissionSale {
+ id: string;
+ currency: string;
+ charged_at: string;
+ stripe_account_id: string;
+ stripe_charge_id: string;
+ invoiced_at: string;
+ created_at: string;
+ updated_at: string;
+ charge_amount_cents: number;
+ refund_amount_cents: number;
+ tax_amount_cents: number;
+ sale_amount_cents: number;
+ referral: RewardfulReferral;
+ affiliate: RewardfulAffiliate;
+}
+
+export interface RewardfulCommission {
+ id: string;
+ created_at: string;
+ updated_at: string;
+ amount: number;
+ currency: string;
+ state: "due" | "paid" | "voided";
+ due_at: string;
+ paid_at: string | null;
+ voided_at: string | null;
+ campaign: RewardfulCampaign;
+ sale: RewardfulCommissionSale;
+}