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

Skip to content

Conversation

@devkiran
Copy link
Collaborator

@devkiran devkiran commented Aug 27, 2025

Summary by CodeRabbit

  • New Features

    • Added optional export columns: Commissions and Net Revenue.
    • Exports now automatically include expanded metric data when relevant columns are selected.
  • Improvements

    • More accurate typing in exports: numeric fields default to 0; text fields default to empty.
    • Dynamic handling of expanded metric fields for partner exports, reducing missing or partial data.
    • Date fields (Created At, Payouts Enabled At) retain existing formatting and ordering.

@vercel
Copy link
Contributor

vercel bot commented Aug 27, 2025

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

Project Deployment Preview Updated (UTC)
dub Ready Ready Preview Aug 27, 2025 7:07pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Adds expanded column metadata to partners schema, introduces includeExpandedFields in the partners export API to fetch expanded data when requested, updates numeric/string typing based on expanded columns, and adds totalCommissions and netRevenue columns to exports.

Changes

Cohort / File(s) Summary of changes
Partners export API
apps/web/app/(ee)/api/partners/export/route.ts
Compute expandedColumns from schema; determine includeExpandedFields based on requested columns; pass includeExpandedFields to getPartners; derive schemaFields types via expandedColumns.includes; retain ordering and date formatting.
Partners schema
apps/web/lib/zod/schemas/partners.ts
Extend exportPartnerColumns entries with expanded: boolean; add totalCommissions and netRevenue (expanded: true, default: false); adjust ordering; export shape now { id, label, default, expanded }; exportPartnerColumnsDefault remains derived from default.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant API as /api/partners/export
  participant S as getPartners(...)
  participant DB as Database

  C->>API: GET /partners/export?columns=...
  API->>API: Parse requested columns
  API->>API: expandedColumns = from schema
  API->>API: includeExpandedFields = any(requested ∩ expandedColumns)
  API->>S: getPartners({ includeExpandedFields, ... })
  S->>DB: Query partners (join/select expanded fields if requested)
  DB-->>S: Partners data
  S-->>API: Partners with/without expanded fields
  API->>API: Build schemaFields (numeric if in expandedColumns)
  API-->>C: Export response (ordered, formatted dates)

  note over API,S: New decision point: includeExpandedFields controls expanded fetch and typing
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • steven-tey

Poem

I thump my paws on columns wide,
Expanded fields now hop inside.
Commissions tall, net revenue bright,
We fetch just right, by moonlit byte.
A tidy warren of types aligned—
Exported trails, precisely defined. 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-csv-imports

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
apps/web/lib/zod/schemas/partners.ts (3)

106-111: OpenAPI/docs mismatch: use “totalCommissions” instead of “commissions”.

Public description should match field ids used elsewhere.

Apply:

-        "Whether to include stats fields on the partner (`clicks`, `leads`, `conversions`, `sales`, `saleAmount`, `commissions`, `netRevenue`). If false, those fields will be returned as 0.",
+        "Whether to include stats fields on the partner (`clicks`, `leads`, `conversions`, `sales`, `saleAmount`, `totalCommissions`, `netRevenue`). If false, those fields will be returned as 0.",

136-140: Filter/validate requested columns to avoid “undefined” CSV headers.

Unknown ids currently flow through, producing an “undefined” column header. Filter to known ids (and optionally dedupe) during parsing.

Apply:

-      columns: z
-        .string()
-        .default(exportPartnersColumnsDefault.join(","))
-        .transform((v) => v.split(",")),
+      columns: z
+        .string()
+        .default(exportPartnersColumnsDefault.join(","))
+        .transform((v) => v.split(","))
+        .transform((ids) => {
+          const allowed = new Set(exportPartnerColumns.map((c) => c.id));
+          return [...new Set(ids.filter((id) => allowed.has(id)))];
+        }),

79-89: Align sort key naming: use “totalCommissions” everywhere instead of “commissions”

To avoid the mismatch between the UI, Zod schema, and API mapping, please make the following mandatory refactors:

• apps/web/lib/zod/schemas/partners.ts
– Around the sortBy enum (lines ~79–89), replace "commissions" with "totalCommissions".

• apps/web/lib/api/partners/get-partners.ts
– In sortColumnsMap (around line 6), rename the key
commissions: "totalCommissions"
to
totalCommissions: "totalCommissions".
– In sortColumnExtraMap (around line 23), rename the key
commissions: "totalSaleAmount"
to
totalCommissions: "totalSaleAmount" (or adjust as needed for your desired secondary sort).

• UI consistency check
– Confirm that in program/partners/partners-table.tsx the sort‐by options array already uses "totalCommissions" (no change needed if it does).

This will ensure the Zod schema, the server‐side mapping, and the client‐side sort keys all refer to the same "totalCommissions" identifier.

apps/web/app/(ee)/api/partners/export/route.ts (1)

44-46: Sanitize and dedupe requested columns before schema/build.

Prevents unknown ids producing an “undefined” header and removes duplicates.

Apply:

-  columns = columns.sort(
+  // keep only known columns and dedupe
+  columns = [...new Set(columns.filter((id) => columnIdToLabel[id]))].sort(
     (a, b) => (columnOrderMap[a] || 999) - (columnOrderMap[b] || 999),
   );
@@
-  columns.forEach((column) => {
+  columns.forEach((column) => {
     if (expandedColumns.includes(column)) {

Note: if you adopt the Set change above, replace the includes call per that diff.

Also applies to: 48-61

🧹 Nitpick comments (3)
apps/web/app/(ee)/api/partners/export/route.ts (3)

16-19: Use a Set for expanded columns to simplify lookups.

Minor perf/readability win and avoids repeated includes scans.

Apply:

-const expandedColumns = exportPartnerColumns
-  .filter((column) => column.expanded)
-  .map((column) => column.id);
+const expandedColumnsSet = new Set(
+  exportPartnerColumns.filter((c) => c.expanded).map((c) => c.id),
+);
@@
-const includeExpandedFields = expandedColumns.some((column) =>
-  columns.includes(column),
-);
+const includeExpandedFields = columns.some((col) =>
+  expandedColumnsSet.has(col),
+);
@@
-  if (expandedColumns.includes(column)) {
+  if (expandedColumnsSet.has(column)) {

Also applies to: 27-30, 50-55


63-77: Avoid recreating the Zod object per row.

Hoist the schema once and reuse during parsing.

Apply:

-    const formattedPartners = partners.map((partner) => {
+    const rowSchema = z.object(schemaFields);
+    const formattedPartners = partners.map((partner) => {
@@
-      return z.object(schemaFields).parse(result);
+      return rowSchema.parse(result);
     });

79-84: Add a filename to the CSV attachment.

Improves UX and downstream handling.

Apply:

-      headers: {
+      headers: {
         "Content-Type": "text/csv",
-        "Content-Disposition": `attachment`,
+        "Content-Disposition": `attachment; filename="partners.csv"`,
       },
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2bd34aa and 6c9c4fd.

📒 Files selected for processing (2)
  • apps/web/app/(ee)/api/partners/export/route.ts (2 hunks)
  • apps/web/lib/zod/schemas/partners.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-05-29T04:45:18.504Z
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/zod/schemas/partners.ts
🧬 Code graph analysis (1)
apps/web/app/(ee)/api/partners/export/route.ts (2)
apps/web/lib/zod/schemas/partners.ts (2)
  • exportPartnerColumns (29-51)
  • partnersExportQuerySchema (132-141)
apps/web/lib/api/partners/get-partners.ts (1)
  • getPartners (33-171)
⏰ 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). (2)
  • GitHub Check: Vade Review
  • GitHub Check: build
🔇 Additional comments (1)
apps/web/lib/zod/schemas/partners.ts (1)

30-51: Expanded metadata and new metrics columns look good; confirm header change impact.

Expanded flags align with route logic and the addition of totalCommissions/netRevenue is consistent with EnrolledPartnerSchema. Note: changing createdAt’s label to “Enrolled at” may affect downstream CSV consumers relying on exact headers.

Please confirm the header rename (“Created at” → “Enrolled at”) is intentional and communicated to users relying on stable CSV headings.

@devkiran devkiran requested a review from steven-tey August 27, 2025 19:17
@steven-tey steven-tey merged commit a75ca6c into main Aug 27, 2025
10 of 11 checks passed
@steven-tey steven-tey deleted the fix-csv-imports branch August 27, 2025 19:33
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