+
Skip to content

Conversation

steven-tey
Copy link
Collaborator

@steven-tey steven-tey commented Sep 2, 2025

Summary by CodeRabbit

  • New Features
    • Improved partner analytics to support filtering by a single link or all enrolled links automatically.
  • Bug Fixes
    • Ensures analytics aggregate only over links tied to the enrollment, preventing mismatches.
    • Standardized error handling for missing or invalid links.
  • Refactor
    • Simplified analytics requests by using link-based identifiers and a composite event, removing redundant parameters.
    • Always loads enrollment links for consistent analytics grouping and ordering.
  • Chores
    • Removed an unused authentication dependency from the partner analytics hook.

Copy link
Contributor

vercel bot commented Sep 2, 2025

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

Project Deployment Preview Updated (UTC)
dub Ready Ready Preview Sep 2, 2025 9:45pm

Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

Shifts analytics fetching to link ID-based queries. Updates two API routes to derive linkIds from program enrollment links, validate optional link parameters, and call getAnalytics with event "composite". Adjusts getProgramEnrollmentOrThrow to return links alongside program. Removes an unused next-auth session import in a SWR hook.

Changes

Cohort / File(s) Summary of changes
LinkId-based analytics flow (Partner Profile Program Analytics)
apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/route.ts
Uses DubApiError; consumes { program, links } from getProgramEnrollmentOrThrow; validates linkId/domain/key against enrollment.links; calls getAnalytics with { linkId } or { linkIds: [...] }; switches to exception-based 404 handling.
LinkId-based analytics flow (Partners Analytics)
apps/web/app/(ee)/api/partners/analytics/route.ts
Always includes links in programEnrollment (ordered by clicks desc); calls getAnalytics with event: "composite" and linkIds from enrollment.links; removes programId/partnerId/tenantId from payload.
Exported return type adjustment
apps/web/lib/api/programs/get-program-enrollment-or-throw
Return type now { program: Program; links: Link[] } instead of only { program: Program }.
SWR cleanup
apps/web/lib/swr/use-partner-analytics.ts
Removes unused next-auth useSession import and usage; no functional change to hook behavior.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant API as route.ts (partner-profile/.../[programId]/analytics)
  participant Svc as getProgramEnrollmentOrThrow
  participant ANA as getAnalytics

  Client->>API: GET /partner-profile/programs/:programId/analytics?linkId|domain&key
  API->>Svc: fetch enrollment for programId
  Svc-->>API: { program, links }
  alt linkId provided
    API->>API: validate linkId exists in links
    API->>ANA: getAnalytics({ event: "composite", linkId })
  else domain+key provided
    API->>API: find link by domain+key in links
    API->>ANA: getAnalytics({ event: "composite", linkId })
  else no specific link
    API->>ANA: getAnalytics({ event: "composite", linkIds: links.map(id) })
  end
  ANA-->>API: analytics result
  API-->>Client: JSON response
Loading
sequenceDiagram
  autonumber
  actor Client
  participant API as route.ts (partners/analytics)
  participant DB as load programEnrollment (include links)
  participant ANA as getAnalytics

  Client->>API: GET /partners/analytics?...groupBy=...
  API->>DB: fetch programEnrollment { include: { links (orderBy clicks desc) } }
  DB-->>API: { programEnrollment, links }
  API->>ANA: getAnalytics({ event: "composite", linkIds: links.map(id), ...filters })
  ANA-->>API: analytics data
  API-->>Client: JSON response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I hop through links, IDs in tow,
Composite trails where metrics flow.
No partner keys, no program IDs—
Just tidy hops through clicky trees.
With cleaner code and errors bright,
I thump approval: all feels right. 🐇✨

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

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 or @coderabbit 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: 1

Caution

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

⚠️ Outside diff range comments (1)
apps/web/app/(ee)/api/partners/analytics/route.ts (1)

189-200: Fix potential runtime crash and limit to actual “top” links

When groupBy === "top_links", analytics.find(...) can return undefined (e.g., if TB returns only top N but programEnrollment.links includes more). Spreading ...analyticsData then throws. Also, this returns all enrollment links, not just the top subset.

Use analytics as the driving set, then join to the enrollment link for metadata.

Apply this diff:

-    const topLinksWithEarnings = programEnrollment.links.map((link) => {
-      const analyticsData = analytics.find((a) => a.id === link.id);
-      const earnings = topLinkEarnings.find((t) => t.linkId === link.id);
-
-      return partnersTopLinksSchema.parse({
-        ...link,
-        ...analyticsData,
-        link: link.id,
-        createdAt: link.createdAt.toISOString(),
-        earnings: Number(earnings?._sum.earnings ?? 0),
-      });
-    });
+    const linkById = new Map(programEnrollment.links.map((l) => [l.id, l]));
+    const topLinksWithEarnings = (analytics as Array<{ id: string }>).map((a) => {
+      const link = linkById.get(a.id);
+      if (!link) return null;
+      const earnings = topLinkEarnings.find((t) => t.linkId === a.id);
+      return partnersTopLinksSchema.parse({
+        ...link,
+        ...a,
+        link: a.id,
+        createdAt: link.createdAt.toISOString(),
+        earnings: Number(earnings?._sum.earnings ?? 0),
+      });
+    }).filter(Boolean);
🧹 Nitpick comments (2)
apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/route.ts (2)

26-38: Good fallback to (domain, key); consider normalizing for case/punycode

If keys can be case-sensitive or punycoded in storage, a straight === may miss matches. Consider normalizing both sides (e.g., decode-case/IDNA on stored, and normalize incoming) to avoid false negatives.


40-44: Consider passing workspaceId for parity and future-proofing

While this endpoint typically targets a single link/timeseries, getAnalytics uses workspaceId for certain groupBys (e.g., top_links) and joins. Passing it costs little and keeps behavior consistent.

Apply this diff:

-    const response = await getAnalytics({
-      ...rest,
-      ...(linkId ? { linkId } : { linkIds: links.map((link) => link.id) }),
-      dataAvailableFrom: program.createdAt,
-    });
+    const response = await getAnalytics({
+      ...rest,
+      ...(linkId ? { linkId } : { linkIds: links.map((link) => link.id) }),
+      workspaceId: program.workspaceId,
+      dataAvailableFrom: program.createdAt,
+    });

Also, ensure callers explicitly set event as intended (e.g., "composite") or that your schema defaults it correctly.

📜 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 20c42d4 and c8ae5b6.

📒 Files selected for processing (3)
  • apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/route.ts (1 hunks)
  • apps/web/app/(ee)/api/partners/analytics/route.ts (2 hunks)
  • apps/web/lib/swr/use-partner-analytics.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/lib/swr/use-partner-analytics.ts
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/route.ts (3)
apps/web/lib/api/programs/get-program-enrollment-or-throw.ts (1)
  • getProgramEnrollmentOrThrow (5-75)
apps/web/lib/api/errors.ts (1)
  • DubApiError (75-92)
apps/web/lib/analytics/get-analytics.ts (1)
  • getAnalytics (20-229)
⏰ 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 (4)
apps/web/app/(ee)/api/partners/analytics/route.ts (1)

54-58: LGTM: including links for linkIds is the right direction

Always including links to drive linkIds keeps the analytics call consistent across groupBys.

apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/route.ts (3)

2-2: LGTM: consistent error handling via DubApiError

Importing and using the shared error type keeps responses uniform.


11-14: LGTM: fetching enrollment with links up front

Destructuring { program, links } from getProgramEnrollmentOrThrow simplifies downstream logic.


19-26: LGTM: validate linkId belongs to this enrollment

Ensures partners can’t query analytics for links outside their enrollment.

Comment on lines 69 to 78
const analytics = await getAnalytics({
programId,
partnerId,
tenantId,
event: "composite",
groupBy,
linkIds: programEnrollment.links.map((link) => link.id),
interval,
start,
end,
timezone,
query,
event: "composite",
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Pass workspaceId to getAnalytics (prevents empty top_links and join miss)

getAnalytics’s top_links path joins on workspaceId to enrich link metadata. Without it, the Tinybird result gets filtered to nothing during the Prisma join, and later code may spread undefined. Add workspaceId: workspace.id.

Apply this diff:

-    const analytics = await getAnalytics({
-      event: "composite",
-      groupBy,
-      linkIds: programEnrollment.links.map((link) => link.id),
-      interval,
-      start,
-      end,
-      timezone,
-      query,
-    });
+    const analytics = await getAnalytics({
+      event: "composite",
+      groupBy,
+      linkIds: programEnrollment.links.map((link) => link.id),
+      workspaceId: workspace.id,
+      interval,
+      start,
+      end,
+      timezone,
+      query,
+    });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const analytics = await getAnalytics({
programId,
partnerId,
tenantId,
event: "composite",
groupBy,
linkIds: programEnrollment.links.map((link) => link.id),
interval,
start,
end,
timezone,
query,
event: "composite",
});
const analytics = await getAnalytics({
event: "composite",
groupBy,
linkIds: programEnrollment.links.map((link) => link.id),
workspaceId: workspace.id,
interval,
start,
end,
timezone,
query,
});
🤖 Prompt for AI Agents
In apps/web/app/(ee)/api/partners/analytics/route.ts around lines 69 to 78, the
getAnalytics call omits workspaceId so the top_links path's Prisma join filters
out results and later code can spread undefined; pass workspaceId: workspace.id
in the getAnalytics argument object (add workspaceId: workspace.id alongside
event, groupBy, linkIds, interval, start, end, timezone, query).

@steven-tey steven-tey merged commit 8906378 into main Sep 2, 2025
9 of 10 checks passed
@steven-tey steven-tey deleted the partner-analytics branch September 2, 2025 21:49
@coderabbitai coderabbitai bot mentioned this pull request Oct 6, 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.

1 participant

点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载