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 commissions

Kiran K0e8bc31077ed
diff --git a/apps/web/app/(ee)/api/cron/import/tolt/route.ts b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
index a8c4bdc313..d1d8eb57d1 100644
--- a/apps/web/app/(ee)/api/cron/import/tolt/route.ts
+++ b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
@@ -1,5 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { importCommissions } from "@/lib/rewardful/import-commissions";
import { importAffiliates } from "@/lib/tolt/import-affiliates";
import { importLinks } from "@/lib/tolt/import-links";
import { importReferrals } from "@/lib/tolt/import-referrals";
@@ -36,6 +37,9 @@ export async function POST(req: Request) {
case "import-referrals":
await importReferrals(payload);
break;
+ case "import-commissions":
+ await importCommissions(payload);
+ break;
}
return NextResponse.json("OK");
diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.ts
index e69de29bb2..6ccb9c0552 100644
--- a/apps/web/lib/tolt/import-commissions.ts
+++ b/apps/web/lib/tolt/import-commissions.ts
@@ -0,0 +1,275 @@
+import { sendEmail } from "@dub/email";
+import CampaignImported from "@dub/email/templates/campaign-imported";
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { CommissionStatus, Program } from "@prisma/client";
+import { createId } from "../api/create-id";
+import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
+import { RewardfulApi } from "../rewardful/api";
+import { MAX_BATCHES, rewardfulImporter } from "../rewardful/importer";
+import { RewardfulCommission } from "../rewardful/types";
+import { getLeadEvent } from "../tinybird";
+import { recordSaleWithTimestamp } from "../tinybird/record-sale";
+import { clickEventSchemaTB } from "../zod/schemas/clicks";
+
+export async function importCommissions({
+ programId,
+ page,
+}: {
+ programId: string;
+ page: number;
+}) {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ const { token, userId, campaignId } = await rewardfulImporter.getCredentials(
+ program.workspaceId,
+ );
+
+ const rewardfulApi = new RewardfulApi({ token });
+
+ let currentPage = page;
+ let hasMoreCommissions = true;
+ let processedBatches = 0;
+
+ 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,
+ program,
+ campaignId,
+ }),
+ ),
+ );
+ currentPage++;
+ processedBatches++;
+ }
+
+ if (hasMoreCommissions) {
+ return await rewardfulImporter.queue({
+ programId: program.id,
+ action: "import-commissions",
+ page: currentPage,
+ });
+ }
+
+ // Imports finished
+ await rewardfulImporter.deleteCredentials(program.workspaceId);
+
+ const workspaceUser = await prisma.projectUsers.findUniqueOrThrow({
+ where: {
+ userId_projectId: {
+ userId,
+ projectId: program.workspaceId,
+ },
+ },
+ include: {
+ project: true,
+ user: true,
+ },
+ });
+
+ if (workspaceUser && workspaceUser.user.email) {
+ await sendEmail({
+ email: workspaceUser.user.email,
+ subject: "Rewardful campaign imported",
+ react: CampaignImported({
+ email: workspaceUser.user.email,
+ workspace: workspaceUser.project,
+ program,
+ provider: "Rewardful",
+ }),
+ });
+ }
+}
+
+// Backfill historical commissions
+async function createCommission({
+ commission,
+ program,
+ campaignId,
+}: {
+ commission: RewardfulCommission;
+ program: Program;
+ campaignId: string;
+}) {
+ if (commission.campaign.id !== campaignId) {
+ console.log(
+ `Affiliate ${commission?.sale?.affiliate?.email} for 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 commissionFound = await prisma.commission.findUnique({
+ where: {
+ invoiceId_programId: {
+ invoiceId: sale.id,
+ programId: program.id,
+ },
+ },
+ });
+
+ if (commissionFound) {
+ console.log(`Commission ${commission.id} already exists, skipping...`);
+ return;
+ }
+
+ // here, we also check for commissions that have already been recorded on Dub
+ // e.g. during the transition period
+ // since we don't have the Stripe invoiceId from Rewardful, we use the referral's Stripe customer ID
+ // and check for commissions that were created with the same amount and within a +-1 hour window
+ const chargedAt = new Date(sale.charged_at);
+ const trackedCommission = await prisma.commission.findFirst({
+ where: {
+ programId: program.id,
+ type: "sale",
+ customer: {
+ stripeCustomerId: sale.referral.stripe_customer_id,
+ },
+ amount: sale.sale_amount_cents,
+ createdAt: {
+ gte: new Date(chargedAt.getTime() - 60 * 60 * 1000), // 1 hour before
+ lte: new Date(chargedAt.getTime() + 60 * 60 * 1000), // 1 hour after
+ },
+ },
+ });
+
+ if (trackedCommission) {
+ console.log(
+ `Commission ${trackedCommission.id} was already recorded on Dub, skipping...`,
+ );
+ return;
+ }
+
+ const customerFound = await prisma.customer.findUnique({
+ where: {
+ stripeCustomerId: sale.referral.stripe_customer_id,
+ },
+ include: {
+ link: true,
+ },
+ });
+
+ if (!customerFound) {
+ console.log(
+ `No customer found for Stripe customer ID ${sale.referral.stripe_customer_id}, skipping...`,
+ );
+ 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);
+
+ const toDubStatus: Record<RewardfulCommission["state"], CommissionStatus> = {
+ pending: "pending",
+ due: "pending",
+ paid: "paid",
+ voided: "canceled",
+ };
+
+ await Promise.all([
+ prisma.commission.create({
+ data: {
+ id: createId({ prefix: "cm_" }),
+ eventId,
+ type: "sale",
+ programId: program.id,
+ partnerId: customerFound.link.partnerId,
+ linkId: customerFound.linkId,
+ customerId: customerFound.id,
+ amount: sale.sale_amount_cents,
+ earnings: commission.amount,
+ currency: sale.currency.toLowerCase(),
+ quantity: 1,
+ status: toDubStatus[commission.state],
+ invoiceId: sale.id, // this is not the actual invoice ID, but we use this to deduplicate the sales
+ createdAt: new Date(sale.created_at),
+ },
+ }),
+
+ recordSaleWithTimestamp({
+ ...clickData,
+ event_id: eventId,
+ event_name: "Invoice paid",
+ amount: sale.sale_amount_cents,
+ customer_id: customerFound.id,
+ payment_processor: "stripe",
+ currency: sale.currency.toLowerCase(),
+ metadata: JSON.stringify(commission),
+ timestamp: new Date(sale.created_at).toISOString(),
+ }),
+
+ // update link stats
+ prisma.link.update({
+ where: { id: customerFound.linkId },
+ data: {
+ sales: { increment: 1 },
+ saleAmount: { increment: sale.sale_amount_cents },
+ },
+ }),
+
+ // update customer stats
+ prisma.customer.update({
+ where: { id: customerFound.id },
+ data: {
+ sales: { increment: 1 },
+ saleAmount: { increment: sale.sale_amount_cents },
+ },
+ }),
+ ]);
+
+ await syncTotalCommissions({
+ partnerId: customerFound.link.partnerId,
+ programId: program.id,
+ });
+}
diff --git a/apps/web/lib/tolt/import-referrals.ts b/apps/web/lib/tolt/import-referrals.ts
new file mode 100644
index 0000000000..92879123cd
--- /dev/null
+++ b/apps/web/lib/tolt/import-referrals.ts
@@ -0,0 +1,202 @@
+import { prisma } from "@dub/prisma";
+import { Link, Project } from "@prisma/client";
+import { ToltApi } from "./api";
+import { MAX_BATCHES, toltImporter } from "./importer";
+import { ToltCustomer } from "./types";
+
+export async function importReferrals({
+ programId,
+ startingAfter,
+}: {
+ programId: string;
+ startingAfter?: string;
+}) {
+ const { workspace } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ },
+ });
+
+ const { token, toltProgramId } = await toltImporter.getCredentials(
+ workspace.id,
+ );
+
+ const toltApi = new ToltApi({ token });
+
+ let hasMore = true;
+ let processedBatches = 0;
+
+ while (hasMore && processedBatches < MAX_BATCHES) {
+ const customers = await toltApi.listCustomers({
+ programId: toltProgramId,
+ startingAfter,
+ });
+
+ if (customers.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const partners = await prisma.partner.findMany({
+ where: {
+ email: {
+ in: customers.map(({ partner }) => partner.email),
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (partners.length === 0) {
+ console.log("No partners found for customers, skipping...");
+ return;
+ }
+
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ partnerId: {
+ in: partners.map((partner) => partner.id),
+ },
+ programId,
+ },
+ select: {
+ partnerId: true,
+ links: true,
+ },
+ });
+
+ const partnerLinksMap = new Map(
+ programEnrollments.map(({ partnerId, links }) => [partnerId, links]),
+ );
+
+ await Promise.all(
+ customers.map((customer) =>
+ createCustomer({
+ workspace,
+ links: partnerLinksMap.get(customer.partner.email) ?? [],
+ customer,
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ processedBatches++;
+ startingAfter = customers[customers.length - 1].id;
+ }
+
+ await toltImporter.queue({
+ programId,
+ action: hasMore ? "import-referrals" : "import-commissions",
+ ...(hasMore && { startingAfter }),
+ });
+}
+
+// Create individual customer entries
+async function createCustomer({
+ customer,
+ workspace,
+ links,
+}: {
+ customer: ToltCustomer;
+ workspace: Pick<Project, "id" | "stripeConnectId">;
+ links: Link[];
+}) {
+ if (links.length === 0) {
+ console.log(`Link not found for referral ${customer.id}, skipping...`);
+ return;
+ }
+
+ // if (
+ // !referral.stripe_customer_id ||
+ // !referral.stripe_customer_id.startsWith("cus_")
+ // ) {
+ // console.log(
+ // `No Stripe customer ID provided for referral ${referralId}, skipping...`,
+ // );
+ // return;
+ // }
+
+ // const customerFound = await prisma.customer.findUnique({
+ // where: {
+ // stripeCustomerId: referral.stripe_customer_id,
+ // },
+ // });
+
+ // if (customerFound) {
+ // console.log(
+ // `A customer already exists with Stripe customer ID ${referral.stripe_customer_id}`,
+ // );
+ // 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,
+ // domain: link.domain,
+ // key: link.key,
+ // workspaceId: workspace.id,
+ // skipRatelimit: true,
+ // timestamp: new Date(customer.created_at).toISOString(),
+ // });
+
+ // const clickEvent = clickEventSchemaTB.parse({
+ // ...clickData,
+ // bot: 0,
+ // qr: 0,
+ // });
+
+ // const customerId = createId({ prefix: "cus_" });
+
+ // await Promise.all([
+ // prisma.customer.create({
+ // data: {
+ // id: customerId,
+ // name:
+ // // if name is null/undefined or starts with cus_, use email as name
+ // !customer.name || customer.name.startsWith("cus_")
+ // ? customer.email
+ // : customer.name,
+ // email: customer.email,
+ // projectId: workspace.id,
+ // projectConnectId: workspace.stripeConnectId,
+ // clickId: clickEvent.click_id,
+ // linkId: link.id,
+ // country: clickEvent.country,
+ // // clickedAt: new Date(customer.created_at),
+ // // createdAt: new Date(customer.became_lead_at),
+ // // externalId: customer.customer_id,
+ // // stripeCustomerId: customer.stripe_customer_id,
+ // },
+ // }),
+
+ // recordLeadWithTimestamp({
+ // ...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 } },
+ // }),
+ // ]);
+}