Skip to content

fix(webapp): accept Plain customers without an external id on customer cards - #4575

Open
isshaddad wants to merge 2 commits into
mainfrom
fix/plain-customer-cards-null-external-id
Open

fix(webapp): accept Plain customers without an external id on customer cards#4575
isshaddad wants to merge 2 commits into
mainfrom
fix/plain-customer-cards-null-external-id

Conversation

@isshaddad

Copy link
Copy Markdown
Collaborator

Plain sends customer.externalId as an explicit null rather than omitting the key. The schema validated it with z.string().optional(), which accepts undefined but rejects null, so every customer we don't set an externalId for got a 400 instead of a card — while the rest worked, which made it look intermittent.

email, externalId and thread are now nullish. One of email/externalId is still required, and the route's existing email fallback resolves these customers.

Three related fixes in the same path:

  • The route returned { cards: [] } when no user matched. Plain records an integration error for any requested key it doesn't get back, so that surfaced as a broken card rather than a hidden one. Every requested key is now answered, with components: null where there's no data.
  • The impersonation link is offered only when the customer matched on externalId — a value we set ourselves. An email match is a weaker claim, since the address on a Plain customer isn't verified and for customers created outside our own writes it comes from whoever sent the message. Email-matched customers get the account rows without a one-click impersonation link.
  • The not-found log recorded raw customer identifiers; it now keeps presence flags only.

The schema and the response helper moved to app/utils/plainCustomerCards.ts so they can be unit-tested without pulling in the db and env modules.

Testing

app/utils/plainCustomerCards.test.ts — 11 tests covering the null shapes, the every-key-answered response, and the missing-vs-zero distinction. Verified locally.

Split out of #4571, which bundled this with an unrelated impersonation fix.

…r cards

Plain sends customer.externalId as an explicit null rather than omitting the key,
and the schema validated it with z.string().optional(), which accepts undefined
but rejects null. Every customer we don't set an externalId for got a 400 instead
of a card, while the rest worked — so it looked intermittent.

email, externalId and thread are now nullish; one of email/externalId is still
required, and the existing email fallback resolves these customers.

Two related fixes in the same path:

- The route returned { cards: [] } when no user matched. Plain records an
  integration error for any requested key it doesn't get back, so that rendered
  as a broken card rather than a hidden one. Every requested key is now answered,
  with components: null where there's no data.
- The impersonation link is offered only when the customer matched on externalId,
  a value we set ourselves. An email match is a weaker claim — the address on a
  Plain customer isn't verified and, for customers created outside our own
  writes, comes from whoever sent the message — so email-matched customers now
  get the account rows without a one-click impersonation link.
- The not-found log recorded raw customer identifiers; it keeps presence flags
  only.

The schema and the response helper live in app/utils so they can be unit-tested
without pulling in the db and env modules.
@changeset-bot

changeset-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: b41af49

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a3ed6c2c-b51b-4ddd-bfef-16f71c0200e5

📥 Commits

Reviewing files that changed from the base of the PR and between 02a1f5e and b41af49.

📒 Files selected for processing (3)
  • apps/webapp/app/routes/api.v1.plain.customer-cards.ts
  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/routes/api.v1.plain.customer-cards.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Detect changes
  • GitHub Check: audit
  • GitHub Check: audit
  • GitHub Check: 🛡️ E2E Auth Tests (full)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Do not reintroduce the removed v1 execution path; RunEngineVersion.V1 branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
apps/webapp/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

Do not import env.server.ts directly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For apps, use typecheck for verification and never use build as the correctness check.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
apps/webapp/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
Use useCallback and useMemo only for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
apps/webapp/app/**/*.ts

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

apps/webapp/app/**/*.ts: Never use request.signal to detect client disconnects. Use getRequestAbortSignal() from app/services/httpAsyncStorage.server.ts, which is wired to Express response close events.
Access environment variables through the env export from app/env.server.ts; never use process.env directly.
Always use Prisma findFirst instead of findUnique.
Always use the $transaction helper from ~/db.server, never call prisma.$transaction or $replica.$transaction directly. Pass isolation levels as strings, use Serializable for correctness-critical read-then-write invariants, and guard possibly undefined helper results when a definite value is required.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
apps/webapp/**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

Test files must not import app/env.server.ts; pass configuration as options instead.

Files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
🧠 Learnings (14)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.

Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.

Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
  • apps/webapp/app/utils/plainCustomerCards.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.

Applied to files:

  • apps/webapp/app/utils/plainCustomerCards.test.ts
🔇 Additional comments (6)
apps/webapp/app/utils/plainCustomerCards.ts (3)

1-31: 🗄️ Data Integrity & Integration

Verify that blank identifiers do not satisfy the request schema.

normalizeEmail returns null for empty and whitespace-only email values at Line 44. Ensure PlainCustomerCardRequestSchema treats blank email and externalId values as absent. Otherwise, { email: " ", externalId: null } can pass the “email or external ID” rule without a usable lookup key and return an empty card instead of a validation error.


33-45: LGTM!


47-73: LGTM!

apps/webapp/app/utils/plainCustomerCards.test.ts (3)

1-60: LGTM!


62-79: LGTM!


81-110: LGTM!


Walkthrough

The change moves Plain customer card request validation into a shared Zod schema. It adds email normalization and a helper that fills missing requested card keys with empty cards. The route uses these utilities for user lookup and response completion. Logs no longer include customer identifiers. Impersonation controls and tokens are generated only for customers matched by externalId. Tests cover validation, normalization, and card completion.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: accepting Plain customers without an external ID on customer cards.
Description check ✅ Passed The description clearly explains the issue, implementation, security considerations, and testing performed, but it omits several template sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/plain-customer-cards-null-external-id

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.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 2 potential issues.

Open in Devin Review

* loaded on the customer page rather than in a thread. `.optional()` accepts `undefined` but
* rejects `null`, which failed the whole request before any lookup could run.
*/
export const PlainCustomerCardRequestSchema = z.object({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Server-only change ships without a release-notes entry

This pull request changes only webapp server code (apps/webapp/app/routes/api.v1.plain.customer-cards.ts, apps/webapp/app/utils/plainCustomerCards.ts) without adding the required release-notes file, so the fix will be missing from the user-visible release notes.
Impact: Users reading the release notes won't see that support cards now work for customers we don't set an id for.

Repository rule: server-only PRs must add a `.server-changes/` entry

AGENTS.md and CONTRIBUTING.md state that when modifying only server components (apps/webapp/, apps/supervisor/, etc.) with no package changes, a .server-changes/ markdown file must be added (frontmatter area: webapp, type: fix, plus a one-line user-facing description — see .server-changes/README.md:7-39). The PR touches only apps/webapp/** and adds no such file.

Prompt for agents
This PR only changes server code under apps/webapp, so per AGENTS.md / CONTRIBUTING.md / .server-changes/README.md it needs a new markdown file in .server-changes/ (e.g. .server-changes/fix-plain-customer-cards.md) with frontmatter `area: webapp` and `type: fix`, and a one-line, user-facing body describing that support customer cards now load for customers without an external id.
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread apps/webapp/app/routes/api.v1.plain.customer-cards.ts Outdated
coderabbitai[bot]

This comment was marked as resolved.

Users are stored with a lowercased, trimmed email and User.email is unique, so an
exact lookup on whatever Plain sends missed a real account whenever the address
arrived with different casing or padding — which it can, since for customers
created outside our own writes it comes from a sender address. Reachable only now
that a null externalId no longer 400s.

The external id lookup also falls back to email when it doesn't resolve, so a
stale id naming a deleted user no longer leaves the card blank for a customer we
could still identify. canImpersonate is derived from which lookup matched rather
than from whether an external id was sent, so falling through to email cannot
unlock the impersonation link.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 2 new potential issues.

Open in Devin Review

Comment on lines +120 to +130
// The external id is ours (`User.id`), so it's tried first. Falling back to email when it
// doesn't resolve covers a stale id — one naming a user row that no longer exists — instead of
// leaving the card blank for a customer we could still identify.
const byExternalId = customer.externalId
? await prisma.user.findFirst({ where: { id: customer.externalId }, include: userInclude })
: null;

const email = normalizeEmail(customer.email);
const user =
byExternalId ??
(email ? await prisma.user.findFirst({ where: { email }, include: userInclude }) : null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 Stale externalId now silently falls back to an email match

Previously an externalId short-circuited the lookup entirely; now a non-matching externalId falls through to an email lookup (apps/webapp/app/routes/api.v1.plain.customer-cards.ts:123-130). That means a Plain customer whose external id points at a user that no longer exists (or a mistyped id) will render whichever account matches the sender address instead of an empty card. Impersonation is correctly gated off byExternalId, so no elevated action follows, but agents will see account rows attributed via an unverified email — worth confirming this is the desired support UX.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +66 to +71
.map(
(key): NoDataCard => ({
key,
components: null,
})
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 No-data cards omit timeToLiveSeconds

The fill-in cards from answerAllCardKeys contain only { key, components: null } while the real cards specify timeToLiveSeconds (15/300). Depending on Plain's defaults, a missing TTL may mean the empty card is cached with a default lifetime, so a customer who becomes resolvable (e.g. after an externalId is set) may keep showing a hidden card until the default TTL elapses. Worth checking Plain's documented default TTL for card responses.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

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