Skip to content

Link resplit script#4157

Open
pepeladeira wants to merge 10 commits into
mainfrom
link-resplit-script
Open

Link resplit script#4157
pepeladeira wants to merge 10 commits into
mainfrom
link-resplit-script

Conversation

@pepeladeira

@pepeladeira pepeladeira commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes
    • Corrects customer attribution for imported Tinybird sales by re-determining the correct referring affiliate/partner.
    • Reassigns customers to the proper destination links, including program and commission updates.
    • Migrates related lead/sale/click events to preserve reporting accuracy.
    • Resets and recalculates commissions and payouts as needed, including overpayment/clawback handling, and updates link totals.
  • Chores
    • Adds a dry-run mode with customer classification and detailed logging to preview changes before applying.

@vercel

vercel Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
dub Ready Ready Preview Jul 15, 2026 4:19pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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.

Changes

Beehiiv customer link resplitting

Layer / File(s) Summary
Classification and event migration helpers
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Adds runtime configuration, Tinybird sale-event classification, Rewardful fallback resolution, enrolled partner lookup, and Tinybird event migration or deletion helpers.
Partner group reassignment
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Creates or simulates destination links, updates customer assignments, corrects commissions and payouts, updates counters and totals, and migrates customer events.
Unattribution and batch execution
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Classifies source-link customers, detaches those without resolved affiliates, resets related commissions, deletes source-link events, and processes each configured source link with failure logging.

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
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately describes the main change: adding a link resplit script.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch link-resplit-script

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pepeladeira
pepeladeira marked this pull request as ready for review July 14, 2026 15:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (3)
apps/web/scripts/customers/beehiiv/fix-link-resplit.ts (3)

456-539: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Overpayment/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 the linkId inconsistency already found in one of these two near-identical paths, extracting a shared reconcilePayoutsForRemovedCommissions({ 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 win

Recommend extracting shared helpers between moveCustomerTbEvents and deleteCustomerTbEvents.

deleteCustomerTbEvents duplicates most of moveCustomerTbEvents'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 | 🔵 Trivial

Consider chunking group.customerIds / commission in arrays for very large groups.

prisma.customer.updateMany/commission.updateMany/commission.findMany throughout moveGroup and unattributeCustomers pass the full customerIds array via id: { 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

📥 Commits

Reviewing files that changed from the base of the PR and between 646e800 and 0daefd8.

📒 Files selected for processing (1)
  • apps/web/scripts/customers/beehiiv/fix-link-resplit.ts

Comment thread apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Comment thread apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Comment thread apps/web/scripts/customers/beehiiv/fix-link-resplit.ts Outdated
Comment thread apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Comment thread apps/web/scripts/customers/beehiiv/fix-link-resplit.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants