Skip to content

feat: implement Community Health Forums (#221) - #268

Open
Dev1822 wants to merge 6 commits into
vallabhatech:mainfrom
Dev1822:feature/issue-221-community-forums
Open

feat: implement Community Health Forums (#221)#268
Dev1822 wants to merge 6 commits into
vallabhatech:mainfrom
Dev1822:feature/issue-221-community-forums

Conversation

@Dev1822

@Dev1822 Dev1822 commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

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:

  • Backend data models (ForumCategory, ForumTopic, ForumPost, ForumReport) and REST APIs.
  • Privacy controls that allow users to post completely anonymously or by using a pseudonym (display_name).
  • A fully-featured frontend with a topic dashboard, categorized threads, upvoting, and a discussion view.
  • A Moderation Dashboard for admins and moderators to review user reports and delete inappropriate content.

Fixes #221

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)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes.

  • Local manual verification of the API endpoints (creating topics, upvoting, reporting).
  • Local manual verification of the React UI components ensuring proper routing and state management.

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works

Summary by CodeRabbit

  • New Features
    • Added Community Forums with categories, topic lists, topic detail with replies, and topic creation.
    • Included anonymous posting with a display-name workflow for non-anonymous posts.
    • Added upvoting and reporting for both topics and replies.
    • Introduced moderation dashboard for pending reports, resolving reports, and soft-deleting topics/posts.
    • Added Forums navigation and protected moderation access for authorized users.

@vercel

vercel Bot commented Jul 15, 2026

Copy link
Copy Markdown

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

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@vallabhatech, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 93df6fce-fc67-4100-8ea8-4d264d8b7a48

📥 Commits

Reviewing files that changed from the base of the PR and between c9318a1 and f7b2459.

📒 Files selected for processing (2)
  • src/App.jsx
  • src/i18n/locales/en.json
📝 Walkthrough

Walkthrough

Adds a community forums feature spanning Mongoose models, Express APIs, frontend navigation and pages, topic interactions, anonymous posting, voting, reporting, and moderator actions.

Changes

Community Forums

Layer / File(s) Summary
Forum data models
server/models/ForumCategory.js, server/models/ForumTopic.js, server/models/ForumPost.js, server/models/ForumReport.js
Adds schemas for categories, topics, posts, and reports with validation, indexes, timestamps, upvotes, author metadata, statuses, and save hooks.
Forum API and route mounting
server/routes/forums.js, server/index.js
Mounts the forums router and adds category, topic, post, voting, reporting, moderation, soft-delete, and report-resolution endpoints.
Forum navigation and browsing
src/App.jsx, src/i18n/locales/en.json, src/pages/Forums/ForumsDashboard.jsx, src/pages/Forums/TopicList.jsx, src/components/Forums/CreateTopicDialog.jsx
Adds forum navigation and routes, category listing and creation, topic listing, and topic creation with anonymous identity options.
Topic interactions
src/pages/Forums/TopicView.jsx
Adds topic and reply loading, reply creation, topic/post upvotes, JWT-based voter state, and report submission.
Moderation dashboard
src/pages/Forums/ModerationDashboard.jsx
Adds pending-report loading, report resolution, and confirmed topic/post deletion actions.

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
Loading

Suggested reviewers: kiranhk-code, diksha78dev

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Core forum models, APIs, anonymity, moderation, and UI are implemented, but sorting/searching from #221 are not evident in the changes. Add forum topic/category sorting and search/filtering, then verify the implementation covers the full #221 usability scope.
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 (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: implementing the Community Health Forums feature.
Out of Scope Changes check ✅ Passed The changes stay focused on the forums feature and do not introduce unrelated scope.
✨ 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.

@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: 15

🧹 Nitpick comments (4)
server/models/ForumTopic.js (1)

4-8: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add 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 value

Extract the API base URL to a constant.

The API base URL (process.env.REACT_APP_API_URL || 'http://localhost:5000') is hardcoded in multiple axios calls 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 TopicView component:

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';

Then update all axios calls 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 value

Simplify 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 win

Validate targetType to prevent unintended API calls.

Falling back to the posts endpoint for any targetType that 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

📥 Commits

Reviewing files that changed from the base of the PR and between 80dcf6a and 4f9849d.

📒 Files selected for processing (13)
  • server/index.js
  • server/models/ForumCategory.js
  • server/models/ForumPost.js
  • server/models/ForumReport.js
  • server/models/ForumTopic.js
  • server/routes/forums.js
  • src/App.jsx
  • src/components/Forums/CreateTopicDialog.jsx
  • src/i18n/locales/en.json
  • src/pages/Forums/ForumsDashboard.jsx
  • src/pages/Forums/ModerationDashboard.jsx
  • src/pages/Forums/TopicList.jsx
  • src/pages/Forums/TopicView.jsx

Comment thread server/models/ForumTopic.js
Comment thread server/routes/forums.js
Comment thread server/routes/forums.js
Comment thread server/routes/forums.js
Comment thread server/routes/forums.js Outdated
Comment thread src/pages/Forums/ForumsDashboard.jsx Outdated
Comment thread src/pages/Forums/ModerationDashboard.jsx Outdated
Comment thread src/pages/Forums/TopicList.jsx Outdated
Comment thread src/pages/Forums/TopicList.jsx
Comment thread src/pages/Forums/TopicView.jsx

@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 `@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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f9849d and c9318a1.

📒 Files selected for processing (10)
  • server/models/ForumPost.js
  • server/models/ForumReport.js
  • server/models/ForumTopic.js
  • server/routes/forums.js
  • src/App.jsx
  • src/components/Forums/CreateTopicDialog.jsx
  • src/pages/Forums/ForumsDashboard.jsx
  • src/pages/Forums/ModerationDashboard.jsx
  • src/pages/Forums/TopicList.jsx
  • src/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

Comment thread src/App.jsx
@Dev1822

Dev1822 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

@vallabhatech , kindly suggest me any changes if needed for this pr. If not kindly merge this pr with gssoc and elusoc labels.

@sonarqubecloud

Copy link
Copy Markdown

@github-actions github-actions Bot added bug Something isn't working documentation Improvements or additions to documentation enhancement New feature or request frontend ui/ux labels Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working documentation Improvements or additions to documentation enhancement New feature or request frontend ui/ux

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Community Health Forums

2 participants