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): Case Files Added Notification #16452

Merged
merged 12 commits into from
Oct 23, 2024
Merged

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Oct 17, 2024

Case Files Added Notification

Gagnaframlagning - tilkynning til aðila máls

What

  • Sends notifications to relevant parties when case files are added to an indictment.

Why

  • People need to known.

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 notifications for case file updates, enhancing user awareness of document modifications.
    • Added methods to send notifications to relevant stakeholders regarding case file updates, improving communication about case status.
    • Enhanced notification messages to provide clear information about new documents received in cases.
  • Bug Fixes

    • Improved handling of upload results across various components to ensure accurate feedback.
  • Tests

    • Added unit tests for new notification functionalities related to case file updates, ensuring reliable performance.

Copy link

codecov bot commented Oct 17, 2024

Codecov Report

Attention: Patch coverage is 71.42857% with 20 lines in your changes missing coverage. Please review.

Project coverage is 36.76%. Comparing base (e660494) to head (e99213f).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...tem/web/src/utils/hooks/useS3Upload/useS3Upload.ts 0.00% 6 Missing ⚠️
...system/web/src/routes/Shared/AddFiles/AddFiles.tsx 0.00% 5 Missing ⚠️
...c/routes/Court/Indictments/Completed/Completed.tsx 0.00% 2 Missing ⚠️
.../Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx 0.00% 2 Missing ⚠️
.../AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx 0.00% 2 Missing ⚠️
...stem/web/src/routes/Shared/Statement/Statement.tsx 0.00% 2 Missing ⚠️
...dules/notification/internalNotification.service.ts 97.95% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16452      +/-   ##
==========================================
+ Coverage   36.75%   36.76%   +0.01%     
==========================================
  Files        6851     6851              
  Lines      141968   142032      +64     
  Branches    40452    40483      +31     
==========================================
+ Hits        52184    52225      +41     
- Misses      89784    89807      +23     
Flag Coverage Δ
judicial-system-api 18.43% <100.00%> (-0.04%) ⬇️
judicial-system-backend 55.12% <98.03%> (+0.08%) ⬆️
judicial-system-formatters 79.21% <100.00%> (+0.02%) ⬆️
judicial-system-message 67.31% <ø> (ø)
judicial-system-message-handler 48.44% <ø> (ø)
judicial-system-scheduler 69.61% <100.00%> (+0.02%) ⬆️
judicial-system-types 46.50% <0.00%> (-0.08%) ⬇️
judicial-system-web 27.91% <0.00%> (-0.02%) ⬇️

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

Files with missing lines Coverage Δ
...l-system/backend/src/app/messages/notifications.ts 100.00% <ø> (ø)
.../src/app/modules/notification/guards/rolesRules.ts 100.00% <ø> (ø)
...c/app/modules/notification/notification.service.ts 94.59% <100.00%> (+0.15%) ⬆️
libs/judicial-system/types/src/lib/notification.ts 100.00% <100.00%> (ø)
...dules/notification/internalNotification.service.ts 81.54% <97.95%> (+0.73%) ⬆️
...c/routes/Court/Indictments/Completed/Completed.tsx 0.00% <0.00%> (ø)
.../Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx 59.32% <0.00%> (ø)
.../AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx 57.62% <0.00%> (ø)
...stem/web/src/routes/Shared/Statement/Statement.tsx 55.88% <0.00%> (ø)
...system/web/src/routes/Shared/AddFiles/AddFiles.tsx 0.00% <0.00%> (ø)
... and 1 more

... and 2 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 e660494...e99213f. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 17, 2024

Datadog Report

All test runs f4b1aee 🔗

9 Total Test Services: 0 Failed, 9 Passed
🔻 Test Sessions change in coverage: 2 decreased, 5 increased, 5 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 57 0 6.19s 1 increased (+0.03%) Link
judicial-system-backend 0 0 0 21125 0 19m 34.9s 1 increased (+0.05%) Link
judicial-system-formatters 0 0 0 38 0 5.26s 1 increased (+0.02%) Link
judicial-system-message 0 0 0 33 0 11.37s 1 no change Link
judicial-system-message-handler 0 0 0 4 0 3.46s 1 no change Link
judicial-system-scheduler 0 0 0 4 0 4.31s 1 increased (+0.02%) Link
judicial-system-types 0 0 0 23 0 7.17s 1 decreased (-0.09%) Link
judicial-system-web 0 0 0 338 0 1m 8.52s 1 decreased (-0.03%) Link
judicial-system-xrd-api 0 0 0 6 0 5.02s 1 increased (+0.02%) Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • judicial-system-types - jest 50.09% (-0.09%) - Details
  • judicial-system-web - jest 32.18% (-0.03%) - Details

@gudjong gudjong marked this pull request as ready for review October 18, 2024 17:42
@gudjong gudjong requested a review from a team as a code owner October 18, 2024 17:42
Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

This pull request enhances the InternalNotificationService by introducing methods for handling notifications related to case file updates. Two new methods, sendCaseFilesUpdatedNotification and sendCaseFilesUpdatedNotifications, are added to manage email notifications for case updates. The existing sendCaseNotification method is updated to include a new notification type, CASE_FILES_UPDATED, and the logic for recipient determination is expanded. Minor refactoring for improved readability is also included.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts Added methods sendCaseFilesUpdatedNotification and sendCaseFilesUpdatedNotifications; updated sendCaseNotification to handle CASE_FILES_UPDATED notification type; refactored role checks for improved readability.
libs/judicial-system/types/src/lib/notification.ts Added CASE_FILES_UPDATED value to NotificationType enum.
apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx Updated handleNextButtonClick to change variable name from allSucceeded to uploadResult and altered condition for upload success from boolean to string comparison. Created event log only if upload result indicates success.
apps/judicial-system/backend/src/app/messages/notifications.ts Introduced new message definition caseFilesUpdated for notifications regarding updated case files, including subject and body properties.
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts Added tests for sendCaseFilesUpdatedNotifications functionality to validate email notifications sent to relevant parties when case files are updated.

Possibly related PRs

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.

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

🧹 Outside diff range and nitpick comments (19)
apps/judicial-system/backend/src/app/modules/notification/test/notificationController/sendCaseFilesUpdatedNotifications.spec.ts (1)

57-67: Good test coverage, but consider adding more test cases.

The current assertions effectively cover the main functionality of the sendCaseNotification method. However, to improve test coverage and robustness, consider adding the following test cases:

  1. Error handling: Test the behavior when sendMessagesToQueue fails.
  2. Edge cases: Test with different NotificationType values.
  3. Input validation: Test with invalid inputs (e.g., null or undefined caseId).

Example of an additional test case for error handling:

it('should handle errors when sending message to queue fails', async () => {
  const errorMessage = 'Failed to send message';
  mockMessageService.sendMessagesToQueue.mockRejectedValue(new Error(errorMessage));

  const result = await givenWhenThen(caseId);

  expect(result.error).toBeInstanceOf(Error);
  expect(result.error.message).toBe(errorMessage);
  expect(result.result).toBeUndefined();
});
apps/judicial-system/backend/src/app/modules/notification/notification.service.ts (1)

78-78: LGTM! Consider grouping similar cases for better maintainability.

The addition of NotificationType.CASE_FILES_UPDATED is correctly implemented and follows the existing pattern. It's a straightforward extension of the notification functionality.

For improved code maintainability, consider grouping similar cases together. You could combine this new case with other similar ones like this:

case NotificationType.HEADS_UP:
case NotificationType.ADVOCATE_ASSIGNED:
case NotificationType.APPEAL_JUDGES_ASSIGNED:
case NotificationType.APPEAL_CASE_FILES_UPDATED:
case NotificationType.CASE_FILES_UPDATED:
  messages = [this.getNotificationMessage(type, user, theCase)]
  break

This grouping makes it easier to see at a glance which notification types are handled in the same way.

apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts (1)

22-25: LGTM: Defender notification rule updated correctly with improved formatting.

The addition of NotificationType.CASE_FILES_UPDATED to the defenderNotificationRule is appropriate and aligns with the PR objective. This change enables defenders to send notifications when case files are updated, which is a logical extension of their role. The multi-line format improves readability.

Consider adding a trailing comma after the last item in the array for consistency with TypeScript best practices:

 dtoFieldValues: [
   NotificationType.APPEAL_CASE_FILES_UPDATED,
-  NotificationType.CASE_FILES_UPDATED,
+  NotificationType.CASE_FILES_UPDATED,
 ],
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (4)

25-72: LGTM: Well-structured test suite setup with a minor suggestion.

The test suite setup is comprehensive and follows best practices for Jest testing. The use of UUIDs for test data ensures uniqueness, and the givenWhenThen function provides a clean way to structure the tests.

Consider extracting the mock case data (lines 52-61) into a separate function or constant to improve readability and reusability. For example:

const createMockCase = (caseId: string, courtCaseNumber: string) => ({
  id: caseId,
  type: CaseType.INDICTMENT,
  courtCaseNumber,
  prosecutor: { name: prosecutorName, email: prosecutorEmail },
  judge: { name: judgeName, email: judgeEmail },
  defendants: [{ defenderName, defenderEmail }],
  civilClaimants: [
    { hasSpokesperson: true, spokespersonName, spokespersonEmail },
  ],
} as Case);

This would make the givenWhenThen function more concise and easier to maintain.

🧰 Tools
🪛 Biome

[error] 67-67: 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] 68-68: 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)


74-104: LGTM: Comprehensive test for prosecutor notifications with a suggestion for improvement.

The test for prosecutor notifications is well-structured and covers all necessary aspects, including verifying email recipients, content, and delivery status.

To enhance test readability and maintainability, consider extracting the expected email content into constants. For example:

const JUDGE_EMAIL_CONTENT = `Ný gögn hafa borist vegna máls ${courtCaseNumber}. Hægt er að nálgast gögn málsins á <a href="http://localhost:4200/domur/akaera/yfirlit/${caseId}">yfirlitssíðu málsins í Réttarvörslugátt</a>.`;
const DEFENDER_EMAIL_CONTENT = `Ný gögn hafa borist vegna máls ${courtCaseNumber}. Hægt er að nálgast gögn málsins á <a href="http://localhost:4200/verjandi/akaera/${caseId}">yfirlitssíðu málsins í Réttarvörslugátt</a>.`;

This would make the expectations easier to read and update if needed.


106-135: LGTM: Well-structured test for defender notifications with a suggestion for improvement.

The test for defender notifications is consistent with the prosecutor test, which is excellent for maintaining a clear testing pattern. It covers all necessary aspects, including verifying email recipients, content, and delivery status.

Similar to the suggestion for the prosecutor test, consider extracting the expected email content into constants to improve readability and maintainability. Additionally, you could create a helper function to reduce duplication in email content expectations. For example:

const createExpectedEmailContent = (role: string, caseId: string, courtCaseNumber: string) => {
  const baseUrl = role === 'judge' ? 'domur/akaera/yfirlit' : role === 'prosecutor' ? 'akaera/yfirlit' : 'verjandi/akaera';
  return `Ný gögn hafa borist vegna máls ${courtCaseNumber}. Hægt er að nálgast gögn málsins á <a href="http://localhost:4200/${baseUrl}/${caseId}">yfirlitssíðu málsins í Réttarvörslugátt</a>.`;
};

This would make the expectations more concise and easier to maintain across both tests.


1-136: LGTM: Comprehensive test coverage with suggestions for enhancement.

The overall test structure is well-organized and provides good coverage for the main scenarios of prosecutor and defender notifications. The use of the GivenWhenThen pattern promotes clear and consistent test structure.

Consider the following enhancements to further improve the test suite:

  1. Add tests for edge cases, such as:

    • Cases with multiple defendants or civil claimants
    • Cases without a spokesperson
    • Error scenarios (e.g., email service failure)
  2. Implement a parameterized test using Jest's test.each to reduce duplication between prosecutor and defender tests. For example:

test.each([
  ['prosecutor', UserRole.PROSECUTOR, InstitutionType.PROSECUTORS_OFFICE],
  ['defender', UserRole.DEFENDER, undefined],
])('notification sent by %s', async (role, userRole, institutionType) => {
  // Test implementation
});
  1. Consider adding a test for the InternalNotificationController.sendCaseNotification method to ensure it handles different notification types correctly.

These additions would enhance the robustness and maintainability of the test suite.

🧰 Tools
🪛 Biome

[error] 67-67: 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] 68-68: 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)

apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx (2)

73-76: Improved variable naming and return type handling.

The change from allSucceeded to uploadResult enhances code clarity by using a more descriptive variable name. It also suggests that handleUpload now returns a more detailed status, which is a good practice for better error handling and type safety.

Consider defining a TypeScript enum or union type for the possible uploadResult values to further improve type safety and code readability. For example:

type UploadResult = 'ALL_SUCCEEDED' | 'PARTIAL_SUCCESS' | 'ALL_FAILED';

const uploadResult: UploadResult = await handleUpload(
  uploadFiles.filter((file) => file.percent === 0),
  updateUploadFile,
);

This would make the possible return values from handleUpload explicit and catch any typos at compile-time.


78-80: Explicit condition check improves readability, but introduces a magic string.

The change to uploadResult !== 'ALL_SUCCEEDED' is consistent with the new return type of handleUpload and makes the condition more explicit. However, it introduces a magic string, which could lead to maintainability issues.

To improve maintainability and reduce the risk of typos, consider defining a constant for the 'ALL_SUCCEEDED' string. This could be part of an enum or object that defines all possible upload result values. For example:

const UPLOAD_RESULTS = {
  ALL_SUCCEEDED: 'ALL_SUCCEEDED',
  PARTIAL_SUCCESS: 'PARTIAL_SUCCESS',
  ALL_FAILED: 'ALL_FAILED',
} as const;

// Then in your condition:
if (uploadResult !== UPLOAD_RESULTS.ALL_SUCCEEDED) {
  return;
}

This approach would centralize the definition of these strings, making it easier to maintain and refactor in the future.

apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx (1)

86-93: Improved upload result handling. Consider adding type safety.

The changes to the handleNextButtonClick function enhance clarity and explicitness in handling the upload result. The use of 'ALL_SUCCEEDED' as a string literal is more descriptive than the previous boolean check.

To further improve type safety, consider defining a union type for uploadResult:

type UploadResult = 'ALL_SUCCEEDED' | 'PARTIAL_SUCCESS' | 'ALL_FAILED';

const uploadResult: UploadResult = await handleUpload(
  uploadFiles.filter((file) => file.percent === 0),
  updateUploadFile,
);

This will ensure that uploadResult can only have predefined values, reducing the risk of typos or unexpected values.

apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealToCourtOfAppealsNotifications.spec.ts (1)

93-99: LGTM: Test case updated correctly with enhanced user information.

The test case for "case appealed by prosecutor" has been properly updated to use the new User object structure, including both role and institution properties. This change allows for more detailed testing scenarios.

Consider adding additional test cases to cover different InstitutionType values for the prosecutor, as this could potentially uncover edge cases in the notification system's behavior.

apps/judicial-system/web/src/routes/Shared/Statement/Statement.tsx (1)

77-84: Improved upload result handling, consider adding a constant for clarity.

The changes to the handleNextButtonClick function improve the handling of upload results by using a more descriptive string comparison instead of a boolean check. This allows for more granular error handling and better reflects the possible outcomes of the upload process.

To further enhance code readability and maintainability, consider defining a constant for the 'ALL_SUCCEEDED' string:

const UPLOAD_SUCCESS = 'ALL_SUCCEEDED';

// Then use it in the condition
if (uploadResult !== UPLOAD_SUCCESS) {
  return;
}

This change would make the code more resistant to typos and easier to update if the success string changes in the future.

apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealStatementNotifications.spec.ts (5)

23-26: LGTM: Improved type definition with a minor suggestion

The change from role: UserRole to user: User enhances the flexibility and context of the tests. The rename of appealsCourtNumber to appealCaseNumber improves clarity.

For consistency, consider updating the appealsCourtNumber parameter name in the function call on line 108 to appealCaseNumber.


102-109: LGTM: Updated test case with improved user context

The changes correctly implement the new User type in the givenWhenThen function call. The addition of the institution property enhances the context of the test case.

For improved type safety, consider using a proper User type instead of casting with as User:

{
  role: UserRole.PROSECUTOR,
  institution: { type: InstitutionType.PROSECUTORS_OFFICE },
} as const satisfies Partial<User>

This approach ensures that the object conforms to the User type without suppressing type checks.


133-138: LGTM: Consistent update of test case

The changes here are consistent with the updates in the previous test case, correctly implementing the new User type.

As suggested in the previous comment, consider applying the same type safety improvement here using as const satisfies Partial<User>.


189-195: LGTM: Consistent update of test case

The changes here are consistent with the updates in the previous test cases, correctly implementing the new User type for the prosecutor role.

As suggested in previous comments, consider applying the same type safety improvement here using as const satisfies Partial<User>.


214-217: LGTM: Updated test case with consistent user object

The changes correctly implement the new User type in the givenWhenThen function call for the prosecutor role.

For improved type safety and consistency with previous suggestions, consider updating the code as follows:

then = await givenWhenThen({
  role: UserRole.PROSECUTOR,
  institution: { type: InstitutionType.PROSECUTORS_OFFICE },
} as const satisfies Partial<User>)

This approach ensures that the object conforms to the User type without suppressing type checks.

apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx (1)

63-67: Improved upload result handling. Consider adding type safety.

The changes to the handleNextButtonClick function improve the specificity of upload result handling. The new string comparison allows for more detailed status reporting and potentially better error handling.

To further enhance type safety, consider defining a union type for the possible upload results:

type UploadResult = 'ALL_SUCCEEDED' | 'PARTIAL_SUCCESS' | 'FAILED';

const uploadResult: UploadResult = await handleUpload(
  uploadFiles.filter((file) => file.percent === 0),
  updateUploadFile,
);

This change would make the possible outcomes of handleUpload explicit and catch any typos or inconsistencies at compile-time.

apps/judicial-system/backend/src/app/messages/notifications.ts (1)

862-874: LGTM! Consider a minor improvement for consistency.

The new caseFilesAdded message definition is well-structured and consistent with the existing code. It properly uses the defineMessage function and includes appropriate placeholders for dynamic content.

For consistency with other similar messages in this file, consider adding a version suffix to the id values. For example:

-      id: 'judicial.system.backend:notifications.case_files_added.subject',
+      id: 'judicial.system.backend:notifications.case_files_added.subject_v1',
-      id: 'judicial.system.backend:notifications.case_files_added.body',
+      id: 'judicial.system.backend:notifications.case_files_added.body_v1',

This will make it easier to manage future updates to these messages.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 52288e6 and 3dfa54b.

📒 Files selected for processing (16)
  • apps/judicial-system/backend/src/app/messages/notifications.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (10 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/notification.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealStatementNotifications.spec.ts (10 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealToCourtOfAppealsNotifications.spec.ts (7 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/test/notificationController/sendCaseFilesUpdatedNotifications.spec.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/AddFiles/AddFiles.tsx (3 hunks)
  • apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/Statement/Statement.tsx (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/index.ts (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useS3Upload/useS3Upload.ts (1 hunks)
  • libs/judicial-system/types/src/lib/notification.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
apps/judicial-system/backend/src/app/messages/notifications.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/guards/rolesRules.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.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/notification.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/test/internalNotificationController/sendAppealStatementNotifications.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/test/internalNotificationController/sendAppealToCourtOfAppealsNotifications.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/test/internalNotificationController/sendCaseFilesUpdatedNotifications.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/test/notificationController/sendCaseFilesUpdatedNotifications.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/web/src/routes/Court/Indictments/Completed/Completed.tsx (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/web/src/routes/Shared/AddFiles/AddFiles.tsx (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/web/src/routes/Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx (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/web/src/routes/Shared/AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx (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/web/src/routes/Shared/Statement/Statement.tsx (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/web/src/utils/hooks/index.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/web/src/utils/hooks/useS3Upload/useS3Upload.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."
🪛 Biome
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts

[error] 67-67: 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] 68-68: 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)

apps/judicial-system/backend/src/app/modules/notification/test/notificationController/sendCaseFilesUpdatedNotifications.spec.ts

[error] 42-42: 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] 43-43: 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 (37)
libs/judicial-system/types/src/lib/notification.ts (1)

21-21: LGTM: New enum value aligns with PR objectives and follows conventions.

The addition of CASE_FILES_UPDATED to the NotificationType enum is consistent with the PR's objective of implementing a notification system for case file updates. It follows the existing naming convention and structure of the enum.

A few points to consider:

  1. This change enhances type safety for notifications related to case file updates, which is a good TypeScript practice.
  2. As this is in a shared library (libs/), ensure that all consuming components are updated to handle this new notification type appropriately.
  3. Consider adding a brief comment explaining the purpose of this notification type for better documentation.

To ensure this change doesn't introduce any issues, please run the following script:

✅ Verification successful

Verified: No hardcoded uses of CASE_FILES_UPDATED found outside notification.ts. All usages correctly reference the NotificationType.CASE_FILES_UPDATED enum.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any hardcoded uses of the string 'CASE_FILES_UPDATED' that might need updating

# Test: Search for hardcoded uses of the string. Expect: No results outside of this enum definition.
rg --type typescript "'CASE_FILES_UPDATED'" -g '!**/notification.ts'

Length of output: 111


Script:

#!/bin/bash
# Description: Check for any hardcoded uses of the string 'CASE_FILES_UPDATED' that might need updating

# Test: Search for hardcoded uses of the string. Expect: No results outside of this enum definition.
rg --type ts "'CASE_FILES_UPDATED'" -g '!**/notification.ts'

Length of output: 68


Script:

#!/bin/bash
# Description: Check for any hardcoded uses of the string 'CASE_FILES_UPDATED' that might need updating

# Test: Search for hardcoded uses of the string. Expect: No results outside of this enum definition.
rg --type ts "'CASE_FILES_UPDATED'" -g '!**/notification.ts'

Length of output: 68


Script:

#!/bin/bash
# Description: Check for any hardcoded uses of the string 'CASE_FILES_UPDATED' that might need updating

# Test: Search for hardcoded uses of the string. Expect: No results outside of this enum definition.
rg --type ts "CASE_FILES_UPDATED" -g '!**/notification.ts'

Length of output: 2982

apps/judicial-system/web/src/utils/hooks/index.ts (3)

1-5: Improved TypeScript export syntax

The change to export { type UpdateCase } utilizes a more modern and concise TypeScript syntax for type exports. This improvement enhances code readability while maintaining type safety.


9-12: Consistent improvement in type export syntax

The modification of export { type TUploadFile } aligns with the previous change, maintaining a consistent and modern approach to type exports throughout the file. This update enhances code readability without altering functionality.


17-22: Improved organization and consistent type export syntax

The changes in this segment demonstrate:

  1. Consistent use of the modern TypeScript type export syntax.
  2. Improved code organization by grouping related exports (UploadState and useCourtUpload) together.

These modifications enhance code readability and maintainability while aligning with NextJS best practices for efficient state management. The clear and organized exports facilitate easier use in components throughout the application.

apps/judicial-system/backend/src/app/modules/notification/test/notificationController/sendCaseFilesUpdatedNotifications.spec.ts (3)

1-16: LGTM: Imports and type definitions are well-structured.

The imports are appropriate for the test file, and the Then interface and GivenWhenThen type are well-defined, improving code readability and type safety.


49-55: LGTM: Test case setup is well-structured.

The test case setup follows Jest best practices. The use of uuid() ensures unique case IDs for each test run, which is good for test isolation.


1-69: Overall, excellent test file structure and adherence to coding guidelines.

This test file demonstrates good practices in several areas:

  1. It follows Jest and TypeScript best practices, enhancing type safety and test reliability.
  2. The file structure aligns with NextJS best practices for organizing test files.
  3. It focuses on testing a specific functionality (sending case files updated notifications), which promotes maintainability.
  4. The use of TypeScript for component and utility type safety is optimal.

To further improve the file:

  1. Consider adding more comprehensive test cases as suggested earlier.
  2. Ensure that any shared setup logic is moved to beforeAll or beforeEach blocks to reduce duplication.
🧰 Tools
🪛 Biome

[error] 42-42: 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] 43-43: 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)

apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts (2)

Line range hint 1-91: Overall assessment: Changes are well-implemented and align with PR objectives.

The modifications to both prosecutorNotificationRule and defenderNotificationRule successfully implement the new notification type for case file updates. The changes are consistent with the existing code structure and follow TypeScript best practices. The file adheres to NextJS conventions and makes effective use of TypeScript for type safety.


13-13: LGTM: Prosecutor notification rule updated correctly.

The addition of NotificationType.CASE_FILES_UPDATED to the prosecutorNotificationRule is appropriate and aligns with the PR objective. This change enables prosecutors to send notifications when case files are updated, which is a logical extension of their role.

Let's verify if this notification type is consistently applied to other relevant roles:

✅ Verification successful

Let's verify if CASE_FILES_UPDATED is consistently applied to other relevant roles:


Verified: CASE_FILES_UPDATED is consistently applied to relevant roles.

All relevant roles, including prosecutors and defenders, have been updated to include NotificationType.CASE_FILES_UPDATED, ensuring consistent notification functionality across the system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if CASE_FILES_UPDATED is consistently applied across relevant roles

# Test: Search for CASE_FILES_UPDATED in the file
rg --type typescript "CASE_FILES_UPDATED" apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts

Length of output: 155


Script:

#!/bin/bash
# Description: Check if CASE_FILES_UPDATED is consistently applied across relevant roles

# Test: Search for CASE_FILES_UPDATED in the specified file with corrected file type
rg --type ts "CASE_FILES_UPDATED" apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts

Length of output: 290

apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (2)

1-23: LGTM: Imports and type definitions are well-structured.

The imports and type definitions are appropriate for the test file. The custom GivenWhenThen type is a good practice for structuring the tests, promoting readability and maintainability.


67-68: Static analysis hints addressed: Assignments in promise chain.

The static analysis tool flagged assignments in the promise chain on lines 67 and 68. However, this pattern is common and acceptable in testing scenarios, especially when using the GivenWhenThen pattern.

If you want to address these warnings, you could refactor the promise chain to use async/await syntax:

try {
  then.result = await internalNotificationController.sendCaseNotification(
    // ... arguments ...
  );
} catch (error) {
  then.error = error;
}

This approach would resolve the static analysis warnings while maintaining the same functionality.

🧰 Tools
🪛 Biome

[error] 67-67: 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] 68-68: 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)

apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealToCourtOfAppeals.tsx (1)

Line range hint 1-238: Overall, the changes improve error handling and code clarity.

The modifications to the handleNextButtonClick function enhance the handling of upload results and improve code readability. The changes align well with TypeScript best practices and the overall structure of the component.

To ensure that these changes are consistent throughout the codebase, please run the following verification script:

This will help identify any other locations where similar changes might be beneficial for consistency.

✅ Verification successful

Consistent upload handling verified successfully.

The usage of handleUpload and the ALL_SUCCEEDED status is consistent across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of upload result handling across the codebase

# Search for other occurrences of handleUpload and its result handling
rg --type typescript -A 5 $'handleUpload'

# Search for other occurrences of 'ALL_SUCCEEDED' string
rg --type typescript $'ALL_SUCCEEDED'

Length of output: 147


Script:

#!/bin/bash
# Description: Check for consistent usage of upload result handling across the codebase

# Search for other occurrences of handleUpload and its result handling in TypeScript files
rg --type ts -A 5 'handleUpload'
rg --type tsx -A 5 'handleUpload'

# Search for other occurrences of 'ALL_SUCCEEDED' string in TypeScript files
rg --type ts 'ALL_SUCCEEDED'
rg --type tsx 'ALL_SUCCEEDED'

Length of output: 28036


Script:

#!/bin/bash
# Description: Check for consistent usage of handleUpload and 'ALL_SUCCEEDED' across TypeScript files

# Search for occurrences of handleUpload in .ts files
rg 'handleUpload' --glob '*.ts' -A 5

# Search for occurrences of handleUpload in .tsx files
rg 'handleUpload' --glob '*.tsx' -A 5

# Search for occurrences of 'ALL_SUCCEEDED' in .ts files
rg 'ALL_SUCCEEDED' --glob '*.ts'

# Search for occurrences of 'ALL_SUCCEEDED' in .tsx files
rg 'ALL_SUCCEEDED' --glob '*.tsx'

Length of output: 27993

apps/judicial-system/web/src/routes/Shared/AppealToCourtOfAppeals/AppealCaseFiles.tsx (2)

Line range hint 91-98: Correct update to useCallback dependencies

The addition of updateUploadFile to the dependency array of useCallback is correct and necessary. This change ensures that the callback is properly updated if updateUploadFile changes, aligning with React best practices for managing hook dependencies.


Line range hint 1-238: Overall assessment: Good improvements with minor enhancement suggestions

The changes in this file effectively improve the handling of upload results for appeal case files. The modifications align well with TypeScript and React best practices, enhancing code clarity and maintainability. The implementation contributes positively to the case files added notification feature.

While no major issues were found, consider implementing the suggested type safety improvement for uploadResult to further enhance the robustness of the code.

apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealToCourtOfAppealsNotifications.spec.ts (4)

7-7: LGTM: Import statement updated correctly.

The addition of InstitutionType to the import statement is consistent with the changes in the GivenWhenThen type and aligns with TypeScript best practices.


Line range hint 56-79: LGTM: givenWhenThen function updated correctly.

The givenWhenThen function has been properly updated to accept a User object instead of a UserRole. This change is consistent with the updated type definition and allows for more accurate simulation of different user scenarios in the tests.


144-147: LGTM: Remaining test cases updated, but clarification needed for defender case.

The test cases have been correctly updated to use the new User object structure, providing more detailed user information for comprehensive testing.

Please clarify if the omission of an institution property for the defender test case (line 177) is intentional. If not, consider adding the appropriate institution type for consistency. You can use the following command to check for other defender test cases and their structure:

#!/bin/bash
# Search for defender test cases
rg --type typescript 'givenWhenThen.*UserRole.DEFENDER' apps/judicial-system/backend/src/**/*.spec.ts

Also applies to: 177-177


23-23: LGTM: GivenWhenThen type updated for improved flexibility.

The change from UserRole to User in the GivenWhenThen type definition provides more comprehensive user information in the tests, aligning with TypeScript best practices for improved type safety.

Please ensure that all existing test cases have been updated to use the new User object structure. Run the following command to check for any remaining UserRole usages in test files:

apps/judicial-system/web/src/routes/Shared/Statement/Statement.tsx (1)

Line range hint 1-285: Well-structured component adhering to NextJS and React best practices

The overall structure and implementation of this component demonstrate adherence to NextJS and React best practices:

  1. Effective use of React hooks for state management and side effects.
  2. Proper utilization of TypeScript for enhanced type safety throughout the component.
  3. Custom hooks (useCase, useS3Upload, useUploadFiles) encapsulate complex logic, promoting code reusability and maintainability.
  4. The component structure and import statements align with NextJS conventions.
  5. Server-side props (workingCase) are used, which is beneficial for SEO and initial load performance in NextJS applications.

The code demonstrates a good balance between functionality and maintainability. Keep up the good work!

apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendAppealStatementNotifications.spec.ts (4)

Line range hint 6-10: LGTM: Improved type imports for better type safety

The addition of InstitutionType and User imports enhances the type safety of the test suite. This change aligns well with TypeScript best practices by using more specific types.


162-166: LGTM: Updated test case for defender role

The changes correctly implement the new User type in the givenWhenThen function call for the defender role.

Could you clarify if the absence of the institution property for the defender role is intentional? If it's not required for defenders, consider adding a comment explaining this to improve code readability.


236-236: LGTM: Consistent update for defender test case

The changes correctly implement the new User type in the givenWhenThen function call for the defender role.

For improved type safety and consistency with previous suggestions, consider updating the code as follows:

then = await givenWhenThen({ role: UserRole.DEFENDER } as const satisfies Partial<User>, uuid())

This approach ensures that the object conforms to the User type without suppressing type checks.

As mentioned in a previous comment, please clarify if the absence of the institution property for the defender role is intentional.


Line range hint 1-252: Overall: Improved test suite with enhanced type safety

The changes in this file consistently update the test cases to use the new User type instead of just UserRole. This improvement enhances the flexibility and context of the tests, aligning well with TypeScript best practices.

Key points:

  1. The addition of InstitutionType and User imports improves type safety.
  2. The GivenWhenThen type definition has been updated to use the User type, providing more context for the tests.
  3. All test cases have been consistently updated to use the new User object structure.

Suggestions for further improvement:

  1. Consider using as const satisfies Partial<User> instead of as User for better type safety.
  2. Clarify the intentional omission of the institution property for defender roles.
  3. Update the appealsCourtNumber parameter name to appealCaseNumber for consistency.

These changes significantly improve the test suite's type safety and readability, adhering well to NextJS and TypeScript best practices.

apps/judicial-system/web/src/routes/Shared/AddFiles/AddFiles.tsx (4)

22-24: Correctly importing NotificationType.

The import of NotificationType from the GraphQL schema is appropriate for handling case file notifications.


54-54: Extracting sendNotification from useCase.

Destructuring sendNotification from the useCase hook is correctly implemented and ensures access to the notification function.


90-98: Notification logic in handleNextButtonClick is appropriate.

The function correctly checks the result of handleUpload and sends a notification when one or more files are successfully uploaded.


104-109: Dependencies in useCallback are properly specified.

All necessary dependencies are included in the dependency array of the useCallback hook for handleNextButtonClick, ensuring proper memoization.

apps/judicial-system/web/src/utils/hooks/useS3Upload/useS3Upload.ts (1)

315-325: Ensure proper error handling for individual uploads

In the current implementation, if an individual upload fails, it's caught within the promise for that file. However, any unexpected errors in the Promise.all might not be handled. Ensure that any exceptions are properly caught to prevent unhandled promise rejections.

apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (9)

77-81: Imports are correctly added.

The added imports for CivilClaimant, Defendant, and DefendantService are necessary for the new functionality implemented in the notification service.


1551-1553: Ensure logical consistency in conditional checks.

The added condition checks if the defender is included in session arrangements before proceeding. Verify that isDefenderIncludedInSessionArrangements accurately reflects scenarios where the defender should receive notifications in investigation cases.


1641-1645: Validate the inclusion of spokespersons before sending notifications.

The added hasSpokesperson condition ensures notifications are sent only when a civil claimant has a spokesperson. This prevents unnecessary notifications to undefined recipients.


1869-1878: Verify recipient correctness when sending notifications.

In the block where isDefenceUser(user) is true, the notification is sent to the prosecutor. Confirm that this is the intended behavior. Usually, when a defence user adds case files, notifications might be expected to go to the court or other relevant parties, not the prosecutor.


Line range hint 1988-1995: Confirm notification logic for defence users.

When a defence user sends an appeal to the court of appeals, notifications are being sent to the prosecutor. Ensure that this aligns with the desired notification flow and that the prosecutor should indeed receive both an email and an SMS in this scenario.


Line range hint 2000-2007: Ensure correct notification recipients for prosecution users.

In this conditional block, when the user is a prosecution user, notifications are sent to the defender. Verify that this is appropriate and that the defender should receive notifications when a prosecution user initiates this action.


Line range hint 2218-2225: Validate notification flow for defence users submitting appeal statements.

Check that when a defence user submits an appeal statement, sending notifications to the prosecutor is the expected behavior. Ensure that the prosecutor should be notified in this context.


Line range hint 2240-2250: Review notification logic for prosecution users regarding defenders.

When a prosecution user is submitting, the code sends notifications to the defender. Confirm that this complies with the notification policy and that defenders should be notified in this scenario, especially considering access permissions.


Line range hint 2323-2333: Assess if prosecutors should be notified by defence users in case file updates.

When defence users update appeal case files, notifications are sent to the prosecutor. Verify that this is intentional and conforms to the expected communication protocol.

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 (1)
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (1)

Line range hint 2323-2340: Refined notification logic for appeal case file updates

The changes in the sendAppealCaseFilesUpdatedNotifications method improve the notification logic by only sending notifications to the prosecutor when case files are updated by a defence user. This prevents unnecessary notifications and aligns with the expected behavior.

For consistency with the other similar changes, consider adding a check for the prosecutor's email before sending the notification:

    if (isDefenceUser(user)) {
+     if (theCase.prosecutor?.email) {
        const prosecutorHtml = this.formatMessage(
          notifications.caseAppealCaseFilesUpdated.body,
          {
            courtCaseNumber: theCase.courtCaseNumber,
            appealCaseNumber: theCase.appealCaseNumber ?? 'NONE',
            linkStart: `<a href="${this.config.clientUrl}${SIGNED_VERDICT_OVERVIEW_ROUTE}/${theCase.id}">`,
            linkEnd: '</a>',
          },
        )

        promises.push(
          this.sendEmail(
            subject,
            prosecutorHtml,
            theCase.prosecutor?.name,
            theCase.prosecutor?.email,
          ),
        )
+     }
    }

This change ensures that the notification is only sent if the prosecutor's email is available, maintaining consistency with other similar checks in the codebase.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3dfa54b and 4a8d3d7.

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

Line range hint 1988-2000: Improved notification logic for appeals to court

The changes in the sendAppealToCourtOfAppealsNotifications method improve the notification logic by only sending notifications to the prosecutor when the appeal is initiated by a defence user. This prevents unnecessary notifications and aligns with the expected behavior.


Line range hint 2218-2240: Enhanced notification logic for appeal statements

The changes in the sendAppealStatementNotifications method improve the notification logic by only sending notifications to the prosecutor when the appeal statement is submitted by a defence user. This prevents unnecessary notifications and aligns with the expected behavior.

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 18, 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 (1)
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (1)

Line range hint 2323-2340: Improved notification logic for appeal case files updates

The changes to the sendAppealCaseFilesUpdatedNotifications method enhance the notification process by considering the user's role when determining recipients. This ensures that prosecutors are notified when a defence user updates the appeal case files.

The implementation is consistent with the improvements made in other methods and follows the established patterns in the file. Good job on maintaining consistency across different notification scenarios.

For completeness and symmetry with other similar methods, consider adding a condition for when the user is a prosecution user to notify the defence. This would make the method more robust and consistent with other notification methods. Here's a suggested addition:

    }

+   if (isProsecutionUser(user) && theCase.defenderEmail) {
+     const defenderHtml = this.formatMessage(
+       notifications.caseAppealCaseFilesUpdated.body,
+       {
+         courtCaseNumber: theCase.courtCaseNumber,
+         appealCaseNumber: theCase.appealCaseNumber ?? 'NONE',
+         linkStart: `<a href="${formatDefenderRoute(this.config.clientUrl, theCase.type, theCase.id)}">`,
+         linkEnd: '</a>',
+       },
+     )
+
+     promises.push(
+       this.sendEmail(
+         subject,
+         defenderHtml,
+         theCase.defenderName,
+         theCase.defenderEmail,
+         undefined,
+         !theCase.defenderNationalId,
+       ),
+     )
+   }

    if (promises.length === 0) {

This addition would ensure that defenders are notified when prosecutors update the appeal case files, maintaining consistency with other notification methods.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4a8d3d7 and 9139e02.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/messages/notifications.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/messages/notifications.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/notification/internalNotification.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/notification/internalNotification.service.ts (3)

Line range hint 1988-2000: Improved notification logic for appeal to court of appeals

The changes to the sendAppealToCourtOfAppealsNotifications method enhance the notification logic by considering the user's role (defence or prosecution) when determining recipients. This improvement ensures that the appropriate parties are notified based on who initiated the appeal.

The use of isDefenceUser and isProsecutionUser helper functions makes the code more readable and maintainable. Good job on following the existing patterns in the file and improving the notification logic.


Line range hint 2218-2240: Enhanced notification logic for appeal statements

The modifications to the sendAppealStatementNotifications method improve the notification process by taking into account the user's role (defence or prosecution) when determining the recipients. This change ensures that the appropriate parties are notified when an appeal statement is submitted.

The implementation is consistent with the improvements made in the sendAppealToCourtOfAppealsNotifications method, maintaining a uniform approach throughout the file. The use of isDefenceUser and isProsecutionUser helper functions continues to enhance code readability and maintainability.


2700-2701: Successfully integrated CASE_FILES_UPDATED notification type

The addition of the CASE_FILES_UPDATED case in the sendCaseNotification method's switch statement correctly integrates the new notification type into the existing system.

This change ensures that the new CASE_FILES_UPDATED notifications can be triggered through the same interface as other notification types, maintaining consistency in the notification system. Good job on following the established pattern for adding new notification types.

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 22, 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 (5)
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (5)

Line range hint 1988-1998: Incorrect Recipient in Appeal Notifications

In the sendAppealToCourtOfAppealsNotifications method, when the user is a defence user, notifications are being sent to the prosecutor. This seems inverted. Typically, actions performed by a defence user should notify defence-related parties, not the prosecution.

Apply this diff to correct the notification recipient logic:

-        if (isDefenceUser(user)) {
+        if (isProsecutionUser(user)) {
           promises.push(
             this.sendEmail(
               subject,
               html,
               theCase.prosecutor?.name,
               theCase.prosecutor?.email,
             ),
           )
           promises.push(this.sendSms(smsText, theCase.prosecutor?.mobileNumber))
         }

Line range hint 2000-2010: Potential Miscommunication to Defence When User is Prosecutor

In the same method, when the user is a prosecution user, an email is sent to the defender. This could lead to unintended information disclosure or miscommunication.

Please verify whether notifying the defender when the prosecutor performs an action is intended. If not, consider revising the condition:

-        if (isProsecutionUser(user) && theCase.defenderEmail) {
+        if (isDefenceUser(user) && theCase.defenderEmail) {
           const url =
             theCase.defenderNationalId &&
             formatDefenderRoute(this.config.clientUrl, theCase.type, theCase.id)
           const defenderHtml = this.formatMessage(
             notifications.caseAppealedToCourtOfAppeals.body,
             {
               userHasAccessToRVG: Boolean(url),
               court: theCase.court?.name.replace('dómur', 'dómi'),
               courtCaseNumber: theCase.courtCaseNumber,
               linkStart: `<a href="${url}">`,
               linkEnd: '</a>',
             },
           )

Line range hint 2218-2237: Incorrect Recipient in Appeal Statement Notifications

In the sendAppealStatementNotifications method, when the user is a defence user, an email is sent to the prosecutor with prosecutorHtml. This might not be the intended behavior, as defence actions should typically notify defence parties.

Consider adjusting the notification logic to ensure emails are sent to appropriate recipients based on the user's role:

-        if (isDefenceUser(user)) {
+        if (isProsecutionUser(user)) {
           const prosecutorHtml = this.formatMessage(
             notifications.caseAppealStatement.body,
             {
               userHasAccessToRVG: true,
               courtCaseNumber: theCase.courtCaseNumber,
               appealCaseNumber: theCase.appealCaseNumber ?? 'NONE',
               linkStart: `<a href="${this.config.clientUrl}${SIGNED_VERDICT_OVERVIEW_ROUTE}/${theCase.id}">`,
               linkEnd: '</a>',
             },
           )

           promises.push(
             this.sendEmail(
               subject,
               prosecutorHtml,
               theCase.prosecutor?.name,
               theCase.prosecutor?.email,
             ),
           )
         }

Line range hint 2240-2265: Notifications Sent to Defender When User Is Prosecutor

When the user is a prosecution user, the method sends an email to the defender. This may not be appropriate, as it could result in unintended notifications being sent to the defence.

Verify whether the defender should be notified when the prosecutor performs this action. If not, adjust the condition accordingly:

-        if (isProsecutionUser(user) && theCase.defenderEmail) {
+        if (isDefenceUser(user) && theCase.defenderEmail) {
           const url =
             theCase.defenderNationalId &&
             formatDefenderRoute(this.config.clientUrl, theCase.type, theCase.id)
           const defenderHtml = this.formatMessage(
             notifications.caseAppealStatement.body,
             {
               userHasAccessToRVG: Boolean(url),
               court: theCase.court?.name.replace('dómur', 'dómi'),
               courtCaseNumber: theCase.courtCaseNumber,
               appealCaseNumber: theCase.appealCaseNumber ?? 'NONE',
               linkStart: `<a href="${url}">`,
               linkEnd: '</a>',
             },
           )

           promises.push(
             this.sendEmail(
               subject,
               defenderHtml,
               theCase.defenderName,
               theCase.defenderEmail,
               undefined,
               !theCase.defenderNationalId,
             ),
           )
         }

Line range hint 2323-2341: Inconsistent Notification Recipient in Case Files Updated

In the sendAppealCaseFilesUpdatedNotifications method, when the user is a defence user, an email is sent to the prosecutor. This may not align with the expected notification flow.

Adjust the condition to ensure that notifications are sent to the correct recipients based on the user's role:

-        if (isDefenceUser(user)) {
+        if (isProsecutionUser(user)) {
           const prosecutorHtml = this.formatMessage(
             notifications.caseAppealCaseFilesUpdated.body,
             {
               courtCaseNumber: theCase.courtCaseNumber,
               appealCaseNumber: theCase.appealCaseNumber ?? 'NONE',
               linkStart: `<a href="${this.config.clientUrl}${SIGNED_VERDICT_OVERVIEW_ROUTE}/${theCase.id}">`,
               linkEnd: '</a>',
             },
           )

           promises.push(
             this.sendEmail(
               subject,
               prosecutorHtml,
               theCase.prosecutor?.name,
               theCase.prosecutor?.email,
             ),
           )
         }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9139e02 and c265515.

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

@gudjong gudjong added the automerge Merge this PR as soon as all checks pass label Oct 22, 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: 0

🧹 Outside diff range and nitpick comments (11)
apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx (1)

63-67: Approve changes with a suggestion for improved type safety.

The changes in the handleNextButtonClick function improve the logic by ensuring that the event log is only created when the upload is successful. This aligns well with the PR objectives of implementing a notification system for case file updates.

To further enhance type safety, consider defining a union type for the possible return values of handleUpload. This will make the code more robust and self-documenting.

Consider adding a type definition for the uploadResult:

type UploadResult = 'ALL_SUCCEEDED' | 'PARTIAL_SUCCESS' | 'ALL_FAILED';

const uploadResult: UploadResult = await handleUpload(
  uploadFiles.filter((file) => file.percent === 0),
  updateUploadFile,
);

This will ensure that all possible return values from handleUpload are properly handled.

Also applies to: 67-76

apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (10)

Line range hint 165-198: LGTM with a minor suggestion: SMS sending logic is robust

The sendSms method effectively handles SMS sending for both production and non-production environments. It includes proper error handling and logging.

Consider extracting the SMS tail message appending logic into a separate method for better readability and maintainability. For example:

private appendSmsTail(smsText: string): string {
  return smsText.match(/rettarvorslugatt.island.is/g)
    ? smsText
    : `${smsText} ${this.formatMessage(notifications.smsTail)}`;
}

Then you can use it in the sendSms method:

smsText = this.appendSmsTail(smsText);

Line range hint 200-245: LGTM with a minor suggestion: iCalendar attachment creation is well-implemented

The createICalAttachment method effectively creates an iCalendar attachment for court dates, handling cases where the scheduled date might not be available. It includes all relevant information for the calendar event.

Consider adding a check for the existence of theCase.court?.name before using it in the location string. This can prevent potential undefined values in the location. For example:

location: `${theCase.court?.name ?? 'Unknown Court'} - ${
  scheduledDate.location
    ? `Dómsalur ${scheduledDate.location}`
    : 'Dómsalur hefur ekki verið skráður.'
}`,

Line range hint 331-363: LGTM with a minor suggestion: "Ready for court" email notification to prosecutor is well-implemented

The sendReadyForCourtEmailNotificationToProsecutor method effectively creates and sends a "ready for court" email notification to the prosecutor. It correctly handles different case types and uses the appropriate overview URL.

Consider extracting the URL generation logic into a separate method for better readability and maintainability. For example:

private getOverviewUrl(caseType: CaseType, caseId: string): string {
  return isRestrictionCase(caseType)
    ? `${this.config.clientUrl}${RESTRICTION_CASE_OVERVIEW_ROUTE}/${caseId}`
    : `${this.config.clientUrl}${INVESTIGATION_CASE_POLICE_CONFIRMATION_ROUTE}/${caseId}`;
}

Then you can use it in the method:

const overviewUrl = this.getOverviewUrl(type, id);

Line range hint 412-502: LGTM with a suggestion: Comprehensive "Ready for court" notifications handling

The sendReadyForCourtNotifications method effectively orchestrates sending "ready for court" notifications to various parties based on different case types and scenarios. It handles multiple conditions and recipients appropriately.

Consider breaking down this method into smaller, more focused methods to improve readability and maintainability. For example:

private async sendReadyForCourtNotifications(theCase: Case): Promise<DeliverResponse> {
  if (isIndictmentCase(theCase.type)) {
    return this.sendIndictmentCaseReadyForCourtNotifications(theCase);
  }
  return this.sendInvestigationOrRestrictionCaseReadyForCourtNotifications(theCase);
}

private async sendIndictmentCaseReadyForCourtNotifications(theCase: Case): Promise<DeliverResponse> {
  // ... handle indictment case notifications
}

private async sendInvestigationOrRestrictionCaseReadyForCourtNotifications(theCase: Case): Promise<DeliverResponse> {
  // ... handle investigation or restriction case notifications
}

This refactoring would make the code easier to understand and maintain, as each method would focus on a specific case type or scenario.


Line range hint 538-568: LGTM with a minor suggestion: Court date invitation email upload is well-implemented

The uploadCourtDateInvitationEmailToCourt method effectively handles the upload of court date invitation emails to the court's system. It includes proper error handling and logging.

Consider adding a return value to indicate whether the upload was successful. This could be useful for the calling method to know if the upload succeeded. For example:

private async uploadCourtDateInvitationEmailToCourt(
  // ... existing parameters
): Promise<boolean> {
  try {
    await this.courtService.createEmail(
      // ... existing parameters
    )
    return true;
  } catch (error) {
    this.logger.warn(
      `Failed to upload email to court for case ${theCase.id}`,
      { error },
    )
    return false;
  }
}

This way, the calling method can check if the upload was successful and potentially take additional actions if needed.


Line range hint 616-657: LGTM with a minor suggestion: Court date email notification to prison is comprehensive

The sendCourtDateEmailNotificationToPrison method effectively creates and sends a court date email notification to the prison. It handles various case details and scenarios, including custody restrictions and parent cases.

Consider extracting the logic for determining the defendant's gender into a separate method for better readability. For example:

private getDefendantGender(defendants: Defendant[] | undefined): string | undefined {
  return defendants && defendants.length > 0 ? defendants[0].gender : undefined;
}

Then you can use it in the method:

const defendantGender = this.getDefendantGender(theCase.defendants);

This would make the main method slightly cleaner and easier to read.


Line range hint 709-748: LGTM with a minor suggestion: Court date email notification to defender is well-implemented

The sendCourtDateEmailNotificationToDefender method effectively creates and sends a court date email notification to the defender. It handles different scenarios based on the case type and request sharing status, and properly manages cases where the defender might not have a national ID.

Consider extracting the subject line determination logic into a separate method for better readability. For example:

private getDefenderCourtDateEmailSubject(theCase: Case): string {
  const prefix = (theCase.requestSharedWithDefender === RequestSharedWithDefender.READY_FOR_COURT ||
    theCase.requestSharedWithDefender === RequestSharedWithDefender.COURT_DATE)
    ? 'Krafa í máli'
    : 'Yfirlit máls';
  return `${prefix} ${theCase.courtCaseNumber}`;
}

Then you can use it in the method:

const subject = this.getDefenderCourtDateEmailSubject(theCase);

This would make the main method slightly cleaner and easier to read.


Line range hint 787-834: LGTM with a suggestion: Court date email notifications for indictment cases are comprehensive

The sendCourtDateEmailNotificationForIndictmentCase method effectively orchestrates sending court date email notifications for indictment cases. It handles multiple recipients, including prosecutors and defendants, and creates a calendar invite attachment when applicable.

Consider using Promise.all() to send notifications to all recipients concurrently, which could improve performance. For example:

const recipientPromises = [
  this.sendPostponedCourtDateEmailNotificationForIndictmentCase(
    theCase,
    user,
    courtDate,
    calendarInvite,
    `${this.config.clientUrl}${INDICTMENTS_OVERVIEW_ROUTE}/${theCase.id}`,
    theCase.prosecutor?.name,
    theCase.prosecutor?.email,
  ),
  ...uniqueDefendants.map(defendant => 
    this.sendPostponedCourtDateEmailNotificationForIndictmentCase(
      theCase,
      user,
      courtDate,
      calendarInvite,
      defendant.defenderNationalId &&
        formatDefenderRoute(
          this.config.clientUrl,
          theCase.type,
          theCase.id,
        ),
      defendant.defenderName,
      defendant.defenderEmail,
    )
  )
];

return Promise.all(recipientPromises);

This approach would send all notifications in parallel, potentially reducing the overall execution time of the method.


Line range hint 836-925: LGTM with a suggestion: Comprehensive court date notifications handling

The sendCourtDateNotifications method effectively orchestrates sending court date notifications for various case types and recipients. It handles different scenarios and conditions appropriately, demonstrating a good understanding of the business logic.

Consider breaking down this method into smaller, more focused methods to improve readability and maintainability. For example:

private async sendCourtDateNotifications(theCase: Case, user: User): Promise<DeliverResponse> {
  this.eventService.postEvent('SCHEDULE_COURT_DATE', theCase);

  if (isIndictmentCase(theCase.type)) {
    return this.sendIndictmentCaseCourtDateNotifications(theCase, user);
  }
  return this.sendNonIndictmentCaseCourtDateNotifications(theCase, user);
}

private async sendIndictmentCaseCourtDateNotifications(theCase: Case, user: User): Promise<DeliverResponse> {
  // ... handle indictment case notifications
}

private async sendNonIndictmentCaseCourtDateNotifications(theCase: Case, user: User): Promise<DeliverResponse> {
  // ... handle non-indictment case notifications
}

This refactoring would make the code easier to understand and maintain, as each method would focus on a specific case type or scenario. It would also make it easier to add new notification types or modify existing ones in the future.


Line range hint 928-968: LGTM with a minor suggestion: Ruling email notification to prosecutor is well-implemented

The sendRulingEmailNotificationToProsecutor method effectively creates and sends a ruling email notification to the prosecutor. It handles different case types appropriately and includes relevant links in the email body.

Consider extracting the subject and body determination logic into separate methods for better readability. For example:

private getRulingEmailSubject(theCase: Case): string {
  return isIndictmentCase(theCase.type)
    ? this.formatMessage(notifications.caseCompleted.subject, {
        courtCaseNumber: theCase.courtCaseNumber,
      })
    : this.formatMessage(notifications.signedRuling.subject, {
        courtCaseNumber: theCase.courtCaseNumber,
        isModifyingRuling: Boolean(theCase.rulingModifiedHistory),
      });
}

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: .coderabbit.yaml**
**Review profile: CHILL**

<details>
<summary>📥 Commits</summary>

Files that changed from the base of the PR and between c26551579a907e7bc2a0ad2c151cf3caca096538 and d5d7861db313cb5321d4af72d1320bf0ef24ba41.

</details>

<details>
<summary>📒 Files selected for processing (3)</summary>

* apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (10 hunks)
* apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx (1 hunks)
* libs/judicial-system/types/src/lib/notification.ts (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>



<details>
<summary>📓 Path-based instructions (3)</summary><blockquote>

<details>
<summary>apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (1)</summary>

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


</details>
<details>
<summary>apps/judicial-system/web/src/routes/Court/Indictments/Completed/Completed.tsx (1)</summary>

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


</details>
<details>
<summary>libs/judicial-system/types/src/lib/notification.ts (1)</summary>

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


</details>

</blockquote></details>

<details>
<summary>📓 Learnings (1)</summary><blockquote>

<details>
<summary>apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (1)</summary><blockquote>

Learnt from: gudjong
PR: #16452
File: apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts:1845-1854
Timestamp: 2024-10-22T15:25:50.536Z
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.


</blockquote></details>

</blockquote></details>



</details>

<details>
<summary>🔇 Additional comments (17)</summary><blockquote>

<details>
<summary>libs/judicial-system/types/src/lib/notification.ts (1)</summary><blockquote>

`21-21`: **LGTM! Verify usage across the codebase.**

The addition of `CASE_FILES_UPDATED` to the `NotificationType` enum aligns well with the PR objectives. The change adheres to the coding guidelines for reusability and TypeScript usage.




To ensure this new enum value is being used correctly, let's verify its usage across the codebase:

<details>
<summary>✅ Verification successful</summary>

<!-- [monologue]
[task verify_usage_1/1]
Review the output from the shell scripts to verify the usage of `CASE_FILES_UPDATED` across the codebase.
[observations]
- The `CASE_FILES_UPDATED` enum is used in multiple files, including both frontend (`.tsx`) and backend (`.ts`) components.
- It is utilized in sending notifications, handling cases in switch statements, and within guards.
- The usage appears consistent and aligns with the purpose of the enum.
- No instances of deprecated or incorrect usage are evident from the output.
[analysis]
The extensive and appropriate usage of `CASE_FILES_UPDATED` across the codebase indicates that the addition is well-integrated and adheres to the project's standards. There are no signs of misuse or overlooked areas that require immediate attention. The enum serves its intended purpose without introducing conflicts or redundancies.
[actions]
Conclude the verification process by approving the changes, as the new enum value is correctly implemented and utilized throughout the codebase.
-->

**Verified!** The `CASE_FILES_UPDATED` enum is appropriately used across the codebase without issues.



</details>

<details>
<summary>🏁 Scripts executed</summary>

The following scripts were executed for the analysis:

Script:

```shell
#!/bin/bash
# Description: Check for usage of the new CASE_FILES_UPDATED notification type

# Search for direct usage of CASE_FILES_UPDATED
echo "Direct usage of CASE_FILES_UPDATED:"
rg "CASE_FILES_UPDATED" --type ts

# Search for switch statements or if-else blocks that might need updating
echo "\nPotential switch statements or if-else blocks to update:"
rg "switch.*NotificationType|if.*NotificationType" --type ts

Length of output: 8715

apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (16)

Line range hint 1-80: LGTM: Import statements are well-organized

The import statements are logically grouped and include all necessary modules and types for the functionality of this service.


Line range hint 81-124: LGTM: Class declaration and constructor follow best practices

The InternalNotificationService class is properly decorated with @Injectable() and extends BaseNotificationService. The constructor uses dependency injection for all required services, following best practices for Angular/NestJS applications.


Line range hint 126-149: LGTM: Comprehensive logic for determining prison notifications

The shouldSendNotificationToPrison method effectively handles various case types and conditions to determine when a notification should be sent to the prison. The logic is clear and covers different scenarios appropriately.


Line range hint 151-163: LGTM: Utility methods for retrieving court contact information

The getCourtMobileNumbers, getCourtAssistantMobileNumbers, and getCourtEmail methods are concise and effectively retrieve the necessary contact information for courts. They properly handle cases where the courtId might be undefined.


Line range hint 248-262: LGTM: Heads-up SMS notification to court is well-implemented

The sendHeadsUpSmsNotificationToCourt method effectively creates and sends a heads-up SMS notification to the court. It utilizes the formatCourtHeadsUpSmsNotification function for message creation and the sendSms method for sending, demonstrating good separation of concerns.


Line range hint 264-274: LGTM: Heads-up notifications method is concise and effective

The sendHeadsUpNotifications method efficiently handles the process of sending heads-up notifications for a case. It appropriately calls the sendHeadsUpSmsNotificationToCourt method and records the notification using recordNotification, ensuring proper logging of the sent notification.


Line range hint 277-290: LGTM: "Ready for court" SMS notification to court is well-implemented

The sendReadyForCourtSmsNotificationToCourt method effectively creates and sends a "ready for court" SMS notification to the court. It utilizes the formatCourtReadyForCourtSmsNotification function for message creation and the sendSms method for sending, maintaining consistency with other similar methods in the class.


Line range hint 292-303: LGTM: "Resubmitted to court" SMS notification method is consistent and effective

The sendResubmittedToCourtSmsNotificationToCourt method maintains consistency with other SMS notification methods in the class. It appropriately uses the formatCourtResubmittedToCourtSmsNotification function for message creation and the sendSms method for sending the notification to the court.


Line range hint 305-329: LGTM: "Resubmitted to court" email notification to defender is well-implemented

The sendResubmittedToCourtEmailNotificationToDefender method effectively creates and sends a "resubmitted to court" email notification to the defender. It properly handles cases where the defender might not have a national ID and uses the formatDefenderResubmittedToCourtEmailNotification function for message creation. The method maintains consistency with other email notification methods in the class.


Line range hint 365-385: LGTM: "Ready for court" email notification to court is well-implemented

The sendReadyForCourtEmailNotificationToCourt method effectively creates and sends a "ready for court" email notification to the court. It appropriately uses the formatCourtIndictmentReadyForCourtEmailNotification function for message creation and maintains consistency with other email notification methods in the class.


Line range hint 387-410: LGTM: "Ready for court" email notification to defender is well-implemented

The sendReadyForCourtEmailNotificationToDefender method effectively creates and sends a "ready for court" email notification to the defender. It properly handles cases where the defender might not have a national ID and uses the formatDefenderReadyForCourtEmailNotification function for message creation. The method maintains consistency with other email notification methods in the class.


Line range hint 505-520: LGTM: "Received by court" SMS notification to prosecutor is well-implemented

The sendReceivedByCourtSmsNotificationToProsecutor method effectively creates and sends a "received by court" SMS notification to the prosecutor. It appropriately uses the formatProsecutorReceivedByCourtSmsNotification function for message creation and maintains consistency with other SMS notification methods in the class.


Line range hint 522-535: LGTM: "Received by court" notifications method is concise and effective

The sendReceivedByCourtNotifications method efficiently handles the process of sending "received by court" notifications. It appropriately calls the sendReceivedByCourtSmsNotificationToProsecutor method and records the notification using recordNotification, ensuring proper logging of the sent notification.


Line range hint 570-614: LGTM: Court date email notification to prosecutor is well-implemented

The sendCourtDateEmailNotificationToProsecutor method effectively creates and sends a court date email notification to the prosecutor. It handles different session arrangements correctly, creates a calendar invite attachment when applicable, and uploads the email to the court's system. The method demonstrates good separation of concerns and error handling.


Line range hint 659-707: LGTM: Court date calendar invite email notification to defender is well-implemented

The sendCourtDateCalendarInviteEmailNotificationToDefender method effectively creates and sends a court date calendar invite email notification to the defender. It handles various case details, creates a calendar invite attachment, and uploads the email to the court's system. The method demonstrates good separation of concerns and error handling.


Line range hint 750-785: LGTM: Postponed court date email notification for indictment cases is well-implemented

The sendPostponedCourtDateEmailNotificationForIndictmentCase method effectively creates and sends a postponed court date email notification for indictment cases. It handles various recipients, properly manages cases where the recipient might not have access to RVG, and uploads the email to the court's system. The method demonstrates good error handling and separation of concerns.

@gudjong gudjong added automerge Merge this PR as soon as all checks pass and removed automerge Merge this PR as soon as all checks pass labels Oct 22, 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 (1)
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (1)

82-116: Consider adding negative test cases.

The current test cases thoroughly verify the happy path for prosecutor-initiated notifications. However, consider adding test cases for:

  • Missing recipient information
  • Failed email delivery scenarios
  • Invalid case data
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d5d7861 and e99213f.

📒 Files selected for processing (3)
  • apps/judicial-system/backend/src/app/messages/notifications.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (10 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/judicial-system/backend/src/app/messages/notifications.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.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/test/internalNotificationController/sendCaseFilesUpdatedNotifications.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."
📓 Learnings (2)
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.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-10-22T15:25:50.536Z
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/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.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-10-22T15:25:50.536Z
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.
🪛 Biome
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts

[error] 75-76: 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] 76-77: 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 (7)
apps/judicial-system/backend/src/app/modules/notification/test/internalNotificationController/sendCaseFilesUpdatedNotifications.spec.ts (2)

1-23: LGTM! Well-structured imports and interfaces.

The imports are organized logically, and the interfaces are well-defined.


118-151: LGTM! Well-structured defender notification tests.

The test cases correctly verify that:

  • Notifications are sent to all relevant parties
  • Role-specific URLs are used in the notifications
  • The prosecutor is notified when a defender adds files (as confirmed by retrieved learning)
apps/judicial-system/backend/src/app/messages/notifications.ts (1)

862-874: LGTM! The new message definition follows best practices.

The caseFilesUpdated message object is well-structured with:

  • Proper internationalization support
  • Clear descriptions for translators
  • Consistent variable usage
  • Conditional text handling for different user access levels
apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts (4)

77-81: LGTM: Imports are well-structured

The new imports for handling civil claimants and defendants are properly organized and necessary for the new case files notification functionality.


1767-1786: LGTM: Well-structured notification method

The method properly handles email formatting and recipient details, with appropriate handling of RVG access links.


2682-2683: LGTM: Proper integration with notification system

The new notification type is correctly integrated into the existing switch statement, maintaining consistency with other notification types.


1788-1873: Consider adding error handling for missing court case number

The method uses theCase.courtCaseNumber directly in notifications without checking if it's defined. While it's likely always set at this point, defensive programming would be beneficial.

Apply this diff to add a safety check:

  private async sendCaseFilesUpdatedNotifications(
    theCase: Case,
    user: User,
  ): Promise<DeliverResponse> {
+   if (!theCase.courtCaseNumber) {
+     this.logger.warn('Missing court case number for notification', { caseId: theCase.id })
+     return { delivered: false }
+   }
    const promises = [
      this.sendCaseFilesUpdatedNotification(

Verify notification access control

The implementation includes specific logic for prosecution and defence users. Let's verify this aligns with the system's access control requirements.

✅ Verification successful

Based on the search results, I can now provide a final response since I have enough context about the access control implementation for notifications in the codebase.

Access control for notifications is properly implemented

The code correctly implements role-based access control for notifications:

  • For prosecution users (isProsecutionUser): Sends notifications to defendants and their defenders
  • For defence users (isDefenceUser): Sends notifications to prosecutors
  • For both roles: Sends notifications to judges and spokespersons

The implementation aligns with the system's access control requirements as evidenced by consistent role checks across the codebase, particularly in:

  • Frontend components for displaying notifications
  • Backend services for sending notifications
  • File access guards
  • Case access filters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify access control implementation for notifications
# Test: Search for other notification types with similar user role checks
rg -A 5 "isProsecutionUser\(user\)" --type ts
rg -A 5 "isDefenceUser\(user\)" --type ts

Length of output: 65658

@kodiakhq kodiakhq bot merged commit 487d14e into main Oct 23, 2024
37 checks passed
@kodiakhq kodiakhq bot deleted the j-s/case-files-added-notification branch October 23, 2024 07:33
@coderabbitai coderabbitai bot mentioned this pull request Oct 23, 2024
6 tasks
svanaeinars pushed a commit that referenced this pull request Oct 23, 2024
* Refactors file upload to return more granular upload result

* Sends case files updated notification from client when files are added

* Sends notifications when case files are added to an indictment case

* Reverts debugging

* Fixes naming

* Fixes naming

* Fixes notification type when storing notification result

* Fixes court name and unit tests

---------

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
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants