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 27, 2025

Summary by CodeRabbit

  • New Features

    • Link values are now automatically normalized (slugified) for consistent, clean URLs.
  • Bug Fixes

    • Improved customer import reliability when internal customer IDs are missing by falling back to email or other IDs, reducing “link not found” errors and improving existence detection.
  • Refactor

    • Unified external customer identity handling across import, creation, logging, and click-event tracking for consistent behavior.

@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 9:46pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Introduces a fallback-based external customer identity in the import flow by computing customerExternalId = customer.customer_id ?? customer.email ?? customer.id; replaces prior customer.customer_id usage with this value across logs, Prisma create payloads, and event payloads. Also slugifies link values and makes ToltCustomerSchema.customer_id nullable.

Changes

Cohort / File(s) Summary
Import identity fallback & usage updates
apps/web/lib/tolt/import-customers.ts
Adds customerExternalId = customer.customer_id ?? customer.email ?? customer.id; replaces customer.customer_id usages in logs, existence checks, commonImportLogInputs.entity_id, Prisma create externalId, and click event payload; removes ToltAffiliate import and the partner parameter from createReferral's usage.
Schema adjustments (slug + nullable)
apps/web/lib/tolt/schemas.ts
Imports slugify and applies z.string().transform((val) => slugify(val)) to ToltLinkSchema.value; makes ToltCustomerSchema.customer_id nullable (`string

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Importer as Batch Import
  participant Zod as Schemas
  participant Resolver as Link Resolver
  participant DB as Prisma
  participant Logger as Logger
  participant Events as Click Emitter

  rect rgb(245,250,255)
    note over Importer,Zod: Parse and normalize inputs
    Importer->>Zod: validate customer + link
    Zod-->>Importer: { customer_id|null, email, id, link.value (slugified) }
    Importer->>Importer: customerExternalId = customer_id ?? email ?? id
  end

  alt Link resolved
    Importer->>Resolver: resolve link (slug / partner.email)
    Resolver-->>Importer: link
    Importer->>DB: upsert Customer { externalId: customerExternalId, ... }
    DB-->>Importer: upsert result
    Importer->>Events: emit click { externalId: customerExternalId, ... }
    Events-->>Importer: ack
    Importer->>Logger: log success (entity_id=customerExternalId)
  else Link not found
    Importer->>Logger: log LINK_NOT_FOUND (entity_id=customerExternalId)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • devkiran

Poem

I hop through fields of IDs bright,
If one is gone I follow light—
Email, id, or customer_id,
I stitch the trail so none are hid.
Slugs pave paths and carrots gleam,
Hooray — imports hum like cream. 🥕🐇


📜 Recent 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 3cc8900 and 063369f.

📒 Files selected for processing (1)
  • apps/web/lib/tolt/import-customers.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/lib/tolt/import-customers.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 fix-tolt

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.

@steven-tey
Copy link
Collaborator Author

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 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

🧹 Nitpick comments (3)
apps/web/lib/tolt/schemas.ts (2)

44-44: Trim before slugifying to avoid leading/trailing dash artifacts.

Apply:

-  value: z.string().transform((val) => slugify(val)), // need to slugify this cause Tolt can sometimes return "john doe"
+  value: z.string().transform((val) => slugify(val.trim())), // need to slugify this cause Tolt can sometimes return "john doe"

50-54: Normalize empty strings to null for customer_id.
Empty string is not nullish; downstream ?? would pick it and produce an empty externalId.

Consider:

-export const ToltCustomerSchema = z.object({
+export const ToltCustomerSchema = z.object({
   id: z.string(),
-  customer_id: z
-    .string()
-    .describe("Internal customer identifier in client's app.")
-    .nullable(),
+  customer_id: z.preprocess(
+    (v) => (typeof v === "string" && v.trim() === "" ? null : v),
+    z.string().describe("Internal customer identifier in client's app.").nullable(),
+  ),
   email: z.string().nullable(),
   name: z.string().nullable(),
apps/web/lib/tolt/import-customers.ts (1)

160-161: Nit: include quotes around id for clearer logs.

-      `A customer already exists with customerExternalId ${customerExternalId}`,
+      `A customer already exists with customerExternalId "${customerExternalId}"`,
📜 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 ee7a834 and 3cc8900.

📒 Files selected for processing (2)
  • apps/web/lib/tolt/import-customers.ts (3 hunks)
  • apps/web/lib/tolt/schemas.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/lib/tolt/import-customers.ts (1)
apps/web/lib/tinybird/log-import-error.ts (1)
  • logImportError (4-7)
⏰ 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 (5)
apps/web/lib/tolt/schemas.ts (1)

1-1: LGTM on adding slugify import.

apps/web/lib/tolt/import-customers.ts (4)

10-10: Type-only import looks right.
Matches the schema changes (nullable customer_id).


139-140: LGTM on improved log context.


153-154: LGTM: unique lookup now aligned with normalized externalId.


214-215: LGTM: create payload uses normalized externalId.

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

♻️ Duplicate comments (2)
apps/web/lib/tolt/import-customers.ts (2)

127-133: Avoid empty-string entity_id; coalesce to first non-empty normalized value

Using ?? will accept "", causing bad keys and uniqueness collisions. Normalize email to lowercase and pick the first non-empty candidate.

-  const commonImportLogInputs = {
+  const normalisedEmail = customer.email?.trim().toLowerCase() ?? null;
+  const entityId =
+    [customer.customer_id, normalisedEmail, customer.id].find(
+      (v): v is string => !!v && v.trim().length > 0,
+    ) ?? customer.id;
+  const commonImportLogInputs = {
     workspace_id: workspace.id,
     import_id: importId,
     source: "tolt",
     entity: "customer",
-    entity_id: customer.customer_id ?? customer.email ?? customer.id,
+    entity_id: entityId,
   } as const;

145-148: Unify customerExternalId with normalized entityId

Reuse the computed entityId to keep logs, lookups, and persistence consistent and non-empty.

-  // if customer_id is null, use customer email or Tolt customer ID as the external ID
-  const customerExternalId =
-    customer.customer_id ?? customer.email ?? customer.id;
+  // external ID: first non-empty of customer_id, normalized email, or Tolt ID
+  const customerExternalId = entityId;
🧹 Nitpick comments (2)
apps/web/lib/tolt/schemas.ts (1)

44-46: Trim before slugifying to avoid stray dashes and inconsistent keys

Slugify after a trim to normalize inputs like " john doe ". Also consider being explicit about lowercase for determinism.

-  value: z.string().transform((val) => slugify(val)), // need to slugify this cause Tolt can sometimes return "john doe"
+  value: z.string().transform((val) => slugify(val.trim())), // trim before slugify
apps/web/lib/tolt/import-customers.ts (1)

160-160: Use structured, low-PII logging

Prefer a concise, structured message and avoid dumping full objects where possible.

-    console.log(
-      `A customer already exists with customerExternalId ${customerExternalId}`,
-    );
+    console.info(`Customer exists; skipping import. externalId=${customerExternalId}`);
📜 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 ee7a834 and 3cc8900.

📒 Files selected for processing (2)
  • apps/web/lib/tolt/import-customers.ts (3 hunks)
  • apps/web/lib/tolt/schemas.ts (2 hunks)
🔇 Additional comments (5)
apps/web/lib/tolt/schemas.ts (1)

1-1: LGTM: import added where used

Import aligns with the new transform usage.

apps/web/lib/tolt/import-customers.ts (4)

10-10: LGTM: types import

Keeps call sites strongly typed.


139-140: Message OK; ensure it reflects normalized entityId

Once the entityId change above lands, this log will automatically reference the normalized ID. No further change needed.


153-154: LGTM: unique lookup by (projectId, externalId)

Correct uniqueness criterion assuming the composite unique exists in Prisma.

If unsure, verify the composite unique in schema: search for @@unique([projectId, externalId]).


214-214: LGTM: persist normalized externalId

This will prevent duplicates and empty keys once normalized upstream.

@steven-tey steven-tey merged commit 4d203fe into main Aug 27, 2025
9 checks passed
@steven-tey steven-tey deleted the fix-tolt branch August 27, 2025 21:58
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