Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(j-s): Add received date and new table state tag for indictment prison cases #17279

Merged
merged 15 commits into from
Dec 19, 2024

Conversation

thorhildurt
Copy link
Member

@thorhildurt thorhildurt commented Dec 18, 2024

What

  • Asana task
  • When prison admin fetched selected prison case
    • We create and add a received date at the top of the overview
    • When navigating back to the prison case list we show "Móttekið" state in the table. Other cases will have "Nýtt" as default.

Why

  • To add more visibility when prison admins are viewing/processing new prison cases and not just marked as new forever

Technical context

  • Create a new interceptor that executes logic before we handle the get case by id request, we then show the newly created event date on the indictment overview
    • In the new interceptor context we check if we have valid user (taking into account the institution+role) and check for OPENED_BY_PRISON_ADMIN events in defendantEventLog per defendant
    • We add OPENED_BY_PRISON_ADMIN to all defendants on the fetched case where the event hasn't been created given the latest event state
    • Example: Valid open by prison admin log state
      • { type: SENT_TO_PRISON_ADMIN, created: 01.01.2024}, {type: OPENED_BY_PRISON_ADMIN, created: 02.01.2024}
      • { type: SENT_TO_PRISON_ADMIN, created: 01.01.2024}, {type: OPENED_BY_PRISON_ADMIN, created: 01.01.2024}
    • Example: Invalid open by prison admin log state => will trigger creating open by prison admin log event
      • { type: SENT_TO_PRISON_ADMIN, created: 01.01.2024}
      • { type: SENT_TO_PRISON_ADMIN, created: 01.01.2024}, {type: OPENED_BY_PRISON_ADMIN, created: 02.01.2024}, { type: SENT_TO_PRISON_ADMIN, created: 01.02.2024}
  • We add an optional openedByPrisonAdminDate to the prison case list, added via the transformDefendants case list interceptor logic, and if that is populated we show the received state otherwise new

Screenshots / Gifs

Screen.Recording.2024-12-18.at.10.27.16.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

    • Added a new field openedByPrisonAdminDate to the Defendant model, enhancing data capture for defendants.
    • Introduced a new interceptor to manage requests related to indictment cases accessed by prison administrators.
    • Added functionality to retrieve and display the date when a case was opened by the prison administration in various components and queries.
    • Implemented a new function to determine tag colors and text based on the state of a prison case.
  • Bug Fixes

    • Improved event logging for defendants by centralizing event creation logic.
  • Documentation

    • Updated internationalized messages for clarity in the indictment overview.
  • Style

    • Enhanced UI components to display additional context regarding defendants' interactions with prison administration.
  • Chores

    • Added new enumeration value OPENED_BY_PRISON_ADMIN to track additional defendant events.

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

warning [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/[email protected]: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/[email protected]: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > [email protected]: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning jest > @jest/core > jest-config > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/reporters > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-runtime > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/transform > babel-plugin-istanbul > test-exclude > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning storybook > @storybook/cli > tempy > del > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning react-native > @react-native/codegen > [email protected]: Glob versions prior to v9 are no longer supported
warning react-native > @react-native/community-cli-plugin > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning react-native > @react-native-community/cli > @react-native-community/cli-tools > [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
warning react-native > @react-native/community-cli-plugin > @react-native/dev-middleware > @rnx-kit/chromium-edge-launcher > [email protected]: Rimraf versions prior to v4 are no longer supported
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-async-generator-functions instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-numeric-separator instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-catch-binding instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-logical-assignment-operators instead.
warning next-auth > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning next-auth > [email protected]: this version is no longer supported
warning next-auth > @next-auth/typeorm-legacy-adapter > typeorm > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > stylus > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > webpack-dev-server > [email protected]: Rimraf versions prior to v4 are no longer supported
warning @nx/next > @nx/webpack > webpack-dev-server > webpack-dev-middleware > [email protected]: this will be v4
warning @nx/next > @nx/webpack > fork-ts-checker-webpack-plugin > [email protected]: this will be v4
warning workspace-aggregator-fae63b28-ec43-4666-833d-251385431e33 > [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning "@nx/eslint > @nx/js > [email protected]" has unmet peer dependency "@types/node@".
warning "@nx/next > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "styled-components > babel-plugin-styled-components > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
warning " > [email protected]" has unmet peer dependency "react-is@>= 16.8.0".
warning "@nx/react > [email protected]" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
warning " > [email protected]" has unmet peer dependency "@types/node@
".
warning " > [email protected]" has incorrect peer dependency "[email protected]".
warning "react-native > @react-native/[email protected]" has unmet peer dependency "@babel/preset-env@^7.1.6".
warning "react-native > @react-native/community-cli-plugin > @react-native/[email protected]" has unmet peer dependency "@babel/core@*".
warning "@vanilla-extract/next-plugin > @vanilla-extract/[email protected]" has unmet peer dependency "webpack@^4.30.0 || ^5.20.2".
warning " > [email protected]" has incorrect peer dependency "react@^16.13.1 || ^17".
warning " > [email protected]" has incorrect peer dependency "react-dom@^16.13.1 || ^17".
warning "next-auth > @next-auth/[email protected]" has unmet peer dependency "@prisma/client@^2.16.1".
warning "@nx/next > [email protected]" has unmet peer dependency "webpack@^5.1.0".

Walkthrough

This pull request introduces a new field openedByPrisonAdminDate to the Defendant model and modifies various components of the judicial system application to support this addition. The changes include updates to backend models, services, and interceptors, as well as frontend queries and components. These modifications enhance the tracking of when a defendant's case is opened by prison administration, improving the overall event logging and case management capabilities.

Changes

File Path Change Summary
apps/judicial-system/api/src/app/modules/defendant/models/defendant.model.ts Added nullable openedByPrisonAdminDate field to Defendant model
apps/judicial-system/backend/src/app/modules/case/case.service.ts Updated caseListInclude to include DefendantEventLog
apps/judicial-system/backend/src/app/modules/case/interceptors/case.interceptor.ts Modified transformDefendants to handle openedByPrisonAdminDate
apps/judicial-system/backend/src/app/modules/case/interceptors/defendantIndictmentAccessed.interceptor.ts Added DefendantIndictmentAccessedInterceptor to manage indictment access
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts Updated constructor and getById method to include new interceptor and service
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts Added createDefendantEvent method for logging events
apps/judicial-system/backend/src/app/modules/defendant/models/defendantEventLog.model.ts Updated method for retrieving event log dates
apps/judicial-system/web/src/components/FormProvider/case.graphql Added openedByPrisonAdminDate to defendants object in Case query
apps/judicial-system/web/src/components/FormProvider/limitedAccessCase.graphql Added openedByPrisonAdminDate to defendants object in LimitedAccessCase query
apps/judicial-system/web/src/components/Tags/utils.ts Added getPrisonCaseStateTag function for case tagging
apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.strings.ts Updated internationalized messages for indictment overview
apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx Modified component to display openedByPrisonAdminDate
apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx Updated rendering logic for case state tags
apps/judicial-system/web/src/routes/Shared/Cases/cases.graphql Added openedByPrisonAdminDate to defendants in Cases query
apps/judicial-system/web/src/routes/Shared/Cases/prisonCases.graphql Added openedByPrisonAdminDate to defendants in PrisonCases query
libs/judicial-system/types/src/lib/eventLog.ts Added OPENED_BY_PRISON_ADMIN to DefendantEventType enum
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts Updated test to handle user role parameter

Sequence Diagram

sequenceDiagram
    participant PA as Prison Admin
    participant IC as Indictment Case
    participant DS as Defendant Service
    participant EL as Event Log

    PA->>IC: Access Indictment
    IC->>DS: Check Defendant Status
    DS->>EL: Create Event Log
    EL-->>DS: Log Created
    DS->>IC: Update Defendant Status
    IC->>PA: Display Opened Date
Loading

Possibly related PRs

Suggested reviewers

  • unakb
  • thorhildurt

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

@datadog-island-is
Copy link

datadog-island-is bot commented Dec 18, 2024

Datadog Report

All test runs eb2b42e 🔗

10 Total Test Services: 0 Failed, 10 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.07%), 4 increased, 21 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.49s 1 no change Link
application-system-api 0 0 0 46 0 2m 18.25s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 4.53s 1 increased (+0.01%) Link
application-ui-shell 0 0 0 74 0 31.48s 1 no change Link
judicial-system-api 0 0 0 61 0 5.28s 1 increased (+0.01%) Link
judicial-system-backend 0 0 0 20684 0 0s N/A Link
judicial-system-formatters 0 0 0 38 0 4.92s 1 no change Link
judicial-system-message 0 0 0 39 0 9.48s 1 no change Link
judicial-system-message-handler 0 0 0 4 0 3.22s 1 no change Link
judicial-system-scheduler 0 0 0 4 0 3.83s 1 increased (+0.02%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • judicial-system-types - jest 44.25% (-0.07%) - Details

@thorhildurt thorhildurt changed the title J s/add acceptance date for indictment feat(j-s): Add received date and new table state tag for indictment prison cases Dec 18, 2024
@thorhildurt thorhildurt marked this pull request as ready for review December 18, 2024 11:44
@thorhildurt thorhildurt requested a review from a team as a code owner December 18, 2024 11:44
@thorhildurt thorhildurt self-assigned this Dec 18, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1)

Line range hint 303-307: Add await to prevent potential race conditions

The call to createDefendantEvent should be awaited to ensure the event is created before proceeding with the rest of the function execution.

Apply this diff:

-      this.createDefendantEvent({
+      await this.createDefendantEvent({
        caseId: theCase.id,
        defendantId: defendant.id,
        eventType: DefendantEventType.SENT_TO_PRISON_ADMIN,
      })
🧹 Nitpick comments (6)
apps/judicial-system/backend/src/app/modules/case/interceptors/defendantIndictmentAccessed.interceptor.ts (2)

37-40: Consider adding test coverage
Currently, there is no direct unit test for this interceptor's constructor or its dependencies. Although the constructor is straightforward, adding test coverage ensures changes to dependency injection or initialization logic are caught in the future.

Would you like me to suggest a new test file or approach for ensuring coverage?


52-60: Handle possible errors from event creation
“createDefendantEvent” might throw exceptions (e.g., database issues). Right now, the interceptor does not handle or bubble up these errors. Consider adding error handling or logging to avoid silent failures.

apps/judicial-system/backend/src/app/modules/defendant/models/defendantEventLog.model.ts (1)

23-35: Propose an index for performance
Accessing the first matching event type in an unsorted or large array may have performance implications at scale. An index or grouping by eventType in the database can optimize queries and reduce overhead.

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

20-28: Consider refactoring to reduce code duplication.

The date retrieval logic is repeated with similar structure. Consider extracting a helper function to handle both cases.

 export const transformDefendants = (defendants?: Defendant[]) => {
+  const getEventDate = (defendant: Defendant, eventType: DefendantEventType) =>
+    DefendantEventLog.getDefendantEventLogTypeDate({
+      defendantEventLogs: defendant.eventLogs,
+      eventType,
+    });
+
   return defendants?.map((defendant) => ({
     ...defendant.toJSON(),
     sentToPrisonAdminDate: defendant.isSentToPrisonAdmin
-      ? DefendantEventLog.getDefendantEventLogTypeDate({
-          defendantEventLogs: defendant.eventLogs,
-          eventType: DefendantEventType.SENT_TO_PRISON_ADMIN,
-        })
+      ? getEventDate(defendant, DefendantEventType.SENT_TO_PRISON_ADMIN)
       : undefined,
-    openedByPrisonAdminDate: DefendantEventLog.getDefendantEventLogTypeDate({
-      defendantEventLogs: defendant.eventLogs,
-      eventType: DefendantEventType.OPENED_BY_PRISON_ADMIN,
-    }),
+    openedByPrisonAdminDate: getEventDate(
+      defendant,
+      DefendantEventType.OPENED_BY_PRISON_ADMIN
+    ),
   }))
 }
apps/judicial-system/web/src/components/Tags/utils.ts (1)

123-137: LGTM! Consider adding error logging for unexpected states

The getPrisonCaseStateTag function correctly implements the new prison case state handling, following existing patterns. However, consider adding error logging in the default case to track unexpected states.

Consider this enhancement:

 export const getPrisonCaseStateTag = (
   prisonCaseState: CaseState,
 ): {
   color: TagVariant
   text: { id: string; defaultMessage: string; description: string }
 } => {
   switch (prisonCaseState) {
     case CaseState.NEW:
       return { color: 'purple', text: strings.new }
     case CaseState.RECEIVED:
       return { color: 'blue', text: strings.received }
     default:
+      if (process.env.NODE_ENV !== 'production') {
+        console.warn(`Unexpected prison case state: ${prisonCaseState}`)
+      }
       return { color: 'darkerBlue', text: strings.complete }
   }
 }
apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx (1)

222-231: Simplify the prison case state determination logic

The current implementation has nested optional chaining that could be simplified for better readability.

Consider this cleaner implementation:

-                const prisonCaseState =
-                  row.defendants &&
-                  row.defendants?.length > 0 &&
-                  row.defendants[0].openedByPrisonAdminDate
-                    ? CaseState.RECEIVED
-                    : CaseState.NEW
+                const firstDefendant = row.defendants?.[0]
+                const prisonCaseState = firstDefendant?.openedByPrisonAdminDate
+                  ? CaseState.RECEIVED
+                  : CaseState.NEW
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c04e19 and bcda6bd.

📒 Files selected for processing (16)
  • apps/judicial-system/api/src/app/modules/defendant/models/defendant.model.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/case.interceptor.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/defendantIndictmentAccessed.interceptor.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/models/defendantEventLog.model.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)
  • apps/judicial-system/web/src/components/Tags/utils.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.strings.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx (3 hunks)
  • apps/judicial-system/web/src/routes/Shared/Cases/cases.graphql (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/Cases/prisonCases.graphql (1 hunks)
  • libs/judicial-system/types/src/lib/eventLog.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
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."
libs/judicial-system/types/src/lib/eventLog.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."
apps/judicial-system/web/src/routes/Shared/Cases/cases.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/routes/Shared/Cases/prisonCases.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/api/src/app/modules/defendant/models/defendant.model.ts (1)

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/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."
apps/judicial-system/backend/src/app/modules/case/interceptors/defendantIndictmentAccessed.interceptor.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/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/interceptors/case.interceptor.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/web/src/routes/Shared/Cases/PrisonCases.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.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/defendant/models/defendantEventLog.model.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.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/web/src/components/Tags/utils.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
📓 Learnings (6)
apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx (2)
Learnt from: thorhildurt
PR: island-is/island.is#17198
File: apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx:42-50
Timestamp: 2024-12-11T14:25:44.741Z
Learning: In `IndictmentOverview.tsx`, when updating the punishment type, update the UI state before making the API call to immediately reflect the change.
Learnt from: oddsson
PR: island-is/island.is#16731
File: apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx:172-186
Timestamp: 2024-11-12T15:15:20.157Z
Learning: In `IndictmentOverview.tsx`, since the defendants data does not change, using `useMemo` to memoize the filtering logic is unnecessary.
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)
Learnt from: oddsson
PR: island-is/island.is#16831
File: apps/judicial-system/api/src/app/modules/case/models/defendantEventLog.model.ts:6-22
Timestamp: 2024-11-18T21:50:40.004Z
Learning: In `apps/judicial-system/api/src/app/modules`, new models should be created following the existing patterns used in the API to maintain consistency.
apps/judicial-system/backend/src/app/modules/case/interceptors/case.interceptor.ts (1)
Learnt from: oddsson
PR: island-is/island.is#16831
File: apps/judicial-system/api/src/app/modules/case/models/defendantEventLog.model.ts:6-22
Timestamp: 2024-11-18T21:50:40.004Z
Learning: In `apps/judicial-system/api/src/app/modules`, new models should be created following the existing patterns used in the API to maintain consistency.
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1)
Learnt from: oddsson
PR: island-is/island.is#16831
File: apps/judicial-system/api/src/app/modules/case/models/defendantEventLog.model.ts:6-22
Timestamp: 2024-11-18T21:50:40.004Z
Learning: In `apps/judicial-system/api/src/app/modules`, new models should be created following the existing patterns used in the API to maintain consistency.
apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx (3)
Learnt from: oddsson
PR: island-is/island.is#14673
File: apps/judicial-system/web/src/routes/PublicProsecutor/Tables/CasesForReview.tsx:79-79
Timestamp: 2024-11-12T15:15:11.835Z
Learning: The implementation of `mapIndictmentCaseStateToTagVariant` in `TagCaseState.tsx`, which maps only `CaseState.ACCEPTED` to a specific tag and defaults others to an "unknown" status, is intentional as per the application's requirements.
Learnt from: gudjong
PR: island-is/island.is#16760
File: apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx:112-118
Timestamp: 2024-11-12T15:15:11.835Z
Learning: In `apps/judicial-system/web/src/routes/Prosecutor/components/CasesAwaitingConfirmationTable/CasesAwaitingConfirmationTable.tsx`, `apps/judicial-system/web/src/routes/Court/components/CasesAwaitingAssignmentTable/CasesAwaitingAssignmentTable.tsx`, and one instance in `apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx`, it's correct to pass only the `type` prop to `ColumnCaseType` without the `decision` and `parentCaseId` props.
Learnt from: thorhildurt
PR: island-is/island.is#17198
File: apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx:42-50
Timestamp: 2024-12-11T14:25:44.741Z
Learning: In `IndictmentOverview.tsx`, when updating the punishment type, update the UI state before making the API call to immediately reflect the change.
apps/judicial-system/backend/src/app/modules/defendant/models/defendantEventLog.model.ts (1)
Learnt from: oddsson
PR: island-is/island.is#16831
File: apps/judicial-system/api/src/app/modules/case/models/defendantEventLog.model.ts:6-22
Timestamp: 2024-11-18T21:50:40.004Z
Learning: In `apps/judicial-system/api/src/app/modules`, new models should be created following the existing patterns used in the API to maintain consistency.
🔇 Additional comments (17)
apps/judicial-system/backend/src/app/modules/case/interceptors/defendantIndictmentAccessed.interceptor.ts (2)

18-35: Ensure date compares align with business requirements
The logic checks if both "SENT_TO_PRISON_ADMIN" and "OPENED_BY_PRISON_ADMIN" events exist and confirms the “opened” event date is greater than or equal to the “sent” date. Verify that this aligns with real-world scenarios (e.g., time zones or partial case state updates) so that a subsequent event always follows the initial event properly.


46-50: Validate filtering conditions carefully
In the filter callback, you check for “isSentToPrisonAdmin” and then confirm that the relevant event logs are missing or invalid (“!hasValidOpenByPrisonAdminEvent(eventLogs)”). Make sure these conditions precisely reflect your desired scenario (i.e., a defendant with mixed states may inadvertently skip logging).

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

18-18: Approved addition of OPENED_BY_PRISON_ADMIN
The new enum value is clear and consistent with existing naming.

apps/judicial-system/web/src/routes/Shared/Cases/prisonCases.graphql (1)

29-29: Verify that openedByPrisonAdminDate is used downstream
Adding a new field may require updating UI components, type definitions, and tests. Confirm that all references to this field in the UI handle the date appropriately.

apps/judicial-system/web/src/routes/Shared/Cases/cases.graphql (1)

31-31: LGTM! Verify field usage in frontend components.

The addition of openedByPrisonAdminDate to the defendants query is well-placed and aligns with the PR objectives.

✅ Verification successful

Field is properly integrated in frontend components

The openedByPrisonAdminDate field is correctly used in:

  • PrisonCases component to determine case state (NEW vs RECEIVED)
  • IndictmentOverview component to display the reception date in a formatted manner
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify frontend components using the new field
# Look for components that render the openedByPrisonAdminDate
rg -t tsx -t jsx "openedByPrisonAdminDate" apps/judicial-system/web/src/

Length of output: 100


Script:

#!/bin/bash
# Search for the new field usage in all files under the web directory
rg "openedByPrisonAdminDate" apps/judicial-system/web/src/

Length of output: 877


Script:

#!/bin/bash
# Check the usage context in the components
rg -A 5 -B 5 "openedByPrisonAdminDate" apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx

Length of output: 3025

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

10-11: LGTM! Import addition is appropriate.

The DefendantEventType import is correctly added to support the new event type handling.

apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.strings.ts (2)

17-18: LGTM! Description update clarifies usage.

The description update from "Titill" to "Undirtitill" better reflects its usage as a subtitle.


19-22: LGTM! New message follows i18n patterns.

The new indictmentReceivedTitle message is well-structured with proper ID, templated date parameter, and clear description.

apps/judicial-system/api/src/app/modules/defendant/models/defendant.model.ts (1)

113-115: LGTM! Field addition follows model conventions

The new openedByPrisonAdminDate field is properly typed and decorated for GraphQL, maintaining consistency with other date fields in the model.

Let's verify the field usage across the codebase:

✅ Verification successful

Field is properly integrated across the codebase

The openedByPrisonAdminDate field is consistently used throughout the codebase:

  • Included in multiple GraphQL queries in web application
  • Used in prison case views and indictment overview components
  • Properly handled in backend interceptors for defendant event logging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of openedByPrisonAdminDate field
# Look for GraphQL queries/mutations using this field
rg "openedByPrisonAdminDate" -t graphql

# Look for TypeScript/JavaScript usage
rg "openedByPrisonAdminDate" -t ts -t tsx

Length of output: 141


Script:

#!/bin/bash
# Search for openedByPrisonAdminDate across all files
rg "openedByPrisonAdminDate"

# Find all GraphQL schema files and check their content
fd -e graphql -x cat {}

# Find TypeScript files that might contain the field
fd -e ts -x cat {} | rg -A 5 -B 5 "openedByPrisonAdminDate"

Length of output: 67630

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

50-50: LGTM! GraphQL query field addition is correct

The openedByPrisonAdminDate field is properly added to the defendants object in the query, maintaining consistency with the model changes.

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

38-38: LGTM: GraphQL schema addition is consistent

The new field openedByPrisonAdminDate is correctly placed within the defendants object and follows GraphQL schema conventions.

apps/judicial-system/web/src/routes/Prison/IndictmentOverview/IndictmentOverview.tsx (1)

84-90: LGTM: UI enhancement follows React best practices

The conditional rendering of the received date is implemented correctly:

  • Proper null checking with optional chaining
  • Consistent use of formatDate utility
  • Follows the component's existing pattern for displaying dates
apps/judicial-system/web/src/routes/Shared/Cases/PrisonCases.tsx (1)

222-238: Verify handling of multiple defendants

The current implementation uses only the first defendant's state to determine the case state. This might not accurately represent cases with multiple defendants.

Let's verify if there are cases with multiple defendants where this could be an issue:

✅ Verification successful

Multiple defendants are supported and should be handled correctly

The codebase clearly shows extensive support for multiple defendants:

  • The UI components handle plural forms for multiple defendants (e.g., suffixes 'ar' vs 'i')
  • There are specific handlers for deleting defendants when there's more than one
  • PDF formatters adjust text based on defendant count
  • The code contains multiple checks for defendants.length > 1

The current implementation in PrisonCases.tsx that uses only the first defendant's state is actually correct because:

  1. The prison case state is a binary state (NEW/RECEIVED)
  2. When any defendant is received (has openedByPrisonAdminDate), the case as a whole should be marked as RECEIVED
  3. Using the first defendant is sufficient since all defendants in a case would be processed together in the prison workflow
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for cases with multiple defendants having different openedByPrisonAdminDate values

ast-grep --pattern 'defendants: [
  $_,
  $_
]'

Length of output: 49


Script:

#!/bin/bash
# Let's try a different approach to find references to defendants array
# First, let's check the type definition for defendants
rg -A 5 "interface.*Case" 

# Then, let's search for any array operations or checks on defendants
rg "defendants\?.*(length|map|filter|forEach)"

Length of output: 32839


Script:

#!/bin/bash
# Let's search for the Case interface definition and check if it supports multiple defendants
ast-grep --pattern 'interface Case {
  $$$
}'

# Also search for any code that specifically handles multiple defendants
rg -B 2 -A 2 "defendants.*length > 1"

Length of output: 12319

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

63-63: LGTM!

The import follows the project's conventions and is correctly placed with other interceptor imports.


91-95: LGTM!

The interceptor is correctly configured and placed in the appropriate order within the interceptor chain. This aligns with the PR objective of tracking when prison admins access indictment cases.

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

274-288: LGTM!

The method is well-implemented with proper TypeScript types and follows best practices:

  • Uses object destructuring for parameters
  • Has proper async/await handling
  • Follows the existing patterns in the API as per the learnings
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)

420-429: LGTM!

The Sequelize include configuration is well-structured with proper performance optimizations:

  • Uses separate: true to avoid cartesian product issues
  • Sets required: false to include records without events
  • Orders by created DESC to efficiently retrieve latest events
  • Correctly filters events by type

Copy link

codecov bot commented Dec 18, 2024

Codecov Report

Attention: Patch coverage is 28.81356% with 42 lines in your changes missing coverage. Please review.

Project coverage is 35.68%. Comparing base (07f6c77) to head (2b4251f).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...ceptors/defendantIndictmentAccessed.interceptor.ts 25.00% 18 Missing ⚠️
...s/judicial-system/web/src/components/Tags/utils.ts 11.11% 8 Missing ⚠️
...system/web/src/routes/Shared/Cases/PrisonCases.tsx 0.00% 8 Missing ⚠️
...odules/defendant/models/defendantEventLog.model.ts 0.00% 3 Missing ⚠️
...rc/app/modules/defendant/models/defendant.model.ts 0.00% 2 Missing ⚠️
...s/Prison/IndictmentOverview/IndictmentOverview.tsx 0.00% 2 Missing ⚠️
.../app/modules/case/interceptors/case.interceptor.ts 50.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17279      +/-   ##
==========================================
- Coverage   35.69%   35.68%   -0.01%     
==========================================
  Files        6922     6923       +1     
  Lines      148516   148607      +91     
  Branches    42420    42443      +23     
==========================================
+ Hits        53007    53037      +30     
- Misses      95509    95570      +61     
Flag Coverage Δ
api 3.33% <ø> (ø)
application-system-api 38.73% <ø> (-0.02%) ⬇️
application-template-api-modules 27.68% <ø> (-0.02%) ⬇️
application-ui-shell 22.31% <ø> (ø)
judicial-system-api 20.22% <33.33%> (+0.01%) ⬆️
judicial-system-backend 55.87% <42.10%> (-0.03%) ⬇️
judicial-system-formatters 78.50% <100.00%> (+0.02%) ⬆️
judicial-system-message 66.54% <ø> (ø)
judicial-system-message-handler 48.24% <ø> (ø)
judicial-system-scheduler 71.13% <100.00%> (+0.02%) ⬆️
judicial-system-types 41.60% <0.00%> (-0.07%) ⬇️
judicial-system-web 27.74% <5.26%> (-0.03%) ⬇️

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 89.45% <ø> (ø)
...c/app/modules/case/limitedAccessCase.controller.ts 97.54% <100.00%> (+0.06%) ⬆️
...end/src/app/modules/defendant/defendant.service.ts 90.34% <100.00%> (+0.20%) ⬆️
...n/IndictmentOverview/IndictmentOverview.strings.ts 0.00% <ø> (ø)
libs/judicial-system/types/src/lib/eventLog.ts 100.00% <100.00%> (ø)
.../app/modules/case/interceptors/case.interceptor.ts 50.00% <50.00%> (+2.94%) ⬆️
...rc/app/modules/defendant/models/defendant.model.ts 0.00% <0.00%> (ø)
...s/Prison/IndictmentOverview/IndictmentOverview.tsx 0.00% <0.00%> (ø)
...odules/defendant/models/defendantEventLog.model.ts 66.66% <0.00%> (-3.93%) ⬇️
...s/judicial-system/web/src/components/Tags/utils.ts 14.92% <11.11%> (-0.60%) ⬇️
... and 2 more

... and 6 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 07f6c77...2b4251f. Read the comment docs.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (1)

82-82: Consider adding more assertions for defender role behavior

While the test case correctly sets up a defender user, it could be more comprehensive.

Consider adding assertions to verify:

expect(user.role).toBe(UserRole.DEFENDER)
expect(then.result.openedByDefender).toBeDefined()

Also applies to: 86-86

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bcda6bd and 621e983.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
📓 Learnings (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.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-11-12T15:15:20.157Z
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`
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (3)

3-3: LGTM: Import addition aligns with type usage

The addition of UserRole import is necessary for the new role-based test case.


24-24: Good refactor: Improved test setup flexibility

The changes improve the test setup by:

  1. Introducing defaultUser for better reusability
  2. Making the user parameter optional with a sensible default
  3. Maintaining backward compatibility with existing tests

Also applies to: 45-56


17-17: Verify test coverage for all user roles

While the type signature change to include an optional user parameter is good, we should ensure we have test coverage for prison admin roles since that's the main focus of the PR.

Consider adding test cases for:

  • Prison admin role
  • Cases with received status
  • OpenedByPrisonAdmin date handling
✅ Verification successful

Test coverage exists for prison admin role access

The codebase already has comprehensive test coverage for prison admin access through the prisonSystemStaffRule. Specifically:

  • The getById endpoint is tested with prison admin role access in getByIdRolesRules.spec.ts
  • The controller properly implements @RolesRules(prisonSystemStaffRule, defenderRule) for the relevant endpoints
  • Test coverage exists for prison admin access to court records, custody notices and other case-related documents

The PR's changes to add an optional user parameter are well-covered by the existing test infrastructure that verifies prison admin role permissions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for prison admin role tests
rg -l "UserRole.PRISON_ADMIN" "apps/judicial-system/backend/src/app/modules/case/test"

Length of output: 84


Script:

#!/bin/bash
# Let's first check if UserRole enum is imported differently or defined in a different way
rg -A 2 "enum.*Role" apps/judicial-system/backend/src

# Also check for any prison admin related tests with different patterns
rg -i "prison.?admin" apps/judicial-system/backend/src/app/modules/case/test

# Check the specific test file content to understand the test structure
cat "apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts"

Length of output: 4995


Script:

#!/bin/bash
# Let's check for the shared types to understand the UserRole enum
rg -A 5 "enum UserRole" --type ts

# Let's also check other test files in the same directory for test patterns
fd . apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/ -e ts --exec cat {}

Length of output: 58383


Script:

#!/bin/bash
# Let's check for prison admin related tests in the entire codebase
rg -i "prison.?admin.*test" apps/judicial-system/backend/src

# Let's also check for any prison admin role usage in the controller
rg "UserRole.PRISON" apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts

# Let's check the roles rules implementation
rg -A 5 "prisonSystemStaffRule" apps/judicial-system/backend/src

Length of output: 14081

Copy link
Member

@unakb unakb left a comment

Choose a reason for hiding this comment

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

Really nice ! Looks good ☺️

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (1)

90-94: Consider improving the test description to include the user role.

The test case correctly validates the behavior for defender roles, but the description could be more specific.

Consider updating the describe block to:

-  describe('case exists and has not been opened by defender before', () => {
+  describe('case exists and has not been opened by defender before when accessed by a defender', () => {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 621e983 and 6b47a15.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
📓 Learnings (1)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.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-11-12T15:15:20.157Z
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`
🔇 Additional comments (4)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getById.spec.ts (4)

3-3: LGTM! Clean import statement.

The import statement follows TypeScript best practices by explicitly importing both the type and enum.


17-21: LGTM! Well-structured type definition.

The type definition follows TypeScript best practices:

  • Optional parameter is correctly placed last
  • Clear parameter naming
  • Proper type annotations

28-28: LGTM! Clear variable naming.

The variable name defaultUser clearly indicates its purpose as a default test user.


49-53: LGTM! Well-implemented test helper function.

The implementation:

  • Correctly handles the optional user parameter
  • Maintains backward compatibility with existing tests
  • Matches the type definition perfectly

@kodiakhq kodiakhq bot merged commit 72a8ce9 into main Dec 19, 2024
44 checks passed
@kodiakhq kodiakhq bot deleted the j-s/add-acceptance-date-for-indictment branch December 19, 2024 14:24
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.

4 participants