The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add scripts for fixing coupon/link
Steven Teyb4ab8772cd9f
diff --git a/apps/web/lib/tinybird/get-sale-event.ts b/apps/web/lib/tinybird/get-sale-event.tsdeleted file mode 100644index fe2bbd550d..0000000000--- a/apps/web/lib/tinybird/get-sale-event.ts+++ /dev/null@@ -1,10 +0,0 @@-import * as z from "zod/v4";-import { tb } from "./client";--export const getSaleEvent = tb.buildPipe({- pipe: "get_sale_event",- parameters: z.object({- eventId: z.string(),- }),- data: z.any(),-});diff --git a/apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts b/apps/web/scripts/customers/beehiiv/fix-case-a-complex.tsnew file mode 100644index 0000000000..b80d41f04b--- /dev/null+++ b/apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts@@ -0,0 +1,300 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import { groupBy, linkConstructorSimple } from "@dub/utils";+import "dotenv-flow/config";+import { bulkCreateLinks } from "../../../lib/api/links/bulk-create-links";+import { syncTotalCommissions } from "../../../lib/api/partners/sync-total-commissions";++// case A: sales come from coupon code only (https://dub.slack.com/archives/C08S54HTHA8/p1782854750091729?thread_ts=1782830134.684169&cid=C08S54HTHA8)+// this variant is for handling cases where there are paid commissions via Dub – in this case we need to create a dummy commission to represent the overpayment + a clawback to balance the books+async function main() {+ const PROGRAM_ID = "prog_xxx";++ const links = await prisma.link.findMany({+ where: {+ id: {+ in: [],+ },+ },+ include: {+ discountCode: {+ include: {+ partner: true,+ },+ },+ partner: true,+ commissions: true,+ },+ });+ if (links.length === 0) {+ console.log("No links found");+ return;+ }+ console.log(`Found ${links.length} links`);++ const data = links.map((link) => ({+ id: link.id,+ currenctPartnerId: link.partnerId,+ actualPartnerId: link.discountCode?.partnerId,+ code: link.discountCode?.code,+ domain: link.domain,+ url: link.url,+ programId: link.programId,+ folderId: link.folderId,+ userId: link.userId,+ projectId: link.projectId,+ processedCommissions: link.commissions+ .filter((commission) => commission.status === "processed")+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissions: link.commissions+ .filter((commission) => commission.status === "paid")+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissionsViaDub: link.commissions+ .filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId !== null,+ )+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissionsImported: link.commissions+ .filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId === null,+ )+ .reduce((acc, commission) => acc + commission.earnings, 0),+ }));++ const complexTransfer = data.filter((link) => link.paidCommissionsViaDub > 0);++ console.table(complexTransfer);++ for (const link of complexTransfer) {+ const updatedLink = await prisma.link.update({+ where: { id: link.id },+ data: {+ key: `${link.code}-coupon`,+ shortLink: linkConstructorSimple({+ domain: link.domain!,+ key: `${link.code}-coupon`,+ }),+ partnerId: link.actualPartnerId!,+ comments: `Link created for Rewardful coupon "${link.code}"`,+ },+ });+ console.log(+ `Updated link ${link.id} with key ${updatedLink.key} and shortLink ${updatedLink.shortLink} and partnerId ${link.actualPartnerId!}`,+ );+ const updatedCustomers = await prisma.customer.updateMany({+ where: {+ linkId: link.id,+ },+ data: {+ programId: PROGRAM_ID,+ partnerId: link.actualPartnerId!,+ },+ });+ console.log(+ `Updated ${updatedCustomers.count} customers for link ${link.id}`,+ );++ while (true) {+ // update non processed and non paid commissions (but include imported paid commissions) directly+ const updatedCommissions = await prisma.commission.updateMany({+ where: {+ linkId: link.id,+ partnerId: link.currenctPartnerId!,+ OR: [+ {+ status: "pending",+ },+ { status: "paid", payoutId: null },+ ],+ },+ data: {+ partnerId: link.actualPartnerId!,+ },+ limit: 250,+ });+ if (updatedCommissions.count < 250) {+ break;+ }+ console.log(+ `Updated ${updatedCommissions.count} non-processed commissions for link ${link.id}`,+ );+ }++ // update processed and paid commissions separately cause they're tied to a payout+ const processedAndPaidCommissions = await prisma.commission.findMany({+ where: {+ linkId: link.id,+ status: {+ in: ["processed", "paid"],+ },+ },+ });+ console.log(+ `Found ${processedAndPaidCommissions.length} processed and paid commissions for link ${link.id}`,+ );++ const updatedProcessedAndPaidCommissions =+ await prisma.commission.updateMany({+ where: {+ id: {+ in: processedAndPaidCommissions.map((commission) => commission.id),+ },+ },+ data: {+ partnerId: link.actualPartnerId!,+ payoutId: null,+ status: "pending",+ },+ });+ console.log(+ `Updated ${updatedProcessedAndPaidCommissions.count} processed and paid commissions for link ${link.id}`,+ );++ // delete activity logs cause they'll be re-added to a new payout+ const deletedActivityLogs = await prisma.activityLog.deleteMany({+ where: {+ resourceType: "commission",+ resourceId: {+ in: processedAndPaidCommissions.map((commission) => commission.id),+ },+ },+ });+ console.log(+ `Deleted ${deletedActivityLogs.count} activity logs for commissions`,+ );++ const paidCommissionsViaDub = processedAndPaidCommissions.filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId !== null,+ );+ const groupedByPayoutId = groupBy(+ paidCommissionsViaDub,+ (commission) => commission.payoutId!,+ );++ for (const payoutId of Object.keys(groupedByPayoutId)) {+ const paidCommissionsTotal = groupedByPayoutId[payoutId].reduce(+ (acc, commission) => acc + commission.earnings,+ 0,+ );+ console.log(+ `Total paid commissions for payout ${payoutId}: ${paidCommissionsTotal}`,+ );++ // since these commissions were paid out to the wrong partner, we need to create a dummy commission to represent the overpayment + a clawback to balance the books+ // first, create the dummy commission for the current partner to represent the overpayment+ const createdCommission = await prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ type: "custom",+ partnerId: link.currenctPartnerId!,+ programId: PROGRAM_ID,+ description: `Overpayment for payout ${payoutId}`,+ earnings: paidCommissionsTotal,+ payoutId,+ amount: 0,+ quantity: 1,+ userId: link.userId,+ status: "paid",+ },+ });++ console.log(+ `Created dummy commission ${createdCommission.id} for overpayment of ${paidCommissionsTotal} for payout ${payoutId}`,+ );++ // then, create the clawback for the current partner to balance the books+ const createdClawback = await prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ type: "custom",+ partnerId: link.currenctPartnerId!,+ programId: PROGRAM_ID,+ description: `Clawback for commission "${createdCommission.id}" (overpayment from incorrectly imported discount code "${link.code}")`,+ earnings: -paidCommissionsTotal,+ amount: 0,+ quantity: 1,+ userId: link.userId,+ },+ });++ console.log(+ `Created clawback ${createdClawback.id} for ${paidCommissionsTotal} paid commissions for link ${link.id}`,+ );+ }++ // retally old payout ID values for processed commissions+ const processedCommissions = processedAndPaidCommissions.filter(+ (commission) => commission.status === "processed",+ );+ const payoutIdsToRetally = [+ ...new Set(+ processedCommissions+ .map((commission) => commission.payoutId!)+ .filter((payoutId): payoutId is string => Boolean(payoutId)),+ ),+ ];++ for (const payoutId of payoutIdsToRetally) {+ const data = await prisma.commission.aggregate({+ _sum: {+ earnings: true,+ },+ where: {+ payoutId,+ },+ });+ const payoutAmount = data._sum.earnings ?? 0;+ if (payoutAmount === 0) {+ console.log(`Deleting payout ${payoutId}`);+ await prisma.payout.delete({+ where: {+ id: payoutId,+ },+ });+ } else {+ console.log(`Updating payout ${payoutId} with amount ${payoutAmount}`);+ await prisma.payout.update({+ where: {+ id: payoutId,+ },+ data: {+ amount: payoutAmount,+ },+ });+ }+ }++ await syncTotalCommissions({+ partnerId: link.currenctPartnerId!,+ programId: PROGRAM_ID,+ });+ await syncTotalCommissions({+ partnerId: link.actualPartnerId!,+ programId: PROGRAM_ID,+ });++ // recreated the old link for the current partner+ const createdLinks = await bulkCreateLinks({+ links: [+ {+ domain: link.domain!,+ key: link.code!,+ url: link.url!,+ trackConversion: true,+ programId: PROGRAM_ID,+ partnerId: link.currenctPartnerId!,+ folderId: link.folderId,+ userId: link.userId,+ projectId: link.projectId,+ },+ ],+ skipRedisCache: true,+ });+ console.log(`Created ${createdLinks.length} links`);+ }+}++main();diff --git a/apps/web/scripts/customers/beehiiv/fix-case-a-simple.ts b/apps/web/scripts/customers/beehiiv/fix-case-a-simple.tsnew file mode 100644index 0000000000..22946cfd6c--- /dev/null+++ b/apps/web/scripts/customers/beehiiv/fix-case-a-simple.ts@@ -0,0 +1,224 @@+import { prisma } from "@/lib/prisma";+import { linkConstructorSimple } from "@dub/utils";+import "dotenv-flow/config";+import { bulkCreateLinks } from "../../../lib/api/links/bulk-create-links";+import { syncTotalCommissions } from "../../../lib/api/partners/sync-total-commissions";++// case A: sales come from coupon code only (https://dub.slack.com/archives/C08S54HTHA8/p1782854750091729?thread_ts=1782830134.684169&cid=C08S54HTHA8)+// this variant is for handling cases where there are no paid commissions via Dub – just do a simple swap+async function main() {+ const PROGRAM_ID = "prog_xxx";++ const links = await prisma.link.findMany({+ where: {+ id: {+ in: [],+ },+ },+ include: {+ discountCode: {+ include: {+ partner: true,+ },+ },+ partner: true,+ commissions: true,+ },+ });+ console.log(`Found ${links.length} links`);+ if (links.length === 0) {+ console.log("No links found");+ return;+ }++ const data = links.map((link) => ({+ id: link.id,+ currenctPartnerId: link.partnerId,+ actualPartnerId: link.discountCode?.partnerId,+ code: link.discountCode?.code,+ domain: link.domain,+ url: link.url,+ programId: link.programId,+ folderId: link.folderId,+ userId: link.userId,+ projectId: link.projectId,+ processedCommissions: link.commissions+ .filter((commission) => commission.status === "processed")+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissions: link.commissions+ .filter((commission) => commission.status === "paid")+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissionsViaDub: link.commissions+ .filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId !== null,+ )+ .reduce((acc, commission) => acc + commission.earnings, 0),+ paidCommissionsImported: link.commissions+ .filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId === null,+ )+ .reduce((acc, commission) => acc + commission.earnings, 0),+ }));++ const simpleTransfer = data.filter(+ (link) => link.paidCommissionsViaDub === 0,+ );++ console.table(simpleTransfer);++ for (const link of simpleTransfer) {+ const updatedLink = await prisma.link.update({+ where: { id: link.id },+ data: {+ key: `${link.code}-coupon`,+ shortLink: linkConstructorSimple({+ domain: link.domain!,+ key: `${link.code}-coupon`,+ }),+ partnerId: link.actualPartnerId!,+ comments: `Link created for Rewardful coupon "${link.code}"`,+ },+ });+ console.log(+ `Updated link ${link.id} with key ${updatedLink.key} and shortLink ${updatedLink.shortLink} and partnerId ${link.actualPartnerId!}`,+ );+ const updatedCustomers = await prisma.customer.updateMany({+ where: {+ linkId: link.id,+ },+ data: {+ programId: PROGRAM_ID,+ partnerId: link.actualPartnerId!,+ },+ });+ console.log(+ `Updated ${updatedCustomers.count} customers for link ${link.id}`,+ );++ const updatedCommissions = await prisma.commission.updateMany({+ where: {+ linkId: link.id,+ status: {+ not: "processed",+ },+ },+ data: {+ partnerId: link.actualPartnerId!,+ },+ });+ console.log(+ `Updated ${updatedCommissions.count} non-processed commissions for link ${link.id}`,+ );++ // update processed commissions separately cause they're tied to a payout+ const processedCommissions = await prisma.commission.findMany({+ where: {+ linkId: link.id,+ status: "processed",+ },+ });+ console.log(+ `Found ${processedCommissions.length} processed commissions for link ${link.id}`,+ );++ const updatedProcessedCommissions = await prisma.commission.updateMany({+ where: {+ id: {+ in: processedCommissions.map((commission) => commission.id),+ },+ },+ data: {+ partnerId: link.actualPartnerId!,+ payoutId: null,+ status: "pending",+ },+ });+ console.log(+ `Updated ${updatedProcessedCommissions.count} processed commissions for link ${link.id}`,+ );++ // delete activity logs cause they'll be re-added to a new payout+ const deletedActivityLogs = await prisma.activityLog.deleteMany({+ where: {+ resourceType: "commission",+ resourceId: {+ in: processedCommissions.map((commission) => commission.id),+ },+ },+ });+ console.log(+ `Deleted ${deletedActivityLogs.count} activity logs for commissions`,+ );++ // retally old payout ID values+ const payoutIdsToRetally = [+ ...new Set(+ processedCommissions+ .map((commission) => commission.payoutId!)+ .filter((payoutId): payoutId is string => Boolean(payoutId)),+ ),+ ];++ for (const payoutId of payoutIdsToRetally) {+ const data = await prisma.commission.aggregate({+ _sum: {+ earnings: true,+ },+ where: {+ payoutId,+ },+ });+ const payoutAmount = data._sum.earnings ?? 0;+ if (payoutAmount === 0) {+ console.log(`Deleting payout ${payoutId}`);+ await prisma.payout.delete({+ where: {+ id: payoutId,+ },+ });+ } else {+ console.log(`Updating payout ${payoutId} with amount ${payoutAmount}`);+ await prisma.payout.update({+ where: {+ id: payoutId,+ },+ data: {+ amount: payoutAmount,+ },+ });+ }+ }++ await syncTotalCommissions({+ partnerId: link.currenctPartnerId!,+ programId: PROGRAM_ID,+ });+ await syncTotalCommissions({+ partnerId: link.actualPartnerId!,+ programId: PROGRAM_ID,+ });++ // recreated the old link for the current partner+ const createdLinks = await bulkCreateLinks({+ links: [+ {+ domain: link.domain!,+ key: link.code!,+ url: link.url!,+ trackConversion: true,+ programId: PROGRAM_ID,+ partnerId: link.currenctPartnerId!,+ folderId: link.folderId,+ userId: link.userId,+ projectId: link.projectId,+ },+ ],+ skipRedisCache: true,+ });+ console.log(`Created ${createdLinks.length} links`);+ }+}++main();diff --git a/apps/web/scripts/customers/beehiiv/fix-case-b.ts b/apps/web/scripts/customers/beehiiv/fix-case-b.tsnew file mode 100644index 0000000000..0ced786024--- /dev/null+++ b/apps/web/scripts/customers/beehiiv/fix-case-b.ts@@ -0,0 +1,84 @@+import { prisma } from "@/lib/prisma";+import "dotenv-flow/config";+import { bulkCreateLinks } from "../../../lib/api/links/bulk-create-links";++// case B: sales come from link only (https://dub.slack.com/archives/C08S54HTHA8/p1782854750091729?thread_ts=1782830134.684169&cid=C08S54HTHA8)+// super simple, just create a new -coupon link for the discount code and assign it to the correct partner+async function main() {+ const PROGRAM_ID = "prog_xxx";++ const discountCodes = await prisma.discountCode.findMany({+ where: {+ programId: PROGRAM_ID,+ linkId: "link_xxx",+ },+ include: {+ link: {+ include: {+ partner: true,+ },+ },+ partner: true,+ },+ });+ if (discountCodes.length === 0) {+ console.log("No discount codes found");+ return;+ }+ console.log(`Found ${discountCodes.length} discount codes`);++ const discountCodesToReassign = discountCodes.filter(+ (discountCode) => discountCode.partnerId !== discountCode.link?.partnerId,+ );++ console.table(+ discountCodesToReassign.map((discountCode) => ({+ id: discountCode.id,+ partnerId: discountCode.partnerId,+ linkPartnerId: discountCode.link?.partnerId,+ partnerName: discountCode.partner?.name,+ linkPartnerName: discountCode.link?.partner?.name,+ saleAmount: discountCode.link?.saleAmount,+ })),+ );++ const linksToCreate = discountCodesToReassign.map((discountCode) => ({+ domain: discountCode.link?.domain!,+ key: `${discountCode.code}-coupon`,+ url: discountCode.link?.url!,+ trackConversion: true,+ programId: discountCode.programId,+ partnerId: discountCode.partnerId,+ folderId: discountCode.link?.folderId,+ userId: discountCode.link?.userId,+ projectId: discountCode.link?.projectId,+ comments: `Link created for Rewardful coupon "${discountCode.code}"`,+ }));++ console.table(linksToCreate);++ const createdLinks = await bulkCreateLinks({+ links: linksToCreate,+ skipRedisCache: true,+ });+ console.log(`Created ${createdLinks.length} links`);++ for (const newLink of createdLinks) {+ const updatedDiscountCode = await prisma.discountCode.update({+ where: {+ programId_code: {+ programId: PROGRAM_ID,+ code: newLink.key.replace("-coupon", ""),+ },+ },+ data: {+ linkId: newLink.id,+ },+ });+ console.log(+ `Updated discount code ${updatedDiscountCode.code} to map to link ${newLink.shortLink}`,+ );+ }+}++main();diff --git a/apps/web/scripts/customers/beehiiv/fix-case-c.ts b/apps/web/scripts/customers/beehiiv/fix-case-c.tsnew file mode 100644index 0000000000..4418721f7a--- /dev/null+++ b/apps/web/scripts/customers/beehiiv/fix-case-c.ts@@ -0,0 +1,279 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import { groupBy } from "@dub/utils";+import "dotenv-flow/config";+import { syncTotalCommissions } from "../../../lib/api/partners/sync-total-commissions";++// case B complex: sales comes from both link and discount code (https://dub.slack.com/archives/C08S54HTHA8/p1782854750091729?thread_ts=1782830134.684169&cid=C08S54HTHA8)+// for these, we first run fix-case-b for the given link, and then run this script to update for the coupon code sales+/*+ run all 3 scripts with this command:+p script customers/beehiiv/fix-case-c+p script tinybird/update-lead-event+p script tinybird/update-sale-event+*/+async function main() {+ const PROGRAM_ID = "prog_xxx";+ const CUSTOMER_ID = "cus_xxx";+ const OLD_LINK_ID = "link_xxx";+ const NEW_LINK_ID = "link_xxx";++ const [oldLink, newLink] = await Promise.all([+ prisma.link.findUniqueOrThrow({+ where: {+ id: OLD_LINK_ID,+ },+ }),+ prisma.link.findUniqueOrThrow({+ where: {+ id: NEW_LINK_ID,+ },+ }),+ ]);++ const updatedCustomer = await prisma.customer.update({+ where: {+ id: CUSTOMER_ID,+ },+ data: {+ linkId: newLink.id,+ programId: PROGRAM_ID,+ partnerId: newLink.partnerId!,+ },+ });+ console.log(+ `Updated customer ${CUSTOMER_ID} with linkId ${newLink.id} and partnerId ${newLink.partnerId}`,+ );++ // update non processed and non paid commissions (but include imported paid commissions) directly+ const updatedCommissions = await prisma.commission.updateMany({+ where: {+ customerId: CUSTOMER_ID,+ OR: [+ {+ status: {+ in: ["pending", "canceled"],+ },+ },+ { status: "paid", payoutId: null },+ ],+ },+ data: {+ linkId: newLink.id,+ partnerId: newLink.partnerId!,+ },+ });+ console.log(+ `Updated ${updatedCommissions.count} non-processed commissions for customer ${CUSTOMER_ID}`,+ );++ // update processed and paid commissions separately cause they're tied to a payout+ const processedAndPaidCommissions = await prisma.commission.findMany({+ where: {+ customerId: CUSTOMER_ID,+ linkId: oldLink.id,+ status: {+ in: ["processed", "paid"],+ },+ },+ });+ console.log(+ `Found ${processedAndPaidCommissions.length} processed and paid commissions for customer ${CUSTOMER_ID}`,+ );++ const updatedProcessedAndPaidCommissions = await prisma.commission.updateMany(+ {+ where: {+ id: {+ in: processedAndPaidCommissions.map((commission) => commission.id),+ },+ },+ data: {+ partnerId: newLink.partnerId!,+ payoutId: null,+ status: "pending",+ },+ },+ );+ console.log(+ `Updated ${updatedProcessedAndPaidCommissions.count} processed and paid commissions for customer ${CUSTOMER_ID}`,+ );++ // delete activity logs cause they'll be re-added to a new payout+ const deletedActivityLogs = await prisma.activityLog.deleteMany({+ where: {+ resourceType: "commission",+ resourceId: {+ in: processedAndPaidCommissions.map((commission) => commission.id),+ },+ },+ });+ console.log(+ `Deleted ${deletedActivityLogs.count} activity logs for commissions`,+ );++ const paidCommissionsViaDub = processedAndPaidCommissions.filter(+ (commission) =>+ commission.status === "paid" && commission.payoutId !== null,+ );+ const groupedByPayoutId = groupBy(+ paidCommissionsViaDub,+ (commission) => commission.payoutId!,+ );++ for (const payoutId of Object.keys(groupedByPayoutId)) {+ const paidCommissionsTotal = groupedByPayoutId[payoutId].reduce(+ (acc, commission) => acc + commission.earnings,+ 0,+ );+ console.log(+ `Total paid commissions for payout ${payoutId}: ${paidCommissionsTotal}`,+ );++ // since these commissions were paid out to the wrong partner, we need to create a dummy commission to represent the overpayment + a clawback to balance the books+ // first, create the dummy commission for the current partner to represent the overpayment+ const createdCommission = await prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ type: "custom",+ partnerId: oldLink.partnerId!,+ programId: PROGRAM_ID,+ description: `Overpayment for payout ${payoutId}`,+ earnings: paidCommissionsTotal,+ payoutId,+ amount: 0,+ quantity: 1,+ userId: oldLink.userId,+ status: "paid",+ },+ });++ console.log(+ `Created dummy commission ${createdCommission.id} for overpayment of ${paidCommissionsTotal} for payout ${payoutId}`,+ );++ // then, create the clawback for the current partner to balance the books+ const createdClawback = await prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ type: "custom",+ partnerId: oldLink.partnerId!,+ programId: PROGRAM_ID,+ description: `Clawback for commission "${createdCommission.id}" (overpayment for payout ${payoutId})`,+ earnings: -paidCommissionsTotal,+ amount: 0,+ quantity: 1,+ userId: oldLink.userId,+ },+ });++ console.log(+ `Created clawback ${createdClawback.id} for ${paidCommissionsTotal} paid commissions for link ${oldLink.id}`,+ );+ }++ // retally old payout ID values for processed commissions+ const processedCommissions = processedAndPaidCommissions.filter(+ (commission) => commission.status === "processed",+ );+ const payoutIdsToRetally = [+ ...new Set(+ processedCommissions+ .map((commission) => commission.payoutId!)+ .filter((payoutId): payoutId is string => Boolean(payoutId)),+ ),+ ];++ for (const payoutId of payoutIdsToRetally) {+ const data = await prisma.commission.aggregate({+ _sum: {+ earnings: true,+ },+ where: {+ payoutId,+ },+ });+ const payoutAmount = data._sum.earnings ?? 0;+ if (payoutAmount === 0) {+ console.log(`Deleting payout ${payoutId}`);+ await prisma.payout.delete({+ where: {+ id: payoutId,+ },+ });+ } else {+ console.log(`Updating payout ${payoutId} with amount ${payoutAmount}`);+ await prisma.payout.update({+ where: {+ id: payoutId,+ },+ data: {+ amount: payoutAmount,+ },+ });+ }+ }++ const updatedOldLink = await prisma.link.update({+ where: {+ id: oldLink.id,+ },+ data: {+ clicks: {+ decrement: 1,+ },+ leads: {+ decrement: 1,+ },+ conversions: {+ decrement: 1,+ },+ sales: {+ decrement: updatedCustomer.sales,+ },+ saleAmount: {+ decrement: updatedCustomer.saleAmount,+ },+ },+ });+ console.log(+ `Updated old link ${oldLink.id} with ${updatedOldLink.clicks} clicks, ${updatedOldLink.leads} leads, ${updatedOldLink.conversions} conversions, ${updatedOldLink.sales} sales, ${updatedOldLink.saleAmount} saleAmount`,+ );++ const updatedNewLink = await prisma.link.update({+ where: {+ id: newLink.id,+ },+ data: {+ clicks: {+ increment: 1,+ },+ leads: {+ increment: 1,+ },+ conversions: {+ increment: 1,+ },+ sales: {+ increment: updatedCustomer.sales,+ },+ saleAmount: {+ increment: updatedCustomer.saleAmount,+ },+ },+ });+ console.log(+ `Updated new link ${newLink.id} with ${updatedNewLink.clicks} clicks, ${updatedNewLink.leads} leads, ${updatedNewLink.conversions} conversions, ${updatedNewLink.sales} sales, ${updatedNewLink.saleAmount} saleAmount`,+ );++ await syncTotalCommissions({+ partnerId: oldLink.partnerId!,+ programId: PROGRAM_ID,+ });+ await syncTotalCommissions({+ partnerId: newLink.partnerId!,+ programId: PROGRAM_ID,+ });+}++main();diff --git a/apps/web/scripts/tinybird/delete-sale-event.ts b/apps/web/scripts/tinybird/delete-sale-event.tsindex d0a107e6ee..f3e4767ce1 100644--- a/apps/web/scripts/tinybird/delete-sale-event.ts+++ b/apps/web/scripts/tinybird/delete-sale-event.ts@@ -1,13 +1,12 @@import { prisma } from "@/lib/prisma";import "dotenv-flow/config";import { syncPartnerLinksStats } from "../../lib/api/partners/sync-partner-links-stats";-import { getSaleEvent } from "../../lib/tinybird/get-sale-event";+import { getSaleEvents } from "./get-sale-events";-// update tinybird sale event+// delete tinybird sale eventasync function main() {- const eventId = "xxx";- const deleteCondition = `event_id = '${eventId}'`;- const { data } = await getSaleEvent({ eventId });+ const customerId = "cus_xxx";+ const { data } = await getSaleEvents({ customerId });const oldData = data[0];if (!oldData) {console.log("No data found");@@ -32,11 +31,11 @@ async function main() {const deleteRes = await Promise.allSettled([deleteData({dataSource: "dub_sale_events",- deleteCondition,+ deleteCondition: `customer_id = '${customerId}'`,}),deleteData({dataSource: "dub_sale_events_mv",- deleteCondition,+ deleteCondition: `customer_id = '${customerId}'`,}),]);console.log(deleteRes);diff --git a/apps/web/scripts/tinybird/get-sale-events.ts b/apps/web/scripts/tinybird/get-sale-events.tsnew file mode 100644index 0000000000..6636d62987--- /dev/null+++ b/apps/web/scripts/tinybird/get-sale-events.ts@@ -0,0 +1,10 @@+import * as z from "zod/v4";+import { tb } from "../../lib/tinybird/client";++export const getSaleEvents = tb.buildPipe({+ pipe: "internal_get_sale_events",+ parameters: z.object({+ customerId: z.string(),+ }),+ data: z.any(),+});diff --git a/apps/web/scripts/tinybird/update-click-event.ts b/apps/web/scripts/tinybird/update-click-event.tsindex f253e41ac5..08784106e6 100644--- a/apps/web/scripts/tinybird/update-click-event.ts+++ b/apps/web/scripts/tinybird/update-click-event.ts@@ -3,9 +3,10 @@ import { getClickEvent } from "../../lib/tinybird/get-click-event";// update tinybird sale eventasync function main() {- const clickId = "D0aoUca8hLdzmJJE";+ const clickId = "xxx";const columnName = "link_id";- const columnValue = "link_xxx";+ const OLD_LINK_ID = "link_xxx";+ const NEW_LINK_ID = "link_xxx";const oldData = await getClickEvent({ clickId });if (!oldData) {@@ -15,7 +16,7 @@ async function main() {const updatedData = {...oldData,vercel_region: "iad1",- [columnName]: columnValue,+ [columnName]: NEW_LINK_ID,};console.log(updatedData);@@ -37,13 +38,13 @@ async function main() {dataSource: "dub_click_events_mv",clickId,columnName,- oldValue: "link_1KPRDAYXXE9D2FYM691BK5C59",+ oldValue: OLD_LINK_ID,}),deleteData({dataSource: "dub_click_events_id",clickId,columnName,- oldValue: "link_1KPRDAYXXE9D2FYM691BK5C59",+ oldValue: OLD_LINK_ID,}),]);console.log(deleteRes);diff --git a/apps/web/scripts/tinybird/update-lead-event.ts b/apps/web/scripts/tinybird/update-lead-event.tsindex f3cc1a8caa..0ccd5d2953 100644--- a/apps/web/scripts/tinybird/update-lead-event.ts+++ b/apps/web/scripts/tinybird/update-lead-event.ts@@ -2,9 +2,10 @@ import { prisma } from "@/lib/prisma";import "dotenv-flow/config";import * as z from "zod/v4";import { tb } from "../../lib/tinybird/client";+import { recordLeadWithTimestamp } from "../../lib/tinybird/record-lead";-const getEvents = tb.buildPipe({- pipe: "internal_get_events",+const getLeadEvents = tb.buildPipe({+ pipe: "internal_get_lead_events",parameters: z.object({customerId: z.string(),}),@@ -13,17 +14,17 @@ const getEvents = tb.buildPipe({// update tinybird lead eventasync function main() {- const customerId = "cus_xxx";- const oldLinkId = "link_xxx";- const newLinkId = "link_xxx";+ const CUSTOMER_ID = "cus_xxx";+ const OLD_LINK_ID = "link_xxx";+ const NEW_LINK_ID = "link_xxx";const newLink = await prisma.link.findUniqueOrThrow({where: {- id: newLinkId,+ id: NEW_LINK_ID,},});- const { data } = await getEvents({ customerId });+ const { data } = await getLeadEvents({ customerId: CUSTOMER_ID });const oldData = data[0];if (!oldData) {console.log("No data found");@@ -34,24 +35,24 @@ async function main() {link_id: newLink.id,key: newLink.key,};- // console.log(updatedData);+ console.log(updatedData);- // const res = await recordLeadWithTimestamp(updatedData);- // console.log(res);+ const res = await recordLeadWithTimestamp(updatedData);+ console.log(res);// delete data from tinybirdconst deleteRes = await Promise.allSettled([deleteData({dataSource: "dub_lead_events",- customerId,+ customerId: CUSTOMER_ID,columnName: "link_id",- oldValue: oldLinkId,+ oldValue: OLD_LINK_ID,}),deleteData({dataSource: "dub_lead_events_mv",- customerId,+ customerId: CUSTOMER_ID,columnName: "link_id",- oldValue: oldLinkId,+ oldValue: OLD_LINK_ID,}),]);console.log(deleteRes);diff --git a/apps/web/scripts/tinybird/update-sale-event.ts b/apps/web/scripts/tinybird/update-sale-event.tsindex 42e4237282..a56f7c5eb2 100644--- a/apps/web/scripts/tinybird/update-sale-event.ts+++ b/apps/web/scripts/tinybird/update-sale-event.ts@@ -1,23 +1,30 @@+import { prisma } from "@/lib/prisma";import "dotenv-flow/config";-import { getSaleEvent } from "../../lib/tinybird/get-sale-event";import { recordSaleWithTimestamp } from "../../lib/tinybird/record-sale";+import { getSaleEvents } from "./get-sale-events";// update tinybird sale eventasync function main() {- const eventId = "nBxldg6VxQNUCCwZ";- const columnName = "event_name";- const columnValue = "New Subscription Name";+ const CUSTOMER_ID = "cus_xxx";+ const OLD_LINK_ID = "link_xxx";+ const NEW_LINK_ID = "link_xxx";- const { data } = await getSaleEvent({ eventId });- const oldData = data[0];- if (!oldData) {+ const newLink = await prisma.link.findUniqueOrThrow({+ where: {+ id: NEW_LINK_ID,+ },+ });++ const { data: oldData } = await getSaleEvents({ customerId: CUSTOMER_ID });+ if (oldData.length === 0) {console.log("No data found");return;}- const updatedData = {- ...oldData,- [columnName]: columnValue,- };+ const updatedData = oldData.map((item) => ({+ ...item,+ link_id: newLink.id,+ key: newLink.key,+ }));console.log(updatedData);const res = await recordSaleWithTimestamp(updatedData);@@ -27,21 +34,15 @@ async function main() {const deleteRes = await Promise.allSettled([deleteData({dataSource: "dub_sale_events",- eventId,- columnName,- oldValue: oldData[columnName],+ customerId: CUSTOMER_ID,+ columnName: "link_id",+ oldValue: OLD_LINK_ID,}),deleteData({dataSource: "dub_sale_events_mv",- eventId,- columnName,- oldValue: oldData[columnName],- }),- deleteData({- dataSource: "dub_sale_events_id",- eventId,- columnName,- oldValue: oldData[columnName],+ customerId: CUSTOMER_ID,+ columnName: "link_id",+ oldValue: OLD_LINK_ID,}),]);console.log(deleteRes);@@ -49,12 +50,12 @@ async function main() {const deleteData = async ({dataSource,- eventId,+ customerId,columnName,oldValue,}: {dataSource: string;- eventId: string;+ customerId: string;columnName: string;oldValue: string;}) => {@@ -66,7 +67,7 @@ const deleteData = async ({Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,"Content-Type": "application/x-www-form-urlencoded",},- body: `delete_condition=event_id='${eventId}' and ${columnName}='${oldValue}'`,+ body: `delete_condition=customer_id='${customerId}' and ${columnName}='${oldValue}'`,},).then((res) => res.json());};