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

Skip to content

Conversation

@steven-tey
Copy link
Collaborator

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

Summary by CodeRabbit

  • New Features

    • Client-side sale tracking now captures customer name, email, avatar, and click ID for richer attribution.
  • Refactor

    • Reordered request field handling in sale-tracking endpoints for consistent payload processing; no change to validations or supported fields.
    • Simplified a lead-backfill script by removing unnecessary imports and relying on inferred types for cleaner code.

@vercel
Copy link
Contributor

vercel bot commented Sep 10, 2025

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

Project Deployment Preview Updated (UTC)
dub Ready Ready Preview Sep 10, 2025 5:11am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 10, 2025

Walkthrough

Client sale tracking route changes payload fields (removes paymentProcessor/invoiceId, adds customerName, customerEmail, customerAvatar, clickId, and reorders metadata); server sale route only reorders local destructuring; a backfill script removes a Prisma import and an explicit type annotation.

Changes

Cohort / File(s) Summary
Client sale tracking route
apps/web/app/(ee)/api/track/sale/client/route.ts
Replaced paymentProcessor and invoiceId in request destructuring with customerName, customerEmail, customerAvatar, clickId; moved metadata position; updated trackSale invocation to pass the new customer fields; host/CORS/validation flow unchanged.
Server sale tracking route
apps/web/app/(ee)/api/track/sale/route.ts
Reordered destructured fields from the parsed body (paymentProcessor/invoiceId moved after eventName; metadata moved after leadEventName); no fields added/removed and trackSale call unmodified.
Backfill script (typing/import cleanup)
apps/web/scripts/perplexity/backfill-leads.ts
Added // @ts-nocheck, removed Prisma import (keeps EventType), and removed an explicit Prisma.CustomerCreateManyInput[] annotation for customersToCreate; runtime mapping/filter logic unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant CR as Client Route (/api/track/sale/client)
  participant SR as Server Route (/api/track/sale)
  participant S as trackSale Service
  participant DB as Database

  C->>CR: POST sale payload\n(amount, currency, customerExternalId,\ncustomerName/customerEmail/customerAvatar, clickId, metadata…)
  CR->>SR: Forward normalized sale data (includes new customer fields)
  SR->>S: Invoke trackSale with payload
  S->>DB: Persist sale and metadata
  DB-->>S: OK / Error
  S-->>SR: Result
  SR-->>CR: Response
  CR-->>C: CORS-wrapped response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • devkiran

"I nibble through the payload's maze,
New fields hop in bright array.
Click IDs sparkle, metadata neat,
I drum my paws for shipping sweet.
Carrot cheers — the routes align and play!"

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly summarizes the primary change by indicating the addition of lead-related parameters to the /track/sale/client endpoint, making it clear and specific to the main update in the pull request.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b21129 and ad25328.

📒 Files selected for processing (1)
  • apps/web/scripts/perplexity/backfill-leads.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/scripts/perplexity/backfill-leads.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). (2)
  • GitHub Check: Vade Review
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch track-sale-client-params

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 and usage tips.

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 fdba367 and 06cc383.

📒 Files selected for processing (2)
  • apps/web/app/(ee)/api/track/sale/client/route.ts (2 hunks)
  • apps/web/app/(ee)/api/track/sale/route.ts (1 hunks)
⏰ 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: build
  • GitHub Check: Vade Review
🔇 Additional comments (3)
apps/web/app/(ee)/api/track/sale/route.ts (1)

25-29: Reordering-only change — LGTM.

Repositioning paymentProcessor/invoiceId and metadata in the destructuring is a no-op for object parsing and call-site usage. Looks good.

apps/web/app/(ee)/api/track/sale/client/route.ts (2)

39-41: Confirm intent for paymentProcessor and invoiceId in client endpoint. Remove them from the request destructuring (lines 39–40) and the subsequent call (lines 61–62) in apps/web/app/(ee)/api/track/sale/client/route.ts if they’re no longer needed.


52-58: trackSale signature & schema support confirmed
customerName, customerEmail, customerAvatar, and clickId are all accepted by the trackSale function and validated in trackSaleRequestSchema (customerEmail uses .email()).

Comment on lines 30 to 44
const {
customerExternalId,
paymentProcessor,
invoiceId,
customerName,
customerEmail,
customerAvatar,
clickId,
amount,
currency,
metadata,
eventName,
paymentProcessor,
invoiceId,
leadEventName,
metadata,
} = trackSaleRequestSchema.parse(body);

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Keep backward-compat for customerExternalId aliases (match server route).

Server route accepts externalId/customerId as fallbacks; client route currently doesn’t. If any clients still send those fields, this becomes a breaking change. Mirror the server’s compatibility here.

Apply this diff within the block to add aliases and compute the effective ID:

-    const {
-      customerExternalId,
+    const {
+      customerExternalId: newExternalId,
+      externalId: oldExternalId,
+      customerId: oldCustomerId,
       customerName,
       customerEmail,
       customerAvatar,
       clickId,
       amount,
       currency,
       eventName,
       paymentProcessor,
       invoiceId,
       leadEventName,
       metadata,
-    } = trackSaleRequestSchema.parse(body);
+    } = trackSaleRequestSchema
+      .extend({
+        customerExternalId: z.string().nullish(),
+        externalId: z.string().nullish(),
+        customerId: z.string().nullish(),
+      })
+      .parse(body);
+
+    const customerExternalId =
+      newExternalId ?? oldExternalId ?? oldCustomerId;

Also add the missing import (outside this hunk):

import { z } from "zod";

Run to verify no call sites rely solely on the old fields:


🏁 Script executed:

#!/bin/bash
rg -nP -C2 '\b(externalId|customerId)\b' --type=ts --type=tsx

Length of output: 27


🏁 Script executed:

#!/bin/bash
rg -nP -C2 '\b(externalId|customerId)\b' --glob '*.ts' --glob '*.tsx'

Length of output: 191088


🏁 Script executed:

#!/bin/bash
file='apps/web/app/(ee)/api/track/sale/client/route.ts'
if [ -f "$file" ]; then
  echo "Searching for externalId in $file"
  grep -n "externalId" "$file" || echo "→ no externalId occurrences"
  echo "Searching for customerId in $file"
  grep -n "customerId" "$file" || echo "→ no customerId occurrences"
else
  echo "→ file not found: $file"
fi

Length of output: 209


Extend client track-sale route schema for backward compatibility
In apps/web/app/(ee)/api/track/sale/client/route.ts, extend trackSaleRequestSchema to accept externalId and customerId as nullable aliases, destructure into newExternalId, oldExternalId, oldCustomerId, then compute

const customerExternalId = newExternalId ?? oldExternalId ?? oldCustomerId;

and add import { z } from "zod".

🤖 Prompt for AI Agents
In apps/web/app/(ee)/api/track/sale/client/route.ts around lines 30 to 44,
extend the trackSaleRequestSchema to also accept externalId and customerId as
nullable aliases (use z import from "zod" at the top), update the destructuring
to pull newExternalId (externalId), oldExternalId (customerExternalId), and
oldCustomerId (customerId) along with the existing fields, then compute the
final customerExternalId with: const customerExternalId = newExternalId ??
oldExternalId ?? oldCustomerId; ensure you import { z } from "zod" and keep the
original fields for backward compatibility.

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 06cc383 and 2b21129.

📒 Files selected for processing (1)
  • apps/web/scripts/perplexity/backfill-leads.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/scripts/perplexity/backfill-leads.ts (1)
apps/web/lib/api/create-id.ts (1)
  • createId (60-69)
⏰ 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/scripts/perplexity/backfill-leads.ts (1)

5-5: Cleanup looks good: keep only EventType import

Dropping the Prisma type-only import reduces weight and avoids unused import noise. No issues.

Comment on lines +165 to 185
const customersToCreate = leadsToBackfill
.map((lead, idx) => {
const clickData = clicksToCreate[idx];
if (!clickData) {
return null;
}
return {
id: createId({ prefix: "cus_" }),
name: generateRandomName(),
externalId: lead.customerExternalId,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
clickId: clickData.click_id,
linkId: clickData.link_id,
country: clickData.country,
clickedAt: new Date(lead.timestamp).toISOString(),
createdAt: new Date(lead.timestamp).toISOString(),
};
})
.filter((c) => c !== null);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Bug: customersToCreate indexes can drift from clicksToCreate (wrong customer→click pairing)

clicksToCreate filters out nulls earlier, but customersToCreate is indexed by leadsToBackfill. If any lead lacked a matching link, indexes shift and customers get paired with the wrong click/link/timestamp — risking incorrect attribution and payouts.

Refactor customersToCreate to derive directly from clicksToCreate so ordering stays consistent:

-      const customersToCreate = leadsToBackfill
-        .map((lead, idx) => {
-          const clickData = clicksToCreate[idx];
-          if (!clickData) {
-            return null;
-          }
-          return {
-            id: createId({ prefix: "cus_" }),
-            name: generateRandomName(),
-            externalId: lead.customerExternalId,
-            projectId: workspace.id,
-            projectConnectId: workspace.stripeConnectId,
-            clickId: clickData.click_id,
-            linkId: clickData.link_id,
-            country: clickData.country,
-            clickedAt: new Date(lead.timestamp).toISOString(),
-            createdAt: new Date(lead.timestamp).toISOString(),
-          };
-        })
-        .filter((c) => c !== null);
+      const customersToCreate = clicksToCreate.map((clickData) => ({
+        id: createId({ prefix: "cus_" }),
+        name: generateRandomName(),
+        externalId: clickData.identity_hash,
+        projectId: workspace.id,
+        projectConnectId: workspace.stripeConnectId,
+        clickId: clickData.click_id,
+        linkId: clickData.link_id,
+        country: clickData.country,
+        clickedAt: clickData.timestamp,
+        createdAt: clickData.timestamp,
+      }));

Optional: to tighten types and drop non-null assertions elsewhere, switch earlier .filter((r) => r !== null) to a type-guard helper and reuse it:

const isNotNull = <T>(x: T | null): x is T => x !== null;
// ...
const clicksToCreate = await Promise.all(/* ... */).then((res) => res.filter(isNotNull));

@steven-tey steven-tey merged commit a20f2d7 into main Sep 10, 2025
8 of 9 checks passed
@steven-tey steven-tey deleted the track-sale-client-params branch September 10, 2025 05:16
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