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

fix(j-s): Merge Case Access #16786

Merged
merged 4 commits into from
Nov 14, 2024
Merged

fix(j-s): Merge Case Access #16786

merged 4 commits into from
Nov 14, 2024

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Nov 8, 2024

Merge Case Access

Laga aðgang verjenda að gögnum í sameinuðum málum

What

  • Fixes defender and spokesperson access to uploaded case files in merged cases.
  • Fixes access to subpoena PDF in merged cases for all full access users.
  • Rewrites case queries with respect to memory footprint.

Why

  • Verified bug.
  • Query optimization.

Screenshots / Gifs

Screen.Recording.2024-11-08.at.21.02.20.mov

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

    • Enhanced GraphQL query now includes detailed information about defendants in cases.
    • Added new notification types for better event handling.
    • Introduced access control improvements for file management and case retrieval.
  • Bug Fixes

    • Adjusted role-based access for retrieving case file URLs.
  • Documentation

    • Updated test cases to reflect changes in query parameters and access control logic.
  • Chores

    • Removed unused imports and parameters across various files to streamline code.

@gudjong gudjong requested a review from a team as a code owner November 8, 2024 21:04
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The changes in this pull request primarily involve modifications to various service and filter files within the judicial system application. Key updates include the removal of unused constants, the introduction of new constants, and enhancements to query structures. Additionally, access control logic has been refined in the FileController, and new fields have been added to the GraphQL query for case information. Test files have also been adjusted to reflect these changes, particularly in how cases are filtered and retrieved, ensuring that the overall functionality remains intact while improving clarity and maintainability.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/case/case.service.ts Removed unused constants (eventTypes, dateTypes, stringTypes), added notificationTypes, restructured Sequelize queries, simplified where clauses, refined update method for case state transitions.
apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts Updated filtering logic to use subqueries for event and date logs based on user roles.
apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts Modified tests for user role filters to reflect subquery changes.
apps/judicial-system/backend/src/app/modules/case/guards/mergedCaseExists.guard.ts Updated canActivate method to assign mergedCaseParent to request.
apps/judicial-system/backend/src/app/modules/case/guards/test/caseExistsGuard.spec.ts Removed order import and parameter from tests.
apps/judicial-system/backend/src/app/modules/case/guards/test/caseHasExistedGuard.spec.ts Removed order import and parameter from tests.
apps/judicial-system/backend/src/app/modules/case/guards/test/limitedAccessCaseExistsGuard.spec.ts Removed order parameter from tests.
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts Removed unused constants, updated query structures, simplified where clauses, refined logging in update method.
apps/judicial-system/backend/src/app/modules/case/test/caseController/*.spec.ts Removed order import and parameter from multiple test files, simplifying query tests.
apps/judicial-system/backend/src/app/modules/file/file.controller.ts Modified access control for getCaseFileSignedUrl and added CaseReceivedGuard to uploadCaseFileToCourt.
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts Enhanced access control logic to use accessControlCase.
apps/judicial-system/backend/src/app/modules/file/test/fileController/getCaseFileSignedUrlRolesRules.spec.ts Updated tests to reflect removal of prisonSystemStaffRule.
apps/judicial-system/web/src/components/FormProvider/case.graphql Added defendants field to GraphQL query with detailed attributes.
libs/judicial-system/types/src/index.ts Added exports for new constants (notificationTypes, eventTypes, dateTypes, stringTypes).
libs/judicial-system/types/src/lib/caseString.ts Added stringTypes constant.
libs/judicial-system/types/src/lib/dateLog.ts Added dateTypes constant.
libs/judicial-system/types/src/lib/eventLog.ts Added eventTypes constant.
libs/judicial-system/types/src/lib/notification.ts Introduced new enums and constants for notifications, updated existing enum references.

Suggested labels

automerge, high priority

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

🧹 Outside diff range and nitpick comments (21)
libs/judicial-system/types/src/lib/caseString.ts (1)

6-6: Consider adding explicit type annotation for better type safety.

While the current implementation works, adding an explicit type annotation would improve type safety and documentation.

-export const stringTypes = Object.values(StringType)
+export const stringTypes: StringType[] = Object.values(StringType)

Also consider adding a JSDoc comment to document the purpose of this constant:

+/** Array of all available string types for case filtering */
 export const stringTypes: StringType[] = Object.values(StringType)
apps/judicial-system/backend/src/app/modules/case/guards/mergedCaseExists.guard.ts (1)

40-42: Consider adding type declarations for request extensions.

To improve type safety and maintainability, consider declaring custom types for the request object extensions.

interface MergedCaseRequest extends Request {
  mergedCaseParent?: Case;
  case?: Case;
  params: {
    caseId: string;
    mergedCaseId?: string;
  };
}
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1)

Line range hint 1-56: Consider adding logging for access denied cases.

For security auditing purposes, it would be valuable to log when access is denied, including the user role and case identifier (but no PII).

    if (
      canLimitedAccessUserViewCaseFile(
        user,
        accessControlCase.type,
        accessControlCase.state,
        caseFile.category,
        accessControlCase.defendants,
        accessControlCase.civilClaimants,
      )
    ) {
      return true
    }

+   logger.warn('Access denied to case file', {
+     userRole: user.role,
+     caseId: theCase.id,
+     isMergedCase: !!request.mergedCaseParent
+   });
    throw new ForbiddenException(`Forbidden for ${user.role}`)
apps/judicial-system/backend/src/app/modules/case/guards/test/caseHasExistedGuard.spec.ts (1)

Line range hint 1-108: Well-structured test suite with comprehensive coverage.

The test suite effectively covers:

  • Success case with proper query parameters
  • Error handling for non-existent cases
  • Validation of missing case IDs

The structure follows Jest best practices and maintains good separation of concerns.

Consider adding test cases for:

  • Cases with isArchived: true
  • Edge cases around merged cases, given this PR's focus on merged case access
libs/judicial-system/types/src/index.ts (1)

24-26: Consider grouping related type exports together.

While the exports are valid, consider organizing related type exports together for better maintainability. The event, date, and string type exports could be grouped with their corresponding type definitions.

- export { EventType, eventTypes } from './lib/eventLog'
- export { DateType, dateTypes } from './lib/dateLog'
- export { StringType, stringTypes } from './lib/caseString'
+ // Case-related types and constants
+ export { 
+   EventType, 
+   eventTypes,
+   DateType, 
+   dateTypes,
+   StringType, 
+   stringTypes 
+ } from './lib/case-types'
apps/judicial-system/backend/src/app/modules/case/guards/test/limitedAccessCaseExistsGuard.spec.ts (1)

14-14: LGTM: Query optimization through centralized attributes and includes.

The import of attributes and include from limitedAccessCase.service aligns well with the PR's objective of optimizing case queries. This centralization helps maintain consistency in query parameters across the codebase.

This approach of centralizing query parameters is particularly beneficial for:

  • Maintaining consistent memory usage across queries
  • Reducing duplication of query specifications
  • Making query parameter updates more maintainable
libs/judicial-system/types/src/lib/notification.ts (1)

64-64: LGTM! Efficient notification type aggregation.

The constant provides a centralized way to access all notification types and supports effective tree-shaking.

Consider adding a type guard or validation function if this constant is used for runtime type checking of notification values.

apps/judicial-system/web/src/components/FormProvider/limitedAccessCase.graphql (1)

211-211: Consider adding field documentation.

To improve schema maintainability, consider adding GraphQL documentation for the new defendants field using a description directive:

+ """
+ Information about defendants in merged cases, including their personal details,
+ defender information, and associated subpoenas.
+ """
  defendants {
apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (2)

89-95: Consider monitoring query performance with the new subquery.

While the subquery implementation is secure (using enum values), it might impact performance on large datasets. Consider:

  1. Adding an index on event_log.case_id and event_log.event_type if not already present
  2. Monitoring query execution time in production

256-264: Optimize the arraignment date subquery.

While the implementation is secure, consider optimizing the query:

  1. Add an index on date_log.case_id and date_log.date_type if not present
  2. Consider batching or pagination for large result sets
apps/judicial-system/backend/src/app/modules/case/test/caseController/extend.spec.ts (1)

Line range hint 1-386: Enhance test coverage for access permissions.

While the test suite comprehensively covers the case extension functionality, considering the PR's primary objective of fixing access permissions for defenders and spokespersons in merged cases, we should add test cases that verify:

  1. Access permissions for defenders in merged cases
  2. Access permissions for spokespersons in merged cases
  3. Access to subpoena PDFs for users with full access

Consider adding these test cases:

describe('access permissions in extended cases', () => {
  it('should allow defender access to merged case files', () => {
    // Test implementation
  })

  it('should allow spokesperson access to merged case files', () => {
    // Test implementation
  })

  it('should allow full access users to access subpoena PDFs', () => {
    // Test implementation
  })
})
apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts (1)

320-326: Consider improving SQL template literal formatting.

While the subquery logic is correct, the SQL formatting could be improved for better readability.

             id: {
               [Op.in]: Sequelize.literal(`
-            (SELECT case_id
-              FROM event_log
-              WHERE event_type = '${EventType.INDICTMENT_SENT_TO_PUBLIC_PROSECUTOR}')
+                (
+                  SELECT case_id
+                  FROM event_log
+                  WHERE event_type = '${EventType.INDICTMENT_SENT_TO_PUBLIC_PROSECUTOR}'
+                )
           `),
             },
apps/judicial-system/backend/src/app/modules/case/test/caseController/transition.spec.ts (3)

Line range hint 82-324: Consider improving test readability and error coverage.

While the test suite is comprehensive, consider these improvements:

  1. The test descriptions in the each blocks could be more readable by using template literals instead of concatenation.
  2. Add test cases for error scenarios, such as invalid state transitions.

Example of improved test description:

-    '$transition $oldState case transitioning to $newState case',
+    `Case transition: ${transition} (${oldState} → ${newState})`,

Line range hint 325-566: Refactor notification testing for better maintainability.

The notification testing logic is spread across multiple test blocks with some duplication. Consider:

  1. Creating a helper function to verify notifications based on transition type and states
  2. Using a shared constant for common notification payloads

Example helper function:

const verifyNotifications = (
  transition: CaseTransition,
  oldState: CaseState,
  newState: CaseState,
  mockMessageService: MessageService,
  theCase: Case,
  user: User,
) => {
  const expectedNotifications = getExpectedNotifications(
    transition,
    oldState,
    newState,
    theCase,
  )
  if (expectedNotifications.length > 0) {
    expect(mockMessageService.sendMessagesToQueue).toHaveBeenCalledWith(
      expectedNotifications.map(type => ({
        type,
        user,
        caseId: theCase.id,
        // ... other common properties
      }))
    )
  } else {
    expect(mockMessageService.sendMessagesToQueue).not.toHaveBeenCalled()
  }
}

Line range hint 567-709: Improve organization of appeal transition tests.

The appeal transition tests mix state transition logic with file handling. Consider:

  1. Moving the case file setup to a separate helper function
  2. Creating constants for common file categories and states

Example refactor:

const createAppealCaseFiles = (
  category: CaseFileCategory,
  state: CaseFileState = CaseFileState.STORED_IN_RVG,
) => ({
  id: uuid(),
  key: uuid(),
  state,
  category,
})

const setupAppealTestCase = (
  type: string,
  state: CaseState,
  appealState?: CaseAppealState,
) => ({
  id: uuid(),
  type,
  state,
  appealState,
  caseFiles: [
    createAppealCaseFiles(CaseFileCategory.PROSECUTOR_APPEAL_BRIEF),
    createAppealCaseFiles(CaseFileCategory.PROSECUTOR_APPEAL_BRIEF_CASE_FILE),
    createAppealCaseFiles(CaseFileCategory.APPEAL_RULING),
  ],
  origin: CaseOrigin.LOKE,
})
apps/judicial-system/web/src/components/FormProvider/case.graphql (1)

317-353: Consider limiting the data fetched to improve performance.

Including all fields for defendants and their subpoenas may increase payload size and impact performance. Consider selecting only the necessary fields required by the client components.

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

2-2: Consider importing types directly from 'sequelize'

Importing Includeable and Transaction from 'sequelize/types' is not recommended. Instead, import them directly from 'sequelize' to maintain compatibility and future-proof the code.

-import { Includeable, Transaction } from 'sequelize/types'
+import { Includeable, Transaction } from 'sequelize'

291-304: Review the use of 'separate: true' in associations

Using separate: true for the civilClaimants and indictmentCounts associations will execute separate queries for each. While this can prevent large JOINs and reduce memory usage for large datasets, it may increase the number of database queries and impact performance. Consider if separate: true is necessary or if eager loading without it would suffice.


316-316: Assess performance implications of 'separate: true' and 'where' clauses

Adding where clauses and separate: true to the eventLogs, dateLogs, caseStrings, and notifications associations can lead to multiple queries being executed. This might impact performance due to increased database load. Evaluate whether these associations require separate: true, or if the filtering can be handled efficiently within the main query.

Also applies to: 324-326, 332-334, 335-341


349-364: Monitor performance of deeply nested includes with 'separate: true'

Including defendants and nested subpoenas within mergedCases using separate: true results in multiple additional queries. This depth of eager loading can negatively affect performance. Consider if all nested data is required immediately or if some associations can be loaded lazily when needed.


398-404: Evaluate necessity of including 'defendants' in case list queries

Including defendants in caseListInclude with separate: true may increase the number of queries when retrieving case lists, potentially impacting performance. Assess whether fetching defendants is essential for the case list view or if it can be deferred to improve efficiency.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5d43b90 and ffb1621.

📒 Files selected for processing (22)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (6 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/mergedCaseExists.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/test/caseExistsGuard.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/test/caseHasExistedGuard.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/test/limitedAccessCaseExistsGuard.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/create.spec.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/extend.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/transition.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/file/file.controller.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/file/test/fileController/getCaseFileSignedUrlRolesRules.spec.ts (1 hunks)
  • apps/judicial-system/web/src/components/FormProvider/case.graphql (1 hunks)
  • apps/judicial-system/web/src/components/FormProvider/limitedAccessCase.graphql (1 hunks)
  • libs/judicial-system/types/src/index.ts (1 hunks)
  • libs/judicial-system/types/src/lib/caseString.ts (1 hunks)
  • libs/judicial-system/types/src/lib/dateLog.ts (1 hunks)
  • libs/judicial-system/types/src/lib/eventLog.ts (1 hunks)
  • libs/judicial-system/types/src/lib/notification.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/file/file.controller.ts
✅ Files skipped from review due to trivial changes (1)
  • libs/judicial-system/types/src/lib/eventLog.ts
🧰 Additional context used
📓 Path-based instructions (20)
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/filters/cases.filter.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/filters/test/cases.filter.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/case/guards/mergedCaseExists.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/case/guards/test/caseExistsGuard.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/case/guards/test/caseHasExistedGuard.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/case/guards/test/limitedAccessCaseExistsGuard.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/case/limitedAccessCase.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/caseController/create.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/case/test/caseController/createCourtCase.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/case/test/caseController/extend.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/case/test/caseController/transition.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/file/guards/limitedAccessViewCaseFile.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/file/test/fileController/getCaseFileSignedUrlRolesRules.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/components/FormProvider/case.graphql (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/components/FormProvider/limitedAccessCase.graphql (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/index.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."
libs/judicial-system/types/src/lib/caseString.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."
libs/judicial-system/types/src/lib/dateLog.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."
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/case/filters/test/cases.filter.spec.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`
apps/judicial-system/backend/src/app/modules/case/guards/test/caseExistsGuard.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-10-17T11:53:19.983Z
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/case/guards/test/caseHasExistedGuard.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-10-17T11:53:19.983Z
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/case/guards/test/limitedAccessCaseExistsGuard.spec.ts (3)
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-10-17T11:53:19.983Z
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-10-17T11:41:45.565Z
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`.
Learnt from: oddsson
PR: island-is/island.is#16463
File: apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/limitedAccessSubpoenaControllerGuards.spec.ts:17-17
Timestamp: 2024-10-21T21:14:47.668Z
Learning: In `LimitedAccessSubpoenaController`, `SubpoenaExistsOptionalGuard` is still used on specific endpoints not covered by the test file `limitedAccessSubpoenaControllerGuards.spec.ts`.
apps/judicial-system/backend/src/app/modules/file/test/fileController/getCaseFileSignedUrlRolesRules.spec.ts (1)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`
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-10-24T17:31:06.252Z
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.
🔇 Additional comments (37)
libs/judicial-system/types/src/lib/dateLog.ts (2)

Line range hint 1-4: LGTM! Well-defined enum for date types.

The enum clearly defines the two types of dates used in the judicial system with descriptive names.


6-6: Good centralization of date type values.

The addition of dateTypes constant improves code maintainability by:

  • Centralizing the date type values in a single location
  • Providing a type-safe array of valid date types
  • Enabling tree-shaking through direct export from the types library

This aligns well with the library coding guidelines for reusability and TypeScript usage.

Let's verify that this constant is now being used consistently across the codebase:

✅ Verification successful

Remaining direct usage of Object.values(DateType) in Sequelize model

The direct usage of Object.values(DateType) in dateLog.model.ts is actually correct and cannot be replaced with the centralized dateTypes constant. This is because:

  • It's used in a Sequelize column definition where the values property requires an immediate array value for enum configuration
  • The values property is part of Sequelize's type definition system and needs to be evaluated during model initialization
  • Using an imported constant here could potentially cause initialization timing issues

The review comment's approval of centralizing date types remains valid for application logic usage, while the Sequelize model definition is a justified exception.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining direct Object.values(DateType) usage that could be replaced with dateTypes
# Expected: No results, indicating all usages have been centralized

rg "Object\.values\(DateType\)" --type ts

Length of output: 249


Script:

#!/bin/bash
# Let's check the content of both files to understand the context better
echo "=== Content of dateLog.ts ==="
cat libs/judicial-system/types/src/lib/dateLog.ts

echo -e "\n=== Content of dateLog.model.ts ==="
cat apps/judicial-system/backend/src/app/modules/case/models/dateLog.model.ts

Length of output: 1895

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

6-6: LGTM! The implementation follows TypeScript best practices.

The exported constant provides a reusable way to access enum values across the codebase, which aligns with the library's reusability guidelines and supports the PR's query optimization goals.

apps/judicial-system/backend/src/app/modules/case/guards/mergedCaseExists.guard.ts (2)

40-42: LGTM! Proper security flow maintained.

The changes correctly maintain the security boundary by performing all necessary validations before updating case references. The order of operations ensures that access control is properly enforced for merged cases.


Line range hint 1-44: Verify integration with access control decorators.

Since this guard handles merged case access, we should verify it's properly combined with other access control mechanisms.

✅ Verification successful

Let me generate another verification script to check specifically how the MergedCaseExistsGuard is used in controllers:


Guard is properly integrated with access control mechanisms

The MergedCaseExistsGuard is correctly integrated with other access control mechanisms. It's used in combination with:

  • Authentication guards (JwtAuthGuard)
  • Role-based guards (RolesGuard)
  • Case-specific guards (CaseExistsGuard, CaseReadGuard)
  • Type validation (CaseTypeGuard)

The guard is used in:

  • FileController and LimitedAccessFileController for file access
  • CaseController and LimitedAccessCaseController for case operations
  • All usages are properly tested as shown in test files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for routes using this guard and verify they have proper access control

# Find controller files using this guard
echo "Searching for routes using MergedCaseExistsGuard..."
rg -l "MergedCaseExistsGuard" apps/judicial-system/backend/src/app/modules

# Check for access control decorators in those files
echo "\nChecking for access control decorators in related files..."
rg "@(UseGuards|Roles|AllowedUserTypes)" apps/judicial-system/backend/src/app/modules

Length of output: 19188


Script:

#!/bin/bash
# Search for routes using MergedCaseExistsGuard and their access control setup
echo "Searching for MergedCaseExistsGuard usage in controllers..."
rg -B 5 -A 5 "MergedCaseExistsGuard" apps/judicial-system/backend/src/app/modules

# Check for any test files related to MergedCaseExistsGuard
echo "\nSearching for related test files..."
rg -l "MergedCaseExistsGuard" "apps/judicial-system/backend/src/app/modules/**/*.spec.ts"

Length of output: 31140

apps/judicial-system/backend/src/app/modules/file/test/fileController/getCaseFileSignedUrlRolesRules.spec.ts (2)

Line range hint 17-37: LGTM! Test structure and implementation are solid.

The test follows best practices:

  • Uses reflection to verify metadata
  • Has proper setup in beforeEach
  • Explicitly verifies each allowed role

Line range hint 1-15: Verify defender access requirements

The PR objectives mention fixing access for defenders, but defenderRule is not included in the role rules being tested. Please verify if defenders should have access to the getCaseFileSignedUrl endpoint.

✅ Verification successful

Let me gather more information about the role rules and controllers to understand the access pattern better.


The omission of defenderRule is correct - there are separate controllers for different access patterns

The verification reveals that the system implements two separate controllers with distinct access patterns:

  • FileController: Regular access for court and prosecutor roles
  • LimitedAccessFileController: Restricted access for defenders and prison staff

The test file under review is for the regular FileController, which intentionally excludes the defenderRule as defender access is handled through the separate LimitedAccessFileController. This separation of concerns is well-structured and maintains proper access control.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if defenderRule is used in other similar test files or the controller
# This helps verify if the omission is intentional or an oversight

echo "Checking for defenderRule usage in related files..."
rg -l "defenderRule" "apps/judicial-system/backend/src/app/modules/file"

echo "\nChecking the actual controller implementation..."
rg "getCaseFileSignedUrl" "apps/judicial-system/backend/src/app/modules/file/file.controller.ts" -A 5

Length of output: 1342


Script:

#!/bin/bash
# Check the implementation of both regular and limited access controllers
echo "Checking FileController implementation..."
rg "@RolesRules" "apps/judicial-system/backend/src/app/modules/file/file.controller.ts" -B 1 -A 5

echo "\nChecking LimitedAccessFileController implementation..."
rg "@RolesRules" "apps/judicial-system/backend/src/app/modules/file/limitedAccessFile.controller.ts" -B 1 -A 5

echo "\nComparing test files for both controllers..."
echo "Regular controller test:"
cat "apps/judicial-system/backend/src/app/modules/file/test/fileController/getCaseFileSignedUrlRolesRules.spec.ts"
echo "\nLimited access controller test:"
cat "apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts"

Length of output: 4724

apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (2)

38-40: LGTM! Clear documentation of merged case handling.

The comment effectively explains the logic for determining which case to use for access control.


40-40: Verify null-safety of mergedCaseParent access.

The nullish coalescing operator is used correctly here, but we should verify that request.mergedCaseParent is properly typed and set.

✅ Verification successful

Let me gather more information about the request type and guard chain.


Let me check one final thing about the request type and the guard chain order.


Null-safety of mergedCaseParent is properly handled

Based on the verification results:

  • mergedCaseParent is set in MergedCaseExistsGuard before being accessed
  • MergedCaseExistsGuard is properly chained before LimitedAccessViewCaseFileGuard in the controller
  • The nullish coalescing operator provides a fallback to theCase if mergedCaseParent is null
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if mergedCaseParent is properly typed and set in related guards/controllers

# Search for type definitions and assignments of mergedCaseParent
rg -A 3 "mergedCaseParent" 

# Search for MergedCaseExistsGuard usage to ensure it's properly chained
ast-grep --pattern 'class $_ implements CanActivate {
  $$$
  @UseGuards($$$MergedCaseExistsGuard$$$)
  $$$
}'

Length of output: 1075


Script:

#!/bin/bash
# Check the request type definition and guard chain
ast-grep --pattern 'interface $_ extends Request {
  $$$
  mergedCaseParent?: $_
  $$$
}'

# Check if MergedCaseExistsGuard is used before LimitedAccessViewCaseFileGuard
rg -B 3 "LimitedAccessViewCaseFileGuard" 

Length of output: 4289


Script:

#!/bin/bash
# Check the request interface and the guard chain in the controller
ast-grep --pattern 'interface JudicialSystemRequest extends Request {
  $$$
}'

# Check the controller's guard chain
ast-grep --pattern '@UseGuards($$$)
export class LimitedAccessFileController {
  $$$
}'

Length of output: 170

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

11-11: LGTM! Query parameter simplification aligns with optimization goals.

The removal of the order parameter from imports and its usage in queries aligns well with the PR's objective of optimizing memory usage in case queries.

libs/judicial-system/types/src/index.ts (2)

21-21: LGTM: Notification types export aligns with access control requirements.

The addition of notificationTypes export supports the PR's objective of improving access permissions by providing standardized notification type constants.


Line range hint 1-93: Verify the impact of new exports on bundle size.

Since this is a library file, we should ensure these new exports don't negatively impact tree-shaking.

apps/judicial-system/backend/src/app/modules/case/guards/test/caseExistsGuard.spec.ts (3)

14-14: LGTM! Import statement cleanup looks good.

The simplified import statement aligns with the broader refactoring effort to remove unnecessary ordering parameters.


Line range hint 75-106: LGTM! Error handling tests are comprehensive.

The tests properly validate both error scenarios with appropriate exceptions and clear error messages.


Line range hint 63-70: Verify query conditions for merged cases.

The test validates basic access conditions, but given the PR's focus on merged cases, we should verify if additional conditions are needed.

Let's check if there are any merged case-specific conditions in other files:

✅ Verification successful

Let me gather more specific information about case state conditions.


Query conditions for merged cases are correctly implemented

The test case's query conditions are comprehensive and align with the codebase implementation. The conditions include:

  • Non-deleted cases (state: { [Op.not]: CaseState.DELETED })
  • Non-archived cases (isArchived: false)
  • Specific case ID (id: caseId)

These conditions are consistently used across the codebase, including in:

  • Case services (case.service.ts, limitedAccessCase.service.ts)
  • Guards (caseExistsGuard.spec.ts)
  • Related services (defendant.service.ts, civilClaimant.service.ts)

The merged case functionality is handled separately through dedicated guards (MergedCaseExistsGuard) and doesn't require additional conditions in the base query.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for merged case-related conditions in model queries
rg -A 5 "merge.*case|case.*merge" --type ts

# Search for any additional where conditions used with CaseState
ast-grep --pattern 'where: {
  $$$
  state: $$$
  $$$
}'

Length of output: 25517


Script:

#!/bin/bash
# Search for case state conditions in guards and models
ast-grep --pattern 'where: {
  $$$
  state: { [Op.not]: CaseState.DELETED }
  $$$
}'

# Search for case state related conditions in the guard file
rg -A 5 "CaseState" apps/judicial-system/backend/src/app/modules/case/guards/caseExistsGuard.ts

Length of output: 298


Script:

#!/bin/bash
# Search for the correct path of caseExistsGuard
fd -t f caseExistsGuard

# Search for case state conditions in the entire codebase
rg -A 5 "state: \{.*\[Op\.not\].*CaseState" --type ts

Length of output: 6758

apps/judicial-system/backend/src/app/modules/case/guards/test/limitedAccessCaseExistsGuard.spec.ts (2)

Line range hint 63-75: LGTM: Comprehensive test coverage for successful case retrieval.

The test case properly validates the guard's behavior when a case exists, including verification of:

  • Correct query parameters (attributes, include, where conditions)
  • Proper filtering of deleted and archived cases
  • Case assignment to request object

Line range hint 78-93: LGTM: Thorough error handling test coverage.

The test suite properly covers error scenarios with appropriate assertions:

  • Non-existent case throwing NotFoundException
  • Missing case ID throwing BadRequestException

Also applies to: 96-108

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

33-34: LGTM! Good separation of institution-specific notifications.

The new enum improves code organization by isolating institution-specific notification types.


57-57: LGTM! Type-safe notification mapping.

The NotificationType enum correctly references the new notification types while maintaining type safety through enum references.

Also applies to: 61-61


Line range hint 66-68: LGTM! Consistent type reference.

The enum correctly references the InstitutionNotificationType, maintaining type safety and consistency.

apps/judicial-system/web/src/components/FormProvider/limitedAccessCase.graphql (1)

211-246: LGTM! Schema changes align perfectly with requirements.

The addition of the defendants field to mergedCases effectively addresses the access permission requirements for merged cases. The field structure comprehensively includes all necessary information, particularly the subpoena details, which directly supports the PR objective of fixing subpoena PDF access.

apps/judicial-system/backend/src/app/modules/case/test/caseController/create.spec.ts (2)

16-16: LGTM: Import change aligns with query optimization goal.

The replacement of the order import with include is consistent with the PR's objective to optimize case queries.


116-116: Verify query optimization impact.

The addition of the include parameter to the findOne query is part of the query optimization effort. Let's verify that this change improves memory usage as intended.

✅ Verification successful

Query optimization appears to be consistently implemented

The codebase shows a consistent pattern of using explicit include parameters in findOne queries across different services, indicating proper implementation of lazy loading. No eager loading configurations were found. The optimization approach aligns with best practices for memory usage by:

  • Using specific includes in case-related queries
  • Avoiding global eager loading settings
  • Implementing consistent query patterns across services
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of include parameter across case queries
# and ensure no direct eager loading is used elsewhere

# Check for consistent usage of include parameter
rg -A 5 "findOne\({" apps/judicial-system/backend

# Check for potential eager loading patterns that might affect performance
ast-grep --pattern 'findOne({ include: $_$ })'

Length of output: 184


Script:

#!/bin/bash
# Let's fix the regex and search for findOne queries
rg -A 5 "findOne\(" apps/judicial-system/backend

# Search for any include patterns in findOne
rg -A 5 "findOne.*include" apps/judicial-system/backend

# Look for eager loading configurations in the model
rg "eager:\s*true" apps/judicial-system/backend

Length of output: 8076

apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (1)

221-223: LGTM! Clear and secure implementation of verdict appeal window check.

The conditions properly handle all cases:

  • Verdict appeal date presence
  • Verdict view date nullability
  • Appeal window period using the constant
apps/judicial-system/backend/src/app/modules/case/test/caseController/createCourtCase.spec.ts (2)

21-21: LGTM! Import change aligns with query optimization goals.

The removal of the order import and retaining only include aligns with the PR's objective of optimizing case queries and memory usage. This change suggests a successful simplification of the query structure without affecting the test functionality.


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

The test suite demonstrates:

  • Thorough coverage of court case creation scenarios
  • Proper state transition testing
  • Comprehensive message queue testing for different case types
  • Robust error handling validation
  • Well-structured test organization using describe/it blocks
  • Effective use of TypeScript types and interfaces

This provides good confidence in the reliability of the case creation functionality.

Let's verify the test coverage:

✅ Verification successful

The shell script results show comprehensive test coverage across different case types and message types in the codebase. Let me verify the specific aspects mentioned in the review comment:

  1. Court case creation scenarios are thoroughly tested in createCourtCase.spec.ts with tests for different case types and validation
  2. State transitions are well covered in multiple test files including transition.spec.ts
  3. Message queue testing is extensive with tests for all MessageType enum values across different scenarios
  4. Error handling is validated in multiple test files with proper error cases
  5. Test organization follows consistent describe/it block structure
  6. TypeScript types and interfaces are properly used throughout

Thorough test coverage confirmed with robust test structure and organization

The test suite demonstrates:

  • Comprehensive coverage of all case types and transitions
  • Extensive message queue testing with all MessageType variants
  • Well-structured test organization
  • Strong type safety with TypeScript
  • Proper error handling validation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any untested case types or message types
# that might need additional test coverage

# Test 1: Check for all CaseType enum values being tested
rg -A 5 "CaseType\." apps/judicial-system/backend/src/app/modules

# Test 2: Check for all MessageType enum values being tested
rg -A 5 "MessageType\." apps/judicial-system/backend/src/app/modules

Length of output: 242454

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

19-19: Verify the impact of the include import change.

The change from order to include import suggests a modification in how cases are queried. This aligns with the PR's objective of rewriting case queries for memory optimization.

Let's verify the implementation of include:

✅ Verification successful

Import change from order to include is correct and properly implemented

The verification shows that:

  1. include is a well-defined constant that specifies the related models to be loaded when querying cases
  2. It's consistently used across both case.service.ts and limitedAccessCase.service.ts
  3. The constant includes proper model relationships for all necessary entities (institutions, users, defendants, etc.)
  4. The ordering is still maintained within the include definitions where needed (e.g., defendants and subpoenas have their own order parameters)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation and usage of the include constant
# to ensure it properly handles access permissions for defenders and spokespersons.

# Test 1: Check the implementation of include
rg -A 10 "export const include = " apps/judicial-system/backend/src/app/modules/case/

# Test 2: Check other usages to ensure consistent implementation
rg "include," apps/judicial-system/backend/src/app/modules/case/

Length of output: 1194


Script:

#!/bin/bash
# Let's check the implementation of include and its relationship with order
# First, let's find the include constant definition
ast-grep --pattern 'export const include ='

# Then, let's check for any order-related constants that might have been replaced
ast-grep --pattern 'export const order ='

# Finally, let's see the actual usage in the test file
rg -B 5 -A 10 "include," apps/judicial-system/backend/src/app/modules/case/test/caseController/extend.spec.ts

Length of output: 545


Script:

#!/bin/bash
# Let's check the case.service.ts file to understand the include constant and its usage
rg -B 5 -A 15 "include" apps/judicial-system/backend/src/app/modules/case/case.service.ts

# Also check if there are any recent changes to this file in the PR
git diff origin/master apps/judicial-system/backend/src/app/modules/case/case.service.ts

# Let's also check the limitedAccessCase.service.ts since it uses include
rg -B 5 -A 15 "include" apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts

Length of output: 13288

apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts (2)

398-400: LGTM! The verdict date conditions are well-structured.

The SQL conditions for checking verdict appeal and view dates are correctly implemented and properly use the VERDICT_APPEAL_WINDOW_DAYS constant.


442-450: LGTM! The arraignment date filter is well-implemented.

The subquery correctly filters cases by arraignment date using the appropriate date type constant.

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

25-27: LGTM: Constants import optimization

The import of pre-computed constant values using Object.values() aligns with the PR's goal of optimizing memory usage.


188-201: LGTM: Enhanced model includes for civil claims

The addition of CivilClaimant and IndictmentCount models with proper configuration (required, order, separate) follows Sequelize best practices.


260-275: LGTM: Proper configuration for merged case access

The nested includes for Defendant and Subpoena models in merged cases directly addresses the PR objective of fixing subpoena PDF access in merged cases.


229-229: Verify query optimization impact

The query optimizations (separate loading and simplified where clauses) align with the PR's goal of improving memory usage. Let's verify the impact.

Also applies to: 235-235, 243-245, 251-252

✅ Verification successful

Let me analyze the results. The search shows extensive usage of Sequelize queries across the codebase. The separate: true optimization is not consistently used in many places where there are nested includes, particularly in services dealing with complex relationships.

Let me verify one more aspect to ensure we have a complete picture:


Query optimization pattern is correctly applied

The separate: true configuration is appropriately used in the LimitedAccessCase service for all nested associations. This pattern:

  • Prevents memory bloat by loading associations separately
  • Is consistently applied to all relevant includes in the service
  • Follows best practices for handling complex nested relationships

The optimization is particularly well implemented here with:

  • Proper ordering (order clauses) for each separate query
  • Correct handling of required/optional associations
  • Strategic application at both parent and nested levels
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining unoptimized queries in the codebase
# that might benefit from similar optimizations

# Look for potential unoptimized Sequelize queries
rg -A 3 "include: \[" --type ts | grep -v "separate: true"

# Look for where clauses that might need similar optimization
rg -A 3 "Op\.in.*Type" --type ts

Length of output: 80559


Script:

#!/bin/bash
# Check the specific file for context around the optimization
rg -B 5 -A 5 "separate: true" apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts

Length of output: 1936

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

34-34: Verify the impact of removing the order import.

The removal of the order import and retaining only the include import suggests a change in how case queries are structured. This aligns with the PR objective of optimizing case queries.

Let's verify if the order import is still used elsewhere:

apps/judicial-system/web/src/components/FormProvider/case.graphql (1)

317-353: ⚠️ Potential issue

Ensure proper handling of sensitive personal information.

The defendants field includes sensitive data such as nationalId, defenderNationalId, and other personal details. Please verify that appropriate access controls are implemented to prevent unauthorized access to this information, ensuring compliance with data protection regulations.

To confirm that only authorized users can access these fields, you can run the following script:

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

42-51: New imports are correctly added

The added imports of dateTypes, eventTypes, notificationTypes, and stringTypes from '@island.is/judicial-system/types' are appropriate and necessary for the updated query conditions.


434-451: Updates to includes are appropriate

The additions of where clauses and separate: true for dateLogs, caseStrings, and eventLogs are acceptable, assuming that performance considerations have been addressed. These changes enhance specificity in data retrieval.

Copy link

codecov bot commented Nov 8, 2024

Codecov Report

Attention: Patch coverage is 94.11765% with 1 line in your changes missing coverage. Please review.

Project coverage is 36.57%. Comparing base (4acfbd4) to head (9bbb08d).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../app/modules/case/guards/mergedCaseExists.guard.ts 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16786      +/-   ##
==========================================
+ Coverage   36.45%   36.57%   +0.12%     
==========================================
  Files        6852     6892      +40     
  Lines      143557   143975     +418     
  Branches    40969    41104     +135     
==========================================
+ Hits        52329    52663     +334     
- Misses      91228    91312      +84     
Flag Coverage Δ
judicial-system-api 19.76% <100.00%> (+0.14%) ⬆️
judicial-system-backend 55.17% <94.11%> (-0.01%) ⬇️
judicial-system-formatters 79.26% <100.00%> (+0.13%) ⬆️
judicial-system-message 66.86% <ø> (ø)
judicial-system-message-handler 47.81% <ø> (ø)
judicial-system-scheduler 70.62% <100.00%> (+0.14%) ⬆️
judicial-system-types 43.58% <0.00%> (-0.41%) ⬇️
judicial-system-web 27.15% <100.00%> (+0.02%) ⬆️

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

Files with missing lines Coverage Δ
...ystem/backend/src/app/modules/case/case.service.ts 90.31% <ø> (-0.09%) ⬇️
...ckend/src/app/modules/case/filters/cases.filter.ts 97.91% <ø> (ø)
.../src/app/modules/case/limitedAccessCase.service.ts 73.27% <100.00%> (-0.90%) ⬇️
...em/backend/src/app/modules/file/file.controller.ts 100.00% <ø> (ø)
...les/file/guards/limitedAccessViewCaseFile.guard.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/index.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/caseString.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/dateLog.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/eventLog.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/notification.ts 100.00% <100.00%> (ø)
... and 1 more

... and 100 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 4acfbd4...9bbb08d. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 8, 2024

Datadog Report

All test runs 3818f98 🔗

9 Total Test Services: 0 Failed, 9 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.47%), 5 increased, 6 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
judicial-system-api 0 0 0 59 0 5.25s 1 increased (+0.16%) Link
judicial-system-backend 0 0 0 21167 0 16m 36.21s 1 no change Link
judicial-system-formatters 0 0 0 38 0 4.85s 1 increased (+0.09%) Link
judicial-system-message 0 0 0 35 0 9.43s 1 no change Link
judicial-system-message-handler 0 0 0 4 0 3.19s 1 no change Link
judicial-system-scheduler 0 0 0 4 0 3.81s 1 increased (+0.13%) Link
judicial-system-types 0 0 0 23 0 6.04s 1 decreased (-0.47%) Link
judicial-system-web 0 0 0 333 0 54.7s 1 increased (+0.03%) Link
judicial-system-xrd-api 0 0 0 6 0 4.75s 1 increased (+0.11%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • judicial-system-types - jest 46.65% (-0.47%) - Details

Copy link
Member

@unakb unakb left a comment

Choose a reason for hiding this comment

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

Looks good!

@gudjong gudjong added deprecated:automerge (Disabled) Merge this PR as soon as all checks pass and removed deprecated:automerge (Disabled) Merge this PR as soon as all checks pass labels Nov 12, 2024
@oddsson oddsson added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 14, 2024
@kodiakhq kodiakhq bot merged commit e47d2b9 into main Nov 14, 2024
37 checks passed
@kodiakhq kodiakhq bot deleted the j-s/fix-merge-case-file-access branch November 14, 2024 13:03
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
* Fixes file and PDF access in merged cases

* removes redundant defendant query

---------

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

Successfully merging this pull request may close these issues.

3 participants