Link resplit script#4157
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR adds a Beehiiv customer resplitting script that classifies source-link customers using Tinybird sale metadata and Rewardful fallback data, reassigns resolved affiliates to dedicated Dub links, resets unattributed customers, corrects commissions and payouts, and migrates or deletes related events. ChangesBeehiiv customer link resplitting
Estimated code review effort: 5 (Critical) | ~90 minutes Sequence Diagram(s)sequenceDiagram
participant Operator
participant main
participant Tinybird
participant Rewardful
participant Dub
Operator->>main: configure DRY_RUN and SOURCE_LINK_IDS
main->>Tinybird: inspect imported sale metadata
Tinybird-->>main: affiliate classification data
main->>Rewardful: resolve missing affiliate data
Rewardful-->>main: referral affiliate or no result
main->>Dub: resolve partners and update customer attribution
main->>Dub: correct commissions and retally payouts
main->>Tinybird: migrate or delete customer events
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts (3)
456-539: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winOverpayment/clawback + retally block is duplicated almost verbatim in
unattributeCustomers(lines 708-791).Both blocks group paid-via-Dub commissions by
payoutId, create the same overpayment/clawback commission pair, and retally the same way. Given thelinkIdinconsistency already found in one of these two near-identical paths, extracting a sharedreconcilePayoutsForRemovedCommissions({ processedAndPaidCommissions, sourceLink, description })helper would reduce the chance of the two copies diverging again.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/web/scripts/customers/beehiiv/fix-link-resplit.ts` around lines 456 - 539, The overpayment/clawback and payout-retally logic is duplicated between the current flow and unattributeCustomers. Extract it into a shared reconcilePayoutsForRemovedCommissions helper accepting processedAndPaidCommissions, sourceLink, and description, then replace both inline blocks with calls to that helper while preserving dry-run behavior, commission metadata, and retally handling.
162-213: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRecommend extracting shared helpers between
moveCustomerTbEventsanddeleteCustomerTbEvents.
deleteCustomerTbEventsduplicates most ofmoveCustomerTbEvents's click-ID collection and per-datasource delete logic (lines 71-159). Extracting a shared "collect click IDs from sale/lead events" helper and a shared "delete sale/lead rows for customer+link" helper would reduce the risk of the two paths drifting (as already happened with the click base-table deletion asymmetry noted above).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/web/scripts/customers/beehiiv/fix-link-resplit.ts` around lines 162 - 213, Extract the duplicated click-ID collection and sale/lead deletion logic from moveCustomerTbEvents and deleteCustomerTbEvents into shared helpers. Reuse those helpers in both functions, preserving the existing customerId/oldLinkId filtering and deletion targets, including the click base-table behavior.
366-380: 🚀 Performance & Scalability | 🔵 TrivialConsider chunking
group.customerIds/ commissioninarrays for very large groups.
prisma.customer.updateMany/commission.updateMany/commission.findManythroughoutmoveGroupandunattributeCustomerspass the fullcustomerIdsarray viaid: { in: [...] }in a single query. For a large Beehiiv cohort this could produce very large parameter lists. The initial classification phase already chunks customers in batches of 20 (line 872); applying the same chunking to these bulk writes would keep query sizes predictable.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/web/scripts/customers/beehiiv/fix-link-resplit.ts` around lines 366 - 380, Chunk the customerIds and commission ID arrays used by moveGroup and unattributeCustomers into batches of 20, matching the existing classification batching, and execute each customer.updateMany, commission.updateMany, and commission.findMany operation per chunk while preserving their current filters and updates.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/web/scripts/customers/beehiiv/fix-link-resplit.ts`:
- Around line 53-68: Update tbDelete and the surrounding cleanup flow to retain
every failed deletion, including non-OK responses and fetch exceptions, as its
dataSource/condition pair instead of only logging it. After all
Promise.allSettled cleanup work completes, print a consolidated summary of the
failed pairs so they can be manually retried, while preserving successful
deletion behavior.
- Around line 950-962: Update main so each resplitLink(sourceLinkId) invocation
is wrapped in a per-link try/catch, allowing the loop to continue processing
subsequent SOURCE_LINK_IDS after a failure. Record the failed sourceLinkId and
error details during processing, then report the accumulated failures after the
loop completes.
- Around line 420-441: Update the processed/paid commission update in the
non-DRY_RUN branch to set linkId to newLink.id alongside partnerId, payoutId,
and status, matching the sibling non-processed update and keeping each
commission’s linkId/partnerId association consistent.
- Around line 383-389: Update the nonProcessedWhere filter in the
fix-link-resplit flow to include linkId scoped to sourceLink.id, matching the
processed/paid query. Apply the same linkId constraint in unattributeCustomers
so commission updates and cancellations only affect the source link’s
commissions for the specified customers.
- Around line 637-643: Update the nonProcessedWhere filter to include the target
linkId alongside customerId, ensuring cancellation only affects pending,
canceled, or unpaid commissions belonging to that link; preserve the existing
status conditions and unattributeCustomerIds filtering.
---
Nitpick comments:
In `@apps/web/scripts/customers/beehiiv/fix-link-resplit.ts`:
- Around line 456-539: The overpayment/clawback and payout-retally logic is
duplicated between the current flow and unattributeCustomers. Extract it into a
shared reconcilePayoutsForRemovedCommissions helper accepting
processedAndPaidCommissions, sourceLink, and description, then replace both
inline blocks with calls to that helper while preserving dry-run behavior,
commission metadata, and retally handling.
- Around line 162-213: Extract the duplicated click-ID collection and sale/lead
deletion logic from moveCustomerTbEvents and deleteCustomerTbEvents into shared
helpers. Reuse those helpers in both functions, preserving the existing
customerId/oldLinkId filtering and deletion targets, including the click
base-table behavior.
- Around line 366-380: Chunk the customerIds and commission ID arrays used by
moveGroup and unattributeCustomers into batches of 20, matching the existing
classification batching, and execute each customer.updateMany,
commission.updateMany, and commission.findMany operation per chunk while
preserving their current filters and updates.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 02947173-109f-4f7a-aa09-1e3db4ea5ba1
📒 Files selected for processing (1)
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Summary by CodeRabbit