Skip to content

refactor: replace Apollo Client with Prisma for user data retrieval i…#8872

Open
mikeallisonJS wants to merge 7 commits intomainfrom
00-00-MA-refactor-journeys-modern-email-prisma
Open

refactor: replace Apollo Client with Prisma for user data retrieval i…#8872
mikeallisonJS wants to merge 7 commits intomainfrom
00-00-MA-refactor-journeys-modern-email-prisma

Conversation

@mikeallisonJS
Copy link
Copy Markdown
Collaborator

@mikeallisonJS mikeallisonJS commented Mar 18, 2026

…n email service

Summary by CodeRabbit

  • Bug Fixes

    • Updated journey invitation subject to include "on NextSteps" for clearer emails.
    • Emails now error when a target user is missing or lacks an email to prevent silent failures.
  • New Features

    • Improved recipient normalization so emails use consistent name, image, and address fields.
    • Batch manager notifications now reliably deliver to all intended recipients.
  • Tests

    • Email tests rewritten to use the new recipient lookup flow for more accurate coverage.

@mikeallisonJS mikeallisonJS requested a review from csiyang March 18, 2026 01:48
@mikeallisonJS mikeallisonJS self-assigned this Mar 18, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 18, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 60363b06-4b07-434d-b429-02f1f5edb2f4

📥 Commits

Reviewing files that changed from the base of the PR and between c39240a and 6152802.

📒 Files selected for processing (1)
  • apis/api-journeys-modern/src/workers/email/service/service.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apis/api-journeys-modern/src/workers/email/service/service.ts

Walkthrough

Replaces Apollo GraphQL user lookups with Prisma user.findUnique/findMany calls across the email service and tests, adds an EmailRecipient normalization helper, and updates tests to use a mocked Prisma users client and adjusted expectations.

Changes

Cohort / File(s) Summary
Email Service
apis/api-journeys-modern/src/workers/email/service/service.ts
Removed Apollo client and GraphQL queries; added EmailRecipient interface and toEmailRecipient() helper. Updated email flows (teamRemoved, teamInvite, journeyAccessRequest, journeyRequestApproved, journeyEditInvite, teamInviteAccepted) to fetch users via prisma.user.findUnique/findMany, validate presence/email, normalize recipients, and use recipient.email for sending.
Email Service Tests
apis/api-journeys-modern/src/workers/email/service/service.spec.ts
Replaced ApolloClient.prototype.query mocks with a mocked @core/prisma/users/client (prisma.user.findUnique, prisma.user.findMany). Tests now supply Prisma mock returns, assert findMany where applicable, and update expected email payloads (IDs, email, firstName, imageUrl) and one subject to include "on NextSteps".

Sequence Diagram(s)

sequenceDiagram
  participant Service as Email Service
  participant Prisma as Prisma Users Client
  participant Renderer as Template Renderer
  participant Sender as Email Sender

  Service->>Prisma: findUnique(userId) / findMany(userIds)
  Prisma-->>Service: user record(s) (id, email, firstName, imageUrl)
  Service->>Service: toEmailRecipient(user) → EmailRecipient
  Service->>Renderer: renderTemplate(template, { recipient })
  Renderer-->>Service: renderedHtml, subject
  Service->>Sender: sendEmail(to=recipient.email, subject, html)
  Sender-->>Service: sendResult
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 'refactor: replace Apollo Client with Prisma for user data retrieval in email service' clearly and directly summarizes the main change: replacing Apollo Client GraphQL mocks with Prisma-based queries for user lookups across the email service.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 00-00-MA-refactor-journeys-modern-email-prisma

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.

@nx-cloud
Copy link
Copy Markdown

nx-cloud bot commented Mar 18, 2026

View your CI Pipeline Execution ↗ for commit ea5785d

Command Status Duration Result
nx affected --target=subgraph-check --base=c008... ✅ Succeeded 1s View ↗
nx affected --target=extract-translations --bas... ✅ Succeeded <1s View ↗
nx affected --target=lint --base=c008d52a47e4e1... ✅ Succeeded <1s View ↗
nx affected --target=type-check --base=c008d52a... ✅ Succeeded <1s View ↗
nx run-many --target=codegen --all --parallel=3 ✅ Succeeded 2s View ↗
nx run-many --target=prisma-generate --all --pa... ✅ Succeeded 4s View ↗

☁️ Nx Cloud last updated this comment at 2026-03-31 01:52:34 UTC

Copy link
Copy Markdown
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: 2

🧹 Nitpick comments (1)
apis/api-journeys-modern/src/workers/email/service/service.spec.ts (1)

195-200: Add regression coverage for the new lookup edge cases.

These specs only mock fully populated user rows. Please add cases for a userId lookup returning email: null and for the manager batch lookup returning fewer rows than requested, so the new recipient-resolution branches fail loudly instead of regressing silently.

Also applies to: 273-288

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apis/api-journeys-modern/src/workers/email/service/service.spec.ts` around
lines 195 - 200, Add two regression tests in service.spec.ts to exercise the
recipient-resolution error branches: 1) Create a test that stubs
mockPrismaUsers.user.findUnique (the userId lookup) to resolve to an object with
email: null (and valid id/firstName) and assert the service throws or rejects
with the expected error when resolving recipients for that userId; 2) Create a
test that stubs mockPrismaUsers.user.findMany (the manager batch lookup used by
the manager-resolution code path) to return fewer rows than the requested
manager IDs and assert the service fails loudly (throws/rejects) rather than
silently continuing. Use the same setup helpers/fixtures already present in the
file and mirror existing test structure around mockPrismaUsers.user.findUnique
and mockPrismaUsers.user.findMany so these new tests cover the two new edge
branches referenced in recipient-resolution.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apis/api-journeys-modern/src/workers/email/service/service.ts`:
- Around line 59-66: The code is coercing null emails to an empty string when
building recipient objects (see recipientUser -> user creation), which allows
invalid recipients to proceed; update the logic to 1) define a shared
EmailRecipient type/helper and use it across the places mentioned (current block
and the similar blocks at the other ranges), 2) check recipientUser.email
explicitly and if it's null/undefined return or throw before any
rendering/sending or preference lookups, and 3) replace the current spread that
sets email: recipientUser.email ?? '' with construction that only creates an
EmailRecipient when email is present (and preserve lastName handling as
optional). Locate and update the recipient construction code paths referencing
recipientUser, ensure preference/delivery functions accept the typed
EmailRecipient only, and remove the empty-string normalization.
- Around line 221-230: The code currently builds recipients via
recipientUserIds.map(id => recipientUsersByUserId.get(id)) and only throws
inside the send loop, which can cause partial delivery; modify the logic in the
block around recipients, recipientUserIds and recipientUsersByUserId to validate
the entire batch before any sends by checking for any undefined entries (e.g.,
find missingIds = recipientUserIds.filter(id => !recipientUsersByUserId.has(id))
or check recipients.some(r => r == null)) and throw a clear error (including
missing ids) if any manager is absent so the subsequent send loop over
recipients only runs when all recipients are present.

---

Nitpick comments:
In `@apis/api-journeys-modern/src/workers/email/service/service.spec.ts`:
- Around line 195-200: Add two regression tests in service.spec.ts to exercise
the recipient-resolution error branches: 1) Create a test that stubs
mockPrismaUsers.user.findUnique (the userId lookup) to resolve to an object with
email: null (and valid id/firstName) and assert the service throws or rejects
with the expected error when resolving recipients for that userId; 2) Create a
test that stubs mockPrismaUsers.user.findMany (the manager batch lookup used by
the manager-resolution code path) to return fewer rows than the requested
manager IDs and assert the service fails loudly (throws/rejects) rather than
silently continuing. Use the same setup helpers/fixtures already present in the
file and mirror existing test structure around mockPrismaUsers.user.findUnique
and mockPrismaUsers.user.findMany so these new tests cover the two new edge
branches referenced in recipient-resolution.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0ba6bdf0-7f1f-4cfb-9512-4e10d75f4115

📥 Commits

Reviewing files that changed from the base of the PR and between cb11c74 and c39240a.

📒 Files selected for processing (2)
  • apis/api-journeys-modern/src/workers/email/service/service.spec.ts
  • apis/api-journeys-modern/src/workers/email/service/service.ts

mikeallisonJS and others added 5 commits March 30, 2026 18:05
- Introduced EmailRecipient interface for better type safety.
- Added toEmailRecipient function to standardize user data transformation.
- Updated service functions to utilize the new recipient handling logic, ensuring email addresses are validated before sending.
- Enhanced error handling for cases where users lack email addresses.
@stage-branch-merger
Copy link
Copy Markdown

I see you added the "on stage" label, I'll get this merged to the stage branch!

@stage-branch-merger
Copy link
Copy Markdown

Merge conflict attempting to merge this into stage. Please fix manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants