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 program import scripts, fix YAxis currencyFormatter

Steven Tey08fc3c1597f7
diff --git a/apps/web/scripts/fillout/backfill-customer-sales.ts b/apps/web/scripts/fillout/backfill-customer-sales.ts
deleted file mode 100644
index 805b8c8cd3..0000000000
--- a/apps/web/scripts/fillout/backfill-customer-sales.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-// @ts-nocheck some weird typing issues below
-
-import { createId } from "@/lib/api/create-id";
-import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
-import { prisma } from "@dub/prisma";
-import { nanoid } from "@dub/utils";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-import { z } from "zod";
-// import { recordSaleWithTimestamp } from "../../lib/tinybird";
-
-const invoicesToProcess: {
- customerExternalId: string;
- invoiceId: string;
- amountPaid: string;
- createdAt: string;
-}[] = [];
-
-// backfill customer sales (similar to backfill customer leads)
-async function main() {
- Papa.parse(fs.createReadStream("fillout-invoices-updated.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- customerExternalId: string;
- invoiceId: string;
- amountPaid: string;
- createdAt: string;
- };
- }) => {
- invoicesToProcess.push({
- customerExternalId: result.data.customerExternalId,
- invoiceId: result.data.invoiceId,
- amountPaid: result.data.amountPaid,
- createdAt: result.data.createdAt,
- });
- },
- complete: async () => {
- const customers = await prisma.customer.findMany({
- where: {
- projectId: "xxx",
- externalId: {
- in: invoicesToProcess.map((invoice) => invoice.customerExternalId),
- },
- },
- include: {
- link: true,
- },
- });
-
- const salesMetadata = invoicesToProcess
- .map((invoice) => {
- const customer = customers.find(
- (customer) => customer.externalId === invoice.customerExternalId,
- );
- if (!customer) {
- return null;
- }
- if (!customer.link) {
- console.log("Customer link not found:", invoice);
- return null;
- }
- return {
- // extra data for commission creation
- partnerId: customer.link.partnerId,
- // sale data
- timestamp: new Date(invoice.createdAt).toISOString(),
- customer_id: customer.id,
- event_id: nanoid(16),
- event_name: "Invoice paid",
- payment_processor: "stripe",
- invoice_id: invoice.invoiceId,
- amount: parseInt(invoice.amountPaid),
- currency: "usd",
- metadata: "",
- // click data
- identity_hash: customer.externalId,
- click_id: customer.clickId,
- link_id: customer.link.id,
- url: customer.link.url,
- ip: "",
- continent: "NA",
- country: "US",
- 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",
- };
- })
- .filter((invoice) => invoice !== null);
-
- const salesMetadataParsed = salesMetadata.map((e) =>
- saleEventSchemaTB
- .extend({
- timestamp: z.string(),
- })
- .parse(e),
- );
-
- console.table(salesMetadataParsed.slice(0, 10));
- console.log(salesMetadataParsed.length);
-
- // const tbRes = await recordSaleWithTimestamp(salesMetadataParsed);
- // console.log(tbRes);
-
- const commissionsToCreate = salesMetadata.map((e) => ({
- id: createId({ prefix: "cm_" }),
- programId: "prog_xxx",
- partnerId: e.partnerId!,
- rewardId: "rw_xxx",
- customerId: e.customer_id,
- linkId: e.link_id,
- eventId: e.event_id,
- invoiceId: e.invoice_id,
- quantity: 1,
- amount: e.amount,
- type: "sale" as const,
- currency: "usd",
- earnings: Math.round(e.amount * 0.3),
- status: "pending" as const,
- createdAt: new Date(e.timestamp),
- }));
-
- console.table(commissionsToCreate.slice(0, 10));
- const prismaRes = await prisma.commission.createMany({
- data: commissionsToCreate,
- skipDuplicates: true,
- });
- console.log(prismaRes);
-
- const statsByLink = salesMetadataParsed.reduce(
- (acc, sale) => {
- acc[sale.link_id] = {
- sales: (acc[sale.link_id]?.sales || 0) + 1,
- saleAmount: (acc[sale.link_id]?.saleAmount || 0) + sale.amount,
- };
- return acc;
- },
- {} as Record<
- string,
- {
- sales: number;
- saleAmount: number;
- }
- >,
- );
-
- console.log(
- JSON.stringify(Object.entries(statsByLink).slice(0, 10), null, 2),
- );
-
- for (const [linkId, stats] of Object.entries(statsByLink)) {
- const res = await prisma.link.update({
- where: { id: linkId },
- data: {
- sales: {
- increment: stats.sales,
- },
- saleAmount: {
- increment: stats.saleAmount,
- },
- },
- });
- console.log(
- `Updated ${linkId} to ${res.sales} sales (+${stats.sales} sales), ${res.saleAmount} saleAmount (+${stats.saleAmount} saleAmount)`,
- );
- }
- },
- });
-}
-
-main();
diff --git a/apps/web/scripts/partners/import-partners.ts b/apps/web/scripts/programs/1-import-partners.ts
similarity index 63%
rename from apps/web/scripts/partners/import-partners.ts
rename to apps/web/scripts/programs/1-import-partners.ts
index f30c122cd8..7b9bfb38f1 100644
--- a/apps/web/scripts/partners/import-partners.ts
+++ b/apps/web/scripts/programs/1-import-partners.ts
@@ -5,50 +5,52 @@ import * as Papa from "papaparse";
import { createAndEnrollPartner } from "../../lib/api/partners/create-and-enroll-partner";
const programId = "prog_xxx";
-const userId = "xxx";
+const userId = "user_xxx";
const groupId = "grp_xxx";
-const partnersToImport: {
+type PartnerData = {
name: string;
email: string;
username: string;
tenantId: string;
enrolledAt: Date;
-}[] = [];
+};
+const partnersToImport: PartnerData[] = [];
+// script to import partners into a program via CSV file
+// NOTE: Remove "server-only" and Axiom logging from handleApiError before running this script
async function main() {
Papa.parse(fs.createReadStream("partners.csv", "utf-8"), {
header: true,
skipEmptyLines: true,
- step: (result: {
- data: {
- userId: string;
- referral: string;
- firstName: string;
- lastName: string;
- email: string;
- createdAt: string;
- };
- }) => {
- partnersToImport.push({
- name: result.data.firstName + " " + result.data.lastName,
- email: result.data.email,
- username: result.data.referral,
- tenantId: result.data.userId,
- enrolledAt: new Date(result.data.createdAt),
- });
+ step: (result: { data: PartnerData }) => {
+ partnersToImport.push(result.data);
},
complete: async () => {
- console.table(partnersToImport);
+ console.log(`Found ${partnersToImport.length} partners to import`);
+
const program = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
},
include: {
workspace: true,
+ partners: {
+ include: {
+ partner: true,
+ },
+ },
},
});
- for (const partner of partnersToImport) {
+ const finalPartnersToImport = partnersToImport.filter(
+ (partner) =>
+ !program.partners.some((p) => p.partner.email === partner.email),
+ );
+ console.log(
+ `Found ${finalPartnersToImport.length} final partners to import`,
+ );
+
+ for (const partner of finalPartnersToImport) {
const enrolledPartner = await createAndEnrollPartner({
workspace: {
id: program.workspace.id,
diff --git a/apps/web/scripts/programs/2-import-partner-links.ts b/apps/web/scripts/programs/2-import-partner-links.ts
new file mode 100644
index 0000000000..e9841dcbae
--- /dev/null
+++ b/apps/web/scripts/programs/2-import-partner-links.ts
@@ -0,0 +1,92 @@
+import { ProcessedLinkProps } from "@/lib/types";
+import { prisma } from "@dub/prisma";
+import "dotenv-flow/config";
+import * as fs from "fs";
+import * as Papa from "papaparse";
+import { bulkCreateLinks } from "../../lib/api/links";
+
+const programId = "prog_xxx";
+const userId = "user_xxx";
+type PartnerLinkData = {
+ email: string;
+ username: string;
+};
+const partnerLinksToImport: PartnerLinkData[] = [];
+
+// script to import any additional partner links into a program via CSV file (run after 1-import-partners.ts)
+async function main() {
+ Papa.parse(fs.createReadStream("partner_links.csv", "utf-8"), {
+ header: true,
+ skipEmptyLines: true,
+ step: (result: { data: PartnerLinkData }) => {
+ partnerLinksToImport.push(result.data);
+ },
+ complete: async () => {
+ console.log(
+ `Found ${partnerLinksToImport.length} partner links to import`,
+ );
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ partners: {
+ where: {
+ partner: {
+ email: {
+ in: partnerLinksToImport.map((link) => link.email),
+ },
+ },
+ },
+ select: {
+ partner: true,
+ tenantId: true,
+ },
+ },
+ },
+ });
+ const partnerMap = new Map(
+ program.partners.map(({ partner, tenantId }) => [
+ partner.email,
+ {
+ id: partner.id,
+ tenantId,
+ },
+ ]),
+ );
+
+ const finalPartnerLinksToImport = partnerLinksToImport
+ .map((link) => {
+ const partner = partnerMap.get(link.email);
+ if (!partner) {
+ return null;
+ }
+ return {
+ domain: program.domain!,
+ key: link.username,
+ url: program.url!,
+ trackConversion: true,
+ programId,
+ partnerId: partner.id,
+ folderId: program.defaultFolderId,
+ userId,
+ projectId: program.workspaceId,
+ tenantId: partner.tenantId,
+ };
+ })
+ .filter(
+ (p): p is NonNullable<typeof p> => p !== null,
+ ) satisfies ProcessedLinkProps[];
+
+ await bulkCreateLinks({
+ links: finalPartnerLinksToImport,
+ skipRedisCache: true,
+ });
+ console.log(`imported ${finalPartnerLinksToImport.length} partner links`);
+ },
+ });
+}
+
+main();
diff --git a/apps/web/scripts/fillout/backfill-customer-leads.ts b/apps/web/scripts/programs/3-import-customer-leads.ts
similarity index 75%
rename from apps/web/scripts/fillout/backfill-customer-leads.ts
rename to apps/web/scripts/programs/3-import-customer-leads.ts
index 81af3a3996..5b1cfae3a9 100644
--- a/apps/web/scripts/fillout/backfill-customer-leads.ts
+++ b/apps/web/scripts/programs/3-import-customer-leads.ts
@@ -1,52 +1,47 @@
-// @ts-nocheck some weird typing issues below
-
import { createId } from "@/lib/api/create-id";
import { generateRandomName } from "@/lib/names";
import { prisma } from "@dub/prisma";
-import { nanoid } from "@dub/utils";
+import { Prisma } from "@dub/prisma/client";
+import { chunk, nanoid, prettyPrint } from "@dub/utils";
import "dotenv-flow/config";
import * as fs from "fs";
import * as Papa from "papaparse";
+import { syncPartnerLinksStats } from "../../lib/api/partners/sync-partner-links-stats";
import { recordLeadWithTimestamp } from "../../lib/tinybird/record-lead";
-let leadsToBackfill: {
+const programId = "prog_xxx";
+type CustomerData = {
customerExternalId: string;
partnerLinkKey: string;
- stripeCustomerId: string | null;
+ stripeCustomerId?: string;
timestamp: string;
-}[] = [];
+};
+const leadsToBackfill: CustomerData[] = [];
// script to backfill customers + leads
// we also use a batching logic for tinybird events ingestion
async function main() {
- Papa.parse(fs.createReadStream("fillout-customers-updated.csv", "utf-8"), {
+ Papa.parse(fs.createReadStream("customers.csv", "utf-8"), {
header: true,
skipEmptyLines: true,
- step: (result: {
- data: {
- userId: string;
- referral: string;
- stripeCustomerId: string;
- createdAt: string;
- };
- }) => {
- leadsToBackfill.push({
- customerExternalId: result.data.userId,
- partnerLinkKey: result.data.referral,
- stripeCustomerId: result.data.stripeCustomerId || null,
- timestamp: result.data.createdAt,
- });
+ step: (result: { data: CustomerData }) => {
+ leadsToBackfill.push(result.data);
},
complete: async () => {
- const workspace = await prisma.project.findUniqueOrThrow({
+ console.table(leadsToBackfill);
+ const program = await prisma.program.findUniqueOrThrow({
where: {
- id: "xxx",
+ id: programId,
+ },
+ include: {
+ workspace: true,
},
});
+ const { workspace } = program;
const partnerLinks = await prisma.link.findMany({
where: {
- domain: "try.fillout.com",
+ domain: program.domain!,
key: {
in: leadsToBackfill.map((lead) => lead.partnerLinkKey),
},
@@ -108,7 +103,7 @@ async function main() {
trigger: "link",
};
})
- .filter((c) => c !== null);
+ .filter((p): p is NonNullable<typeof p> => p !== null);
// clickhouse only supports max 12 partitions (months) for a given event backfill
// so we need to transform this into a list of lists, one for each year
@@ -164,7 +159,9 @@ async function main() {
createdAt: new Date(lead.timestamp).toISOString(),
};
})
- .filter((c) => c !== null);
+ .filter(
+ (p): p is NonNullable<typeof p> => p !== null,
+ ) satisfies Prisma.CustomerCreateManyInput[];
console.table(customersToCreate.slice(0, 10));
@@ -172,7 +169,7 @@ async function main() {
data: customersToCreate,
skipDuplicates: true,
});
- console.log("backfilled customers", JSON.stringify(customerRes, null, 2));
+ console.log("backfilled customers", prettyPrint(customerRes));
const leadsToCreate = clicksToCreate.map((clickData, idx) => ({
...clickData,
@@ -198,7 +195,7 @@ async function main() {
const leadsBatch = leads as typeof leadsToCreate;
console.log(`backfilling ${leadsBatch.length} leads for ${year}`);
const leadRes = await recordLeadWithTimestamp(leadsBatch);
- console.log("backfilled leads", JSON.stringify(leadRes, null, 2));
+ console.log("backfilled leads", prettyPrint(leadRes));
});
const statsByLink = finalLeadsToBackfill
@@ -236,25 +233,38 @@ async function main() {
>,
);
- console.log(
- JSON.stringify(Object.entries(statsByLink).slice(0, 10), null, 2),
- );
+ console.log(prettyPrint(Object.entries(statsByLink).slice(0, 10)));
- for (const [linkId, stats] of Object.entries(statsByLink)) {
- const res = await prisma.link.update({
- where: { id: linkId },
- data: {
- clicks: {
- increment: stats.clicks,
- },
- leads: {
- increment: stats.leads,
- },
- lastLeadAt: stats.lastLeadAt,
- },
- });
+ const statsByLinkChunks = chunk(Object.entries(statsByLink), 50);
+ for (let i = 0; i < statsByLinkChunks.length; i++) {
+ const chunk = statsByLinkChunks[i];
console.log(
- `Updated ${linkId} to ${res.clicks} clicks (+${stats.clicks} clicks), ${res.leads} leads (+${stats.leads} leads)`,
+ `backfilling stats for ${chunk.length} links in batch ${i + 1} of ${statsByLinkChunks.length}`,
+ );
+ await Promise.all(
+ chunk.map(async ([linkId, stats]) => {
+ const res = await prisma.link.update({
+ where: { id: linkId },
+ data: {
+ clicks: {
+ increment: stats.clicks,
+ },
+ leads: {
+ increment: stats.leads,
+ },
+ lastLeadAt: stats.lastLeadAt,
+ },
+ });
+ console.log(
+ `Updated ${linkId} to ${res.clicks} clicks (+${stats.clicks} clicks), ${res.leads} leads (+${stats.leads} leads)`,
+ );
+ const syncRes = await syncPartnerLinksStats({
+ partnerId: res.partnerId!,
+ programId: program.id,
+ eventType: "lead",
+ });
+ console.log("synced stats", prettyPrint(syncRes));
+ }),
);
}
},
diff --git a/apps/web/scripts/fillout/export-stripe-invoices.ts b/apps/web/scripts/programs/4-export-stripe-invoices.ts
similarity index 66%
rename from apps/web/scripts/fillout/export-stripe-invoices.ts
rename to apps/web/scripts/programs/4-export-stripe-invoices.ts
index 0cf19dd104..7b7271bd16 100644
--- a/apps/web/scripts/fillout/export-stripe-invoices.ts
+++ b/apps/web/scripts/programs/4-export-stripe-invoices.ts
@@ -4,37 +4,27 @@ import * as fs from "fs";
import * as Papa from "papaparse";
import { stripeAppClient } from "../../lib/stripe";
-const programId = "prog_xxx";
-const customersToImport: {
- externalId: string;
- referralLink: string;
- createdAt: Date;
- stripeCustomerId: string;
-}[] = [];
+const programId = "prog_1K89GZ21QE2YC296FHHBMCFSM";
+type CustomerData = {
+ customerExternalId: string;
+ partnerLinkKey: string;
+ stripeCustomerId?: string;
+ timestamp: string;
+};
+const customersToImport: CustomerData[] = [];
// script to export stripe invoices based on the customer's stripeCustomerId
async function main() {
- Papa.parse(fs.createReadStream("fillout-customers-updated.csv", "utf-8"), {
+ Papa.parse(fs.createReadStream("customers.csv", "utf-8"), {
header: true,
skipEmptyLines: true,
- step: (result: {
- data: {
- userId: string;
- referral: string;
- stripeCustomerId: string;
- createdAt: string;
- };
- }) => {
+ step: (result: { data: CustomerData }) => {
if (result.data.stripeCustomerId) {
- customersToImport.push({
- externalId: result.data.userId,
- referralLink: result.data.referral,
- createdAt: new Date(result.data.createdAt),
- stripeCustomerId: result.data.stripeCustomerId,
- });
+ customersToImport.push(result.data);
}
},
complete: async () => {
+ console.log(`Found ${customersToImport.length} paying customers`);
const program = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
@@ -63,7 +53,7 @@ async function main() {
);
const invoicesToBackfill = invoices.data.map((invoice) => ({
- customerExternalId: customer.externalId,
+ customerExternalId: customer.customerExternalId,
invoiceId: invoice.id,
amountPaid: invoice.amount_paid,
createdAt: new Date(invoice.created * 1000).toISOString(),
@@ -77,9 +67,12 @@ async function main() {
"createdAt",
]);
+ const filePath = "customer_stripe_invoices.csv";
+ const fileExists = fs.existsSync(filePath);
+
fs.appendFileSync(
- "fillout-invoices-updated.csv",
- Papa.unparse(invoicesToBackfill, { header: false }) + "\n",
+ filePath,
+ Papa.unparse(invoicesToBackfill, { header: !fileExists }) + "\n",
);
}
}
diff --git a/apps/web/scripts/programs/5-import-customer-sales.ts b/apps/web/scripts/programs/5-import-customer-sales.ts
new file mode 100644
index 0000000000..5abe1bc8cc
--- /dev/null
+++ b/apps/web/scripts/programs/5-import-customer-sales.ts
@@ -0,0 +1,276 @@
+import { createId } from "@/lib/api/create-id";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
+import { RewardProps } from "@/lib/types";
+import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
+import { prisma } from "@dub/prisma";
+import { chunk, nanoid, prettyPrint } from "@dub/utils";
+import "dotenv-flow/config";
+import * as fs from "fs";
+import * as Papa from "papaparse";
+import { z } from "zod";
+import { syncTotalCommissions } from "../../lib/api/partners/sync-total-commissions";
+import { recordSaleWithTimestamp } from "../../lib/tinybird";
+
+const programId = "prog_xxx";
+const groupId = "grp_xxx";
+
+type InvoiceData = {
+ customerExternalId: string;
+ invoiceId: string;
+ amountPaid: string;
+ createdAt: string;
+};
+const invoicesToProcess: InvoiceData[] = [];
+
+// script to import customer sales (similar to 3-import-customer-leads.ts)
+async function main() {
+ Papa.parse(fs.createReadStream("customer_stripe_invoices.csv", "utf-8"), {
+ header: true,
+ skipEmptyLines: true,
+ step: (result: { data: InvoiceData }) => {
+ invoicesToProcess.push(result.data);
+ },
+ complete: async () => {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: true,
+ rewards: {
+ where: {
+ salePartnerGroup: {
+ id: groupId,
+ },
+ },
+ },
+ },
+ });
+
+ const reward = program.rewards[0];
+ if (!reward) {
+ throw new Error("No sale reward found for group " + groupId);
+ }
+
+ const customers = await prisma.customer.findMany({
+ where: {
+ projectId: program.workspace.id,
+ externalId: {
+ in: invoicesToProcess.map((invoice) => invoice.customerExternalId),
+ },
+ },
+ include: {
+ link: true,
+ },
+ });
+
+ const salesMetadata = invoicesToProcess
+ .map((invoice) => {
+ // don't process invoices with amount 0
+ if (invoice.amountPaid === "0") {
+ return null;
+ }
+ const customer = customers.find(
+ (customer) => customer.externalId === invoice.customerExternalId,
+ );
+ if (!customer) {
+ return null;
+ }
+ if (!customer.link) {
+ console.log("Customer link not found:", invoice);
+ return null;
+ }
+ return {
+ // extra data for commission creation
+ partnerId: customer.link.partnerId,
+ // sale data
+ timestamp: new Date(invoice.createdAt).toISOString(),
+ customer_id: customer.id,
+ event_id: nanoid(16),
+ event_name: "Invoice paid",
+ payment_processor: "stripe",
+ invoice_id: invoice.invoiceId,
+ amount: parseInt(invoice.amountPaid),
+ currency: "usd",
+ metadata: "",
+ // click data
+ identity_hash: customer.externalId,
+ click_id: customer.clickId,
+ link_id: customer.link.id,
+ url: customer.link.url,
+ ip: "",
+ continent: "NA",
+ country: "US",
+ 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",
+ };
+ })
+ .filter((p): p is NonNullable<typeof p> => p !== null);
+
+ const salesMetadataParsed = salesMetadata.map((e) =>
+ saleEventSchemaTB
+ .extend({
+ timestamp: z.string(),
+ })
+ .parse(e),
+ );
+
+ console.table(salesMetadataParsed.slice(0, 10));
+ console.log(salesMetadataParsed.length);
+
+ const tbRes = await recordSaleWithTimestamp(salesMetadataParsed);
+ console.log(tbRes);
+
+ const commissionsToCreate = salesMetadata.map((e) => ({
+ id: createId({ prefix: "cm_" }),
+ programId,
+ partnerId: e.partnerId!,
+ rewardId: reward.id,
+ customerId: e.customer_id,
+ linkId: e.link_id,
+ eventId: e.event_id,
+ invoiceId: e.invoice_id,
+ quantity: 1,
+ amount: e.amount,
+ type: "sale" as const,
+ currency: "usd",
+ earnings: calculateSaleEarnings({
+ reward: reward as RewardProps,
+ sale: {
+ quantity: 1,
+ amount: e.amount,
+ },
+ }),
+ // // mark all commission until nov 30 as paid
+ // status: (new Date(e.timestamp) < new Date("2025-12-01")
+ // ? "paid"
+ // : "pending") as CommissionStatus,
+ createdAt: new Date(e.timestamp),
+ }));
+
+ console.table(commissionsToCreate.slice(0, 10));
+ const prismaRes = await prisma.commission.createMany({
+ data: commissionsToCreate,
+ skipDuplicates: true,
+ });
+ console.log(prismaRes);
+
+ const statsByLink = salesMetadataParsed.reduce(
+ (acc, sale) => {
+ acc[sale.link_id] = {
+ sales: (acc[sale.link_id]?.sales || 0) + 1,
+ saleAmount: (acc[sale.link_id]?.saleAmount || 0) + sale.amount,
+ customerIds: new Set([
+ ...(acc[sale.link_id]?.customerIds || []),
+ sale.customer_id,
+ ]),
+ };
+ return acc;
+ },
+ {} as Record<
+ string,
+ {
+ sales: number;
+ saleAmount: number;
+ customerIds: Set<string>;
+ }
+ >,
+ );
+
+ console.log(prettyPrint(Object.entries(statsByLink).slice(0, 10)));
+
+ const statsByLinkChunks = chunk(Object.entries(statsByLink), 50);
+ for (let i = 0; i < statsByLinkChunks.length; i++) {
+ const chunk = statsByLinkChunks[i];
+ console.log(
+ `backfilling stats for ${chunk.length} links in batch ${i + 1} of ${statsByLinkChunks.length}`,
+ );
+ await Promise.all(
+ chunk.map(async ([linkId, stats]) => {
+ const res = await prisma.link.update({
+ where: { id: linkId },
+ data: {
+ sales: {
+ increment: stats.sales,
+ },
+ saleAmount: {
+ increment: stats.saleAmount,
+ },
+ conversions: stats.customerIds.size,
+ },
+ });
+ console.log(
+ `Updated ${linkId} to ${res.sales} sales (+${stats.sales} sales), ${res.saleAmount} saleAmount (+${stats.saleAmount} saleAmount), ${res.conversions} conversions (+${stats.customerIds.size} conversions)`,
+ );
+ const syncRes = await syncTotalCommissions({
+ partnerId: res.partnerId!,
+ programId: program.id,
+ });
+ console.log("synced total commissions", prettyPrint(syncRes));
+ }),
+ );
+ }
+
+ const statsByCustomer = salesMetadataParsed.reduce(
+ (acc, sale) => {
+ acc[sale.customer_id] = {
+ sales: (acc[sale.customer_id]?.sales || 0) + 1,
+ saleAmount: (acc[sale.customer_id]?.saleAmount || 0) + sale.amount,
+ };
+ return acc;
+ },
+ {} as Record<
+ string,
+ {
+ sales: number;
+ saleAmount: number;
+ }
+ >,
+ );
+ console.log(prettyPrint(Object.entries(statsByCustomer).slice(0, 10)));
+
+ const statsByCustomerChunks = chunk(Object.entries(statsByCustomer), 50);
+ for (let i = 0; i < statsByCustomerChunks.length; i++) {
+ const chunk = statsByCustomerChunks[i];
+ console.log(
+ `backfilling stats for ${chunk.length} customers in batch ${i + 1} of ${statsByCustomerChunks.length}`,
+ );
+ await Promise.all(
+ chunk.map(async ([customerId, stats]) => {
+ const res = await prisma.customer.update({
+ where: { id: customerId },
+ data: {
+ sales: { increment: stats.sales },
+ saleAmount: { increment: stats.saleAmount },
+ },
+ });
+ console.log(
+ `Updated ${customerId} to ${res.sales} sales (+${stats.sales} sales), ${res.saleAmount} saleAmount (+${stats.saleAmount} saleAmount)`,
+ );
+ }),
+ );
+ }
+ },
+ });
+}
+
+main();
diff --git a/apps/web/ui/analytics/analytics-area-chart.tsx b/apps/web/ui/analytics/analytics-area-chart.tsx
index 111b70d40f..d5c560f2de 100644
--- a/apps/web/ui/analytics/analytics-area-chart.tsx
+++ b/apps/web/ui/analytics/analytics-area-chart.tsx
@@ -177,7 +177,10 @@ export function AnalyticsAreaChart({
showGridLines
tickFormat={
resource === "sales" && saleUnit === "saleAmount"
- ? (v) => `$${nFormatter(v)}`
+ ? (v) =>
+ currencyFormatter(v, {
+ trailingZeroDisplay: "stripIfInteger",
+ })
: nFormatter
}
/>
diff --git a/packages/email/src/templates/connect-payout-reminder.tsx b/packages/email/src/templates/connect-payout-reminder.tsx
index cdef3795af..1fbcfc2238 100644
--- a/packages/email/src/templates/connect-payout-reminder.tsx
+++ b/packages/email/src/templates/connect-payout-reminder.tsx
@@ -22,7 +22,7 @@ export default function ConnectPayoutReminder({
{
id: "1",
name: "Acme",
- logo: "https://dubassets.com/programs/prog_CYCu7IMAapjkRpTnr8F1azjN/logo_ObfFYsM",
+ logo: "https://dubassets.com/programs/prog_CYCu7IMAapjkRpTnr8F1azjN/logo_HPEaC8P",
amount: 120_00,
},
{