feat: implement Community Health Forums (#221) - #268
Conversation
|
@Dev1822 is attempting to deploy a commit to the vallabhatech's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
Warning Review limit reached
Next review available in: 56 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAdds a community forums feature spanning Mongoose models, Express APIs, frontend navigation and pages, topic interactions, anonymous posting, voting, reporting, and moderator actions. ChangesCommunity Forums
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Visitor
participant ForumsDashboard
participant TopicView
participant forums.js
participant MongoDB
Visitor->>ForumsDashboard: open /forums
ForumsDashboard->>forums.js: GET categories
forums.js->>MongoDB: query ForumCategory
MongoDB-->>forums.js: categories
forums.js-->>ForumsDashboard: category response
Visitor->>TopicView: open a topic
TopicView->>forums.js: GET topic and posts
forums.js->>MongoDB: query ForumTopic and ForumPost
MongoDB-->>forums.js: topic and posts
forums.js-->>TopicView: topic response
Visitor->>TopicView: submit reply or upvote
TopicView->>forums.js: POST interaction
forums.js->>MongoDB: save interaction
MongoDB-->>forums.js: updated record
forums.js-->>TopicView: updated response
Suggested reviewers: 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 15
🧹 Nitpick comments (4)
server/models/ForumTopic.js (1)
4-8: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAdd indexes matching the new forum query patterns.
The primary listing and moderation queries otherwise degrade into collection scans as forum data grows.
server/models/ForumTopic.js#L4-L8: index category and activity ordering used by topic listings.server/models/ForumPost.js#L4-L8: index topic and creation ordering used by discussion loading.server/models/ForumReport.js#L23-L31: index report status and descending creation time.🤖 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 `@server/models/ForumTopic.js` around lines 4 - 8, Replace the affected schema definitions with indexes matching the forum query patterns: in server/models/ForumTopic.js at lines 4-8, add a compound index on category and activity ordering; in server/models/ForumPost.js at lines 4-8, add a compound index on topic and creation ordering; and in server/models/ForumReport.js at lines 23-31, add a compound index on report status and descending creation time.src/pages/Forums/TopicView.jsx (1)
38-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the API base URL to a constant.
The API base URL (
process.env.REACT_APP_API_URL || 'http://localhost:5000') is hardcoded in multipleaxioscalls throughout this component. Extracting it into a top-level constant will improve readability and make the code easier to maintain.♻️ Proposed refactor
Define the constant outside the
TopicViewcomponent:const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';Then update all
axioscalls to use the constant. For example:- const res = await axios.get(`${process.env.REACT_APP_API_URL || 'http://localhost:5000'}/api/forums/topics/${topicId}`); + const res = await axios.get(`${API_BASE_URL}/api/forums/topics/${topicId}`);🤖 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 `@src/pages/Forums/TopicView.jsx` at line 38, Extract the repeated API base URL expression into a top-level API_BASE_URL constant outside the TopicView component, then update every axios call in TopicView to build its request URL from that constant while preserving the existing endpoint paths.src/pages/Forums/ModerationDashboard.jsx (2)
111-111: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify with optional chaining.
You can use optional chaining to make this property access more concise and readable.
✨ Proposed refactor
- <TableCell>{report.reportedBy ? report.reportedBy.name : 'Unknown'}</TableCell> + <TableCell>{report.reportedBy?.name || 'Unknown'}</TableCell>🤖 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 `@src/pages/Forums/ModerationDashboard.jsx` at line 111, Update the reportedBy display in the moderation dashboard table to use optional chaining for the nested name access, while preserving “Unknown” as the fallback when reportedBy or its name is absent.
58-58: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winValidate
targetTypeto prevent unintended API calls.Falling back to the
postsendpoint for anytargetTypethat isn't'Topic'could lead to unintended deletions if new report types (e.g.,'User','Comment') are introduced later. Consider adding an explicit check to throw an error or abort if the type is unrecognized.🛡️ Proposed refactor
- const endpoint = targetType === 'Topic' ? `/api/forums/topics/${targetId}` : `/api/forums/posts/${targetId}`; + if (targetType !== 'Topic' && targetType !== 'Post') { + throw new Error(`Unsupported target type: ${targetType}`); + } + const endpoint = targetType === 'Topic' ? `/api/forums/topics/${targetId}` : `/api/forums/posts/${targetId}`;🤖 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 `@src/pages/Forums/ModerationDashboard.jsx` at line 58, Validate targetType before constructing the endpoint in the moderation action: allow only 'Topic' and 'Post', map each explicitly to its corresponding API path, and abort or throw for any unrecognized type instead of defaulting to the posts endpoint. Update the endpoint logic near the targetType check while preserving existing behavior for valid report types.
🤖 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/models/ForumTopic.js`:
- Around line 51-55: Update the ForumTopicSchema.pre('save') hook so vote-only
saves do not modify updatedAt; preserve updatedAt changes for genuine topic
activity by setting it explicitly in the relevant activity-update paths, or use
a dedicated lastActivityAt field consistently for sorting and activity tracking.
In `@server/routes/forums.js`:
- Around line 160-161: Update the ForumTopic lookups in both voting routes to
exclude soft-deleted topics by adding a status-not-deleted condition to each
findById query. Preserve the existing 404 response when no eligible topic is
found.
- Around line 231-234: Update the ForumReport query in the pending-reports route
to stop populating the reporter’s email address by default. Keep the reporter
name and existing report/target data available, and only expose email through a
separate explicitly authorized admin workflow if such a path already exists.
- Around line 64-69: Update the public forum query handlers for category topics
and topic posts to use cursor-based pagination with a bounded page size. Apply
the cursor and limit to the Mongoose queries, return pagination metadata or a
next cursor consistent with the API contract, and preserve the existing sorting,
filtering, and response behavior for each page.
- Around line 97-111: In the topic creation handler, validate categoryId as a
valid MongoDB ObjectId and use ForumCategory.findById to confirm the category
exists before constructing or saving ForumTopic; return a 404 response when no
category is found, while preserving the existing 400 response for missing
required fields.
- Around line 46-54: Update the error handling in the POST /categories handler
around ForumCategory.save: return status 400 for validation errors and status
409 for duplicate-key conflicts, while preserving the existing 500 response for
other unexpected errors.
- Around line 206-220: Update the POST /reports handler to validate targetId as
a valid ObjectId, then fetch the matching active forum topic or post based on
targetType before constructing ForumReport. Return a client error when the
identifier is invalid or no active target exists, and only call report.save()
after the target lookup succeeds.
- Around line 163-171: Update the topic vote-toggle logic around upvoteIndex and
topic.save() to use one atomic conditional document update instead of reading,
mutating, and saving the topic in separate steps. Make the update add
req.user._id when the user has not upvoted and remove it when they have,
preserving toggle behavior safely under concurrent requests.
In `@src/App.jsx`:
- Line 324: Update the forum authentication flow to use the shared AuthContext
token instead of localStorage.getItem('token') in ForumsDashboard,
CreateTopicDialog, and ModerationDashboard, preserving authenticated request
headers. Guard the /forums/moderation route in App.jsx with the existing
authentication/role protection, and gate category creation, topic creation, and
moderation controls in ForumsDashboard and TopicList according to login and
role.
In `@src/components/Forums/CreateTopicDialog.jsx`:
- Around line 17-24: Update the topic submission validation and payload
construction in CreateTopicDialog so non-anonymous posts require a display name
or use the authenticated user’s profile name; only apply the “Anonymous User”
fallback when isAnonymous is true. Ensure isAnonymous false is never submitted
with an anonymous fallback display name.
In `@src/pages/Forums/ForumsDashboard.jsx`:
- Line 92: Update the Grid usage rendering each forum category card in the
category map to use MUI v9 sizing props instead of the removed item, xs, sm, and
md props, preserving the 12/6/4 responsive column widths and the existing
cat._id key.
In `@src/pages/Forums/ModerationDashboard.jsx`:
- Line 47: Update the reports state update in handleResolve to use the
functional setter form, filtering from the latest previous reports state rather
than the captured reports array. Preserve the existing _id !== reportId removal
behavior.
In `@src/pages/Forums/TopicList.jsx`:
- Around line 88-90: In the topic upvote count display within TopicList, replace
the misleading FaComment icon with the existing or appropriate vote/up-arrow
icon while keeping the topic.upvotes count and surrounding layout unchanged.
- Around line 66-71: Replace the clickable ListItem usage in the topic list with
a non-button ListItem containing a ListItemButton configured with
disablePadding, and move the existing onClick, key, divider, and styling
behavior to the appropriate elements. Remove the obsolete button prop while
preserving navigation through navigate.
In `@src/pages/Forums/TopicView.jsx`:
- Around line 42-47: Update the token parsing inside fetchTopicData with an
inner try...catch so malformed JWTs cannot abort the topic fetch. Before calling
atob, convert the JWT payload’s Base64Url characters to standard Base64 and
handle decoding or JSON parsing failures by ignoring the user ID hint while
allowing the existing topic request to continue.
---
Nitpick comments:
In `@server/models/ForumTopic.js`:
- Around line 4-8: Replace the affected schema definitions with indexes matching
the forum query patterns: in server/models/ForumTopic.js at lines 4-8, add a
compound index on category and activity ordering; in server/models/ForumPost.js
at lines 4-8, add a compound index on topic and creation ordering; and in
server/models/ForumReport.js at lines 23-31, add a compound index on report
status and descending creation time.
In `@src/pages/Forums/ModerationDashboard.jsx`:
- Line 111: Update the reportedBy display in the moderation dashboard table to
use optional chaining for the nested name access, while preserving “Unknown” as
the fallback when reportedBy or its name is absent.
- Line 58: Validate targetType before constructing the endpoint in the
moderation action: allow only 'Topic' and 'Post', map each explicitly to its
corresponding API path, and abort or throw for any unrecognized type instead of
defaulting to the posts endpoint. Update the endpoint logic near the targetType
check while preserving existing behavior for valid report types.
In `@src/pages/Forums/TopicView.jsx`:
- Line 38: Extract the repeated API base URL expression into a top-level
API_BASE_URL constant outside the TopicView component, then update every axios
call in TopicView to build its request URL from that constant while preserving
the existing endpoint paths.
🪄 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: 5879c4be-6345-4b87-9883-4dd39595c41a
📒 Files selected for processing (13)
server/index.jsserver/models/ForumCategory.jsserver/models/ForumPost.jsserver/models/ForumReport.jsserver/models/ForumTopic.jsserver/routes/forums.jssrc/App.jsxsrc/components/Forums/CreateTopicDialog.jsxsrc/i18n/locales/en.jsonsrc/pages/Forums/ForumsDashboard.jsxsrc/pages/Forums/ModerationDashboard.jsxsrc/pages/Forums/TopicList.jsxsrc/pages/Forums/TopicView.jsx
There was a problem hiding this comment.
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 `@src/App.jsx`:
- Around line 305-313: Update RequireAuth to read the loading state from
useAuth() and return a loading/deferred state before evaluating either redirect.
Only redirect unauthenticated users to /login or unauthorized users to /forums
after loading completes, while preserving the existing access checks.
🪄 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: 94625355-b215-4c5f-8f15-74b2a8c008ae
📒 Files selected for processing (10)
server/models/ForumPost.jsserver/models/ForumReport.jsserver/models/ForumTopic.jsserver/routes/forums.jssrc/App.jsxsrc/components/Forums/CreateTopicDialog.jsxsrc/pages/Forums/ForumsDashboard.jsxsrc/pages/Forums/ModerationDashboard.jsxsrc/pages/Forums/TopicList.jsxsrc/pages/Forums/TopicView.jsx
🚧 Files skipped from review as they are similar to previous changes (5)
- server/models/ForumReport.js
- server/models/ForumTopic.js
- src/components/Forums/CreateTopicDialog.jsx
- server/routes/forums.js
- src/pages/Forums/TopicView.jsx
|
@vallabhatech , kindly suggest me any changes if needed for this pr. If not kindly merge this pr with gssoc and elusoc labels. |
|



Description
Implemented Community Health Forums to allow users to discuss health conditions, share experiences, and offer support to others in the community. This aligns with the "Ecosystem Expansion" phase and adds a dedicated social/support dimension to the platform.
The implementation includes:
ForumCategory,ForumTopic,ForumPost,ForumReport) and REST APIs.display_name).Fixes #221
Type of change
How Has This Been Tested?
Please describe the tests that you ran to verify your changes.
Checklist:
Summary by CodeRabbit