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

feat(j-s): Defender Updated Notification #16801

Merged
merged 13 commits into from
Nov 15, 2024
Merged

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Nov 11, 2024

Defender Updated Notification

Senda tilkynningar til dómstóls þegar verjandi er valinn á island.is

What

  • Sends notification to court when defendant chooses a defender from island.is.
  • Stops updating defendants, defenders and prosecutors in court via the court API. The robot now handles defendants and prosecutors and soon defenders as well.
  • Moves the initiation of defender selected notifications to the defendant service.
  • Moves the sending of defender selected notifications to the defendant notification service.

Why

  • The court needs to know.

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

Release Notes

  • New Features

    • Introduced a new guard for validating the existence of a defendant's national ID.
  • Improvements

    • Enhanced error handling and logging in various services and controllers.
    • Simplified email notification processes to accommodate multiple recipients.
    • Refined message handling and update logic for subpoenas and defendants.
    • Updated the notification system to better categorize notifications related to defendants and subpoenas.
  • Bug Fixes

    • Resolved inconsistencies in case update handling and message queue interactions.
  • Refactor

    • Consolidated case management logic and improved the structure of notification types.
    • Updated method signatures and streamlined logic within several services.
    • Removed unnecessary imports and simplified control flow in various modules.

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces significant modifications across various components of the judicial system application. Key changes include the refactoring of case management logic in the CaseController and CaseService, updates to notification handling in the DefendantNotificationService, and the introduction of a new guard for validating defendant national IDs. Additionally, there are adjustments to test suites to reflect these changes. The overall focus is on enhancing the clarity, efficiency, and maintainability of the code while ensuring robust error handling and user role validation.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/case/case.controller.ts Removed several imports; updated update and getConnectedCases methods; refined logic for handling case resent explanations.
apps/judicial-system/backend/src/app/modules/case/case.service.ts Refactored addMessagesForIndictmentCourtCaseConnectionToQueue; enhanced update method with more robust handling; improved error logging.
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts Updated method for archiving defendants; no significant logic changes.
apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts Modified test suite to reflect changes in message queue interactions for indictment cases.
apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts Enhanced test coverage for the update method, including new test cases for various fields.
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts Updated method name in tests to reflect changes in the service.
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts Renamed and refactored methods for clarity; added new method for handling indictment case updates.
apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts Added new guard for validating the existence of a defendant's national ID.
apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts Updated updateDefendant method to change how updates are processed.
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts Refactored sendEmails method to handle multiple recipients; added new notification handling logic.
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts Added new message definitions for notifications related to defender selection.
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts Added logging to the sendDefendantNotification method.
apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts Updated controller route definition.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts Refactored methods to simplify logic and eliminate unnecessary parameters.
libs/judicial-system/types/src/lib/notification.ts Restructured notification types; removed and added enums for better organization.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb

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.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 11, 2024

Datadog Report

All test runs 7e7faab 🔗

9 Total Test Services: 0 Failed, 9 Passed
⬆️ Test Sessions change in coverage: 1 increased (+0.13%), 11 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
judicial-system-api 0 0 0 59 0 7.55s 1 no change Link
judicial-system-backend 0 0 0 21159 0 23m 24.09s 1 increased (+0.13%) Link
judicial-system-formatters 0 0 0 38 0 6.38s 1 no change Link
judicial-system-message 0 0 0 35 0 13.17s 1 no change Link
judicial-system-message-handler 0 0 0 4 0 4.26s 1 no change Link
judicial-system-scheduler 0 0 0 4 0 4.83s 1 no change Link
judicial-system-types 0 0 0 23 0 8.09s 1 no change Link
judicial-system-web 0 0 0 333 0 1m 16.09s 1 no change Link
judicial-system-xrd-api 0 0 0 6 0 5.74s 1 no change Link

Copy link

codecov bot commented Nov 12, 2024

Codecov Report

Attention: Patch coverage is 66.66667% with 41 lines in your changes missing coverage. Please review.

Project coverage is 36.51%. Comparing base (fda8787) to head (0fb4483).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ckend/src/app/modules/subpoena/subpoena.service.ts 8.33% 22 Missing ⚠️
...ules/notification/defendantNotification.service.ts 58.33% 10 Missing ⚠️
...end/src/app/modules/defendant/defendant.service.ts 85.36% 6 Missing ⚠️
...ackend/src/app/modules/subpoena/subpoena.module.ts 0.00% 2 Missing ⚠️
...dules/notification/subpoenaNotification.service.ts 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16801      +/-   ##
==========================================
+ Coverage   36.42%   36.51%   +0.09%     
==========================================
  Files        6852     6853       +1     
  Lines      143576   143626      +50     
  Branches    40983    41073      +90     
==========================================
+ Hits        52297    52452     +155     
+ Misses      91279    91174     -105     
Flag Coverage Δ
judicial-system-api 19.76% <100.00%> (ø)
judicial-system-backend 55.25% <66.66%> (+0.12%) ⬆️
judicial-system-formatters 79.26% <100.00%> (ø)
judicial-system-message 66.99% <ø> (ø)
judicial-system-message-handler 47.99% <ø> (ø)
judicial-system-scheduler 70.67% <100.00%> (ø)
judicial-system-types 43.58% <0.00%> (ø)
judicial-system-web 27.16% <ø> (ø)

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/case/case.controller.ts 86.95% <ø> (ø)
...ystem/backend/src/app/modules/case/case.service.ts 90.63% <100.00%> (ø)
...ckend/src/app/modules/case/internalCase.service.ts 85.12% <100.00%> (ø)
...efendant/guards/defendantNationalIdExists.guard.ts 100.00% <100.00%> (ø)
.../modules/defendant/internalDefendant.controller.ts 100.00% <100.00%> (+10.00%) ⬆️
...ules/notification/defendantNotification.strings.ts 100.00% <ø> (ø)
...es/notification/internalNotification.controller.ts 96.36% <ø> (ø)
...dules/notification/subpoenaNotification.strings.ts 100.00% <ø> (ø)
...src/app/modules/subpoena/dto/updateSubpoena.dto.ts 100.00% <ø> (ø)
...pp/modules/subpoena/internalSubpoena.controller.ts 90.00% <ø> (ø)
... and 8 more

... and 47 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 fda8787...0fb4483. Read the comment docs.

@gudjong gudjong marked this pull request as ready for review November 12, 2024 12:25
@gudjong gudjong requested a review from a team as a code owner November 12, 2024 12:25
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: 15

🧹 Outside diff range and nitpick comments (26)
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts (2)

5-6: Consider using a more specific type instead of any

The any type bypasses TypeScript's type checking. Consider using a more specific type like Type<DefendantExistsGuard>[] or create a custom type for guards.

-  // eslint-disable-next-line @typescript-eslint/no-explicit-any
-  let guards: any[]
+  let guards: Type<DefendantExistsGuard>[]

9-13: Consider extracting the metadata key as a constant

The hardcoded string '__guards__' could be extracted into a constant or imported from a shared configuration to improve maintainability.

+  const GUARDS_METADATA_KEY = '__guards__'
+
   guards = Reflect.getMetadata(
-    '__guards__',
+    GUARDS_METADATA_KEY,
     InternalDefendantController.prototype.deliverDefendantToCourt,
   )
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (1)

9-9: Replace any[] with a more specific type.

Instead of using any[] with an eslint disable comment, consider using a more specific type for better type safety.

-  // eslint-disable-next-line @typescript-eslint/no-explicit-any
-  let guards: any[]
+  let guards: Array<new () => CaseTypeGuard | DefendantNationalIdExistsGuard>
apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (3)

33-33: Handle potential undefined defendants array

The optional chaining on theCase.defendants?.find might hide a potential issue where defendants array is undefined.

Add explicit check:

+   if (!theCase.defendants) {
+     throw new BadRequestException('Case has no defendants')
+   }
-   const defendant = theCase.defendants?.find(
+   const defendant = theCase.defendants.find(

40-42: Normalize error message format

Consider normalizing the error message format and including more context for debugging.

Suggested improvement:

    throw new NotFoundException(
-     `Defendant with given national id of case ${theCase.id} does not exist`,
+     `Defendant not found: nationalId=${normalizedAndFormatedNationalId}, caseId=${theCase.id}`,
    )

30-31: Fix typo in variable name

The variable name contains a typo: "Formated" should be "Formatted".

Apply this fix:

- const normalizedAndFormatedNationalId =
+ const normalizedAndFormattedNationalId =
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (1)

8-8: Fix typo in message descriptions

The word "choise" should be "choice" in both message descriptions.

-      'Subject of the notification sent when the defendant defender choise in an indictment has changed',
+      'Subject of the notification sent when the defendant defender choice in an indictment has changed',
-      'Body of the notification sent when the defendant defender choise in an indictment has changed',
+      'Body of the notification sent when the defendant defender choice in an indictment has changed',

Also applies to: 15-15

apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (2)

16-28: Enhance test data setup for better clarity and type safety.

The test data setup could be improved in several ways:

  1. The update object is cast to InternalUpdateDefendantDto without proper type definition
  2. Test values like 'somevalue' are not descriptive of real use cases

Consider this improvement:

-  const update = { somefield: 'somevalue' } as InternalUpdateDefendantDto
+  const update: InternalUpdateDefendantDto = {
+    // Add realistic test data based on DTO fields
+    name: 'John Doe',
+    email: '[email protected]',
+    // ... other required fields
+  }

1-77: Consider restructuring tests to align with notification requirements.

Given that this PR implements defender selection notifications, the test suite should explicitly verify:

  1. Court notification triggers when defender is selected
  2. Proper state transitions during the defender selection process
  3. Integration with the notification service

This will ensure the tests fully validate the PR's primary objective of court notifications for defender selection.

🧰 Tools
🪛 Biome

[error] 53-53: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 54-54: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

libs/judicial-system/types/src/lib/notification.ts (1)

53-57: LGTM! Consider adding JSDoc comments

The new notification types are well-integrated into the main NotificationType enum, maintaining consistency with the codebase's pattern of referencing specific enum types.

Consider adding JSDoc comments to document the purpose and usage of each notification type, especially the new ones. For example:

+ /** Notification sent when a defendant selects their defender through island.is */
  DEFENDANT_SELECTED_DEFENDER = DefendantNotificationType.DEFENDANT_SELECTED_DEFENDER,
+ /** Notification sent when a defender is assigned to a defendant */
  DEFENDER_ASSIGNED = DefendantNotificationType.DEFENDER_ASSIGNED,
apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (1)

72-74: Update API documentation to reflect the changes

The @ApiOkResponse description mentions "by case and national id" which is no longer accurate since we're using the @CurrentDefendant() decorator.

   @ApiOkResponse({
     type: Defendant,
-    description: 'Updates defendant information by case and national id',
+    description: 'Updates defendant information for the current case',
   })
apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (2)

11-16: Consider renaming the interface for better clarity.

The interface Then could be more descriptive. Consider renaming it to GuardTestResult or GuardActivationResult to better reflect its purpose in testing the guard's activation outcomes.

-interface Then {
+interface GuardTestResult {
   result: boolean
   error: Error
 }

39-66: Consider enhancing type safety and test data organization.

While the test is well-structured, consider these improvements:

  1. Add type definitions for the test data objects
  2. Extract test data setup to a separate helper/fixture
interface TestDefendant {
  id: string;
  nationalId: string;
  caseId: string;
}

interface TestCase {
  id: string;
  defendants: TestDefendant[];
}

// In a separate test-helpers.ts file
export const createTestDefendant = (overrides?: Partial<TestDefendant>): TestDefendant => ({
  id: uuid(),
  nationalId: uuid(),
  caseId: uuid(),
  ...overrides
});
apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (1)

53-53: Consider exposing DefendantService in the return object.

While DefendantService is correctly added as a provider, it's not included in the module's return object. This might limit test cases that need to access and verify interactions with the mocked DefendantService.

Consider adding it to the return object:

  return {
    userService,
    pdfService,
    policeService,
    fileService,
    subpoenaModel,
    subpoenaService,
    subpoenaController,
    internalSubpoenaController,
    limitedAccessSubpoenaController,
+   defendantService: subpoenaModule.get<DefendantService>(DefendantService),
  }
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (1)

64-64: Consider enhancing error handling granularity.

The service has good error handling, but we could improve error reporting by distinguishing between different types of failures (email service errors, formatting errors, etc.) to aid in debugging and monitoring.

Consider wrapping the email sending logic in a try-catch block with specific error types:

try {
  return await this.sendEmail(/*...*/);
} catch (error) {
  if (error instanceof EmailServiceError) {
    this.logger.error('Email service failed', { error, recipient });
  } else if (error instanceof FormattingError) {
    this.logger.error('Message formatting failed', { error, template });
  }
  throw error;
}
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)

Line range hint 63-123: Documentation needed for the new defender notification flow

The PR objectives mention that documentation updates are pending. Since this endpoint now supports defender selection notifications, it should be documented in the API documentation.

Consider adding a specific example in the @ApiCreatedResponse description to clarify the defender selection notification case:

  @ApiCreatedResponse({
    type: DeliverResponse,
    description:
-     'Sends defendant related notifications for an existing defendant',
+     'Sends defendant related notifications for an existing defendant, including defender selection notifications to the court',
  })
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts (2)

55-74: Add validation for empty recipients array

While the implementation handles multiple recipients well, consider adding validation for an empty recipients array to prevent unnecessary processing.

  private async sendEmails(
    theCase: Case,
    notificationType: DefendantNotificationType,
    subject: string,
    body: string,
    to: { name?: string; email?: string }[],
  ) {
+   if (!to?.length) {
+     return { delivered: true, recipients: [] };
+   }
    const promises: Promise<Recipient>[] = []

Line range hint 1-1: Add documentation for the new notification type

As mentioned in the PR objectives, documentation updates are pending. Please add JSDoc comments describing the new DEFENDANT_SELECTED_DEFENDER notification type and its usage.

apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (1)

25-25: LGTM! Consider enhancing test maintainability.

The addition of the required type parameter improves type safety and makes the test cases more explicit. This aligns well with the notification system requirements for different case types.

Consider creating an enum or constant for default test values to reduce duplication and improve maintainability:

const DEFAULT_TEST_CASES = {
  CUSTODY: { type: CaseType.CUSTODY, courtCaseNumber: uuid() },
  INDICTMENT: { type: CaseType.INDICTMENT, courtCaseNumber: uuid() },
  // ... other common test cases
} as const;

Also applies to: 56-56, 66-66

apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1)

Line range hint 1-450: Comprehensive test coverage with robust structure

The test suite effectively covers:

  • Successful case archiving with proper data encryption
  • Clearing of sensitive information
  • Transaction handling
  • Error cases (no case found)

The test structure follows best practices with clear setup, comprehensive mocking, and explicit expectations.

Consider adding test cases for:

  1. Encryption failures
  2. Transaction rollback scenarios
  3. Partial data clearing failures
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

Line range hint 419-498: Consider implementing batch processing for better performance.

The archiving process performs multiple database operations in sequence within a transaction. For large datasets with many defendants, files, and indictment counts, this could lead to performance issues.

Consider implementing batch processing for the updates:

+ // Batch process defendants
+ const defendantUpdates = theCase.defendants?.map(defendant => {
+   const [clearedProperties, archive] = collectEncryptionProperties(
+     defendantEncryptionProperties,
+     defendant
+   );
+   defendantsArchive.push(archive);
+   return { id: defendant.id, properties: clearedProperties };
+ }) ?? [];
+ 
+ await this.defendantService.batchUpdateDefendants(
+   theCase.id,
+   defendantUpdates,
+   transaction
+ );
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

116-116: Simplify variable initialization

The variable message is initialized to undefined by default. Consider removing the redundant assignment.

Apply this diff to simplify the variable declaration:

-let message: Message | undefined = undefined
+let message: Message | undefined

119-136: Refactor message creation to reduce code duplication

The message object creation for both success and failure cases is similar. Refactoring can eliminate duplication and enhance readability.

Consider applying this refactor:

if (serviceStatus && serviceStatus !== subpoena.serviceStatus) {
  if (isSuccessfulServiceStatus(serviceStatus) || isFailedServiceStatus(serviceStatus)) {
    const notificationType = isSuccessfulServiceStatus(serviceStatus)
      ? SubpoenaNotificationType.SERVICE_SUCCESSFUL
      : SubpoenaNotificationType.SERVICE_FAILED

    message = {
      type: MessageType.SUBPOENA_NOTIFICATION,
      caseId: subpoena.caseId,
      elementId: [subpoena.defendantId, subpoena.id],
      body: {
        type: notificationType,
      },
    }
  }
}

198-198: Maintain consistent language in code comments

The comment is in Icelandic. For consistency and clarity, consider translating code comments to English.

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

132-158: Simplify nested 'if' statements for better readability

Consider combining the nested conditions into a single 'if' statement to enhance readability.

Proposed refactor:

-        if (updatedDefendant.isDefenderChoiceConfirmed) {
-          if (
-            updatedDefendant.defenderChoice === DefenderChoice.CHOOSE ||
-            updatedDefendant.defenderChoice === DefenderChoice.DELEGATE
-          ) {
+        if (
+          updatedDefendant.isDefenderChoiceConfirmed &&
+          (updatedDefendant.defenderChoice === DefenderChoice.CHOOSE ||
+            updatedDefendant.defenderChoice === DefenderChoice.DELEGATE)
+        ) {
           // TODO: Update defender with robot if needed

257-268: Ensure consistent parameter usage in 'update' method

In the update method, updateIndictmentCase is called without the user parameter, while updateRequestCase requires it. Consider passing user to updateIndictmentCase for consistency, or confirm that it is not needed.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d7bffc4 and 84c232d.

📒 Files selected for processing (26)
  • apps/judicial-system/backend/src/app/modules/case/case.controller.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (9 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.strings.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (3 hunks)
  • libs/judicial-system/types/src/lib/notification.ts (2 hunks)
💤 Files with no reviewable changes (6)
  • apps/judicial-system/backend/src/app/modules/case/case.controller.ts
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts
  • apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.strings.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts
🧰 Additional context used
📓 Path-based instructions (19)
apps/judicial-system/backend/src/app/modules/case/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."
apps/judicial-system/backend/src/app/modules/case/internalCase.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/backend/src/app/modules/case/test/internalCaseController/archive.spec.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/defendant/defendant.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/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.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/defendant/guards/test/defendantNationalIdExistsGuard.spec.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/defendant/internalDefendant.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/defendant/test/defendantController/update.spec.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/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.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/defendant/test/internalDefendantController/updateDefendant.spec.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/defendant/test/internalDefendantController/updateDefendantGuards.spec.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/notification/defendantNotification.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/backend/src/app/modules/notification/defendantNotification.strings.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/notification/internalNotification.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/notification/subpoenaNotification.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/backend/src/app/modules/subpoena/subpoena.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/subpoena/subpoena.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/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.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."
libs/judicial-system/types/src/lib/notification.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (6)
apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts:175-185
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In the Jest tests for the `LimitedAccessViewCaseFileGuard` in `apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts`, code duplication in the `beforeEach` blocks is acceptable and should remain unchanged.
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (2)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts:175-185
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In the Jest tests for the `LimitedAccessViewCaseFileGuard` in `apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts`, code duplication in the `beforeEach` blocks is acceptable and should remain unchanged.
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfGuards.spec.ts:24-25
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In certain scenarios within the judicial-system backend, the `RolesGuard` may intentionally follow the `CaseExistsGuard` when specific roles rules require the guard order to be reversed, as seen in tests like `getIndictmentPdfGuards.spec.ts`.
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16452
File: apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts:1845-1854
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In the `sendCaseFilesUpdatedNotifications` method within `internalNotification.service.ts`, when the `user` is a defence user, it is intended to send notifications to the prosecutor.
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (3)
Learnt from: oddsson
PR: island-is/island.is#16329
File: apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts:143-177
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In `apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts`, the method `sendEmails` currently uses `Promise.all` for multiple recipients, and changing it to `Promise.allSettled` is considered for a future iteration.
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-11-10T17:05:23.796Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
Learnt from: gudjong
PR: island-is/island.is#16452
File: apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts:1845-1854
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In the `sendCaseFilesUpdatedNotifications` method within `internalNotification.service.ts`, when the `user` is a defence user, it is intended to send notifications to the prosecutor.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.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-11-10T17:05:23.796Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
libs/judicial-system/types/src/lib/notification.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16556
File: apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts:13-16
Timestamp: 2024-11-10T09:23:37.036Z
Learning: In the `CaseNotificationType` enum in `libs/judicial-system/types/src/lib/notification.ts`, `APPEAL_CASE_FILES_UPDATED` and `CASE_FILES_UPDATED` are distinct notification types that need to remain separate, as they serve different purposes in the notification system.
🪛 Biome
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts

[error] 53-53: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 54-54: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (32)
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (2)

1-26: Verify notification integration with defender updates.

The PR's objective is to implement notifications when a defender is selected, but this test file only covers the guards for updating defendant information. Please ensure that:

  1. The updateDefendant method triggers appropriate notifications
  2. There are separate test files covering the notification functionality
#!/bin/bash
# Description: Check for notification-related tests and implementations

# Search for notification-related test files
echo "Searching for notification test files..."
fd -e spec.ts -e test.ts | rg -l "Notification|notification"

# Search for notification service usage in the defendant controller
echo "Checking notification service integration..."
ast-grep --pattern 'class InternalDefendantController {
  $$$
  updateDefendant($$$) {
    $$$
    notificationService.$$$
    $$$
  }
  $$$
}'

18-25: 🛠️ Refactor suggestion

Verify guard order and enhance test coverage.

While the test verifies the presence and configuration of both guards, consider adding these improvements:

  1. The test should verify that the guard order is correct for this specific endpoint
  2. Add negative test cases to verify guard behavior with invalid inputs

Here's a script to verify if the guard order is consistent with similar endpoints:

Consider adding these test cases:

it('should reject when case type is not in investigationCases', () => {
  const guard = new guards[0]();
  // Test with invalid case type
});

it('should reject when defendant national ID does not exist', () => {
  const guard = new guards[1]();
  // Test with non-existent national ID
});
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts (1)

7-7: LGTM: Import aligns with defender notification feature

The addition of DefendantModule import is consistent with the PR's objective of implementing defender selection notifications.

apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (1)

1-14: LGTM! Clean implementation following NestJS patterns

The imports and class declaration follow NestJS best practices, with proper use of decorators and interface implementation.

apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (2)

4-16: LGTM! Message structure and format are well-defined

The new message definitions:

  • Follow the established pattern for notification messages
  • Use consistent HTML formatting
  • Properly handle dynamic content with placeholders
  • Maintain language consistency with the system

4-16: Verify uniqueness of message IDs

The message IDs look correct, but let's verify they are unique across the codebase to prevent any potential conflicts.

✅ Verification successful

Message IDs are unique across the codebase

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for duplicate message IDs across the codebase

# Search for the specific message IDs
echo "Checking defendantSelectedDefenderSubject ID..."
rg "judicial\.system\.backend:defendant_notifications\.defendant_selected_defender_subject" -A 2

echo "Checking defendantSelectedDefenderBody ID..."
rg "judicial\.system\.backend:defendant_notifications\.defendant_selected_defender_body" -A 2

Length of output: 1378

apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (1)

1-15: LGTM! Well-structured TypeScript interfaces and imports.

The type definitions and imports are organized logically and follow TypeScript best practices.

libs/judicial-system/types/src/lib/notification.ts (3)

23-26: LGTM! Well-structured enum for defendant notifications

The new DefendantNotificationType enum clearly separates defender-related notifications, improving code organization and type safety. This aligns well with the PR objective of implementing notifications for defender selection.


28-31: Good separation of concerns

Moving subpoena-related notifications to a dedicated enum improves code organization and maintainability. The success/failure states are clearly defined.

Let's verify the migration of these notification types:

#!/bin/bash
# Check for any old references to these notification types
# that might have been missed during refactoring
rg "SERVICE_SUCCESSFUL|SERVICE_FAILED" --type ts -B 2 -A 2

Line range hint 8-8: Remove or schedule removal of deprecated enum value

The comment indicates ADVOCATE_ASSIGNED will be removed, but it's still present in the enum. This creates technical debt and could lead to confusion.

Let's verify if this enum value is still in use:

Consider:

  1. Remove it now if it's unused
  2. Create a deprecation timeline if it's still in use
  3. Document the migration path to the new DefendantNotificationType.DEFENDER_ASSIGNED
✅ Verification successful

ADVOCATE_ASSIGNED is unused and can be safely removed

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of ADVOCATE_ASSIGNED
rg "ADVOCATE_ASSIGNED" --type ts

Length of output: 4317

apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (1)

20-20: LGTM! Clean import additions

The new imports enhance type safety and validation by introducing the investigation cases type and the national ID guard.

Also applies to: 22-22, 27-27

apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (4)

18-38: Well-structured test setup with good error handling!

The test suite setup follows best practices with:

  • Clean mock implementation
  • Reusable GivenWhenThen pattern
  • Proper error handling

68-92: LGTM! Comprehensive error case testing.

The test properly validates both the exception type and message content for the non-existent defendant scenario.


94-107: LGTM! Clear and focused edge case testing.

The test appropriately validates the guard's behavior when the case is missing.


109-124: LGTM! Verify guard usage in controllers.

The test case is well-implemented. To ensure complete coverage, let's verify where this guard is being used.

✅ Verification successful

Guard usage in controllers verified.

  • apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts uses DefendantNationalIdExistsGuard with @UseGuards.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of DefendantNationalIdExistsGuard in controllers
ast-grep --pattern 'class $_ {
  $$$
  @UseGuards($$$DefendantNationalIdExistsGuard$$$)
  $$$
}'

Length of output: 98


Script:

#!/bin/bash
# Search for any usage of DefendantNationalIdExistsGuard across the codebase
rg 'DefendantNationalIdExistsGuard' --context 2

Length of output: 4975

apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (1)

16-16: LGTM! Import and mock setup looks good.

The DefendantService import and mock setup follow the established patterns in the codebase.

Also applies to: 33-33

apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)

122-122: LGTM! Verify notification flow in DefendantNotificationService

The addition of the defendant parameter aligns with the PR objective of implementing defender selection notifications. The change is properly guarded and logged.

Let's verify the notification flow in the service:

✅ Verification successful

Verified! DefendantNotificationService handles the defendant parameter correctly and sends notifications to the appropriate recipients.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that DefendantNotificationService properly handles the defendant parameter
# and sends notifications to the correct recipients

# Check the service implementation
ast-grep --pattern 'sendDefendantNotification(type: $_, theCase: $_, defendant: $_) {
  $$$
}'

# Look for defender-related notification types
rg -A 5 "DEFENDER" apps/judicial-system/backend/src/app/modules/notification

Length of output: 22081

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

13-16: LGTM! Clean import structure

The imports are well-organized and follow the pattern of centralizing route constants.


Line range hint 188-207: LGTM! Well-structured notification handling

The notification handling is well-organized with proper error handling and logging. The switch statement is complete and the parameter order is consistent throughout the service.

apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (1)

Line range hint 86-217: LGTM! Comprehensive test coverage for different case types.

The test suite effectively covers various update scenarios with appropriate case types:

  • Basic updates with CUSTODY cases
  • Court delivery updates with INDICTMENT cases
  • National ID changes with TELECOMMUNICATIONS cases
  • Defender choice confirmation with appropriate notifications

The test structure is clean and follows best practices.

apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1)

290-296: Method name change improves clarity and consistency

The renaming from updateForArcive to updateDatabaseDefendant better reflects the method's purpose and follows naming conventions. The test correctly verifies that sensitive defendant data is cleared during archiving.

Let's verify the consistency of this method name change across the codebase:

✅ Verification successful

Method name change verified and consistent across the codebase

The method updateForArcive has been successfully renamed to updateDatabaseDefendant. No remaining instances of the old method name were found, and the new method is correctly implemented in the DefendantService class.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of the old method name and verify the new method name implementation

# Check for any remaining instances of old method name
rg "updateForArcive"

# Verify the implementation of the new method name
ast-grep --pattern 'class DefendantService {
  $$$
  updateDatabaseDefendant($$$) {
    $$$
  }
  $$$
}'

Length of output: 42633

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

421-421: Method name updated for clarity and correctness.

The rename from updateForArcive to updateDatabaseDefendant improves code clarity by using a more descriptive and correctly spelled method name.


Line range hint 421-427: Verify error handling in the transaction.

The defendant update is part of a critical archiving process that handles sensitive data. Ensure that any errors during the update are properly caught and rolled back within the transaction.

apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

33-33: Import of DefendantService is appropriate

The addition of DefendantService import aligns with the updated logic and promotes better modularity.


74-74: Proper injection of DefendantService into the constructor

Injecting DefendantService into the constructor allows for dependency injection, enhancing testability and maintainability.


218-218: Ensure proper error handling for asynchronous calls

Since addMessagesForSubpoenaUpdateToQueue is an asynchronous function and is not awaited, any errors it throws may be unhandled. Consider adding error handling to capture potential exceptions.

apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (5)

93-130: Method 'sendRequestCaseUpdateDefendantMessages' logic is correct

The method appropriately handles message queuing based on defendant updates.


196-201: Optional 'transaction' parameter is handled correctly

The optional transaction parameter in updateDatabaseDefendant should not cause issues with Sequelize's update method.


215-235: Method 'updateRequestCase' functions as intended

The method updates the defendant and sends necessary messages for request cases.


237-249: Method 'updateIndictmentCase' functions as intended

The method updates the defendant and handles indictment case-specific messaging appropriately.


270-307: Method 'updateRestricted' logic is sound

The method correctly updates restricted defendant fields and sends notifications when necessary.

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

751-753: Verify omission of prosecutor and defendant messages in notifications

In the updated addMessagesForIndictmentCourtCaseConnectionToQueue method, the messages for delivering prosecutor and defendant information to the court (getDeliverProsecutorToCourtMessages and getDeliverDefendantToCourtMessages) are no longer included in the messages array. Please confirm that this change is intentional and that necessary notifications to the prosecutor and defendant are being handled elsewhere if required.

Run the following script to verify where these message functions are being invoked:

✅ Verification successful

Omission Verified
Notifications to the prosecutor and defendant are managed through separate methods and are handled appropriately elsewhere in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for calls to `getDeliverProsecutorToCourtMessages` and `getDeliverDefendantToCourtMessages` in the codebase.

# Search for invocations in the codebase
rg 'this\.getDeliver(Prosecutor|Defendant)ToCourtMessages' -A 5

Length of output: 1842


Script:

#!/bin/bash
# Description: Search for construction or manipulation of the `messages` array in the codebase to verify handling of prosecutor and defendant notifications.

rg 'const messages[:=].*' -A 10

Length of output: 10695

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

🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (2)

146-146: Address the TODO comment about robot defender updates.

The comment indicates missing functionality for robot defender updates.

Would you like me to help create a GitHub issue to track this TODO item?


270-307: Consider enhancing the method documentation.

While the implementation is solid, consider structuring the comments as JSDoc for better IDE integration and documentation generation.

Example improvement:

-    // The reason we have a separate dto for this is because requests that end here
-    // are initiated by outside API's which should not be able to edit other fields
-    // Defendant updated originating from the judicial system should use the UpdateDefendantDto
-    // and go through the update method above using the defendantId.
+    /**
+     * Updates defendant data from external APIs with restricted access.
+     * 
+     * @remarks
+     * - Uses a separate DTO to restrict field access for external APIs
+     * - Internal updates should use UpdateDefendantDto through the update method
+     * - Judge confirmation required for all changes
+     */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 84c232d and ad1529f.

📒 Files selected for processing (3)
  • apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts
  • apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/defendant/defendant.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."
🔇 Additional comments (4)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (4)

93-130: LGTM! Well-structured message handling refactor.

The refactoring improves code maintainability by:

  • Using early return pattern
  • Collecting messages before sending them in a single operation
  • Clear separation of concerns

132-160: LGTM! Well-structured notification handling for indictment cases.

The implementation correctly:

  • Handles defender choice confirmation
  • Sends appropriate notifications
  • Uses early returns for better flow control

Line range hint 196-235: LGTM! Clear separation of database operations.

The refactoring improves code organization by:

  • Using a more descriptive method name
  • Making transaction parameter optional
  • Separating database operations from message handling

237-268: LGTM! Well-structured case type-specific handling.

The implementation provides:

  • Clear separation between indictment and request cases
  • Type-safe routing using isIndictmentCase
  • Proper delegation to specific handlers

Copy link
Member

@unakb unakb left a comment

Choose a reason for hiding this comment

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

Really nice changes and cleanup of code 🎉

@gudjong gudjong added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 15, 2024
Copy link
Contributor

kodiakhq bot commented Nov 15, 2024

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

@kodiakhq kodiakhq bot removed the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 15, 2024
@gudjong gudjong added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 15, 2024
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: 1

🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)

116-144: Consider extracting common message structure

The message handling refactoring is good, but there's room for improvement:

Consider extracting the common message structure to reduce duplication:

 private async addMessagesForSubpoenaUpdateToQueue(
   subpoena: Subpoena,
   serviceStatus?: ServiceStatus,
 ): Promise<void> {
   let message: Message | undefined = undefined
+  
+  const createNotificationMessage = (type: SubpoenaNotificationType): Message => ({
+    type: MessageType.SUBPOENA_NOTIFICATION,
+    caseId: subpoena.caseId,
+    elementId: [subpoena.defendantId, subpoena.id],
+    body: { type }
+  })

   if (serviceStatus && serviceStatus !== subpoena.serviceStatus) {
     if (isSuccessfulServiceStatus(serviceStatus)) {
-      message = {
-        type: MessageType.SUBPOENA_NOTIFICATION,
-        caseId: subpoena.caseId,
-        elementId: [subpoena.defendantId, subpoena.id],
-        body: {
-          type: SubpoenaNotificationType.SERVICE_SUCCESSFUL,
-        },
-      }
+      message = createNotificationMessage(SubpoenaNotificationType.SERVICE_SUCCESSFUL)
     } else if (isFailedServiceStatus(serviceStatus)) {
-      message = {
-        type: MessageType.SUBPOENA_NOTIFICATION,
-        caseId: subpoena.caseId,
-        elementId: [subpoena.defendantId, subpoena.id],
-        body: {
-          type: SubpoenaNotificationType.SERVICE_FAILED,
-        },
-      }
+      message = createNotificationMessage(SubpoenaNotificationType.SERVICE_FAILED)
     }
   }

178-187: Simplify complex conditional check

The conditional check for defender-related updates is quite lengthy and could be simplified.

Consider extracting the condition into a helper method:

+  private hasDefenderUpdates(update: UpdateSubpoenaDto): boolean {
+    return !!(
+      update.defenderChoice ||
+      update.defenderNationalId ||
+      update.defenderName ||
+      update.defenderEmail ||
+      update.defenderPhoneNumber ||
+      update.requestedDefenderChoice ||
+      update.requestedDefenderNationalId ||
+      update.requestedDefenderName
+    )
+  }

   if (
     subpoena.case &&
     subpoena.defendant &&
-    (defenderChoice ||
-      defenderNationalId ||
-      defenderName ||
-      defenderEmail ||
-      defenderPhoneNumber ||
-      requestedDefenderChoice ||
-      requestedDefenderNationalId ||
-      requestedDefenderName)
+    this.hasDefenderUpdates(update)
   ) {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad1529f and 2b2ed00.

📒 Files selected for processing (4)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.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."
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)

33-33: LGTM: Clean dependency injection of DefendantService

The addition of DefendantService follows the dependency injection pattern and aligns with the goal of centralizing defender-related logic.

Also applies to: 74-74


198-213: Address TODO comment and validate defender updates

The comment "Færa message handling í defendant service" indicates incomplete work for message handling migration.

Please verify:

  1. Is the message handling migration to DefendantService complete?
  2. Should we add validation for the defender updates?

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

🧹 Outside diff range and nitpick comments (3)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

198-198: Remove or implement the TODO comment

The comment "Færa message handling í defendant service" (Move message handling to defendant service) suggests incomplete refactoring. Either implement the suggested change or remove the comment if it's no longer applicable.


178-187: Simplify the defender fields condition check

The current condition check is verbose and could be simplified for better readability.

Consider extracting the condition into a helper method:

-if (
-  subpoena.case &&
-  subpoena.defendant &&
-  (defenderChoice ||
-    defenderNationalId ||
-    defenderName ||
-    defenderEmail ||
-    defenderPhoneNumber ||
-    requestedDefenderChoice ||
-    requestedDefenderNationalId ||
-    requestedDefenderName)
-) {
+const hasDefenderUpdates = (update: UpdateSubpoenaDto): boolean => {
+  return Boolean(
+    update.defenderChoice ||
+    update.defenderNationalId ||
+    update.defenderName ||
+    update.defenderEmail ||
+    update.defenderPhoneNumber ||
+    update.requestedDefenderChoice ||
+    update.requestedDefenderNationalId ||
+    update.requestedDefenderName
+  )
+}
+
+if (subpoena.case && subpoena.defendant && hasDefenderUpdates(update)) {

191-196: Extract defender choice reset logic

The nested conditions for resetting defender choice confirmation could be simplified.

Consider extracting the logic:

-const resetDefenderChoiceConfirmed =
-  subpoena.defendant?.isDefenderChoiceConfirmed &&
-  ((defenderChoice &&
-    subpoena.defendant?.defenderChoice !== defenderChoice) ||
-    (defenderNationalId &&
-      subpoena.defendant?.defenderNationalId !== defenderNationalId))
+const shouldResetDefenderChoice = (
+  defendant: Defendant,
+  updates: UpdateSubpoenaDto
+): boolean => {
+  if (!defendant.isDefenderChoiceConfirmed) return false;
+  
+  return (
+    (updates.defenderChoice && defendant.defenderChoice !== updates.defenderChoice) ||
+    (updates.defenderNationalId && defendant.defenderNationalId !== updates.defenderNationalId)
+  );
+};
+
+const resetDefenderChoiceConfirmed = shouldResetDefenderChoice(subpoena.defendant, update);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad1529f and 2b2ed00.

📒 Files selected for processing (4)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.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."
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

74-74: LGTM: Clean dependency injection of DefendantService

The addition of DefendantService follows the established dependency injection pattern and supports the separation of concerns for defender-related operations.


116-144: LGTM: Improved message handling logic

The refactoring simplifies the message queue handling by:

  • Using a single message instead of an array
  • Removing unnecessary defender-related parameters
  • Consolidating the message type handling

199-213: LGTM: Clean delegation to DefendantService

The delegation of defender-related updates to DefendantService follows good separation of concerns and aligns with the PR objectives.

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

🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)

198-198: Remove or address the TODO comment

The comment "Færa message handling í defendant service" suggests incomplete refactoring. Either complete the message handling move to DefendantService or remove the comment.


178-187: Consider extracting the defender update condition to a method

The complex conditional check for defender-related changes could be extracted into a readable method like hasDefenderChanges() to improve maintainability.

+  private hasDefenderChanges(update: UpdateSubpoenaDto): boolean {
+    return !!(
+      update.defenderChoice ||
+      update.defenderNationalId ||
+      update.defenderName ||
+      update.defenderEmail ||
+      update.defenderPhoneNumber ||
+      update.requestedDefenderChoice ||
+      update.requestedDefenderNationalId ||
+      update.requestedDefenderName
+    )
+  }

   if (
     subpoena.case &&
     subpoena.defendant &&
-    (defenderChoice ||
-      defenderNationalId ||
-      defenderName ||
-      defenderEmail ||
-      defenderPhoneNumber ||
-      requestedDefenderChoice ||
-      requestedDefenderNationalId ||
-      requestedDefenderName)
+    this.hasDefenderChanges(update)
   ) {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b2ed00 and 0fb4483.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.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."
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)

33-33: LGTM: Proper dependency injection of DefendantService

The addition of DefendantService aligns with the PR objectives of centralizing defender-related operations.

Also applies to: 74-74


116-144: Add error handling for message queue operations

The message queue operation should include error handling to prevent silent failures.

@kodiakhq kodiakhq bot merged commit 17ef240 into main Nov 15, 2024
37 checks passed
@kodiakhq kodiakhq bot deleted the j-s/defender-changed-notification branch November 15, 2024 14:09
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
* Adss a defendant national id

* Removes unused imports

* Stops updating defendants via API in indictment cases on court case number assignment as these updates are sent to the robot

* Adds a guard to get a defender by national id

* Rewrites update defendant by national id

* Refactors defendant update messages

* Restricts defendant restricted updates to indictment cases

* Moves defendand defender choice updates and notifications to defendant classes

* Update unit tests and fixxes some issues

* Fixes email sending trigger and guard

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants