The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
script improvements
Pedro Ladeira7be20c1cb1a9
diff --git a/apps/web/scripts/customers/beehiiv/reassign-tinybird.ts b/apps/web/scripts/customers/beehiiv/reassign-tinybird.tsindex ce66362b1b..c20d9be257 100644--- a/apps/web/scripts/customers/beehiiv/reassign-tinybird.ts+++ b/apps/web/scripts/customers/beehiiv/reassign-tinybird.ts@@ -15,6 +15,16 @@ const getRawCustomerEvents = tb.buildPipe({data: z.any(),});+async function parseTinybirdResponse(res: Response) {+ const text = await res.text();++ if (!res.ok) {+ throw new Error(`Tinybird request failed (${res.status}): ${text}`);+ }++ return text ? JSON.parse(text) : null;+}+async function tbDelete(dataSource: string, condition: string) {if (DRY_RUN) {console.log(` [dry] DELETE ${dataSource} WHERE ${condition}`);@@ -27,8 +37,8 @@ async function tbDelete(dataSource: string, condition: string) {Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,"Content-Type": "application/x-www-form-urlencoded",},- body: `delete_condition=${condition}`,- }).then((r) => r.json());+ body: new URLSearchParams({ delete_condition: condition }),+ }).then(parseTinybirdResponse);console.log(` deleted ${dataSource}: ${JSON.stringify(res)}`);}@@ -36,9 +46,12 @@ async function tbDelete(dataSource: string, condition: string) {async function tbIngest(datasource: string, payload: unknown) {return fetch(`${TB_BASE}/v0/events?name=${datasource}&wait=true`, {method: "POST",- headers: { Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}` },+ headers: {+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,+ "Content-Type": "application/json",+ },body: JSON.stringify(payload),- }).then((r) => r.json());+ }).then(parseTinybirdResponse);}// Move a single customer's events from `oldLinkId` to `newLinkId`.@@ -65,7 +78,9 @@ export async function moveCustomerEvents({return;}- const { data: events } = await getRawCustomerEvents({ customerId });+ const { data: allEvents } = await getRawCustomerEvents({ customerId });++ const events = allEvents.filter((e: any) => e.link_id === oldLinkId);const sales = events.filter((e: any) => "amount" in e && e.amount !== null && e.amount !== undefined,@@ -116,7 +131,7 @@ export async function moveCustomerEvents({if (customer?.clickId) {const click = await getClickEvent({ clickId: customer.clickId });- if (click) {+ if (click && click.link_id === oldLinkId) {console.log(` 1 click event (${customer.clickId})`);if (!DRY_RUN) {@@ -128,8 +143,10 @@ export async function moveCustomerEvents({}const condition = `click_id='${customer.clickId}' and link_id='${oldLinkId}'`;+await tbDelete("dub_click_events_mv", condition);await tbDelete("dub_click_events_id", condition);+ await tbDelete("dub_click_events", condition);}}}diff --git a/apps/web/scripts/customers/beehiiv/reassign-utils.ts b/apps/web/scripts/customers/beehiiv/reassign-utils.tsindex b43539f0da..0b75b4dafb 100644--- a/apps/web/scripts/customers/beehiiv/reassign-utils.ts+++ b/apps/web/scripts/customers/beehiiv/reassign-utils.ts@@ -87,15 +87,37 @@ export function parseCsv(content: string): string[][] {export function loadCrossref(csvPath: string): CrossrefRow[] {const content = readFileSync(csvPath, "utf-8");- const [, ...dataRows] = parseCsv(content);+ const [header, ...dataRows] = parseCsv(content);++ if (!header || header.length === 0) {+ throw new Error(`Crossref CSV is empty or has no header: ${csvPath}`);+ }++ const normalized = header.map((h) => h.trim().toLowerCase());+ const columnIndex = (name: string): number => {+ const idx = normalized.indexOf(name.toLowerCase());+ if (idx === -1) {+ throw new Error(+ `Crossref CSV is missing the "${name}" column. Found: [${header.join(", ")}]`,+ );+ }+ return idx;+ };++ const stripeIdx = columnIndex("Stripe Customer ID");+ const customerEmailIdx = columnIndex("Customer Email");+ const affiliateEmailIdx = columnIndex("Rewardful Affiliate Email");+ const partnerEmailIdx = columnIndex("Dub Partner Email");return dataRows- .filter((r) => r.length >= 7 && r[0]?.startsWith("cus_"))+ .filter((r) => r[stripeIdx]?.startsWith("cus_")).map((r) => ({- stripeCustomerId: r[0].trim(),- customerEmail: (r[2] || "").trim(),- rewardfulAffiliateEmail: (r[4] || "").trim().toLowerCase(),- dubPartnerEmail: (r[6] || "").trim().toLowerCase(),+ stripeCustomerId: r[stripeIdx].trim(),+ customerEmail: (r[customerEmailIdx] || "").trim(),+ rewardfulAffiliateEmail: (r[affiliateEmailIdx] || "")+ .trim()+ .toLowerCase(),+ dubPartnerEmail: (r[partnerEmailIdx] || "").trim().toLowerCase(),}));}@@ -121,6 +143,18 @@ export function buildOwnerMap(rows: CrossrefRow[]): Map<string, string> {for (const [customerId, counts] of byCustomer) {const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]);+ const topCount = sorted[0][1];+ const tiedTopOwners = sorted.filter(([, count]) => count === topCount);++ if (tiedTopOwners.length > 1) {+ console.warn(+ `⚠️ Customer ${customerId} has an ambiguous affiliate owner (tie between ${tiedTopOwners+ .map(([email]) => email)+ .join(", ")}); skipping reassignment.`,+ );+ continue;+ }+if (sorted.length > 1) {console.warn(`⚠️ Customer ${customerId} maps to multiple affiliates: ${sorted