Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(j-s): Update subpoena status from digital-mailbox #16645

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

oddsson
Copy link
Member

@oddsson oddsson commented Oct 30, 2024

Update subpoena status from digital-mailbox

Asana

What

When a case is fetched on minar-sidur, we now check if we've received a subpoena status from LRH and if not, we try to fetch it from them.

Why

LRH sends the subpoena status when it changes on their end. If something happens and they are unable to do so, then this is a failsafe.

Checklist:

  • I have performed a self-review of my own code
  • 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
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced a new controller, InternalPoliceController, allowing users to retrieve the status of subpoenas via a dedicated GET endpoint.
  • Improvements

    • Enhanced the getSubpoenaStatus method to allow optional user parameters, improving flexibility in request handling.
    • Added error handling for service status retrieval in the CaseService, ensuring better reliability and user feedback.

These updates enhance the functionality and user experience within the judicial system application.

@oddsson oddsson requested a review from a team as a code owner October 30, 2024 11:46
Copy link
Contributor

coderabbitai bot commented Oct 30, 2024

Walkthrough

A new controller, InternalPoliceController, has been added to the police module, which includes a GET endpoint for retrieving the status of a subpoena. This endpoint requires authentication and checks for the existence of a case. Additionally, the PoliceService has been updated to make the user parameter optional in its getSubpoenaStatus method. Furthermore, a new private method, fetchServiceStatus, has been introduced in the CaseService to handle service status retrieval for subpoenas.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts Added InternalPoliceController and getSubpoenaStatus method to handle subpoena status requests.
apps/judicial-system/backend/src/app/modules/police/police.module.ts Updated PoliceModule to include InternalPoliceController.
apps/judicial-system/backend/src/app/modules/police/police.service.ts Modified getSubpoenaStatus method to make the user parameter optional and updated logging logic.
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts Added fetchServiceStatus method to retrieve service status of subpoenas and updated getCaseInfo.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb
  • gudjong

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (5)
apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (3)

13-16: Consider adding rate limiting for the internal API.

While the endpoint is properly secured with TokenGuard and CaseExistsGuard, consider adding rate limiting to prevent potential abuse of the LRH status check endpoint.


22-26: Enhance API documentation for better clarity.

The current API documentation could be more descriptive. Consider adding:

  • Expected error responses
  • Format of the subpoena status
  • Rate limiting details if implemented

Example enhancement:

 @ApiOkResponse({
   type: Subpoena,
-  description: 'Gets subpoena status',
+  description: 'Retrieves the current status of a subpoena from LRH. Returns cached status if available, otherwise fetches fresh status.',
 })
+@ApiResponse({ status: 403, description: 'Forbidden - Invalid or missing token' })
+@ApiResponse({ status: 404, description: 'Case or subpoena not found' })

1-36: Add unit tests for the new controller.

As mentioned in the PR objectives, tests are missing. Please add unit tests to cover:

  • Successful status retrieval
  • Error handling scenarios
  • Guard behavior

Would you like me to help generate the unit test suite for this controller?

apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (1)

241-286: Consider architectural improvements for status updates.

The current implementation fetches status updates synchronously during case retrieval, which could impact response times. Consider these architectural improvements:

  1. Implement caching for status responses with a reasonable TTL
  2. Consider implementing a background job for status updates
  3. Add retry mechanism with exponential backoff for failed status fetches

This would improve performance and reliability while reducing load on the LRH service.

Would you like assistance in implementing any of these improvements?

apps/judicial-system/backend/src/app/modules/police/police.service.ts (1)

Line range hint 339-424: Consider enhancing error logging for digital-mailbox.

When the user is undefined (digital-mailbox case), we might want to include additional context in the error event to help with debugging and monitoring.

Consider adding more context to the error event:

         this.eventService.postErrorEvent(
           'Failed to get subpoena',
           {
             subpoenaId,
             actor: user?.name || 'Digital-mailbox',
             institution: user?.institution?.name,
+            source: user ? 'user' : 'digital-mailbox',
+            timestamp: new Date().toISOString(),
           },
           reason,
         )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 45ec2fd and 9cb963d.

📒 Files selected for processing (5)
  • apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/police/police.module.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/police/police.service.ts (2 hunks)
  • apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.controller.ts (1 hunks)
  • apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/police/police.module.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/police/police.service.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.controller.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
📓 Learnings (1)
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-10-14T21:34:16.234Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
🪛 Biome
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts

[error] 102-102: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
apps/judicial-system/backend/src/app/modules/police/police.module.ts (2)

17-17: LGTM! Controllers array updated correctly.

The InternalPoliceController is properly integrated into the module. Since this module uses circular dependencies with forwardRef, ensure the new controller doesn't introduce additional circular dependencies.

#!/bin/bash
# Check for potential circular dependencies in the new controller
rg -A 5 "import.*from.*police.module" --type ts

4-4: Verify the controller import path

The import path looks correct, but let's verify the file exists and follows the module structure.

✅ Verification successful

The results show that the internalPolice.controller.ts file exists in the correct location and the import path is correctly specified. The controller is properly imported and used in the police.module.ts. Let's verify the controller's implementation and its dependencies to ensure everything is properly connected.


Import path and module structure are correctly implemented

The verification confirms:

  • The internalPolice.controller.ts file exists in the correct location
  • The controller is properly imported and registered in the module
  • Circular dependencies are properly handled with forwardRef
  • The module structure follows NestJS best practices
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence and location of the controller file
fd "internalPolice.controller.ts" --type f

# Check for any other internal police related files that might need updates
rg "InternalPoliceController" --type ts

Length of output: 1433


Script:

#!/bin/bash
# Check the implementation of InternalPoliceController
ast-grep --pattern 'export class InternalPoliceController {
  $$$
}'

# Check for any circular dependencies
rg -B 2 -A 2 "forwardRef" apps/judicial-system/backend/src/app/modules/police/police.module.ts

Length of output: 501

apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (2)

1-11: LGTM! Dependencies are properly organized.

The imports are well-structured and include all necessary decorators, types, and services.


27-35: ⚠️ Potential issue

Add error handling for LRH communication failures.

The current implementation doesn't handle potential failures when communicating with LRH. Consider adding try-catch block and proper error responses.

Example implementation:

 getSubpoenaStatus(
   @Param('subpoenaId') subpoenaId: string,
   @CurrentCase() theCase: Case,
   @CurrentHttpUser() user: User,
 ): Promise<Subpoena> {
   this.logger.debug(`Gets subpoena status in case ${theCase.id}`)
-
-  return this.policeService.getSubpoenaStatus(subpoenaId, user)
+  try {
+    return this.policeService.getSubpoenaStatus(subpoenaId, user)
+  } catch (error) {
+    this.logger.error(
+      `Failed to fetch subpoena status for case ${theCase.id}`,
+      error,
+    )
+    throw new ServiceUnavailableException('Unable to fetch subpoena status from LRH')
+  }
 }

Let's verify if error handling is implemented in the PoliceService:

apps/judicial-system/backend/src/app/modules/police/police.service.ts (2)

410-411: LGTM! The changes align with the PR objectives.

The modifications to make the user parameter optional and provide a default actor for error logging are well-implemented. This enables the digital-mailbox to check subpoena status while maintaining existing functionality.


Line range hint 339-424: Verify error handling in the digital-mailbox integration.

The method now supports being called without a user, which implies it's being integrated with the digital-mailbox system. Let's verify this integration.

✅ Verification successful

Let me gather more information about the digital-mailbox integration by checking the actual implementation and calls.


Let me check one more aspect to see how the digital-mailbox API actually calls the police service.


Error handling in digital-mailbox integration is properly implemented

The verification shows that:

  • The digital-mailbox API has proper error handling with specific exception types (NotFoundException, BadGatewayException)
  • Error messages are appropriately propagated and transformed
  • The police service's getSubpoenaStatus method correctly handles the optional user parameter, logging errors with 'Digital-mailbox' as the actor when no user is provided
  • The integration is properly set up with dedicated endpoints and error handling patterns
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for digital-mailbox integration points and error handling
# Test: Look for digital-mailbox related code and error handling
rg -l "digital-mailbox|Digital-mailbox" --type ts

# Test: Check for calls to getSubpoenaStatus without user parameter
ast-grep --pattern 'getSubpoenaStatus($subpoenaId)'

Length of output: 597


Script:

#!/bin/bash
# Check digital-mailbox API implementation and how it interacts with police service
rg -A 10 "getSubpoenaStatus" apps/judicial-system/digital-mailbox-api/

# Check for any error handling patterns in digital-mailbox API
rg -A 5 "catch|throw|error" apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts

# Look for the actual integration point between digital-mailbox and police service
ast-grep --pattern 'import { PoliceService } from'

Length of output: 2511


Script:

#!/bin/bash
# Check for the actual service status check implementation in digital-mailbox API
rg -A 15 "serviceStatus|subpoena.*status" apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts

# Look for the controller endpoints that might be calling getSubpoenaStatus
rg -A 10 "@Get.*subpoena|@Post.*subpoena" apps/judicial-system/digital-mailbox-api/src/

Length of output: 2215

Copy link

codecov bot commented Oct 30, 2024

Codecov Report

Attention: Patch coverage is 0% with 19 lines in your changes missing coverage. Please review.

Project coverage is 36.72%. Comparing base (e50ded3) to head (2045817).
Report is 17 commits behind head on main.

Files with missing lines Patch % Lines
...rc/app/modules/police/internalPolice.controller.ts 0.00% 15 Missing ⚠️
...m/backend/src/app/modules/police/police.service.ts 0.00% 3 Missing ⚠️
...em/backend/src/app/modules/police/police.module.ts 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16645      +/-   ##
==========================================
- Coverage   36.78%   36.72%   -0.06%     
==========================================
  Files        6855     6859       +4     
  Lines      142311   142572     +261     
  Branches    40584    40636      +52     
==========================================
+ Hits        52348    52363      +15     
- Misses      89963    90209     +246     
Flag Coverage Δ
air-discount-scheme-backend 54.08% <ø> (ø)
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
api-catalogue-services 77.85% <ø> (ø)
api-domains-air-discount-scheme 36.93% <ø> (ø)
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.48% <ø> (ø)
api-domains-communications 39.91% <ø> (ø)
api-domains-criminal-record 48.00% <ø> (ø)
api-domains-driving-license 44.48% <ø> (ø)
api-domains-education 31.58% <ø> (ø)
api-domains-health-insurance 34.77% <ø> (ø)
api-domains-mortgage-certificate 34.98% <ø> (ø)
api-domains-payment-schedule 41.16% <ø> (ø)
application-api-files 56.78% <ø> (ø)
application-core 71.41% <ø> (+0.24%) ⬆️
application-system-api 41.31% <ø> (-0.01%) ⬇️
application-template-api-modules 27.79% <ø> (+0.01%) ⬆️
application-templates-accident-notification 29.24% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.30% <ø> (ø)
application-templates-driving-license 18.40% <ø> (ø)
application-templates-estate 12.25% <ø> (ø)
application-templates-example-payment 25.20% <ø> (ø)
application-templates-financial-aid 15.47% <ø> (-0.03%) ⬇️
application-templates-general-petition 23.42% <ø> (ø)
application-templates-inheritance-report 6.51% <ø> (ø)
application-templates-marriage-conditions 15.18% <ø> (ø)
application-templates-mortgage-certificate 43.55% <ø> (ø)
application-templates-parental-leave 29.94% <ø> (ø)
application-types 6.62% <ø> (ø)
application-ui-shell 21.22% <ø> (ø)
auth-admin-web 2.43% <ø> (ø)
auth-nest-tools 30.02% <ø> (ø)
auth-react 22.26% <ø> (ø)
auth-shared 75.00% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.67% <ø> (ø)
clients-driving-license-book 43.80% <ø> (ø)
clients-financial-statements-inao 49.32% <ø> (ø)
clients-license-client 1.83% <ø> (ø)
clients-middlewares 72.86% <ø> (-0.26%) ⬇️
clients-regulations 42.80% <ø> (ø)
clients-rsk-company-registry 29.76% <ø> (ø)
clients-rsk-personal-tax-return 38.00% <ø> (ø)
clients-smartsolutions 12.77% <ø> (ø)
clients-syslumenn 49.49% <ø> (ø)
clients-zendesk 54.61% <ø> (ø)
cms 0.42% <ø> (ø)
cms-translations 39.04% <ø> (ø)
content-search-index-manager 95.65% <ø> (ø)
content-search-toolkit 8.16% <ø> (ø)
contentful-apps 5.44% <ø> (ø)
dokobit-signing 63.38% <ø> (ø)
download-service 44.22% <ø> (ø)
email-service 61.13% <ø> (ø)
feature-flags 91.11% <ø> (ø)
file-storage 53.71% <ø> (ø)
financial-aid-backend 52.43% <ø> (-3.82%) ⬇️
financial-aid-shared 17.81% <ø> (-1.14%) ⬇️
icelandic-names-registry-backend 53.97% <ø> (ø)
infra-nest-server 48.17% <ø> (ø)
infra-tracing 43.24% <ø> (ø)
island-ui-core 28.86% <ø> (ø)
judicial-system-api 19.52% <ø> (+0.09%) ⬆️
judicial-system-audit-trail 69.43% <ø> (ø)
judicial-system-backend 55.27% <0.00%> (-0.04%) ⬇️
judicial-system-formatters 79.91% <ø> (+0.08%) ⬆️
judicial-system-message 67.37% <ø> (ø)
judicial-system-message-handler 48.53% <ø> (ø)
judicial-system-scheduler 70.62% <ø> (+0.09%) ⬆️
judicial-system-types 44.13% <ø> (+0.03%) ⬆️
judicial-system-web 27.65% <ø> (-0.08%) ⬇️
license-api 42.53% <ø> (+0.01%) ⬆️
localization 10.15% <ø> (ø)
logging 48.43% <ø> (ø)
message-queue 67.80% <ø> (-0.79%) ⬇️
nest-audit 68.20% <ø> (ø)
nest-aws 61.15% <ø> (ø)
nest-config 78.44% <ø> (ø)
nest-core 43.54% <ø> (ø)
nest-feature-flags 51.52% <ø> (ø)
nest-problem 45.85% <ø> (ø)
nest-sequelize 94.44% <ø> (ø)
nest-swagger 51.71% <ø> (ø)
nova-sms 62.74% <ø> (ø)
portals-admin-regulations-admin 1.84% <ø> (ø)
portals-core 16.01% <ø> (ø)
reference-backend 49.79% <ø> (ø)
regulations 16.78% <ø> (ø)
residence-history 85.00% <ø> (ø)
services-auth-admin-api 51.89% <ø> (ø)
services-auth-delegation-api 57.45% <ø> (ø)
services-auth-ids-api 51.45% <ø> (+<0.01%) ⬆️
services-auth-personal-representative 45.04% <ø> (-0.08%) ⬇️
services-auth-personal-representative-public 41.26% <ø> (+<0.01%) ⬆️
services-auth-public-api 48.95% <ø> (ø)
services-documents 60.58% <ø> (ø)
services-endorsements-api 53.59% <ø> (ø)
services-sessions 65.34% <ø> (-0.05%) ⬇️
services-university-gateway 49.47% <ø> (-0.03%) ⬇️
services-user-notification 46.93% <ø> (ø)
services-user-profile 61.77% <ø> (-0.08%) ⬇️
shared-components 27.51% <ø> (ø)
shared-form-fields 31.22% <ø> (ø)
shared-mocking 64.62% <ø> (ø)
shared-pii 92.85% <ø> (ø)
shared-problem 87.50% <ø> (ø)
shared-utils 27.69% <ø> (ø)
skilavottord-ws 24.18% <ø> (ø)
testing-e2e 66.66% <ø> (ø)
web 1.80% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...em/backend/src/app/modules/police/police.module.ts 0.00% <0.00%> (ø)
...m/backend/src/app/modules/police/police.service.ts 63.67% <0.00%> (-0.29%) ⬇️
...rc/app/modules/police/internalPolice.controller.ts 0.00% <0.00%> (ø)

... and 28 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e50ded3...2045817. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 30, 2024

Datadog Report

All test runs bc2b338 🔗

101 Total Test Services: 0 Failed, 98 Passed
🔻 Test Sessions change in coverage: 3 decreased, 2 increased, 195 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-backend 0 0 0 81 0 30.66s N/A Link
air-discount-scheme-web 0 0 0 2 0 6.96s N/A Link
api 0 0 0 4 0 2.33s N/A Link
api-catalogue-services 0 0 0 23 0 9.01s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 16.01s N/A Link
api-domains-assets 0 0 0 3 0 9.54s N/A Link
api-domains-auth-admin 0 0 0 18 0 10.19s 1 no change Link
api-domains-communications 0 0 0 5 0 29.55s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.36s N/A Link
api-domains-driving-license 0 0 0 23 0 27.34s N/A Link

🔻 Code Coverage Decreases vs Default Branch (3)

  • message-queue - jest 68.26% (-0.9%) - Details
  • clients-middlewares - jest 75.6% (-0.1%) - Details
  • judicial-system-backend - jest 58.69% (-0.05%) - Details

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9cb963d and 2045817.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (1 hunks)
  • apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🪛 Biome
apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/police/internalPolice.controller.ts (2)

1-10: LGTM! Dependencies are well organized.

The imports follow NestJS best practices and include all necessary decorators, guards, and types.


12-19: Verify internal API access controls.

While the endpoint is properly guarded with TokenGuard, being an internal API endpoint requires additional verification of access controls.

Let's verify the access control implementation:

✅ Verification successful

Let me generate one more verification script to check the CaseExistsGuard implementation:


Internal API endpoints are properly secured

The security implementation for internal API endpoints is robust and appropriate:

  • TokenGuard validates requests using a secret token in the Authorization header
  • CaseExistsGuard ensures valid case IDs and prevents unauthorized access
  • All internal controllers consistently use these guards
  • The pattern is consistently applied across other internal endpoints (notifications, subpoenas, files, etc.)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper access control implementation in the auth module
# Expected: Find TokenGuard implementation to ensure it properly restricts access to internal endpoints

# Check TokenGuard implementation
echo "Checking TokenGuard implementation..."
rg -A 10 "export class TokenGuard"

# Check for other internal endpoints and their guards
echo "Checking other internal endpoint guards..."
rg -g "*.controller.ts" "api/internal" -A 5

Length of output: 5630


Script:

#!/bin/bash
# Check CaseExistsGuard implementation
echo "Checking CaseExistsGuard implementation..."
rg -A 10 "export class CaseExistsGuard"

# Check if there are any additional security checks in the module configuration
echo "Checking module configuration..."
rg -g "*.module.ts" "TokenGuard|CaseExistsGuard" -A 5

Length of output: 1475

Comment on lines +21 to +25
@Get('subpoenaStatus/:subpoenaId')
@ApiOkResponse({
type: Subpoena,
description: 'Gets subpoena status',
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for subpoenaId.

The endpoint should validate the subpoenaId parameter format before processing.

Consider adding a DTO with class-validator:

export class SubpoenaParamsDto {
  @IsString()
  @IsNotEmpty()
  @Matches(/^[a-zA-Z0-9-]+$/) // adjust regex based on expected format
  subpoenaId: string;
}

Then use it in the controller:

-  @Param('subpoenaId') subpoenaId: string,
+  @Param() params: SubpoenaParamsDto,

Comment on lines +21 to +33
@Get('subpoenaStatus/:subpoenaId')
@ApiOkResponse({
type: Subpoena,
description: 'Gets subpoena status',
})
getSubpoenaStatus(
@Param('subpoenaId') subpoenaId: string,
@CurrentCase() theCase: Case,
): Promise<Subpoena> {
this.logger.debug(`Gets subpoena status in case ${theCase.id}`)

return this.policeService.getSubpoenaStatus(subpoenaId)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and improve parameter usage.

Several improvements are needed in the implementation:

  1. The injected theCase parameter is not used in the service call
  2. Missing error handling for invalid subpoenaId or service failures
  3. The debug log could include more context (subpoenaId)

Consider applying these improvements:

 getSubpoenaStatus(
   @Param('subpoenaId') subpoenaId: string,
   @CurrentCase() theCase: Case,
 ): Promise<Subpoena> {
-  this.logger.debug(`Gets subpoena status in case ${theCase.id}`)
+  this.logger.debug(
+    `Getting subpoena status (id: ${subpoenaId}) for case ${theCase.id}`
+  )
 
-  return this.policeService.getSubpoenaStatus(subpoenaId)
+  try {
+    return this.policeService.getSubpoenaStatus(subpoenaId, theCase)
+  } catch (error) {
+    this.logger.error(
+      `Failed to get subpoena status: ${error.message}`,
+      error
+    )
+    throw error
+  }
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +99 to +108
const defendant = response.defendants[0]

if (!defendant) {
throw new NotFoundException('No defendant found for this case')
}

if (defendant.subpoenas && defendant.subpoenas[0].subpoenaId) {
await this.fetchServiceStatus(id, defendant.subpoenas[0].subpoenaId)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve subpoena status handling and code safety.

While the null check for defendant is good, there are two improvements needed:

  1. The fetched subpoena status is not being used
  2. The conditional check can be simplified using optional chaining

Apply this diff:

    const defendant = response.defendants[0]

    if (!defendant) {
      throw new NotFoundException('No defendant found for this case')
    }

-   if (defendant.subpoenas && defendant.subpoenas[0].subpoenaId) {
-     await this.fetchServiceStatus(id, defendant.subpoenas[0].subpoenaId)
+   if (defendant.subpoenas?.[0]?.subpoenaId) {
+     const statusResponse = await this.fetchServiceStatus(
+       id,
+       defendant.subpoenas[0].subpoenaId
+     )
+     // Update the case response with the fetched status
+     Object.assign(response, statusResponse)
    }

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


💡 Codebase verification

Missing test coverage for subpoena status functionality

The implementation of subpoena status checking appears incomplete:

  • The fetchServiceStatus method is implemented but lacks test coverage (no .spec.ts file found)
  • While other services (police.controller, police.resolver) handle subpoena status, this new implementation in case.service.ts needs proper testing
  • The method is marked as private, suggesting it's an internal implementation detail, but its behavior should still be verified through public method tests
🔗 Analysis chain

Verify the subpoena status update mechanism.

Let's verify that the subpoena status update mechanism works as expected with LRH.


Let me gather more information about the subpoena status handling implementation.


Let me check one more aspect to understand the complete flow of subpoena status handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other places in the codebase that might need to handle subpoena status updates

# Test 1: Check for other methods that might need to handle subpoena status
echo "Checking for other methods that might need subpoena status handling..."
rg -l "subpoena.*status" --type ts

# Test 2: Check for test coverage of the new functionality
echo "Checking for test coverage..."
fd -e spec.ts -e test.ts case.service

Length of output: 566


Script:

#!/bin/bash
# Check the actual implementation of subpoena status handling in the found files
echo "Checking subpoena status implementations..."
rg "subpoena.*status" -B 2 -A 2 --type ts

# Check for the fetchServiceStatus method implementation
echo "Checking fetchServiceStatus implementation..."
ast-grep --pattern 'fetchServiceStatus($$$) {
  $$$
}'

Length of output: 3760


Script:

#!/bin/bash
# Check for the case service test file and its content
echo "Checking case service test implementation..."
rg "fetchServiceStatus" -B 2 -A 2 apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.spec.ts

# Check for the actual implementation of fetchServiceStatus in the service
echo "Checking fetchServiceStatus in case service..."
rg "fetchServiceStatus" -B 2 -A 2 apps/judicial-system/digital-mailbox-api/src/app/modules/cases/case.service.ts

Length of output: 795

🧰 Tools
🪛 Biome

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +244 to +288
private async fetchServiceStatus(
caseId: string,
subpoenaId: string,
): Promise<InternalCaseResponse> {
try {
const res = await fetch(
`${this.config.backendUrl}/api/internal/case/${caseId}/subpoenaStatus/${subpoenaId}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${this.config.secretToken}`,
},
},
)

if (!res.ok) {
if (res.status === 404) {
throw new NotFoundException(`Case ${caseId} not found`)
}

const reason = await res.text()

throw new BadGatewayException(
reason ||
'Unexpected error occurred while fetching serviceStatus by subpoenaID',
)
}

const caseData = await res.json()

return caseData
} catch (reason) {
if (
reason instanceof BadGatewayException ||
reason instanceof NotFoundException
) {
throw reason
}

throw new BadGatewayException(
`Failed to fetch serviceStatus by subpoenaId: ${reason.message}`,
)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance error handling and response validation in fetchServiceStatus.

Several improvements can be made to enhance the robustness of this method:

  1. Use URL class for safer URL construction
  2. Add response type validation
  3. Make error messages more specific
  4. Improve error handling

Apply this diff:

  private async fetchServiceStatus(
    caseId: string,
    subpoenaId: string,
  ): Promise<InternalCaseResponse> {
    try {
+     const url = new URL(
+       `/api/internal/case/${caseId}/subpoenaStatus/${subpoenaId}`,
+       this.config.backendUrl
+     ).toString()
+
      const res = await fetch(
-       `${this.config.backendUrl}/api/internal/case/${caseId}/subpoenaStatus/${subpoenaId}`,
+       url,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            authorization: `Bearer ${this.config.secretToken}`,
          },
        },
      )

      if (!res.ok) {
        if (res.status === 404) {
-         throw new NotFoundException(`Case ${caseId} not found`)
+         throw new NotFoundException(
+           `Case ${caseId} or subpoena ${subpoenaId} not found`
+         )
        }

        const reason = await res.text()

        throw new BadGatewayException(
          reason ||
-           'Unexpected error occurred while fetching serviceStatus by subpoenaID',
+           `Failed to fetch service status for case ${caseId} and subpoena ${subpoenaId}`,
        )
      }

      const caseData = await res.json()
+     
+     // Validate response type
+     if (!caseData || typeof caseData !== 'object') {
+       throw new BadGatewayException('Invalid response format from service status endpoint')
+     }

      return caseData
    } catch (reason) {
      if (
        reason instanceof BadGatewayException ||
        reason instanceof NotFoundException
      ) {
        throw reason
      }

      throw new BadGatewayException(
-       `Failed to fetch serviceStatus by subpoenaId: ${reason.message}`,
+       `Failed to fetch service status for case ${caseId} and subpoena ${subpoenaId}: ${reason.message}`,
      )
    }
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async fetchServiceStatus(
caseId: string,
subpoenaId: string,
): Promise<InternalCaseResponse> {
try {
const res = await fetch(
`${this.config.backendUrl}/api/internal/case/${caseId}/subpoenaStatus/${subpoenaId}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${this.config.secretToken}`,
},
},
)
if (!res.ok) {
if (res.status === 404) {
throw new NotFoundException(`Case ${caseId} not found`)
}
const reason = await res.text()
throw new BadGatewayException(
reason ||
'Unexpected error occurred while fetching serviceStatus by subpoenaID',
)
}
const caseData = await res.json()
return caseData
} catch (reason) {
if (
reason instanceof BadGatewayException ||
reason instanceof NotFoundException
) {
throw reason
}
throw new BadGatewayException(
`Failed to fetch serviceStatus by subpoenaId: ${reason.message}`,
)
}
}
private async fetchServiceStatus(
caseId: string,
subpoenaId: string,
): Promise<InternalCaseResponse> {
try {
const url = new URL(
`/api/internal/case/${caseId}/subpoenaStatus/${subpoenaId}`,
this.config.backendUrl
).toString()
const res = await fetch(
url,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${this.config.secretToken}`,
},
},
)
if (!res.ok) {
if (res.status === 404) {
throw new NotFoundException(
`Case ${caseId} or subpoena ${subpoenaId} not found`
)
}
const reason = await res.text()
throw new BadGatewayException(
reason ||
`Failed to fetch service status for case ${caseId} and subpoena ${subpoenaId}`,
)
}
const caseData = await res.json()
// Validate response type
if (!caseData || typeof caseData !== 'object') {
throw new BadGatewayException('Invalid response format from service status endpoint')
}
return caseData
} catch (reason) {
if (
reason instanceof BadGatewayException ||
reason instanceof NotFoundException
) {
throw reason
}
throw new BadGatewayException(
`Failed to fetch service status for case ${caseId} and subpoena ${subpoenaId}: ${reason.message}`,
)
}
}

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