Skip to content

fixes #125, address remaining review issues from PR #124 - #180

Merged
yash-pouranik merged 2 commits into
geturbackend:mainfrom
tirth1356:fix/mail-template-issues
May 19, 2026
Merged

fixes #125, address remaining review issues from PR #124 #180
yash-pouranik merged 2 commits into
geturbackend:mainfrom
tirth1356:fix/mail-template-issues

Conversation

@tirth1356

@tirth1356 tirth1356 commented May 17, 2026

Copy link
Copy Markdown
Contributor

fixed #125

This PR addresses the follow-up tasks from PR #124, improving error sanitization, increasing test coverage, resolving SDK type mismatches, and cleaning up test execution noise.

Changes Summary:

  1. Error Sanitization: Replaced raw DB/Mongoose error message leaks inside the mail template endpoints of apps/dashboard-api/src/controllers/project.controller.js with a generic "Internal server error" message, only exposing details in development mode.
  2. Added Test Coverage: Wrote comprehensive unit tests inside apps/public-api/src/__tests__/mail.controller.test.js to verify:
    • Successful resolution of project-scoped mail templates.
    • Successful fallback to global/system mail templates when a project-scoped one is not found.
  3. Resolved SDK Type Mismatch: Updated the sendMailSchema Zod definition for the to field in packages/common/src/utils/input.validation.js to natively accept both a single email string and an array of email strings (z.union([z.string().email(), z.array(z.string().email())])), matching the SDK's definitions.
  4. Test Noise Elimination: Silenced expected error/debug console output generated by positive & negative testing assertions in:
    • apps/dashboard-api/src/middlewares/authMiddleware.js
    • apps/public-api/src/controllers/data.controller.js
    • packages/common/src/queues/publicEmailQueue.js

🛠️ Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • 🎨 UI/UX improvement (Frontend only)
  • ⚙️ Refactor / Chore

🧪 Testing & Validation

Backend Verification:

  • I have run npm test or the local Jest runner inside the monorepo directories and all tests passed cleanly.
  • New unit tests have been added for the mail template resolution paths.

✅ Checklist

  • My code follows the code style of this project.
  • I have performed a self-review of my code.
  • My changes generate no new warnings or errors.
  • Test runs are clean and free of unnecessary error outputs.

Summary by CodeRabbit

  • New Features

    • Mail sending accepts a single recipient or an array of recipients.
  • Bug Fixes

    • Standardized server error handling for mail-template endpoints.
    • Reduced noisy error logging during test runs and queue failures.
  • Tests

    • Added tests covering DB-backed mail template selection, rendering, and fallback behavior.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@tirth1356 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 46 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3c8b62df-606c-4a18-8546-96239f53f578

📥 Commits

Reviewing files that changed from the base of the PR and between b81c8ca and 3b78063.

📒 Files selected for processing (6)
  • apps/dashboard-api/src/controllers/project.controller.js
  • apps/dashboard-api/src/middlewares/authMiddleware.js
  • apps/public-api/src/__tests__/mail.controller.test.js
  • apps/public-api/src/controllers/data.controller.js
  • packages/common/src/queues/publicEmailQueue.js
  • packages/common/src/utils/input.validation.js
📝 Walkthrough

Walkthrough

Suppresses console error noise during tests, updates dashboard mail-template controllers to forward 500s via Express next(AppError), relaxes sendMail validation to accept single or multiple recipients, and adds tests that exercise DB-backed template selection and queue payload assertions.

Changes

Test environment logging and mail template enhancements

Layer / File(s) Summary
Test environment logging suppression
apps/dashboard-api/src/middlewares/authMiddleware.js, apps/public-api/src/controllers/data.controller.js, packages/common/src/queues/publicEmailQueue.js
JWT verification errors, data controller catch blocks, and email queue failures now conditionally log only when NODE_ENV !== 'test'.
Mail template endpoint error standardization
apps/dashboard-api/src/controllers/project.controller.js
listMailTemplates, listGlobalMailTemplates, getMailTemplate, createMailTemplate, updateMailTemplate, and deleteMailTemplate now accept (req,res,next) and forward 500s via next(new AppError(500, "Internal server error")), re-forwarding existing AppErrors.
Mail template multi-recipient and DB-backed tests
packages/common/src/utils/input.validation.js, apps/public-api/src/__tests__/mail.controller.test.js
sendMailSchema.to accepts a string or non-empty array of emails; tests mock MailTemplate.findOne to validate project-scoped and global fallback template selection, and assert publicEmailQueue.add payloads, templateUsed, call order, and job options.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested labels

backend, quality:clean, level-3

Suggested reviewers

  • yash-pouranik

Poem

🐰 A rabbit nibbles noisy logs away,

Quiet tests in morning's gentle ray.
Templates seek project, then global halls,
Queueing messages with tidy calls.
Hop, tests pass clean — the meadow softly claps.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title references issue #125 and PR #124 but lacks specificity about the main changes (error sanitization, test coverage, validation updates, logging suppression). Consider a more descriptive title like 'Sanitize mail template errors and suppress test logging' or 'Fix mail template error handling and add DB template tests' to better convey the primary changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
apps/public-api/src/controllers/data.controller.js (1)

87-99: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Stop leaking raw internal errors from controller catch paths

Several touched catch blocks still send raw err.message/details to clients (e.g., Line 94, Line 98, Line 370, Line 444, Line 509, Line 513, Line 575), which leaks internal DB/runtime details and breaks the controller response contract. Return a sanitized message and keep detailed error info server-side only.

Suggested pattern
- return res.status(500).json({ error: err.message });
+ return next(new AppError("Internal server error", 500));
- return res.status(409).json({
-   error: "Duplicate value violates unique constraint.",
-   details: err.message,
- });
+ return next(new AppError("Duplicate value violates unique constraint.", 409));
- return res.status(500).json({
-   success: false,
-   data: {},
-   message: err.message || "Failed to execute aggregation.",
- });
+ return next(new AppError("Failed to execute aggregation.", 500));

As per coding guidelines, "**/src/controllers/**/*.{js,ts}: All API endpoints return: { success: bool, data: {}, message: "" }. Use AppError class for errors — never raw throw, never expose MongoDB errors to client."

Also applies to: 178-189, 367-371, 429-446, 502-514, 572-576

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/public-api/src/controllers/data.controller.js` around lines 87 - 99, The
controller currently returns raw internal error messages (e.g., using
err.message and details in the catch path around isDuplicateKeyError) which
leaks DB/runtime internals and violates the response contract; update the catch
blocks in apps/public-api/src/controllers/data.controller.js to stop sending
err.message or err details to clients, instead log the full error server-side
(console.error or logger) and return a sanitized response shaped as { success:
false, data: {}, message: "<user-friendly message>" } using the AppError
pattern; for duplicate-key errors detected by isDuplicateKeyError(err) return a
409 with a generic message like "Conflict: duplicate value" (no DB details), for
other errors return a 500 with a generic message like "Internal server error",
and ensure any thrown errors in this controller use the AppError class rather
than raw error objects.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/dashboard-api/src/controllers/project.controller.js`:
- Around line 1598-1601: Several catch blocks in project.controller.js currently
return res.status(500).json({ error, details: ... }) and leak backend error
text; update each of these catch blocks (the ones that call
res.status(500).json(...) for 500 responses) to follow the controller response
contract by returning res.status(500).json({ success: false, data: {}, message:
"Internal server error" }) and remove any use of err.message or a details field
so no MongoDB/backend error text is exposed to clients; apply the same change to
all six occurrences that currently return the { error, details } payload.

In `@apps/public-api/src/__tests__/mail.controller.test.js`:
- Around line 176-231: The test currently only asserts output while mocking
MailTemplate.findOne loosely, which can hide regressions in lookup order/scope;
after invoking mailController.sendMail add assertions on MailTemplate.findOne
calls to ensure the first call queried the project-scoped template and the
second called the global fallback (e.g.,
expect(MailTemplate.findOne).toHaveBeenNthCalledWith(1,
expect.objectContaining({ name: 'welcome', projectId: 'proj_1' })) and
expect(MailTemplate.findOne).toHaveBeenNthCalledWith(2,
expect.objectContaining({ name: 'welcome', projectId: null })) so the test fails
if the controller no longer queries project-first then global).

---

Outside diff comments:
In `@apps/public-api/src/controllers/data.controller.js`:
- Around line 87-99: The controller currently returns raw internal error
messages (e.g., using err.message and details in the catch path around
isDuplicateKeyError) which leaks DB/runtime internals and violates the response
contract; update the catch blocks in
apps/public-api/src/controllers/data.controller.js to stop sending err.message
or err details to clients, instead log the full error server-side (console.error
or logger) and return a sanitized response shaped as { success: false, data: {},
message: "<user-friendly message>" } using the AppError pattern; for
duplicate-key errors detected by isDuplicateKeyError(err) return a 409 with a
generic message like "Conflict: duplicate value" (no DB details), for other
errors return a 500 with a generic message like "Internal server error", and
ensure any thrown errors in this controller use the AppError class rather than
raw error objects.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0682ec95-9843-4f9a-b91e-96cdf8e88a6d

📥 Commits

Reviewing files that changed from the base of the PR and between dd7bebd and a325fc1.

📒 Files selected for processing (6)
  • apps/dashboard-api/src/controllers/project.controller.js
  • apps/dashboard-api/src/middlewares/authMiddleware.js
  • apps/public-api/src/__tests__/mail.controller.test.js
  • apps/public-api/src/controllers/data.controller.js
  • packages/common/src/queues/publicEmailQueue.js
  • packages/common/src/utils/input.validation.js

Comment thread apps/dashboard-api/src/controllers/project.controller.js Outdated
Comment thread apps/public-api/src/__tests__/mail.controller.test.js
@yash-pouranik

Copy link
Copy Markdown
Member

Hello @tirth1356
Thank you for the PR
Can u please resolve this merge conflicts and fix the issue shared by coderabbitai?

@yash-pouranik

Copy link
Copy Markdown
Member

@tirth1356
r u there???

@tirth1356

Copy link
Copy Markdown
Contributor Author

yes im there, sorry for late reply i have done the changes and will push it soon @yash-pouranik

@tirth1356
tirth1356 force-pushed the fix/mail-template-issues branch from b81c8ca to 3b78063 Compare May 19, 2026 10:35
@tirth1356

Copy link
Copy Markdown
Contributor Author

done @yash-pouranik, all conflicts have been resolved and the above given review is also considered

@yash-pouranik

Copy link
Copy Markdown
Member

@coderabbitai
Please check if theres any lost of code? bcoz there were conflict.
and OK to merge?
Then will review manually.

@coderabbitai

coderabbitai Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check for any residual merge conflict markers in the changed files
echo "=== Checking for residual merge conflict markers ==="
rg -n "(<<<<<<<|=======|>>>>>>>) " --type js

echo ""
echo "=== project.controller.js - mail template functions ==="
cat apps/dashboard-api/src/controllers/project.controller.js

echo ""
echo "=== authMiddleware.js ==="
cat apps/dashboard-api/src/middlewares/authMiddleware.js

echo ""
echo "=== mail.controller.test.js ==="
cat apps/public-api/src/__tests__/mail.controller.test.js

echo ""
echo "=== data.controller.js - catch blocks ==="
cat apps/public-api/src/controllers/data.controller.js

echo ""
echo "=== publicEmailQueue.js ==="
cat packages/common/src/queues/publicEmailQueue.js

echo ""
echo "=== input.validation.js - sendMailSchema ==="
cat packages/common/src/utils/input.validation.js

Length of output: 145306


@yash-pouranik: I've inspected all changed files after the conflict resolution. Here's the verdict:


✅ No merge conflict markers found

Zero residual <<<<<<< / ======= / >>>>>>> markers exist anywhere in the JS codebase.

✅ No code loss detected — all changes are intact

File Expected Change Status
apps/dashboard-api/src/controllers/project.controller.js All 6 mail-template functions (listMailTemplates, listGlobalMailTemplates, getMailTemplate, createMailTemplate, updateMailTemplate, deleteMailTemplate) accept next and forward 500s via next(new AppError(500, "Internal server error")) ✅ Present
apps/dashboard-api/src/middlewares/authMiddleware.js console.error guarded by NODE_ENV !== 'test' ✅ Present
apps/public-api/src/__tests__/mail.controller.test.js New DB-backed project-scoped + global-fallback template tests; MailTemplate.findOne mock added ✅ Present
apps/public-api/src/controllers/data.controller.js console.error suppressed in test env across all 7 endpoints ✅ Present
packages/common/src/queues/publicEmailQueue.js failed handler logs guarded by NODE_ENV !== 'test' ✅ Present
packages/common/src/utils/input.validation.js sendMailSchema.to accepts string or array via z.union([...]) ✅ Present

🟡 One minor observation (non-blocking)

createMailTemplate and updateMailTemplate catch blocks do not have an if (err instanceof AppError) return next(err) pass-through guard (unlike the other 4 mail template handlers). This is not a bug since those handlers don't internally throw AppErrors — but it's a small inconsistency worth noting for future maintenance.


Overall: the PR looks good from a code-integrity standpoint and is safe to merge after your manual review. 🐇

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

follow-up: address remaining review issues from PR #124 (mail templates)

2 participants