Skip to content

Refactor/comment controller rest#97

Merged
HerrKanin merged 3 commits into
mainfrom
refactor/comment-controller-rest
Apr 23, 2026
Merged

Refactor/comment controller rest#97
HerrKanin merged 3 commits into
mainfrom
refactor/comment-controller-rest

Conversation

@HerrKanin

@HerrKanin HerrKanin commented Apr 22, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Release Notes

  • Refactor
    • Modernized comment submission handling with REST API patterns instead of server-side redirects
    • Enhanced client-side form interactions for improved asynchronous comment processing

@coderabbitai

coderabbitai Bot commented Apr 22, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The pull request converts CommentController from @Controller to @RestController and restructures the comment submission flow from form-encoded POST with server-side redirect to JSON-based REST request with explicit status response. Corresponding test and frontend changes update request/response handling to match the new REST semantics.

Changes

Cohort / File(s) Summary
REST Controller Conversion
src/main/java/org/example/team6backend/comment/controller/CommentController.java
Changed annotation from @Controller to @RestController; updated POST /comments to accept @RequestBody and return ResponseEntity<Void> with 200 OK instead of redirect string; removed @ResponseBody from GET /comments/incident/{incidentId}.
Test Request/Response Format
src/test/java/org/example/team6backend/comment/controller/CommentControllerTest.java
Updated shouldCreateCommentAndRedirectToIncidentPage test to send JSON request body instead of form parameters; changed expected response from 3xxRedirection to isOk() status.
Frontend Form Submission
src/main/resources/static/viewincident.html
Replaced server-posting HTML form with client-side JavaScript handler; added submitComment() function that sends JSON POST to /comments, attaches CSRF token via header, validates input, handles response, and refreshes comments and activity log on success.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Feature/comment #49: Directly related—modifies the same CommentController to expose REST endpoints for /comments with JSON request/response handling.
  • Feature/view incident #71: Directly related—also modifies CommentController and updates the same /comments endpoints with REST-style request binding and response type changes.

Poem

🐰 A hop from forms to JSON streams so clean,
Where redirects once flew, responses now convene,
The rabbit's REST API dances bright,
AJAX whispers through the digital night,
Comments flow as JSON takes flight! ✨

🚥 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 title accurately describes the main change: refactoring CommentController from @Controller to @RestController, which is the primary architectural change across the codebase.
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
  • Commit unit tests in branch refactor/comment-controller-rest

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: 2

🧹 Nitpick comments (1)
src/test/java/org/example/team6backend/comment/controller/CommentControllerTest.java (1)

60-67: Rename the test to match the REST behavior.

The test no longer verifies a redirect, so the current name is stale.

♻️ Proposed rename
-	void shouldCreateCommentAndRedirectToIncidentPage() throws Exception {
+	void shouldCreateCommentWithJsonPayload() throws Exception {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/org/example/team6backend/comment/controller/CommentControllerTest.java`
around lines 60 - 67, The test method
shouldCreateCommentAndRedirectToIncidentPage() has a stale name because it no
longer asserts a redirect; rename it to reflect the actual behavior (e.g.,
shouldCreateCommentAndReturnOk or shouldCreateCommentAndRespondWithStatusOk) and
update the method name in CommentControllerTest accordingly so any references
(the `@Test` method name shouldCreateCommentAndRedirectToIncidentPage) match the
new name; do not change the assertions or request payload, only rename the test
method for clarity.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@src/main/java/org/example/team6backend/comment/controller/CommentController.java`:
- Around line 31-32: The createComment controller method currently uses
request.getUserId(), allowing client-controlled impersonation; update the method
signature to accept `@AuthenticationPrincipal` CustomUserDetails userDetails and
pass userDetails.getUser().getId() into commentService.createComment instead of
request.getUserId(), and remove the userId field and its getter from
CommentRequest so the controller derives the user id from the authenticated
principal; keep the rest of the call (incidentId and message) unchanged and
mirror the pattern used in UserController/NotificationController.

In `@src/main/resources/templates/viewincident.html`:
- Around line 162-163: The viewIncident handler does not add the CSRF token to
the model while the template expects ${_csrf.token} and ${_csrf.headerName};
update the viewIncident method to supply the CSRF token the same way
createIncident does — accept a CsrfToken parameter (or obtain it from the
request) and call model.addAttribute("_csrf", csrf) so the template can read
token and headerName for the fetch POST to /comments.

---

Nitpick comments:
In
`@src/test/java/org/example/team6backend/comment/controller/CommentControllerTest.java`:
- Around line 60-67: The test method
shouldCreateCommentAndRedirectToIncidentPage() has a stale name because it no
longer asserts a redirect; rename it to reflect the actual behavior (e.g.,
shouldCreateCommentAndReturnOk or shouldCreateCommentAndRespondWithStatusOk) and
update the method name in CommentControllerTest accordingly so any references
(the `@Test` method name shouldCreateCommentAndRedirectToIncidentPage) match the
new name; do not change the assertions or request payload, only rename the test
method for clarity.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 11a5c1c0-9970-4c8e-a1f4-9c9e9de84ffb

📥 Commits

Reviewing files that changed from the base of the PR and between 90400b1 and 069494d.

📒 Files selected for processing (3)
  • src/main/java/org/example/team6backend/comment/controller/CommentController.java
  • src/main/resources/templates/viewincident.html
  • src/test/java/org/example/team6backend/comment/controller/CommentControllerTest.java

Comment thread src/main/resources/static/viewincident.html

@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

🧹 Nitpick comments (1)
src/main/resources/static/viewincident.html (1)

159-172: Minor: textarea should have a name/id-based label and wire CSRF header name safely.

Nitpicks on the new form:

  • The <textarea> has no associated <label> — accessibility-only concern, low priority.
  • [csrfHeader]: csrfToken uses the hidden-input value as a dynamic header name. If csrfHeader renders empty (see the CSRF model concern), this becomes header "": "", which some browsers silently drop and Spring will then reject. Consider defaulting to "X-CSRF-TOKEN" when the rendered value is empty, or validating before sending:
if (!csrfHeader || !csrfToken) {
    console.error("CSRF token not available");
    alert("Session expired, please reload the page.");
    return;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/resources/static/viewincident.html` around lines 159 - 172, The
textarea in the comment form (id="messageInput") lacks an associated label—add a
<label> tied to messageInput (using for/id or a hidden label for visual design)
to improve accessibility; and when building the CSRF header for the request,
validate the hidden inputs csrfHeader and csrfToken (ids "csrfHeader" and
"csrfToken") and default the header name to "X-CSRF-TOKEN" if csrfHeader is
empty or missing, or show a user-friendly error/abort (e.g., log and alert) when
either value is absent before sending the request to avoid sending an empty
header name.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/resources/static/viewincident.html`:
- Around line 377-415: In submitComment, prevent double-submits by disabling the
form submitter during the async fetch and re-enabling it in finally: capture the
button via event.submitter (or fallback to
document.getElementById("submitCommentBtn") if you use an explicit id), set
disabled = true before the fetch and ensure disabled = false in a finally block
after loadComments/loadActivityLog; also add a client-side guard that reads
document.getElementById("userIdInput").value.trim() and alerts/returns if empty
(so you don't send a request with blank userId), keeping the existing behavior
of trimming message and existing headers (csrfToken/csrfHeader) and reusing the
same JSON payload structure.

---

Nitpick comments:
In `@src/main/resources/static/viewincident.html`:
- Around line 159-172: The textarea in the comment form (id="messageInput")
lacks an associated label—add a <label> tied to messageInput (using for/id or a
hidden label for visual design) to improve accessibility; and when building the
CSRF header for the request, validate the hidden inputs csrfHeader and csrfToken
(ids "csrfHeader" and "csrfToken") and default the header name to "X-CSRF-TOKEN"
if csrfHeader is empty or missing, or show a user-friendly error/abort (e.g.,
log and alert) when either value is absent before sending the request to avoid
sending an empty header name.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c8a6b645-9cf6-482f-8b84-c359c54418e0

📥 Commits

Reviewing files that changed from the base of the PR and between 069494d and e7f3063.

📒 Files selected for processing (1)
  • src/main/resources/static/viewincident.html

Comment thread src/main/resources/static/viewincident.html
@HerrKanin
HerrKanin merged commit 8e74b47 into main Apr 23, 2026
3 checks passed
@kristinaxm
kristinaxm deleted the refactor/comment-controller-rest branch April 23, 2026 17:30
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.

1 participant