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.

rename workspace → stripeWebhookWorkspace to fix fluid issue, remove old scripts

Steven Tey4b45c37f0864
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
index 7afaa5adbc..d13aea76d3 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
@@ -144,7 +144,7 @@ export const POST = withAxiom(async (req: Request) => {
!result.response.startsWith("Workspace not found") &&
event.account
) {
- const workspace = await prisma.project.findUnique({
+ const stripeWebhookWorkspace = await prisma.project.findUnique({
where: {
stripeConnectId: event.account,
},
@@ -152,9 +152,9 @@ export const POST = withAxiom(async (req: Request) => {
id: true,
},
});
- if (workspace) {
+ if (stripeWebhookWorkspace) {
// if workspace exists, we set the workspace ID
- result.workspaceId = workspace.id;
+ result.workspaceId = stripeWebhookWorkspace.id;
}
}
diff --git a/apps/web/scripts/customers/framer/1-process-framer-combined.ts b/apps/web/scripts/customers/framer/1-process-framer-combined.ts
deleted file mode 100644
index a47971ab71..0000000000
--- a/apps/web/scripts/customers/framer/1-process-framer-combined.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-import * as z from "zod/v4";
-import { tb } from "../../../lib/tinybird/client";
-
-/*
- Script to convert framer-combined.csv that Framer gave us
- into framer_remaining_events_final_final.csv
- (script 1 of 3 for Framer backfill)
-*/
-
-const getFramerLeadEvents = tb.buildPipe({
- pipe: "get_framer_lead_events",
- parameters: z.object({
- linkIds: z
- .union([z.string(), z.array(z.string())])
- .transform((v) => (Array.isArray(v) ? v : v.split(","))),
- }),
- data: z.any(),
-});
-
-const framerCombinedData: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
-}[] = [];
-const externalIdEventNameSet = new Set<string>();
-
-async function processFramerData(linkToBackfill: {
- via: string;
- linkId: string;
-}) {
- return new Promise<void>((resolve) => {
- Papa.parse(fs.createReadStream("framer_combined.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
- };
- }) => {
- if (linkToBackfill.via === result.data.via) {
- // check if externalId:eventName pair already exists in framerCombinedData
- if (
- externalIdEventNameSet.has(
- `${result.data.externalId}:${result.data.eventName}`,
- )
- ) {
- return;
- }
- externalIdEventNameSet.add(
- `${result.data.externalId}:${result.data.eventName}`,
- );
- framerCombinedData.push({
- via: result.data.via,
- externalId: result.data.externalId,
- eventName: result.data.eventName,
- creationDate: result.data.creationDate,
- });
- }
- },
- complete: async () => {
- console.log(
- `Found ${framerCombinedData.length} framerCombinedData for ${linkToBackfill.via} (${linkToBackfill.linkId})`,
- );
-
- const { data: leadEvents } = await getFramerLeadEvents({
- linkIds: linkToBackfill.linkId,
- });
-
- const customerIdsSet = new Set(
- leadEvents.map((event) => event.customer_id),
- );
-
- const customers = await prisma.customer.findMany({
- where: {
- id: {
- in: Array.from(customerIdsSet),
- },
- },
- select: {
- id: true,
- externalId: true,
- },
- });
-
- const processedLeadEvents = leadEvents.map((event) => {
- const customer = customers.find(
- (customer) => customer.id === event.customer_id,
- )!;
- return {
- linkId: event.link_id,
- externalId: customer.externalId!,
- eventName: event.event_name,
- creationDate: event.timestamp,
- };
- });
-
- console.log(
- `Found ${processedLeadEvents.length} processedLeadEvents for ${linkToBackfill.via} (${linkToBackfill.linkId})`,
- );
-
- // find events in framerCombinedData that don't exist in processedLeadEvents
- const eventsToBackfill = framerCombinedData.filter(
- (event) =>
- !processedLeadEvents.find(
- (ple) =>
- ple.externalId.toLowerCase() ===
- event.externalId.toLowerCase() &&
- ple.eventName.toLowerCase() === event.eventName.toLowerCase(),
- ),
- );
-
- console.log(
- `Found ${eventsToBackfill.length} events to backfill for ${linkToBackfill.via} (${linkToBackfill.linkId})`,
- );
- // append to framer_remaining_events_final_final.csv
- fs.appendFileSync(
- "framer_remaining_events_final_final.csv",
- Papa.unparse(eventsToBackfill),
- );
- resolve();
- },
- });
- });
-}
-
-async function main() {
- const linksWithSales = JSON.parse(
- fs.readFileSync("framer_links_with_sales_to_backfill.json", "utf-8"),
- );
-
- if (linksWithSales.length === 0) {
- console.log("No more links to process!");
- return;
- }
-
- // Get the first link to process
- const linkToProcess = linksWithSales[0];
-
- if (linkToProcess.linkId) {
- console.log(
- `Processing link: ${linkToProcess.via} (${linkToProcess.linkId})`,
- );
-
- await processFramerData(linkToProcess);
- } else {
- console.log("No linkId found for linkToProcess");
- }
-
- // Remove the processed link from the array
- linksWithSales.shift();
-
- // Write the updated array back to the file
- fs.writeFileSync(
- "framer_links_with_sales_to_backfill.json",
- JSON.stringify(linksWithSales, null, 2),
- );
-
- console.log(`Remaining links to process: ${linksWithSales.length}`);
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/2-sort-lead-events-by-date.ts b/apps/web/scripts/customers/framer/2-sort-lead-events-by-date.ts
deleted file mode 100644
index 2401af8df4..0000000000
--- a/apps/web/scripts/customers/framer/2-sort-lead-events-by-date.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-/*
- Script to sort framer_remaining_events_final_final.csv
- by creation date and split by year
- (script 2 of 3 for Framer backfill)
-*/
-
-type PayloadItem = {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: Date;
-};
-
-const framerRemainingEvents: PayloadItem[] = [];
-
-async function main() {
- Papa.parse(
- fs.createReadStream("framer_remaining_events_final_final.csv", "utf-8"),
- {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
- };
- }) => {
- framerRemainingEvents.push({
- ...result.data,
- creationDate: new Date(result.data.creationDate),
- });
- },
- complete: async () => {
- const sortedEvents = framerRemainingEvents.sort(
- (a, b) => a.creationDate.getTime() - b.creationDate.getTime(),
- );
- // split by year (2025, 2024, 2023, 2022, etc.)
- const eventsByYears = sortedEvents.reduce(
- (acc, event) => {
- const year = event.creationDate.getFullYear();
- if (!acc[year]) {
- acc[year] = [];
- }
- acc[year].push(event);
- return acc;
- },
- {} as Record<number, PayloadItem[]>,
- );
-
- // write to files
- Object.entries(eventsByYears).forEach(([year, events]) => {
- fs.writeFileSync(
- `framer_remaining_events_final_final_${year}.csv`,
- Papa.unparse(events),
- );
- });
- },
- },
- );
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/3-backfill-tb-events.ts b/apps/web/scripts/customers/framer/3-backfill-tb-events.ts
deleted file mode 100644
index 19f71fa31b..0000000000
--- a/apps/web/scripts/customers/framer/3-backfill-tb-events.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-import { createId } from "@/lib/api/create-id";
-import { generateRandomName } from "@/lib/names";
-import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
-import { prisma } from "@dub/prisma";
-import { linkConstructorSimple, nanoid } from "@dub/utils";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-import { recordLeadWithTimestamp } from "../../../lib/tinybird/record-lead";
-import { recordSaleWithTimestamp } from "../../../lib/tinybird/record-sale";
-
-/*
- Script to backfill events in Tinybird
- (script 3 of 3 for Framer backfill)
-*/
-
-type PayloadItem = {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: Date;
-};
-
-let framerRemainingEvents: PayloadItem[] = [];
-
-const FRAMER_WORKSPACE_ID = "xxx";
-const DOMAIN = "framer.link";
-const PAGE_NUMBER = 14;
-const PAGE_SIZE = 2500;
-
-async function main() {
- Papa.parse(
- fs.createReadStream(
- "framer_remaining_events_final_final_2024.csv",
- "utf-8",
- ),
- {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
- };
- }) => {
- framerRemainingEvents.push({
- ...result.data,
- creationDate: new Date(result.data.creationDate),
- });
- },
- complete: async () => {
- const start = PAGE_NUMBER * PAGE_SIZE;
- const end = (PAGE_NUMBER + 1) * PAGE_SIZE;
-
- console.log(
- `Processing PAGE_NUMBER ${PAGE_NUMBER}: events ${start} - ${end} of ${framerRemainingEvents.length}`,
- );
-
- framerRemainingEvents = framerRemainingEvents.slice(start, end);
-
- const links = await prisma.link.findMany({
- where: {
- shortLink: {
- in: framerRemainingEvents.map((p) =>
- linkConstructorSimple({
- domain: DOMAIN,
- key: p.via,
- }),
- ),
- },
- },
- select: {
- id: true,
- key: true,
- url: true,
- domain: true,
- programId: true,
- partnerId: true,
- },
- });
-
- let validEntries: PayloadItem[] = [];
- let invalidEntries: (PayloadItem & { error: string })[] = [];
-
- framerRemainingEvents.map((p) => {
- if (!links.some((l) => l.key === p.via)) {
- invalidEntries.push({
- ...p,
- error: `Link for via tag ${p.via} not found.`,
- });
- return;
- }
-
- if (
- links.some((l) => l.key === p.via && (!l.partnerId || !l.programId))
- ) {
- invalidEntries.push({
- ...p,
- error: `Link for via tag ${p.via} has no partnerId or programId.`,
- });
- return;
- }
-
- validEntries.push(p);
- });
-
- const linkMap = new Map(links.map((l) => [l.key, l]));
-
- const workspace = await prisma.project.findUniqueOrThrow({
- where: {
- id: FRAMER_WORKSPACE_ID,
- },
- });
-
- const customerData = validEntries.map((p) => {
- return {
- id: createId({ prefix: "cus_" }),
- name: generateRandomName(),
- externalId: p.externalId,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- clickId: nanoid(16),
- linkId: linkMap.get(p.via)!.id,
- clickedAt: p.creationDate,
- createdAt: p.creationDate,
- };
- });
-
- await prisma.customer.createMany({
- data: customerData,
- skipDuplicates: true,
- });
-
- const finalCustomers = await prisma.customer.findMany({
- where: {
- projectId: workspace.id,
- externalId: {
- in: customerData.map((c) => c.externalId),
- },
- },
- });
-
- const customerMap = new Map(
- finalCustomers.map((c) => [
- c.externalId,
- { id: c.id, clickId: c.clickId },
- ]),
- );
-
- const dataArray = validEntries.map((p) => {
- const link = linkMap.get(p.via)!;
-
- const clickData = {
- timestamp: p.creationDate.toISOString(),
- identity_hash: p.externalId,
- click_id: customerMap.get(p.externalId)!.clickId,
- workspace_id: workspace.id,
- link_id: link.id,
- domain: link.domain,
- key: link.key,
- url: link.url,
- ip: "",
- continent: "NA",
- country: "Unknown",
- region: "Unknown",
- city: "Unknown",
- latitude: "Unknown",
- longitude: "Unknown",
- vercel_region: "",
- device: "Desktop",
- device_vendor: "Unknown",
- device_model: "Unknown",
- browser: "Unknown",
- browser_version: "Unknown",
- engine: "Unknown",
- engine_version: "Unknown",
- os: "Unknown",
- os_version: "Unknown",
- cpu_architecture: "Unknown",
- ua: "Unknown",
- bot: 0,
- qr: 0,
- referer: "(direct)",
- referer_url: "(direct)",
- trigger: "link",
- };
-
- const clickEvent = clickEventSchemaTB.parse(clickData);
-
- const leadEventData = {
- ...clickEvent,
- event_id: nanoid(16),
- event_name: p.eventName,
- customer_id: customerMap.get(p.externalId)!.id,
- timestamp: p.creationDate.toISOString(),
- };
-
- const saleEventId = nanoid(16);
-
- const saleEventData = {
- ...clickEvent,
- event_id: saleEventId,
- event_name: "Invoice paid",
- amount: 0,
- customer_id: customerMap.get(p.externalId)!.id,
- payment_processor: "stripe",
- currency: "usd",
- timestamp: p.creationDate.toISOString(),
- };
-
- return {
- payload: p,
- linkData: link,
- clickData,
- leadEventData,
- saleEventData,
- };
- });
-
- // console.log("clickData");
- // console.log(dataArray.map((d) => d.clickData).slice(0, 5));
-
- // console.log("leadEventData");
- // console.log(dataArray.map((d) => d.leadEventData).slice(0, 5));
-
- // console.log("saleEventData");
- // console.log(dataArray.map((d) => d.saleEventData).slice(0, 5));
-
- const res = await Promise.all([
- // Record clicks
- fetch(
- `${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- "Content-Type": "application/x-ndjson",
- },
- body: dataArray
- .map((d) => JSON.stringify(d.clickData))
- .join("\n"),
- },
- ).then((res) => res.json()),
-
- // Record leads
- recordLeadWithTimestamp(dataArray.map((d) => d.leadEventData)),
-
- // Record sales
- recordSaleWithTimestamp(dataArray.map((d) => d.saleEventData)),
- ]);
-
- console.log(res);
- console.log(
- `Also encountered ${invalidEntries.length} invalid entries`,
- );
- },
- },
- );
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/backfill-commissions.ts b/apps/web/scripts/customers/framer/backfill-commissions.ts
deleted file mode 100644
index 681f5af283..0000000000
--- a/apps/web/scripts/customers/framer/backfill-commissions.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { createId } from "@/lib/api/create-id";
-import { prisma } from "@dub/prisma";
-import { CommissionStatus, CommissionType } from "@dub/prisma/client";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-const commissionsToBackfill: {
- partnerEmail: string;
- totalCommissionCents: number;
-}[] = [];
-
-const FRAMER_PROGRAM_ID = "prog_";
-const MONTH_TO_BACKFILL = new Date("2025-05-15");
-
-async function main() {
- // First read the sales data
- Papa.parse(
- fs.createReadStream("framer_backfill_commissions_may.csv", "utf-8"),
- {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- partner_email: string;
- total_commission_cents: string;
- };
- }) => {
- commissionsToBackfill.push({
- partnerEmail: result.data.partner_email,
- totalCommissionCents: parseInt(result.data.total_commission_cents),
- });
- },
- complete: async () => {
- console.log(
- `Found ${commissionsToBackfill.length} commissions to backfill`,
- );
- const partners = await prisma.partner.findMany({
- where: {
- email: {
- in: commissionsToBackfill.map((p) => p.partnerEmail),
- },
- },
- });
-
- const processedData = commissionsToBackfill
- .map((p) => {
- const partner = partners.find((_p) => _p.email === p.partnerEmail);
- if (!partner) {
- console.log(`Partner not found: ${p.partnerEmail}`);
- return null;
- }
- return {
- partnerId: partner.id,
- ...p,
- };
- })
- .filter((p): p is NonNullable<typeof p> => p !== null);
-
- const manualCommissions = processedData.map((d) => {
- return {
- id: createId({ prefix: "cm_" }),
- programId: FRAMER_PROGRAM_ID,
- partnerId: d.partnerId,
- type: CommissionType.custom,
- amount: 0,
- quantity: 1,
- earnings: d.totalCommissionCents,
- status: CommissionStatus.pending,
- createdAt: MONTH_TO_BACKFILL,
- description: `Imported commissions from FirstPromoter (${MONTH_TO_BACKFILL.toLocaleString(
- "en-US",
- {
- month: "long",
- year: "numeric",
- },
- )})`,
- };
- });
-
- console.table(manualCommissions);
-
- // Add manual commissions to the database
- await prisma.commission.createMany({
- data: manualCommissions,
- skipDuplicates: true,
- });
- },
- },
- );
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/check-pending-payout-totals.ts b/apps/web/scripts/customers/framer/check-pending-payout-totals.ts
deleted file mode 100644
index a13c923077..0000000000
--- a/apps/web/scripts/customers/framer/check-pending-payout-totals.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-
-async function main() {
- const payouts = await prisma.payout.findMany({
- where: {
- programId: "prog_xxx",
- status: "pending",
- },
- });
-
- const commissions = await prisma.commission.groupBy({
- by: ["payoutId"],
- where: {
- payoutId: { in: payouts.map((payout) => payout.id) },
- },
- _sum: {
- earnings: true,
- },
- });
-
- // go through each to make sure total === amount, and log each
- for (const payout of payouts) {
- const total =
- commissions.find((commission) => commission.payoutId === payout.id)?._sum
- .earnings ?? 0;
-
- if (total !== payout.amount) {
- console.log(
- `ALERT: Payout ${payout.id} has a total of ${total} but an amount of ${payout.amount}`,
- );
- } else {
- console.log(
- `Payout ${payout.id} matches ${total}, ${payout.amount}. skipping...`,
- );
- }
- }
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/get-links-to-backfill.ts b/apps/web/scripts/customers/framer/get-links-to-backfill.ts
deleted file mode 100644
index a2ed00a6d5..0000000000
--- a/apps/web/scripts/customers/framer/get-links-to-backfill.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-const tbLinkData: { link_id: string; sales: number }[] = [];
-
-async function main() {
- Papa.parse(fs.createReadStream("framer_links_with_sales.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: { data: { link_id: string; sales: string } }) => {
- tbLinkData.push({
- link_id: result.data.link_id,
- sales: parseInt(result.data.sales),
- });
- },
- complete: async () => {
- console.log(`Found ${tbLinkData.length} links with sales in Tinybird`);
- const prismaLinkData = await prisma.link.findMany({
- where: {
- programId: "prog_xxx",
- sales: {
- gt: 0,
- },
- },
- select: {
- id: true,
- key: true,
- sales: true,
- },
- orderBy: {
- sales: "desc",
- },
- });
- console.log(`Found ${prismaLinkData.length} links with sales in Prisma`);
-
- let linksWithSameSalesCount = 0;
- const linksWithDifferentSalesCount = prismaLinkData
- .map((prismaLink) => {
- const tbLink = tbLinkData.find(
- (tbLink) => tbLink.link_id === prismaLink.id,
- );
- // if the sales count is the roughly the same (within a 10% margin),
- // if means it was backfilled correctly – don't return the link
- if (
- tbLink &&
- (tbLink.sales === prismaLink.sales ||
- tbLink.sales / prismaLink.sales < 1.1 ||
- tbLink.sales / prismaLink.sales > 0.9)
- ) {
- linksWithSameSalesCount++;
- return null;
- }
- return {
- linkId: prismaLink.id,
- via: prismaLink.key,
- prismaSales: prismaLink.sales,
- tbSales: tbLink?.sales || 0,
- };
- })
- .filter(Boolean);
- console.log(
- `Found ${linksWithSameSalesCount} links with the same sales count`,
- );
- console.log(
- `Found ${linksWithDifferentSalesCount.length} links with different sales count:`,
- );
- console.table(linksWithDifferentSalesCount.slice(0, 100));
-
- // write to file
- fs.writeFileSync(
- "framer_links_to_backfill.csv",
- Papa.unparse(linksWithDifferentSalesCount),
- );
- },
- });
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/get-remaining-links-to-backfill.ts b/apps/web/scripts/customers/framer/get-remaining-links-to-backfill.ts
deleted file mode 100644
index ad0434ba40..0000000000
--- a/apps/web/scripts/customers/framer/get-remaining-links-to-backfill.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-const framerCombinedData: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
-}[] = [];
-const externalIdEventNameSet = new Set<string>();
-
-const salesData: Record<string, number> = {};
-
-async function main() {
- // First read the sales data
- Papa.parse(fs.createReadStream("framer_links_with_sales.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- link_id: string;
- sales: string;
- };
- }) => {
- salesData[result.data.link_id] = parseInt(result.data.sales);
- },
- complete: () => {
- console.log(
- `Found ${Object.keys(salesData).length} links with sales data`,
- );
- // After sales data is loaded, process the combined data
- processCombinedData();
- },
- });
-}
-
-function processCombinedData() {
- Papa.parse(fs.createReadStream("framer_combined.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: string;
- };
- }) => {
- // check if externalId:eventName pair already exists in framerCombinedData
- if (
- externalIdEventNameSet.has(
- `${result.data.externalId}:${result.data.eventName}`,
- )
- ) {
- return;
- }
- externalIdEventNameSet.add(
- `${result.data.externalId}:${result.data.eventName}`,
- );
- framerCombinedData.push({
- via: result.data.via,
- externalId: result.data.externalId,
- eventName: result.data.eventName,
- creationDate: result.data.creationDate,
- });
- },
- complete: async () => {
- console.log(`Found ${framerCombinedData.length} links in Framer`);
-
- // convert to via + count
- const viaCount = framerCombinedData.reduce(
- (acc, curr) => {
- acc[curr.via] = (acc[curr.via] || 0) + 1;
- return acc;
- },
- {} as Record<string, number>,
- );
-
- // order by count
- const viaCountArray = Object.entries(viaCount)
- .map(([via, count]) => ({
- via,
- count,
- }))
- .sort((a, b) => b.count - a.count);
-
- const prismaLinks = await prisma.link.findMany({
- where: {
- domain: "framer.link",
- key: {
- in: viaCountArray.map(({ via }) => via),
- },
- },
- select: {
- id: true,
- key: true,
- },
- });
-
- const linkIdsWithCount = viaCountArray
- .map(({ via }) => {
- const link = prismaLinks.find((link) => link.key === via);
- const count = viaCount[via];
- const sales = link ? salesData[link.id] || 0 : 0;
- if (count === sales) {
- return null;
- }
- return {
- linkId: link?.id,
- via,
- count,
- recordedSales: sales,
- };
- })
- .filter(Boolean);
-
- // Sort by sales instead of count
- linkIdsWithCount.sort(
- (a, b) => (b?.recordedSales || 0) - (a?.recordedSales || 0),
- );
-
- console.log(
- `Found ${linkIdsWithCount.length} links with sales data that need to be backfilled`,
- );
-
- console.table(linkIdsWithCount.slice(0, 100));
-
- fs.writeFileSync(
- "framer_links_with_sales_to_backfill.json",
- JSON.stringify(linkIdsWithCount, null, 2),
- );
- },
- });
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/mark-commissions-pending.ts b/apps/web/scripts/customers/framer/mark-commissions-pending.ts
deleted file mode 100644
index daae01e6ab..0000000000
--- a/apps/web/scripts/customers/framer/mark-commissions-pending.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-let eventIds: string[] = [];
-
-async function main() {
- Papa.parse(fs.createReadStream("framer_pending_event_ids.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: { data: { event_id: string } }) => {
- eventIds.push(result.data.event_id);
- },
- complete: async () => {
- const commissionsToUpdate = await prisma.commission.findMany({
- where: {
- eventId: { in: eventIds },
- status: {
- not: "pending",
- },
- },
- take: 500,
- });
-
- const updateCommissions = await prisma.commission.updateMany({
- where: {
- id: { in: commissionsToUpdate.map((commission) => commission.id) },
- },
- data: {
- status: "pending",
- },
- });
-
- console.log(`Updated ${updateCommissions.count} commissions`);
- },
- });
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/process-lead-events.ts b/apps/web/scripts/customers/framer/process-lead-events.ts
deleted file mode 100644
index 31ec745ceb..0000000000
--- a/apps/web/scripts/customers/framer/process-lead-events.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-// @ts-nocheck
-
-import { prisma } from "@dub/prisma";
-import { chunk } from "@dub/utils";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-type RawDataProps = {
- event_name: string;
- timestamp: string;
- customer_id: string;
- link_id: string;
-};
-
-type ProcessedDataProps = {
- via: string;
- externalId: string;
- eventName: string;
- creationDate: Date;
-};
-
-let rawData: RawDataProps[] = [];
-let customerIdsSet = new Set<string>();
-let linkIdsSet = new Set<string>();
-
-const BATCH = 7;
-const FRAMER_WORKSPACE_ID = "xxx";
-
-async function main() {
- Papa.parse(
- fs.createReadStream(`get_framer_lead_events_${BATCH}.csv`, "utf-8"),
- {
- header: true,
- skipEmptyLines: true,
- step: (result: { data: RawDataProps }) => {
- const { customer_id, link_id } = result.data;
- rawData.push(result.data);
- linkIdsSet.add(link_id);
- customerIdsSet.add(customer_id);
- },
- complete: async () => {
- const linkIdsArray = Array.from(linkIdsSet);
- const customerIdsArray = Array.from(customerIdsSet);
-
- console.log(
- `Found ${linkIdsArray.length} links and ${customerIdsArray.length} customers`,
- );
-
- const links = await prisma.link.findMany({
- where: {
- id: {
- in: linkIdsArray,
- },
- projectId: FRAMER_WORKSPACE_ID,
- },
- select: {
- id: true,
- key: true,
- },
- });
-
- let customers: { id: string; externalId: string | null }[] = [];
- const customerIdChunks = chunk(customerIdsArray, 1000);
- for (const customerIdChunk of customerIdChunks) {
- const data = await prisma.customer.findMany({
- where: {
- id: {
- in: customerIdChunk,
- },
- projectId: FRAMER_WORKSPACE_ID,
- },
- select: {
- id: true,
- externalId: true,
- },
- });
- customers.push(...data);
- }
-
- console.log(`Found ${customers.length} customers`);
-
- const processedData = rawData
- .map((data) => {
- const link = links.find((link) => link.id === data.link_id);
- const customer = customers.find(
- (customer) => customer.id === data.customer_id,
- );
- if (!link || !customer || !customer.externalId) {
- return null;
- }
- return {
- via: link.key,
- externalId: customer.externalId,
- eventName: data.event_name,
- creationDate: new Date(data.timestamp),
- };
- })
- .filter((data) => data !== null) satisfies ProcessedDataProps[];
-
- fs.writeFileSync(
- `processed_framer_lead_events_${BATCH}.csv`,
- Papa.unparse(processedData),
- );
- },
- },
- );
-}
-
-main();
diff --git a/apps/web/scripts/customers/framer/split-bounty-payouts.ts b/apps/web/scripts/customers/framer/split-bounty-payouts.ts
new file mode 100644
index 0000000000..b7efb58ca6
--- /dev/null
+++ b/apps/web/scripts/customers/framer/split-bounty-payouts.ts
@@ -0,0 +1,127 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import "dotenv-flow/config";
+
+async function main() {
+ const bountySubmissions = await prisma.bountySubmission.findMany({
+ where: {
+ bountyId: "bnty_1K4WFVHAH5V8R8DB5A3Z58KMB",
+ status: "approved",
+ },
+ include: {
+ commission: true,
+ },
+ });
+
+ const payouts = await prisma.payout.findMany({
+ where: {
+ programId: bountySubmissions[0].programId,
+ partnerId: {
+ in: bountySubmissions.map((submission) => submission.partnerId),
+ },
+ status: "pending",
+ id: {
+ in: bountySubmissions.map(
+ (submission) => submission.commission?.payoutId!,
+ ),
+ },
+ amount: {
+ gt: 200_00,
+ },
+ partner: {
+ payoutsEnabledAt: {
+ not: null,
+ },
+ },
+ },
+ include: {
+ commissions: {
+ where: {
+ id: {
+ in: bountySubmissions.map(
+ (submission) => submission.commission?.id!,
+ ),
+ },
+ },
+ },
+ },
+ });
+ console.log(
+ `Found ${payouts.length} payouts to update, ${payouts.reduce((acc, payout) => acc + payout.commissions.length, 0)} commissions to update`,
+ );
+
+ for (const payout of payouts) {
+ const otherCommissions = await prisma.commission.findMany({
+ where: {
+ payoutId: payout.id,
+ id: {
+ not: payout.commissions[0].id,
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+ if (otherCommissions.length === 0) {
+ console.log(`No other commissions to update for payout ${payout.id}`);
+ continue;
+ }
+ const totalEarnings = otherCommissions.reduce(
+ (acc, commission) => acc + commission.earnings,
+ 0,
+ );
+ const periodStart = otherCommissions[0].createdAt;
+ const periodEnd = otherCommissions[otherCommissions.length - 1].createdAt;
+
+ const newPayout = await prisma.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId: payout.programId,
+ partnerId: payout.partnerId,
+ periodStart,
+ periodEnd,
+ amount: totalEarnings,
+ description: "Dub Partners payout (Framer)",
+ },
+ });
+
+ console.log(
+ `Created new payout ${newPayout.id} with amount ${newPayout.amount}`,
+ );
+
+ const updatedOtherCommissions = await prisma.commission.updateMany({
+ where: {
+ payoutId: payout.id,
+ id: {
+ not: payout.commissions[0].id,
+ },
+ },
+ data: {
+ payoutId: newPayout.id,
+ },
+ });
+
+ console.log(
+ `Updated ${updatedOtherCommissions.count} other commissions to point to the new payout`,
+ );
+
+ const updateCurrentPayout = await prisma.payout.update({
+ where: {
+ id: payout.id,
+ },
+ data: {
+ amount: payout.commissions[0].earnings,
+ periodStart: payout.commissions[0].createdAt,
+ periodEnd: payout.commissions[0].createdAt,
+ },
+ });
+ console.log(
+ `Updated current payout ${payout.id} with amount ${updateCurrentPayout.amount}`,
+ );
+ }
+
+ const url = `https://app.dub.co/framer/program/payouts?status=pending&confirmPayouts=true&selectedPayoutIds=${payouts.map((payout) => payout.id).join(",")}`;
+ console.log(url);
+}
+
+main();