refactor: clean up Incident module code#109
Conversation
- Replace manual getters/setters with @Getter/@Setter in Incident entity - Replace manual constructor with @requiredargsconstructor in IncidentService - Extract getUser() helper method in IncidentController - Standardize @AuthenticationPrincipal parameter name to userDetails - Replace SecurityContextHolder with @AuthenticationPrincipal in getIncidentById - Extract validateNotClosed() and validateHandlerOrAdmin() helper methods - Extract string literals to constants (TARGET_TYPE, INCIDENT_PREFIX, NOT_FOUND_MESSAGE) - Replace lambda with method reference (Objects::nonNull) in IncidentResponse - Replace unnamed exception variable with unnamed pattern (_) - Fix SonarQube warnings for logging and null-safety annotations
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 34 minutes and 5 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThe incident module undergoes refactoring to improve code maintainability. Lombok adoption replaces manual constructors and accessors in Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/java/org/example/team6backend/incident/controller/IncidentController.java (1)
151-167: 🛠️ Refactor suggestion | 🟠 Major
closeIncident/resolveIncidentbypass the newgetUser(...)helper.These two endpoints still call
userDetails.getUser()directly. IfuserDetailsis null (e.g., principal resolution edge cases like the ones the helper was specifically introduced to handle), this throws NPE instead of returning401. For consistency withcreateIncident,assignIncident,unassignIncident,updateStatus, etc., route them throughgetUser(...)too.♻️ Suggested change
public ResponseEntity<IncidentResponse> closeIncident(`@PathVariable` Long incidentId, `@AuthenticationPrincipal` CustomUserDetails userDetails) { log.info("PATCH /api/incidents/{}/close - Closing incident", incidentId); - Incident closedIncident = incidentService.closeIncident(incidentId, userDetails.getUser()); + Incident closedIncident = incidentService.closeIncident(incidentId, getUser(userDetails)); return ResponseEntity.ok(IncidentResponse.fromEntityBasic(closedIncident)); } ... public ResponseEntity<IncidentResponse> resolveIncident(`@PathVariable` Long incidentId, `@AuthenticationPrincipal` CustomUserDetails userDetails) { log.info("PATCH /api/incidents/{}/resolve - Resolving incident", incidentId); - Incident resolvedIncident = incidentService.resolveIncident(incidentId, userDetails.getUser()); + Incident resolvedIncident = incidentService.resolveIncident(incidentId, getUser(userDetails)); return ResponseEntity.ok(IncidentResponse.fromEntityBasic(resolvedIncident)); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/org/example/team6backend/incident/controller/IncidentController.java` around lines 151 - 167, The closeIncident and resolveIncident methods call userDetails.getUser() directly which can NPE; instead, use the controller's existing getUser(...) helper to resolve the authenticated user and return 401 when it is absent. Update closeIncident(...) and resolveIncident(...) to call getUser(userDetails) (or whatever the helper signature is) and pass the returned User to incidentService.closeIncident(...) / incidentService.resolveIncident(...), keeping the existing logging and ResponseEntity.ok(...) flow.
🧹 Nitpick comments (1)
src/main/java/org/example/team6backend/incident/service/IncidentService.java (1)
144-146:getByIdskipped theNOT_FOUND_MESSAGEstandardization.Every other lookup in this file (
deleteIncident,assignIncidentToHandler,updateIncidentStatus,unassignIncident,closeIncident,resolveIncident) was migrated toNOT_FOUND_MESSAGE + incidentId, butgetByIdstill throws a generic"Not found". Worth aligning so the error surface is uniform and consumers can rely on a single message format.♻️ Suggested change
- public Incident getById(Long id, AppUser user) { - Incident incident = incidentRepository.findByIdWithDocuments(id) - .orElseThrow(() -> new ResourceNotFoundException("Not found")); + public Incident getById(Long id, AppUser user) { + Incident incident = incidentRepository.findByIdWithDocuments(id) + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + id));🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/org/example/team6backend/incident/service/IncidentService.java` around lines 144 - 146, The getById method in IncidentService throws a hardcoded "Not found"; change it to use the standardized NOT_FOUND_MESSAGE concatenated with the incident id to match other lookups: update the ResourceNotFoundException thrown in getById (after incidentRepository.findByIdWithDocuments(id)) to throw new ResourceNotFoundException(NOT_FOUND_MESSAGE + id) so the error format is consistent with deleteIncident, assignIncidentToHandler, updateIncidentStatus, unassignIncident, closeIncident and resolveIncident.
🤖 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/incident/controller/IncidentController.java`:
- Around line 46-56: In getUser(CustomUserDetails userDetails) remove the
System.out.println debug call and avoid dereferencing userDetails before
null-check: first check if (userDetails == null) and only then fall back to
SecurityContextHolder auth lookup (as done now), and if auth principal is a
CustomUserDetails cd, verify cd.getUser() is non-null before returning it; if
cd.getUser() is null or no auth principal is present throw new
ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required"). If
you want to keep a debug message use the class SLF4J logger at debug level
(log.debug(...)) after confirming userDetails != null.
In `@src/main/java/org/example/team6backend/incident/dto/IncidentResponse.java`:
- Around line 63-66: The catch block in IncidentResponse that currently reads
"catch (Exception _)" swallows all exceptions and should at minimum log the
throwable before falling back to response.setHasDocuments(false) and
response.setDocuments(new ArrayList<>()); add an SLF4J logger to the class (or
move this mapping out of the DTO into a service/mapper) and change the catch to
log the exception at warn or debug level (including the exception object) so
failures like LazyInitializationException are visible while preserving the
fallback behavior.
In
`@src/main/java/org/example/team6backend/incident/service/IncidentService.java`:
- Around line 253-254: Replace the 3-arg auditLogService.log calls for the
security-relevant operations UPDATE_STATUS, UNASSIGN_INCIDENT, CLOSE_INCIDENT,
and RESOLVE_INCIDENT with the 5-arg overload that includes the target type and
target id so audit filtering works; specifically, for each call that currently
invokes auditLogService.log(operation, currentUser.getName() + " changed " +
INCIDENT_PREFIX + incidentId + ... , currentUser) (and the analogous message
patterns for unassign/close/resolve), pass the Incident target type constant and
incidentId as the fourth and fifth arguments (i.e.,
auditLogService.log(operation, message, currentUser, TARGET_TYPE, incidentId)),
keeping the existing message, currentUser, INCIDENT_PREFIX and incidentId
variables intact.
In
`@src/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java`:
- Around line 132-135: In IncidentControllerTest::getById_shouldBlockIfAnonymous
replace the broad .andExpect(status().is4xxClientError()) with a specific
expected status to avoid masking regressions (e.g.,
.andExpect(status().isUnauthorized()) or .andExpect(status().isForbidden())
depending on the security contract you intend); update the assertion to the
precise status that the controller/security layer should return for anonymous
users so the test fails if it changes unexpectedly.
---
Outside diff comments:
In
`@src/main/java/org/example/team6backend/incident/controller/IncidentController.java`:
- Around line 151-167: The closeIncident and resolveIncident methods call
userDetails.getUser() directly which can NPE; instead, use the controller's
existing getUser(...) helper to resolve the authenticated user and return 401
when it is absent. Update closeIncident(...) and resolveIncident(...) to call
getUser(userDetails) (or whatever the helper signature is) and pass the returned
User to incidentService.closeIncident(...) /
incidentService.resolveIncident(...), keeping the existing logging and
ResponseEntity.ok(...) flow.
---
Nitpick comments:
In
`@src/main/java/org/example/team6backend/incident/service/IncidentService.java`:
- Around line 144-146: The getById method in IncidentService throws a hardcoded
"Not found"; change it to use the standardized NOT_FOUND_MESSAGE concatenated
with the incident id to match other lookups: update the
ResourceNotFoundException thrown in getById (after
incidentRepository.findByIdWithDocuments(id)) to throw new
ResourceNotFoundException(NOT_FOUND_MESSAGE + id) so the error format is
consistent with deleteIncident, assignIncidentToHandler, updateIncidentStatus,
unassignIncident, closeIncident and resolveIncident.
🪄 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: 153ab0d4-5845-40e7-856c-772289584b4b
📒 Files selected for processing (5)
src/main/java/org/example/team6backend/incident/controller/IncidentController.javasrc/main/java/org/example/team6backend/incident/dto/IncidentResponse.javasrc/main/java/org/example/team6backend/incident/entity/Incident.javasrc/main/java/org/example/team6backend/incident/service/IncidentService.javasrc/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java
- Fix anonymous user test to expect 401 instead of generic 4xx - Add targetType and targetId to all audit log calls in IncidentService - Add warning log when document loading fails in IncidentResponse - Remove debug System.out.println from getUser() helper - Add null check for cd.getUser() in getUser() fallback path
Summary by CodeRabbit
Bug Fixes
Refactor
Tests