Skip to content

feat(emergency-contacts): add emergency contact management with CRUD, primary contact, and quick-access actions (Closes #143)#184

Open
SakethSumanBathini wants to merge 2 commits into
vallabhatech:mainfrom
SakethSumanBathini:feat/emergency-contacts
Open

feat(emergency-contacts): add emergency contact management with CRUD, primary contact, and quick-access actions (Closes #143)#184
SakethSumanBathini wants to merge 2 commits into
vallabhatech:mainfrom
SakethSumanBathini:feat/emergency-contacts

Conversation

@SakethSumanBathini

@SakethSumanBathini SakethSumanBathini commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements full emergency contact management — users can store up to 3 contacts, designate a primary, and reach them instantly with one-tap call/SMS/email actions directly from their profile.

Closes #143


What was built

New files (2)

File Purpose
server/routes/emergencyContacts.js 4 REST endpoints (GET/POST/PUT/DELETE) with validation, max-3 enforcement, and automatic primary-contact promotion
src/components/EmergencyContacts.jsx Self-contained MUI v6 component rendered inside Profile — add/edit/delete dialogs, Set-as-Primary toggle, one-tap call/SMS/email action buttons

Modified files (4)

File Change
server/models/User.js Added EmergencyContactSchema subdoc (name, relationship, phone, email, isPrimary) + emergencyContacts array field. Purely additive — zero existing fields changed.
server/index.js +1 line: mount router at /api/auth/emergency-contacts (after the existing /api/auth line)
src/pages/Profile.jsx +2 lines: import + render <EmergencyContacts /> below the existing profile card
src/i18n/locales/en.json +28 keys in the profile namespace (all emergency-contact strings). fallbackLng: "en" means other locales degrade gracefully until translated.

API endpoints

All routes require Authorization: Bearer <token> (handled by the existing authMiddleware).

Method Endpoint Description
GET /api/auth/emergency-contacts List the user's contacts
POST /api/auth/emergency-contacts Add a contact (name + phone required; max 3 enforced; first contact auto-set as primary)
PUT /api/auth/emergency-contacts/:id Update a contact's fields; setting isPrimary: true clears the previous primary
DELETE /api/auth/emergency-contacts/:id Remove a contact; if it was primary, the next contact is auto-promoted

Frontend features

  • Add / Edit / Delete — inline form with confirmation dialog for destructive actions
  • Set as Primary — star icon on each non-primary card; exactly one primary always maintained
  • Quick-access actions — one-tap tel:, sms:, and mailto: links on each contact card
  • Max-3 guard — Add button disabled + info banner once the limit is reached
  • Relationship field — optional free-text (Mother, Spouse, Friend, etc.)
  • Loading + error states — spinner on fetch, alert on API errors
  • Note on "notify" — the issue describes quick notification of contacts. The app has no server-side SMS/email infrastructure, so notifications are implemented as instant device-native links (tel/sms/mailto), which work offline and require no external API keys

PR isolation from open PR #183

This PR deliberately avoids touching server/routes/auth.js or src/context/AuthContext.js (both modified in open PR #183). Emergency-contact data flows through dedicated endpoints, so the two PRs modify different hunks of server/index.js and share no other files — they auto-merge in either order.


Verification

Check Result
node --check on all 3 backend files
User model: subdoc _id, default empty array, .id() lookup
4 routes load: GET / POST / PUT / DELETE
8/8 logic assertions: auto-primary, max-3 block, primary-clearing, promote-on-delete, no-crash on bad id
Both JSX files compile
All 28 t('profile:…') keys present in en.json
All 21 MUI components + 8 icons are valid v6 exports
en.json valid JSON (46 total profile keys)
User.js: zero removals — purely additive
index.js: +1 line only
Profile.jsx: +import +render only

Checklist

  • Assigned before opening this PR (vallabhatech replied "kindly proceed!")
  • Branch based on main
  • No new npm dependencies added
  • All new i18n keys documented in en.json; other locales fall back to English via fallbackLng

Summary by CodeRabbit

  • New Features
    • Users can now add, edit, and remove up to 3 emergency contacts from their profile
    • Users can designate a primary emergency contact for faster access
    • Emergency contacts support quick actions: call, message, and email
    • Emergency contact management is now available in multiple languages with localized labels and feedback messages

@vercel

vercel Bot commented Jun 20, 2026

Copy link
Copy Markdown

@SakethSumanBathini is attempting to deploy a commit to the vallabhatech's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a33729f7-5d32-4e23-83cf-68f635b10196

📥 Commits

Reviewing files that changed from the base of the PR and between 790f92e and 1aeef03.

📒 Files selected for processing (10)
  • server/routes/emergencyContacts.js
  • src/i18n/locales/ar.json
  • src/i18n/locales/de.json
  • src/i18n/locales/es.json
  • src/i18n/locales/fr.json
  • src/i18n/locales/hi.json
  • src/i18n/locales/ja.json
  • src/i18n/locales/pt.json
  • src/i18n/locales/ru.json
  • src/i18n/locales/zh.json
✅ Files skipped from review due to trivial changes (6)
  • src/i18n/locales/fr.json
  • src/i18n/locales/hi.json
  • src/i18n/locales/es.json
  • src/i18n/locales/zh.json
  • src/i18n/locales/de.json
  • src/i18n/locales/ru.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/routes/emergencyContacts.js

📝 Walkthrough

Walkthrough

Adds end-to-end emergency contact management. A new EmergencyContactSchema is embedded in UserSchema. An Express router exposes authenticated GET, POST, PUT, and DELETE endpoints at /api/auth/emergency-contacts, enforcing a 3-contact maximum and primary-contact promotion logic. A React EmergencyContacts component with CRUD forms, contact cards, and a delete-confirmation dialog is added to the Profile page, backed by new i18n strings in 10 languages.

Changes

Emergency Contact Management

Layer / File(s) Summary
EmergencyContact Mongoose schema
server/models/User.js
Introduces EmergencyContactSchema (name, relationship, phone, email, isPrimary with constraints/defaults) as an embedded subdocument and adds emergencyContacts: [EmergencyContactSchema] array to UserSchema.
Emergency contacts API router
server/routes/emergencyContacts.js, server/index.js
Defines an authMiddleware-protected Express router with GET (fetch all), POST (add with count limit and primary logic), PUT (update fields with isPrimary promotion), and DELETE (remove with primary reassignment). Mounts the router at /api/auth/emergency-contacts.
EmergencyContacts React component and English localization
src/components/EmergencyContacts.jsx, src/i18n/locales/en.json
Adds the EmergencyContacts component handling fetch-on-mount, add/edit/delete/set-primary flows with a max-3 guard, flash alerts, loading state, contact cards with call/SMS/email action links, and a delete confirmation dialog. Includes all required English UI strings in the profile i18n section.
Localization for additional languages
src/i18n/locales/ar.json, src/i18n/locales/de.json, src/i18n/locales/es.json, src/i18n/locales/fr.json, src/i18n/locales/hi.json, src/i18n/locales/ja.json, src/i18n/locales/pt.json, src/i18n/locales/ru.json, src/i18n/locales/zh.json
Adds emergency contacts UI translations in Arabic, German, Spanish, French, Hindi, Japanese, Portuguese, Russian, and Mandarin, mirroring English localization keys across titles, form labels, field placeholders, primary-contact actions, success/error/validation messages, and load failures.
Profile page integration
src/pages/Profile.jsx
Imports and renders EmergencyContacts inside the Profile card content area.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant ProfilePage
  participant EmergencyContacts
  participant API as /api/auth/emergency-contacts
  participant MongoDB

  User->>ProfilePage: Open profile
  ProfilePage->>EmergencyContacts: render
  EmergencyContacts->>API: GET /
  API->>MongoDB: User.findById(req.user.id)
  MongoDB-->>API: user.emergencyContacts[]
  API-->>EmergencyContacts: 200 contacts[]

  User->>EmergencyContacts: Submit add/edit form
  EmergencyContacts->>API: POST / or PUT /:id
  API->>MongoDB: user.save()
  MongoDB-->>API: updated contacts[]
  API-->>EmergencyContacts: 201/200 contacts[]
  EmergencyContacts-->>User: Flash success alert

  User->>EmergencyContacts: Confirm delete
  EmergencyContacts->>API: DELETE /:id
  API->>MongoDB: splice + promote primary + user.save()
  MongoDB-->>API: updated contacts[]
  API-->>EmergencyContacts: 200 contacts[]
  EmergencyContacts-->>User: Flash success alert
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • vallabhatech/CareSync#52: Extends i18n locale JSONs with profile/emergency-contacts strings consumed by the new EmergencyContacts UI, building on react-i18next infrastructure.
  • vallabhatech/CareSync#54: Both PRs modify server/index.js to mount authenticated API routers in the Express middleware chain; main PR adds /api/auth/emergency-contacts after existing /api/auth mounting.

Suggested labels

ELUSOC, VETERAN, documentation, enhancement, ui/ux, frontend, backend

Suggested reviewers

  • vallabhatech

Poem

🐇 Hop hop, the rabbit checks who to call,
Three contacts stored, that covers them all.
A name, a phone, an email just in case,
One marked "primary" — first in the race.
With a form and a flash, the UI shines bright,
Emergency ready from morning to night! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly matches the main changes: implementing emergency contact management with full CRUD operations, primary contact support, and quick-access actions.
Linked Issues check ✅ Passed All coding requirements from #143 are met: emergency contact storage (User model schema, MongoDB backend), CRUD operations (emergencyContacts routes), primary contact designation, and quick-access actions (call/SMS/email buttons).
Out of Scope Changes check ✅ Passed All changes directly support emergency contact management: schema, routes, frontend component, i18n translations, and profile integration are all in scope per #143.

✏️ 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

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@server/routes/emergencyContacts.js`:
- Line 37: The isPrimary variable assignment on lines 37 and 114 uses Boolean()
coercion which incorrectly treats the string "false" as truthy, causing wrong
primary contact reassignment. Replace the Boolean(req.body.isPrimary) calls with
explicit validation that checks if the value is specifically the string "true"
(such as comparing req.body.isPrimary === "true" or req.body.isPrimary === true)
to properly distinguish between true and false values from the request body.
🪄 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 Plus

Run ID: bceb27f6-1eb6-4923-a007-fd641e14459e

📥 Commits

Reviewing files that changed from the base of the PR and between 636917d and 790f92e.

📒 Files selected for processing (6)
  • server/index.js
  • server/models/User.js
  • server/routes/emergencyContacts.js
  • src/components/EmergencyContacts.jsx
  • src/i18n/locales/en.json
  • src/pages/Profile.jsx

Comment thread server/routes/emergencyContacts.js Outdated
…8n key-structure test) and fix Boolean isPrimary coercion
@SakethSumanBathini

Copy link
Copy Markdown
Contributor Author

Hi @vallabhatech — follow-up commit (1aeef03) addresses both review findings: the Boolean coercion bug on isPrimary, and CI now passes with 30/30 tests (added the new i18n keys to all 9 locale files). Ready for review whenever you have a moment!

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
4.9% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@SakethSumanBathini

Copy link
Copy Markdown
Contributor Author

Quality Gate Failed Quality Gate failed

Failed conditions 4.9% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

The 4.9% duplication flag is a false positive inherent to i18n locale files — SonarQube sees identical JSON key names (e.g. "emergencyContactsTitle") across all 10 locale files and counts them as duplicate code, even though the values are different translations. This can be resolved by adding src/i18n/locales/** to SonarQube's duplication exclusions in the project settings.

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.

Emergency Contact Management

1 participant