-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(j-s): Defender Updated Notification #16801
Conversation
…umber assignment as these updates are sent to the robot
…er-changed-notification
WalkthroughThe pull request introduces significant modifications across various components of the judicial system application. Key changes include the refactoring of case management logic in the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
Datadog ReportAll test runs ✅ 9 Total Test Services: 0 Failed, 9 Passed Test Services
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 15
🧹 Outside diff range and nitpick comments (26)
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts (2)
5-6
: Consider using a more specific type instead ofany
The
any
type bypasses TypeScript's type checking. Consider using a more specific type likeType<DefendantExistsGuard>[]
or create a custom type for guards.- // eslint-disable-next-line @typescript-eslint/no-explicit-any - let guards: any[] + let guards: Type<DefendantExistsGuard>[]
9-13
: Consider extracting the metadata key as a constantThe hardcoded string
'__guards__'
could be extracted into a constant or imported from a shared configuration to improve maintainability.+ const GUARDS_METADATA_KEY = '__guards__' + guards = Reflect.getMetadata( - '__guards__', + GUARDS_METADATA_KEY, InternalDefendantController.prototype.deliverDefendantToCourt, )apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (1)
9-9
: Replaceany[]
with a more specific type.Instead of using
any[]
with an eslint disable comment, consider using a more specific type for better type safety.- // eslint-disable-next-line @typescript-eslint/no-explicit-any - let guards: any[] + let guards: Array<new () => CaseTypeGuard | DefendantNationalIdExistsGuard>apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (3)
33-33
: Handle potential undefined defendants arrayThe optional chaining on
theCase.defendants?.find
might hide a potential issue where defendants array is undefined.Add explicit check:
+ if (!theCase.defendants) { + throw new BadRequestException('Case has no defendants') + } - const defendant = theCase.defendants?.find( + const defendant = theCase.defendants.find(
40-42
: Normalize error message formatConsider normalizing the error message format and including more context for debugging.
Suggested improvement:
throw new NotFoundException( - `Defendant with given national id of case ${theCase.id} does not exist`, + `Defendant not found: nationalId=${normalizedAndFormatedNationalId}, caseId=${theCase.id}`, )
30-31
: Fix typo in variable nameThe variable name contains a typo: "Formated" should be "Formatted".
Apply this fix:
- const normalizedAndFormatedNationalId = + const normalizedAndFormattedNationalId =apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (1)
8-8
: Fix typo in message descriptionsThe word "choise" should be "choice" in both message descriptions.
- 'Subject of the notification sent when the defendant defender choise in an indictment has changed', + 'Subject of the notification sent when the defendant defender choice in an indictment has changed',- 'Body of the notification sent when the defendant defender choise in an indictment has changed', + 'Body of the notification sent when the defendant defender choice in an indictment has changed',Also applies to: 15-15
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (2)
16-28
: Enhance test data setup for better clarity and type safety.The test data setup could be improved in several ways:
- The
update
object is cast toInternalUpdateDefendantDto
without proper type definition- Test values like 'somevalue' are not descriptive of real use cases
Consider this improvement:
- const update = { somefield: 'somevalue' } as InternalUpdateDefendantDto + const update: InternalUpdateDefendantDto = { + // Add realistic test data based on DTO fields + name: 'John Doe', + email: '[email protected]', + // ... other required fields + }
1-77
: Consider restructuring tests to align with notification requirements.Given that this PR implements defender selection notifications, the test suite should explicitly verify:
- Court notification triggers when defender is selected
- Proper state transitions during the defender selection process
- Integration with the notification service
This will ensure the tests fully validate the PR's primary objective of court notifications for defender selection.
🧰 Tools
🪛 Biome
[error] 53-53: The assignment should not be in an expression.
The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.(lint/suspicious/noAssignInExpressions)
[error] 54-54: The assignment should not be in an expression.
The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.(lint/suspicious/noAssignInExpressions)
libs/judicial-system/types/src/lib/notification.ts (1)
53-57
: LGTM! Consider adding JSDoc commentsThe new notification types are well-integrated into the main
NotificationType
enum, maintaining consistency with the codebase's pattern of referencing specific enum types.Consider adding JSDoc comments to document the purpose and usage of each notification type, especially the new ones. For example:
+ /** Notification sent when a defendant selects their defender through island.is */ DEFENDANT_SELECTED_DEFENDER = DefendantNotificationType.DEFENDANT_SELECTED_DEFENDER, + /** Notification sent when a defender is assigned to a defendant */ DEFENDER_ASSIGNED = DefendantNotificationType.DEFENDER_ASSIGNED,apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (1)
72-74
: Update API documentation to reflect the changesThe
@ApiOkResponse
description mentions "by case and national id" which is no longer accurate since we're using the@CurrentDefendant()
decorator.@ApiOkResponse({ type: Defendant, - description: 'Updates defendant information by case and national id', + description: 'Updates defendant information for the current case', })apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (2)
11-16
: Consider renaming the interface for better clarity.The interface
Then
could be more descriptive. Consider renaming it toGuardTestResult
orGuardActivationResult
to better reflect its purpose in testing the guard's activation outcomes.-interface Then { +interface GuardTestResult { result: boolean error: Error }
39-66
: Consider enhancing type safety and test data organization.While the test is well-structured, consider these improvements:
- Add type definitions for the test data objects
- Extract test data setup to a separate helper/fixture
interface TestDefendant { id: string; nationalId: string; caseId: string; } interface TestCase { id: string; defendants: TestDefendant[]; } // In a separate test-helpers.ts file export const createTestDefendant = (overrides?: Partial<TestDefendant>): TestDefendant => ({ id: uuid(), nationalId: uuid(), caseId: uuid(), ...overrides });apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (1)
53-53
: Consider exposing DefendantService in the return object.While DefendantService is correctly added as a provider, it's not included in the module's return object. This might limit test cases that need to access and verify interactions with the mocked DefendantService.
Consider adding it to the return object:
return { userService, pdfService, policeService, fileService, subpoenaModel, subpoenaService, subpoenaController, internalSubpoenaController, limitedAccessSubpoenaController, + defendantService: subpoenaModule.get<DefendantService>(DefendantService), }
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (1)
64-64
: Consider enhancing error handling granularity.The service has good error handling, but we could improve error reporting by distinguishing between different types of failures (email service errors, formatting errors, etc.) to aid in debugging and monitoring.
Consider wrapping the email sending logic in a try-catch block with specific error types:
try { return await this.sendEmail(/*...*/); } catch (error) { if (error instanceof EmailServiceError) { this.logger.error('Email service failed', { error, recipient }); } else if (error instanceof FormattingError) { this.logger.error('Message formatting failed', { error, template }); } throw error; }apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)
Line range hint
63-123
: Documentation needed for the new defender notification flowThe PR objectives mention that documentation updates are pending. Since this endpoint now supports defender selection notifications, it should be documented in the API documentation.
Consider adding a specific example in the
@ApiCreatedResponse
description to clarify the defender selection notification case:@ApiCreatedResponse({ type: DeliverResponse, description: - 'Sends defendant related notifications for an existing defendant', + 'Sends defendant related notifications for an existing defendant, including defender selection notifications to the court', })apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts (2)
55-74
: Add validation for empty recipients arrayWhile the implementation handles multiple recipients well, consider adding validation for an empty recipients array to prevent unnecessary processing.
private async sendEmails( theCase: Case, notificationType: DefendantNotificationType, subject: string, body: string, to: { name?: string; email?: string }[], ) { + if (!to?.length) { + return { delivered: true, recipients: [] }; + } const promises: Promise<Recipient>[] = []
Line range hint
1-1
: Add documentation for the new notification typeAs mentioned in the PR objectives, documentation updates are pending. Please add JSDoc comments describing the new
DEFENDANT_SELECTED_DEFENDER
notification type and its usage.apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (1)
25-25
: LGTM! Consider enhancing test maintainability.The addition of the required
type
parameter improves type safety and makes the test cases more explicit. This aligns well with the notification system requirements for different case types.Consider creating an enum or constant for default test values to reduce duplication and improve maintainability:
const DEFAULT_TEST_CASES = { CUSTODY: { type: CaseType.CUSTODY, courtCaseNumber: uuid() }, INDICTMENT: { type: CaseType.INDICTMENT, courtCaseNumber: uuid() }, // ... other common test cases } as const;Also applies to: 56-56, 66-66
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1)
Line range hint
1-450
: Comprehensive test coverage with robust structureThe test suite effectively covers:
- Successful case archiving with proper data encryption
- Clearing of sensitive information
- Transaction handling
- Error cases (no case found)
The test structure follows best practices with clear setup, comprehensive mocking, and explicit expectations.
Consider adding test cases for:
- Encryption failures
- Transaction rollback scenarios
- Partial data clearing failures
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)
Line range hint
419-498
: Consider implementing batch processing for better performance.The archiving process performs multiple database operations in sequence within a transaction. For large datasets with many defendants, files, and indictment counts, this could lead to performance issues.
Consider implementing batch processing for the updates:
+ // Batch process defendants + const defendantUpdates = theCase.defendants?.map(defendant => { + const [clearedProperties, archive] = collectEncryptionProperties( + defendantEncryptionProperties, + defendant + ); + defendantsArchive.push(archive); + return { id: defendant.id, properties: clearedProperties }; + }) ?? []; + + await this.defendantService.batchUpdateDefendants( + theCase.id, + defendantUpdates, + transaction + );apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)
116-116
: Simplify variable initializationThe variable
message
is initialized toundefined
by default. Consider removing the redundant assignment.Apply this diff to simplify the variable declaration:
-let message: Message | undefined = undefined +let message: Message | undefined
119-136
: Refactor message creation to reduce code duplicationThe
message
object creation for both success and failure cases is similar. Refactoring can eliminate duplication and enhance readability.Consider applying this refactor:
if (serviceStatus && serviceStatus !== subpoena.serviceStatus) { if (isSuccessfulServiceStatus(serviceStatus) || isFailedServiceStatus(serviceStatus)) { const notificationType = isSuccessfulServiceStatus(serviceStatus) ? SubpoenaNotificationType.SERVICE_SUCCESSFUL : SubpoenaNotificationType.SERVICE_FAILED message = { type: MessageType.SUBPOENA_NOTIFICATION, caseId: subpoena.caseId, elementId: [subpoena.defendantId, subpoena.id], body: { type: notificationType, }, } } }
198-198
: Maintain consistent language in code commentsThe comment is in Icelandic. For consistency and clarity, consider translating code comments to English.
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (2)
132-158
: Simplify nested 'if' statements for better readabilityConsider combining the nested conditions into a single 'if' statement to enhance readability.
Proposed refactor:
- if (updatedDefendant.isDefenderChoiceConfirmed) { - if ( - updatedDefendant.defenderChoice === DefenderChoice.CHOOSE || - updatedDefendant.defenderChoice === DefenderChoice.DELEGATE - ) { + if ( + updatedDefendant.isDefenderChoiceConfirmed && + (updatedDefendant.defenderChoice === DefenderChoice.CHOOSE || + updatedDefendant.defenderChoice === DefenderChoice.DELEGATE) + ) { // TODO: Update defender with robot if needed
257-268
: Ensure consistent parameter usage in 'update' methodIn the
update
method,updateIndictmentCase
is called without theuser
parameter, whileupdateRequestCase
requires it. Consider passinguser
toupdateIndictmentCase
for consistency, or confirm that it is not needed.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (26)
apps/judicial-system/backend/src/app/modules/case/case.controller.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/case/case.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts
(3 hunks)apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts
(2 hunks)apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts
(9 hunks)apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts
(5 hunks)apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.strings.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts
(2 hunks)apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
(4 hunks)apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts
(3 hunks)libs/judicial-system/types/src/lib/notification.ts
(2 hunks)
💤 Files with no reviewable changes (6)
- apps/judicial-system/backend/src/app/modules/case/case.controller.ts
- apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
- apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts
- apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.strings.ts
- apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts
- apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts
✅ Files skipped from review due to trivial changes (1)
- apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts
🧰 Additional context used
📓 Path-based instructions (19)
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
libs/judicial-system/types/src/lib/notification.ts (1)
Pattern libs/**/*
: "Confirm that the code adheres to the following:
- Reusability of components and hooks across different NextJS apps.
- TypeScript usage for defining props and exporting types.
- Effective tree-shaking and bundling practices."
📓 Learnings (6)
apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts:175-185
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In the Jest tests for the `LimitedAccessViewCaseFileGuard` in `apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts`, code duplication in the `beforeEach` blocks is acceptable and should remain unchanged.
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (2)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts:175-185
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In the Jest tests for the `LimitedAccessViewCaseFileGuard` in `apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts`, code duplication in the `beforeEach` blocks is acceptable and should remain unchanged.
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfGuards.spec.ts:24-25
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In certain scenarios within the judicial-system backend, the `RolesGuard` may intentionally follow the `CaseExistsGuard` when specific roles rules require the guard order to be reversed, as seen in tests like `getIndictmentPdfGuards.spec.ts`.
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16452
File: apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts:1845-1854
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In the `sendCaseFilesUpdatedNotifications` method within `internalNotification.service.ts`, when the `user` is a defence user, it is intended to send notifications to the prosecutor.
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts (3)
Learnt from: oddsson
PR: island-is/island.is#16329
File: apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts:143-177
Timestamp: 2024-11-10T17:05:28.408Z
Learning: In `apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts`, the method `sendEmails` currently uses `Promise.all` for multiple recipients, and changing it to `Promise.allSettled` is considered for a future iteration.
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-10T17:05:23.796Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
Learnt from: gudjong
PR: island-is/island.is#16452
File: apps/judicial-system/backend/src/app/modules/notification/internalNotification.service.ts:1845-1854
Timestamp: 2024-11-10T17:05:23.796Z
Learning: In the `sendCaseFilesUpdatedNotifications` method within `internalNotification.service.ts`, when the `user` is a defence user, it is intended to send notifications to the prosecutor.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-10T17:05:23.796Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
libs/judicial-system/types/src/lib/notification.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16556
File: apps/judicial-system/backend/src/app/modules/notification/guards/rolesRules.ts:13-16
Timestamp: 2024-11-10T09:23:37.036Z
Learning: In the `CaseNotificationType` enum in `libs/judicial-system/types/src/lib/notification.ts`, `APPEAL_CASE_FILES_UPDATED` and `CASE_FILES_UPDATED` are distinct notification types that need to remain separate, as they serve different purposes in the notification system.
🪛 Biome
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts
[error] 53-53: The assignment should not be in an expression.
The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.
(lint/suspicious/noAssignInExpressions)
[error] 54-54: The assignment should not be in an expression.
The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.
(lint/suspicious/noAssignInExpressions)
🔇 Additional comments (32)
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts (2)
1-26
: Verify notification integration with defender updates.
The PR's objective is to implement notifications when a defender is selected, but this test file only covers the guards for updating defendant information. Please ensure that:
- The
updateDefendant
method triggers appropriate notifications - There are separate test files covering the notification functionality
#!/bin/bash
# Description: Check for notification-related tests and implementations
# Search for notification-related test files
echo "Searching for notification test files..."
fd -e spec.ts -e test.ts | rg -l "Notification|notification"
# Search for notification service usage in the defendant controller
echo "Checking notification service integration..."
ast-grep --pattern 'class InternalDefendantController {
$$$
updateDefendant($$$) {
$$$
notificationService.$$$
$$$
}
$$$
}'
18-25
: 🛠️ Refactor suggestion
Verify guard order and enhance test coverage.
While the test verifies the presence and configuration of both guards, consider adding these improvements:
- The test should verify that the guard order is correct for this specific endpoint
- Add negative test cases to verify guard behavior with invalid inputs
Here's a script to verify if the guard order is consistent with similar endpoints:
Consider adding these test cases:
it('should reject when case type is not in investigationCases', () => {
const guard = new guards[0]();
// Test with invalid case type
});
it('should reject when defendant national ID does not exist', () => {
const guard = new guards[1]();
// Test with non-existent national ID
});
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts (1)
7-7
: LGTM: Import aligns with defender notification feature
The addition of DefendantModule import is consistent with the PR's objective of implementing defender selection notifications.
apps/judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts (1)
1-14
: LGTM! Clean implementation following NestJS patterns
The imports and class declaration follow NestJS best practices, with proper use of decorators and interface implementation.
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.strings.ts (2)
4-16
: LGTM! Message structure and format are well-defined
The new message definitions:
- Follow the established pattern for notification messages
- Use consistent HTML formatting
- Properly handle dynamic content with placeholders
- Maintain language consistency with the system
4-16
: Verify uniqueness of message IDs
The message IDs look correct, but let's verify they are unique across the codebase to prevent any potential conflicts.
✅ Verification successful
Message IDs are unique across the codebase
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for duplicate message IDs across the codebase
# Search for the specific message IDs
echo "Checking defendantSelectedDefenderSubject ID..."
rg "judicial\.system\.backend:defendant_notifications\.defendant_selected_defender_subject" -A 2
echo "Checking defendantSelectedDefenderBody ID..."
rg "judicial\.system\.backend:defendant_notifications\.defendant_selected_defender_body" -A 2
Length of output: 1378
apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendant.spec.ts (1)
1-15
: LGTM! Well-structured TypeScript interfaces and imports.
The type definitions and imports are organized logically and follow TypeScript best practices.
libs/judicial-system/types/src/lib/notification.ts (3)
23-26
: LGTM! Well-structured enum for defendant notifications
The new DefendantNotificationType
enum clearly separates defender-related notifications, improving code organization and type safety. This aligns well with the PR objective of implementing notifications for defender selection.
28-31
: Good separation of concerns
Moving subpoena-related notifications to a dedicated enum improves code organization and maintainability. The success/failure states are clearly defined.
Let's verify the migration of these notification types:
#!/bin/bash
# Check for any old references to these notification types
# that might have been missed during refactoring
rg "SERVICE_SUCCESSFUL|SERVICE_FAILED" --type ts -B 2 -A 2
Line range hint 8-8
: Remove or schedule removal of deprecated enum value
The comment indicates ADVOCATE_ASSIGNED
will be removed, but it's still present in the enum. This creates technical debt and could lead to confusion.
Let's verify if this enum value is still in use:
Consider:
- Remove it now if it's unused
- Create a deprecation timeline if it's still in use
- Document the migration path to the new
DefendantNotificationType.DEFENDER_ASSIGNED
✅ Verification successful
ADVOCATE_ASSIGNED is unused and can be safely removed
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for any remaining usage of ADVOCATE_ASSIGNED
rg "ADVOCATE_ASSIGNED" --type ts
Length of output: 4317
apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts (1)
20-20
: LGTM! Clean import additions
The new imports enhance type safety and validation by introducing the investigation cases type and the national ID guard.
Also applies to: 22-22, 27-27
apps/judicial-system/backend/src/app/modules/defendant/guards/test/defendantNationalIdExistsGuard.spec.ts (4)
18-38
: Well-structured test setup with good error handling!
The test suite setup follows best practices with:
- Clean mock implementation
- Reusable GivenWhenThen pattern
- Proper error handling
68-92
: LGTM! Comprehensive error case testing.
The test properly validates both the exception type and message content for the non-existent defendant scenario.
94-107
: LGTM! Clear and focused edge case testing.
The test appropriately validates the guard's behavior when the case is missing.
109-124
: LGTM! Verify guard usage in controllers.
The test case is well-implemented. To ensure complete coverage, let's verify where this guard is being used.
✅ Verification successful
Guard usage in controllers verified.
apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts
usesDefendantNationalIdExistsGuard
with@UseGuards
.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for usage of DefendantNationalIdExistsGuard in controllers
ast-grep --pattern 'class $_ {
$$$
@UseGuards($$$DefendantNationalIdExistsGuard$$$)
$$$
}'
Length of output: 98
Script:
#!/bin/bash
# Search for any usage of DefendantNationalIdExistsGuard across the codebase
rg 'DefendantNationalIdExistsGuard' --context 2
Length of output: 4975
apps/judicial-system/backend/src/app/modules/subpoena/test/createTestingSubpoenaModule.ts (1)
16-16
: LGTM! Import and mock setup looks good.
The DefendantService import and mock setup follow the established patterns in the codebase.
Also applies to: 33-33
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts (1)
122-122
: LGTM! Verify notification flow in DefendantNotificationService
The addition of the defendant
parameter aligns with the PR objective of implementing defender selection notifications. The change is properly guarded and logged.
Let's verify the notification flow in the service:
✅ Verification successful
Verified! DefendantNotificationService handles the defendant parameter correctly and sends notifications to the appropriate recipients.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that DefendantNotificationService properly handles the defendant parameter
# and sends notifications to the correct recipients
# Check the service implementation
ast-grep --pattern 'sendDefendantNotification(type: $_, theCase: $_, defendant: $_) {
$$$
}'
# Look for defender-related notification types
rg -A 5 "DEFENDER" apps/judicial-system/backend/src/app/modules/notification
Length of output: 22081
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts (2)
13-16
: LGTM! Clean import structure
The imports are well-organized and follow the pattern of centralizing route constants.
Line range hint 188-207
: LGTM! Well-structured notification handling
The notification handling is well-organized with proper error handling and logging. The switch statement is complete and the parameter order is consistent throughout the service.
apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts (1)
Line range hint 86-217
: LGTM! Comprehensive test coverage for different case types.
The test suite effectively covers various update scenarios with appropriate case types:
- Basic updates with CUSTODY cases
- Court delivery updates with INDICTMENT cases
- National ID changes with TELECOMMUNICATIONS cases
- Defender choice confirmation with appropriate notifications
The test structure is clean and follows best practices.
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/archive.spec.ts (1)
290-296
: Method name change improves clarity and consistency
The renaming from updateForArcive
to updateDatabaseDefendant
better reflects the method's purpose and follows naming conventions. The test correctly verifies that sensitive defendant data is cleared during archiving.
Let's verify the consistency of this method name change across the codebase:
✅ Verification successful
Method name change verified and consistent across the codebase
The method updateForArcive
has been successfully renamed to updateDatabaseDefendant
. No remaining instances of the old method name were found, and the new method is correctly implemented in the DefendantService
class.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for any remaining instances of the old method name and verify the new method name implementation
# Check for any remaining instances of old method name
rg "updateForArcive"
# Verify the implementation of the new method name
ast-grep --pattern 'class DefendantService {
$$$
updateDatabaseDefendant($$$) {
$$$
}
$$$
}'
Length of output: 42633
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (2)
421-421
: Method name updated for clarity and correctness.
The rename from updateForArcive
to updateDatabaseDefendant
improves code clarity by using a more descriptive and correctly spelled method name.
Line range hint 421-427
: Verify error handling in the transaction.
The defendant update is part of a critical archiving process that handles sensitive data. Ensure that any errors during the update are properly caught and rolled back within the transaction.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)
33-33
: Import of DefendantService
is appropriate
The addition of DefendantService
import aligns with the updated logic and promotes better modularity.
74-74
: Proper injection of DefendantService
into the constructor
Injecting DefendantService
into the constructor allows for dependency injection, enhancing testability and maintainability.
218-218
: Ensure proper error handling for asynchronous calls
Since addMessagesForSubpoenaUpdateToQueue
is an asynchronous function and is not awaited, any errors it throws may be unhandled. Consider adding error handling to capture potential exceptions.
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (5)
93-130
: Method 'sendRequestCaseUpdateDefendantMessages' logic is correct
The method appropriately handles message queuing based on defendant updates.
196-201
: Optional 'transaction' parameter is handled correctly
The optional transaction
parameter in updateDatabaseDefendant
should not cause issues with Sequelize's update method.
215-235
: Method 'updateRequestCase' functions as intended
The method updates the defendant and sends necessary messages for request cases.
237-249
: Method 'updateIndictmentCase' functions as intended
The method updates the defendant and handles indictment case-specific messaging appropriately.
270-307
: Method 'updateRestricted' logic is sound
The method correctly updates restricted defendant fields and sends notifications when necessary.
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)
751-753
: Verify omission of prosecutor and defendant messages in notifications
In the updated addMessagesForIndictmentCourtCaseConnectionToQueue
method, the messages for delivering prosecutor and defendant information to the court (getDeliverProsecutorToCourtMessages
and getDeliverDefendantToCourtMessages
) are no longer included in the messages
array. Please confirm that this change is intentional and that necessary notifications to the prosecutor and defendant are being handled elsewhere if required.
Run the following script to verify where these message functions are being invoked:
✅ Verification successful
Omission Verified
Notifications to the prosecutor and defendant are managed through separate methods and are handled appropriately elsewhere in the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Search for calls to `getDeliverProsecutorToCourtMessages` and `getDeliverDefendantToCourtMessages` in the codebase.
# Search for invocations in the codebase
rg 'this\.getDeliver(Prosecutor|Defendant)ToCourtMessages' -A 5
Length of output: 1842
Script:
#!/bin/bash
# Description: Search for construction or manipulation of the `messages` array in the codebase to verify handling of prosecutor and defendant notifications.
rg 'const messages[:=].*' -A 10
Length of output: 10695
...app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts
Show resolved
Hide resolved
...app/modules/defendant/test/internalDefendantController/deliverDefendantToCourtGuards.spec.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.module.ts
Show resolved
Hide resolved
.../judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts
Show resolved
Hide resolved
.../judicial-system/backend/src/app/modules/defendant/guards/defendantNationalIdExists.guard.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/defendant/test/defendantController/update.spec.ts
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (2)
146-146
: Address the TODO comment about robot defender updates.The comment indicates missing functionality for robot defender updates.
Would you like me to help create a GitHub issue to track this TODO item?
270-307
: Consider enhancing the method documentation.While the implementation is solid, consider structuring the comments as JSDoc for better IDE integration and documentation generation.
Example improvement:
- // The reason we have a separate dto for this is because requests that end here - // are initiated by outside API's which should not be able to edit other fields - // Defendant updated originating from the judicial system should use the UpdateDefendantDto - // and go through the update method above using the defendantId. + /** + * Updates defendant data from external APIs with restricted access. + * + * @remarks + * - Uses a separate DTO to restrict field access for external APIs + * - Internal updates should use UpdateDefendantDto through the update method + * - Judge confirmation required for all changes + */
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (3)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts
(3 hunks)apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts
(2 hunks)apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/judicial-system/backend/src/app/modules/defendant/internalDefendant.controller.ts
- apps/judicial-system/backend/src/app/modules/defendant/test/internalDefendantController/updateDefendantGuards.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (4)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (4)
93-130
: LGTM! Well-structured message handling refactor.
The refactoring improves code maintainability by:
- Using early return pattern
- Collecting messages before sending them in a single operation
- Clear separation of concerns
132-160
: LGTM! Well-structured notification handling for indictment cases.
The implementation correctly:
- Handles defender choice confirmation
- Sends appropriate notifications
- Uses early returns for better flow control
Line range hint 196-235
: LGTM! Clear separation of database operations.
The refactoring improves code organization by:
- Using a more descriptive method name
- Making transaction parameter optional
- Separating database operations from message handling
237-268
: LGTM! Well-structured case type-specific handling.
The implementation provides:
- Clear separation between indictment and request cases
- Type-safe routing using
isIndictmentCase
- Proper delegation to specific handlers
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/notification/defendantNotification.service.ts
Show resolved
Hide resolved
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Really nice changes and cleanup of code 🎉
This PR currently has a merge conflict. Please resolve this and then re-add the |
…er-changed-notification
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)
116-144
: Consider extracting common message structureThe message handling refactoring is good, but there's room for improvement:
Consider extracting the common message structure to reduce duplication:
private async addMessagesForSubpoenaUpdateToQueue( subpoena: Subpoena, serviceStatus?: ServiceStatus, ): Promise<void> { let message: Message | undefined = undefined + + const createNotificationMessage = (type: SubpoenaNotificationType): Message => ({ + type: MessageType.SUBPOENA_NOTIFICATION, + caseId: subpoena.caseId, + elementId: [subpoena.defendantId, subpoena.id], + body: { type } + }) if (serviceStatus && serviceStatus !== subpoena.serviceStatus) { if (isSuccessfulServiceStatus(serviceStatus)) { - message = { - type: MessageType.SUBPOENA_NOTIFICATION, - caseId: subpoena.caseId, - elementId: [subpoena.defendantId, subpoena.id], - body: { - type: SubpoenaNotificationType.SERVICE_SUCCESSFUL, - }, - } + message = createNotificationMessage(SubpoenaNotificationType.SERVICE_SUCCESSFUL) } else if (isFailedServiceStatus(serviceStatus)) { - message = { - type: MessageType.SUBPOENA_NOTIFICATION, - caseId: subpoena.caseId, - elementId: [subpoena.defendantId, subpoena.id], - body: { - type: SubpoenaNotificationType.SERVICE_FAILED, - }, - } + message = createNotificationMessage(SubpoenaNotificationType.SERVICE_FAILED) } }
178-187
: Simplify complex conditional checkThe conditional check for defender-related updates is quite lengthy and could be simplified.
Consider extracting the condition into a helper method:
+ private hasDefenderUpdates(update: UpdateSubpoenaDto): boolean { + return !!( + update.defenderChoice || + update.defenderNationalId || + update.defenderName || + update.defenderEmail || + update.defenderPhoneNumber || + update.requestedDefenderChoice || + update.requestedDefenderNationalId || + update.requestedDefenderName + ) + } if ( subpoena.case && subpoena.defendant && - (defenderChoice || - defenderNationalId || - defenderName || - defenderEmail || - defenderPhoneNumber || - requestedDefenderChoice || - requestedDefenderNationalId || - requestedDefenderName) + this.hasDefenderUpdates(update) ) {
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (4)
apps/judicial-system/backend/src/app/modules/case/case.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
(4 hunks)
💤 Files with no reviewable changes (1)
- apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/judicial-system/backend/src/app/modules/case/case.service.ts
- apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)
33-33
: LGTM: Clean dependency injection of DefendantService
The addition of DefendantService follows the dependency injection pattern and aligns with the goal of centralizing defender-related logic.
Also applies to: 74-74
198-213
: Address TODO comment and validate defender updates
The comment "Færa message handling í defendant service" indicates incomplete work for message handling migration.
Please verify:
- Is the message handling migration to DefendantService complete?
- Should we add validation for the defender updates?
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (3)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)
198-198
: Remove or implement the TODO commentThe comment "Færa message handling í defendant service" (Move message handling to defendant service) suggests incomplete refactoring. Either implement the suggested change or remove the comment if it's no longer applicable.
178-187
: Simplify the defender fields condition checkThe current condition check is verbose and could be simplified for better readability.
Consider extracting the condition into a helper method:
-if ( - subpoena.case && - subpoena.defendant && - (defenderChoice || - defenderNationalId || - defenderName || - defenderEmail || - defenderPhoneNumber || - requestedDefenderChoice || - requestedDefenderNationalId || - requestedDefenderName) -) { +const hasDefenderUpdates = (update: UpdateSubpoenaDto): boolean => { + return Boolean( + update.defenderChoice || + update.defenderNationalId || + update.defenderName || + update.defenderEmail || + update.defenderPhoneNumber || + update.requestedDefenderChoice || + update.requestedDefenderNationalId || + update.requestedDefenderName + ) +} + +if (subpoena.case && subpoena.defendant && hasDefenderUpdates(update)) {
191-196
: Extract defender choice reset logicThe nested conditions for resetting defender choice confirmation could be simplified.
Consider extracting the logic:
-const resetDefenderChoiceConfirmed = - subpoena.defendant?.isDefenderChoiceConfirmed && - ((defenderChoice && - subpoena.defendant?.defenderChoice !== defenderChoice) || - (defenderNationalId && - subpoena.defendant?.defenderNationalId !== defenderNationalId)) +const shouldResetDefenderChoice = ( + defendant: Defendant, + updates: UpdateSubpoenaDto +): boolean => { + if (!defendant.isDefenderChoiceConfirmed) return false; + + return ( + (updates.defenderChoice && defendant.defenderChoice !== updates.defenderChoice) || + (updates.defenderNationalId && defendant.defenderNationalId !== updates.defenderNationalId) + ); +}; + +const resetDefenderChoiceConfirmed = shouldResetDefenderChoice(subpoena.defendant, update);
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (4)
apps/judicial-system/backend/src/app/modules/case/case.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
(1 hunks)apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
(0 hunks)apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
(4 hunks)
💤 Files with no reviewable changes (1)
- apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/judicial-system/backend/src/app/modules/case/case.service.ts
- apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)
74-74
: LGTM: Clean dependency injection of DefendantService
The addition of DefendantService follows the established dependency injection pattern and supports the separation of concerns for defender-related operations.
116-144
: LGTM: Improved message handling logic
The refactoring simplifies the message queue handling by:
- Using a single message instead of an array
- Removing unnecessary defender-related parameters
- Consolidating the message type handling
199-213
: LGTM: Clean delegation to DefendantService
The delegation of defender-related updates to DefendantService follows good separation of concerns and aligns with the PR objectives.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)
198-198
: Remove or address the TODO commentThe comment "Færa message handling í defendant service" suggests incomplete refactoring. Either complete the message handling move to DefendantService or remove the comment.
178-187
: Consider extracting the defender update condition to a methodThe complex conditional check for defender-related changes could be extracted into a readable method like
hasDefenderChanges()
to improve maintainability.+ private hasDefenderChanges(update: UpdateSubpoenaDto): boolean { + return !!( + update.defenderChoice || + update.defenderNationalId || + update.defenderName || + update.defenderEmail || + update.defenderPhoneNumber || + update.requestedDefenderChoice || + update.requestedDefenderNationalId || + update.requestedDefenderName + ) + } if ( subpoena.case && subpoena.defendant && - (defenderChoice || - defenderNationalId || - defenderName || - defenderEmail || - defenderPhoneNumber || - requestedDefenderChoice || - requestedDefenderNationalId || - requestedDefenderName) + this.hasDefenderChanges(update) ) {
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Pattern apps/**/*
: "Confirm that the code adheres to the following:
- NextJS best practices, including file structure, API routes, and static generation methods.
- Efficient state management and server-side rendering techniques.
- Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)
33-33
: LGTM: Proper dependency injection of DefendantService
The addition of DefendantService aligns with the PR objectives of centralizing defender-related operations.
Also applies to: 74-74
116-144
: Add error handling for message queue operations
The message queue operation should include error handling to prevent silent failures.
* Adss a defendant national id * Removes unused imports * Stops updating defendants via API in indictment cases on court case number assignment as these updates are sent to the robot * Adds a guard to get a defender by national id * Rewrites update defendant by national id * Refactors defendant update messages * Restricts defendant restricted updates to indictment cases * Moves defendand defender choice updates and notifications to defendant classes * Update unit tests and fixxes some issues * Fixes email sending trigger and guard --------- Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Defender Updated Notification
Senda tilkynningar til dómstóls þegar verjandi er valinn á island.is
What
Why
Checklist:
Summary by CodeRabbit
Release Notes
New Features
Improvements
Bug Fixes
Refactor