Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@steven-tey
Copy link
Collaborator

@steven-tey steven-tey commented Aug 4, 2025

Summary by CodeRabbit

  • Performance Improvements

    • Enhanced commission import efficiency by batching customer and lead event data retrieval, reducing redundant queries and improving processing speed.
  • Refactor

    • Centralized lead event fetching logic into a reusable module for improved code organization and maintainability.
  • Bug Fixes

    • Updated email template download link to correct API endpoint path.

@vercel
Copy link
Contributor

vercel bot commented Aug 4, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
dub ✅ Ready (Inspect) Visit Preview Aug 4, 2025 2:46am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

This update introduces batched fetching of customer and lead event data in the commission import process, refactors related functions to accept pre-fetched datasets, modularizes the Tinybird lead events pipe into a reusable library, and adjusts the backfill script to use this shared module. Additionally, a new Tinybird pipe is added for lead events, and an email template URL is updated.

Changes

Cohort / File(s) Change Summary
Commission Import Refactor
apps/web/lib/rewardful/import-commissions.ts
Refactored to prefetch all relevant customers and their lead events in batches, passing these datasets to createCommission for efficiency. Function signatures updated accordingly.
Tinybird Lead Events Module & Pipe
apps/web/lib/tinybird/get-lead-events.ts, pipes/get_lead_events.pipe
Added new Tinybird pipe get_lead_events.pipe querying lead events by customer IDs. Created a new module exporting getLeadEvents wrapping this pipe with Zod validation.
Backfill Script Refactor
apps/web/scripts/backfill-customers.ts
Refactored to import getLeadEvents from the new shared module, removing its inline definition and promoting reuse.
Email Template Update
packages/email/src/templates/program-imported.tsx
Updated the import logs download URL by inserting "workspaces" into the API path.

Sequence Diagram(s)

sequenceDiagram
    participant Importer as importCommissions
    participant DB as Prisma DB
    participant TB as Tinybird
    participant Creator as createCommission

    Importer->>DB: Fetch customers by stripeCustomerId (batch)
    Importer->>TB: getLeadEvents for customerIds (batch)
    loop For each commission in batch
        Importer->>Creator: Pass commission, customersData, customerLeadEvents
        Creator->>Creator: Lookup customer & leadEvent in prefetched data
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A batch of bunnies, quick and bright,
Prefetch their carrots before the night.
No more hopping back and forth,
They gather all their treats up north.
With tidy code and pipes anew,
This rabbit says, “Efficiency—woohoo!” 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve-commissions-import

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@steven-tey
Copy link
Collaborator Author

@CodeRabbit please do a final review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

@steven-tey I'll conduct a final review of the PR focusing on the commission import efficiency improvements and the getLeadEvents implementation.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/web/lib/tinybird/get-lead-events.ts (1)

1-11: Well-structured reusable module for lead events fetching.

The implementation correctly extracts the Tinybird pipe construction into a shared module, promoting code reuse and maintainability. The use of Zod validation for both parameters and data ensures type safety.

Consider adding JSDoc documentation to improve developer experience:

+/**
+ * Fetches lead events from Tinybird for the specified customer IDs.
+ * @param customerIds - Array of customer IDs to fetch lead events for
+ * @returns Promise resolving to lead events data
+ */
 export const getLeadEvents = tb.buildPipe({
   pipe: "get_lead_events",
   parameters: z.object({
     customerIds: z.string().array(),
   }),
   data: leadEventSchemaTB,
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac82184 and bf5f4b4.

📒 Files selected for processing (3)
  • apps/web/lib/rewardful/import-commissions.ts (7 hunks)
  • apps/web/lib/tinybird/get-lead-events.ts (1 hunks)
  • apps/web/scripts/backfill-customers.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: in apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward conditi...
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/rewards-logic.tsx:268-275
Timestamp: 2025-07-30T15:29:54.131Z
Learning: In apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward condition, dependent fields (attribute, operator, value) should be reset rather than preserved because different entities (customer vs sale) have different available attributes. Maintaining existing fields when the entity changes would create invalid state combinations and confusing UX.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
📚 Learning: in the partnerprogramsummary email template (packages/email/src/templates/partner-program-summary.ts...
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:0-0
Timestamp: 2025-05-29T04:45:18.504Z
Learning: In the PartnerProgramSummary email template (packages/email/src/templates/partner-program-summary.tsx), the stat titles are hardcoded constants ("Clicks", "Leads", "Sales", "Earnings") that will always match the ICONS object keys after toLowerCase() conversion, so icon lookup failures are not possible.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
📚 Learning: in apps/web/lib/api/links/bulk-create-links.ts, the team accepts the risk of potential undefined res...
Learnt from: devkiran
PR: dubinc/dub#2177
File: apps/web/lib/api/links/bulk-create-links.ts:66-84
Timestamp: 2025-06-06T07:59:03.120Z
Learning: In apps/web/lib/api/links/bulk-create-links.ts, the team accepts the risk of potential undefined results from links.find() operations when building invalidLinks arrays, because existing links are fetched from the database based on the input links, so matches are expected to always exist.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (6)
apps/web/scripts/backfill-customers.ts (1)

5-5: Clean refactor to use the shared getLeadEvents module.

The import statement correctly references the new shared module, eliminating code duplication while maintaining the existing functionality of the backfill script.

apps/web/lib/rewardful/import-commissions.ts (5)

5-5: Appropriate imports for the batch processing refactor.

The new imports support the performance optimization:

  • Customer, Link types for the prefetched data structures
  • getLeadEvents from the new shared module
  • LeadEventTB type for the lead events array

Also applies to: 9-9, 12-12


55-70: Excellent performance optimization with batch data fetching.

This change eliminates the N+1 query problem by:

  1. Prefetching all customers for the current batch of commissions
  2. Bulk fetching lead events for all customers at once
  3. Passing the prefetched data to avoid repeated queries

The implementation correctly extracts Stripe customer IDs from commissions, filters out null values, and includes the related link data needed downstream.


138-139: Updated function signature to support batch processing.

The createCommission function now accepts the prefetched datasets as parameters, enabling in-memory lookups instead of individual database queries. The type annotations correctly reflect the data structures with included relations.

Also applies to: 146-147


250-253: Efficient in-memory lookup replaces database query.

The customer lookup now uses the prefetched customersData array instead of a Prisma query, significantly improving performance by eliminating database round trips.


303-305: Streamlined lead event processing with prefetched data.

The changes correctly:

  1. Use array lookup instead of API call for lead events (lines 303-305)
  2. Simplify the existence check by removing the data length validation (line 307)
  3. Parse the lead event object directly instead of accessing data[0] (line 321)

This maintains the same validation logic while leveraging the batch-fetched data for better performance.

Also applies to: 307-307, 321-321

@steven-tey
Copy link
Collaborator Author

@CodeRabbit final review like your life depends on it

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll conduct an extremely thorough review of every aspect of this efficiency improvement. Let me examine the actual implementation details to ensure everything is bulletproof.


🏁 Script executed:

#!/bin/bash
# Get the complete implementation of all three modified files
echo "=== apps/web/lib/rewardful/import-commissions.ts ==="
cat apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== apps/web/lib/tinybird/get-lead-events.ts ==="
cat apps/web/lib/tinybird/get-lead-events.ts

echo -e "\n=== apps/web/scripts/backfill-customers.ts ==="
cat apps/web/scripts/backfill-customers.ts

Length of output: 13318


@steven-tey
Copy link
Collaborator Author

@coderabbitai final review please

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the current implementation to assess final state
echo "=== Current import-commissions.ts implementation ==="
cat apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== Current get-lead-events.ts implementation ==="
cat apps/web/lib/tinybird/get-lead-events.ts

echo -e "\n=== Check for any error handling improvements ==="
rg -A 5 -B 2 "try|catch|error" apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== Verify the batching logic and edge cases ==="
rg -A 3 -B 3 "customersData.*length|customerLeadEvents" apps/web/lib/rewardful/import-commissions.ts

Length of output: 12343


@steven-tey
Copy link
Collaborator Author

@coderabbitai final review please

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the current state of the import-commissions.ts file to see if error handling was added
echo "=== Checking for error handling improvements in import-commissions.ts ==="
cat apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== Look for try-catch blocks specifically ==="
rg -A 10 -B 5 "try\s*{|catch" apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== Check if batch operations are wrapped in error handling ==="
rg -A 5 -B 5 "customersData.*=.*await|customerLeadEvents.*=.*await" apps/web/lib/rewardful/import-commissions.ts

echo -e "\n=== Verify if empty array check was added ==="
rg -A 3 -B 3 "customersData\.length|\.length.*>" apps/web/lib/rewardful/import-commissions.ts

Length of output: 11641


Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
pipes/get_lead_events.pipe (1)

3-13: Consider query optimization for better performance.

The SQL query structure is solid with proper parameterization and conditional logic. However, consider these optimizations:

  1. Column selection: Using SELECT * might be inefficient if not all columns are needed. Consider selecting only required columns.
  2. Result limiting: Without a LIMIT clause, this could return very large datasets for customers with many lead events.

Consider this optimization if only specific columns are needed:

-    SELECT *
+    SELECT customer_id, timestamp, event_type, /* other required columns */
     FROM dub_lead_events

Or add pagination support:

     ORDER BY timestamp DESC
+    {% if defined(limit) %} LIMIT {{ Int32(limit, 1000) }} {% end %}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf5f4b4 and ac92db0.

📒 Files selected for processing (2)
  • packages/email/src/templates/program-imported.tsx (1 hunks)
  • pipes/get_lead_events.pipe (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/email/src/templates/program-imported.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (2)
pipes/get_lead_events.pipe (2)

1-2: LGTM! Token definition follows best practices.

The read-only token is appropriately scoped for a data fetching endpoint.


14-17: LGTM! Proper endpoint type definition.

The endpoint type is correctly specified for HTTP access, and the file structure follows Tinybird conventions.

@steven-tey
Copy link
Collaborator Author

@CodeRabbit final review please, you didn't provide one before

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

No description provided.

@steven-tey
Copy link
Collaborator Author

@CodeRabbit full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac82184 and ac92db0.

📒 Files selected for processing (5)
  • apps/web/lib/rewardful/import-commissions.ts (7 hunks)
  • apps/web/lib/tinybird/get-lead-events.ts (1 hunks)
  • apps/web/scripts/backfill-customers.ts (1 hunks)
  • packages/email/src/templates/program-imported.tsx (1 hunks)
  • pipes/get_lead_events.pipe (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: in apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward conditi...
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/rewards-logic.tsx:268-275
Timestamp: 2025-07-30T15:29:54.131Z
Learning: In apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward condition, dependent fields (attribute, operator, value) should be reset rather than preserved because different entities (customer vs sale) have different available attributes. Maintaining existing fields when the entity changes would create invalid state combinations and confusing UX.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
📚 Learning: in the partnerprogramsummary email template (packages/email/src/templates/partner-program-summary.ts...
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:0-0
Timestamp: 2025-05-29T04:45:18.504Z
Learning: In the PartnerProgramSummary email template (packages/email/src/templates/partner-program-summary.tsx), the stat titles are hardcoded constants ("Clicks", "Leads", "Sales", "Earnings") that will always match the ICONS object keys after toLowerCase() conversion, so icon lookup failures are not possible.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
📚 Learning: in apps/web/lib/api/links/bulk-create-links.ts, the team accepts the risk of potential undefined res...
Learnt from: devkiran
PR: dubinc/dub#2177
File: apps/web/lib/api/links/bulk-create-links.ts:66-84
Timestamp: 2025-06-06T07:59:03.120Z
Learning: In apps/web/lib/api/links/bulk-create-links.ts, the team accepts the risk of potential undefined results from links.find() operations when building invalidLinks arrays, because existing links are fetched from the database based on the input links, so matches are expected to always exist.

Applied to files:

  • apps/web/lib/rewardful/import-commissions.ts
🧬 Code Graph Analysis (1)
apps/web/lib/tinybird/get-lead-events.ts (1)
apps/web/lib/zod/schemas/leads.ts (1)
  • leadEventSchemaTB (87-96)
🔇 Additional comments (8)
packages/email/src/templates/program-imported.tsx (1)

66-66: LGTM! API path restructuring implemented correctly.

The addition of "workspaces" to the download URL path aligns with the broader API restructuring mentioned in the PR objectives.

pipes/get_lead_events.pipe (1)

1-16: LGTM! Well-structured Tinybird pipe definition.

The pipe correctly implements:

  • Proper token definition with READ permissions
  • Conditional filtering by customerIds array using Tinybird's templating syntax
  • Appropriate ordering by timestamp DESC for recent events first
  • Clean SQL structure that selects all columns from dub_lead_events
apps/web/scripts/backfill-customers.ts (1)

5-5: LGTM! Clean refactor to use shared module.

The extraction of getLeadEvents from inline definition to a shared module promotes code reuse and maintainability, while keeping the same functionality.

apps/web/lib/tinybird/get-lead-events.ts (1)

1-11: LGTM! Well-implemented type-safe Tinybird pipe wrapper.

The module correctly implements:

  • Proper pipe name matching the Tinybird pipe definition
  • Type-safe parameter validation with Zod schema for customerIds array
  • Appropriate data schema using leadEventSchemaTB
  • Clean module structure following established patterns
apps/web/lib/rewardful/import-commissions.ts (4)

250-253: LGTM! Efficient in-memory customer lookup.

The replacement of individual Prisma queries with in-memory lookups using the pre-fetched customersData array significantly improves performance by eliminating N+1 database queries.


303-305: LGTM! Efficient in-memory lead event lookup.

The replacement of individual getLeadEvent calls with in-memory lookups using the pre-fetched customerLeadEvents array eliminates N+1 API calls and improves performance significantly.


307-321: LGTM! Correct handling of lead event data structure.

The logic correctly handles the lead event lookup and parsing:

  • Proper existence check for leadEvent
  • Updated parsing to use leadEvent directly instead of leadEvent.data
  • Maintains existing validation and error handling flow

55-70: Add robust error and edge‐case handling around batch fetch

Please update lines 55–70 of apps/web/lib/rewardful/import-commissions.ts to guard against failures and empty results when fetching customers and lead events:

  • Wrap both prisma.customer.findMany and getLeadEvents in a try/catch so one bad batch won’t crash the entire import loop.
  • Before calling getLeadEvents, check for an empty customersData array and skip or short-circuit that batch.
  • Validate that the response from getLeadEvents actually has a data property before using it.

Suggested diff:

@@ apps/web/lib/rewardful/import-commissions.ts
-    const customersData = await prisma.customer.findMany({
+    try {
+      const customersData = await prisma.customer.findMany({
         where: {
           stripeCustomerId: {
             in: commissions
               .map((commission) => commission.sale.referral.stripe_customer_id)
               .filter(Boolean),
           },
         },
         include: { link: true },
-    const customerLeadEvents = await getLeadEvents({
-      customerIds: customersData.map((customer) => customer.id),
-    }).then((res) => res.data);
+      });
+
+      if (customersData.length === 0) {
+        // No matching customers; skip this batch
+        continue;
+      }
+
+      const response = await getLeadEvents({
+        customerIds: customersData.map((c) => c.id),
+      });
+
+      if (!response?.data) {
+        throw new Error('Unexpected getLeadEvents response');
+      }
+
+      const customerLeadEvents = response.data;
+    } catch (error) {
+      console.error(`Batch fetch failed at page ${currentPage}:`, error);
+      // move on to next batch without halting the import
+      continue;
+    }

Please verify that:

  • Your loop variables (currentPage, processedBatches, etc.) still align with this flow.
  • getLeadEvents always returns an object with a data field in all success cases.

@steven-tey steven-tey merged commit 1c34642 into main Aug 4, 2025
7 of 8 checks passed
@steven-tey steven-tey deleted the improve-commissions-import branch August 4, 2025 02:49
@coderabbitai coderabbitai bot mentioned this pull request Oct 17, 2025
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.

2 participants