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

chore(j-s): Set current user as prosecutor in new indictments #18005

Merged
merged 18 commits into from
Feb 19, 2025

Conversation

oddsson
Copy link
Member

@oddsson oddsson commented Feb 18, 2025

Set current user as prosecutor in new indictments

Asana

What

In #17921 we moved the prosecutor selection to the defendant screen. There were a few issues with that PR that this PR fixes. The main things are

  • When creating a new indictment, the current user should be selected by default as a prosecutor.
  • The CreateCase endpoint needs to have a prosecutorId field to be able to create cases with prosecutors.

This makes the changes done to the e2e tests, where a prosecutor was selected manually, redundant.

A note on code quality

There is a change in this PR that is not ideal in terms of code quality.

My issue with this is that the ProsecutorSelection component is now being controlled in two places, in the component itself and via the onChange prop. The reason for this is that the prosectors are fetched inside the component and if an indictment is being created, we need to select from that list, but if the case exists, then we don't use that list. I have a few ideas on how to potentially fix this, but all of them are somewhat complex in implementation and I feel like it's not worth the effort. If you strongly disagree, then let's talk about it 😉

Why

Better UX

Screenshots / Gifs

Screen.Recording.2025-02-18.at.10.54.31.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

    • Cases can now optionally include a prosecutor identifier, allowing more flexible case creation, especially for indictments.
    • The prosecutor selection interface has been enhanced with improved default handling, ensuring a prosecutor’s details are always available.
    • The createCase mutation response now includes a type field, providing additional information about the created case.
  • Refactor

    • The workflow for assigning prosecutor details during case creation has been streamlined, simplifying the selection process and reducing redundant steps.
  • Bug Fixes

    • Removed unnecessary dependencies on prosecutor selection in the defendant validation logic, enhancing the clarity and reliability of the case management process.

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request introduces an optional prosecutorId field to the case creation input structures. The new field, along with its validation and GraphQL decorations, is added in both API and backend DTOs. The backend service logic for case creation has been updated to conditionally assign the prosecutorId based on the case type. Simultaneously, UI components and hooks managing prosecutor selection have been refined, and related end-to-end tests adjusted by removing manual selection steps. Minor formatting and import cleanups were also performed.

Changes

File(s) Change Summary
apps/judicial-system/api/.../createCase.input.ts
apps/judicial-system/backend/.../createCase.dto.ts
Added optional prosecutorId field with validation and GraphQL decorators.
apps/judicial-system/backend/.../case.service.ts Modified the create() method to conditionally assign prosecutorId based on case type and user role.
apps/judicial-system/web/src/components/ProsecutorSelection/ProsecutorSelection.tsx
apps/judicial-system/web/src/routes/Prosecutor/.../Defendant.tsx
apps/judicial-system/web/src/routes/Prosecutor/components/ProsecutorSection/ProsecutorSection.tsx
Updated UI components to simplify prosecutor selection logic and working case state management.
apps/judicial-system/web/src/utils/hooks/useCase/index.ts Enhanced the createCase hook to include the selected prosecutor's ID in the mutation input.
apps/judicial-system/web/src/routes/Court/Indictments/Summary/Summary.tsx Removed an unused import (format from path).
apps/system-e2e/src/tests/judicial-system/regression/indictment-tests.spec.ts Removed test steps related to explicit prosecutor selection during indictment case creation.

Possibly related PRs

  • fix(j-s): Generated PDFs #16625: The changes in the main PR, which involve adding a prosecutorId field to the CreateCaseInput and CreateCaseDto classes, are directly related to the modifications in the retrieved PR that enhance the visibility of generated PDF files for prosecutors, as both involve the handling of prosecutor-related data in the case management system.
  • fix(j-s): Display correct verdict appeal info for defenders  #16533: The changes in the main PR, which involve adding a prosecutorId field to the CreateCaseInput and CreateCaseDto classes, are related to the modifications in the retrieved PR that enhance the handling of defendants and their appeal deadlines, as both involve updates to the case management structure and data handling in the judicial system.
  • chore(j-s): Move prosecutor selection from processing to defendant screen #17876: The changes in the main PR, which involve adding a prosecutorId field to the CreateCaseInput and modifying the create method in CaseService, are related to the retrieved PR as both involve the handling and selection of the prosecutor in the case creation process.

Suggested labels

automerge

Suggested reviewers

  • thorhildurt

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c57b1e and e82ea33.

📒 Files selected for processing (1)
  • apps/judicial-system/web/src/utils/hooks/useCase/createCase.graphql (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/web/src/utils/hooks/useCase/createCase.graphql
🔇 Additional comments (1)
apps/judicial-system/web/src/utils/hooks/useCase/createCase.graphql (1)

4-4: New Field "type" Added to Mutation Response

The addition of the type field on line 4 enriches the mutation response by providing extra context regarding the created case. Please ensure that the backend GraphQL type definitions and resolvers have been updated to support this new field and that the frontend components consuming the mutation are adjusted accordingly.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@oddsson oddsson changed the title J s/prosecutor section refactor chore(j-s): Set current user as prosecutor in new indictments Feb 18, 2025
Copy link

nx-cloud bot commented Feb 18, 2025

View your CI Pipeline Execution ↗ for commit 6aebb66.

Command Status Duration Result
nx run-many --target=build --projects=judicial-... ✅ Succeeded 17s View ↗
nx run-many --target=build --projects=judicial-... ✅ Succeeded 13s View ↗
nx run-many --projects judicial-system-backend ... ✅ Succeeded 1s View ↗
nx run-many --projects judicial-system-api,judi... ✅ Succeeded 1s View ↗
nx run-many --target=build --projects=system-e2... ✅ Succeeded 2s View ↗
nx run-many --target=lint --projects=judicial-s... ✅ Succeeded 1s View ↗
nx run-many --target=codegen/frontend-client --... ✅ Succeeded 13s View ↗
nx run-many --target=codegen/backend-schema --a... ✅ Succeeded 24s View ↗

☁️ Nx Cloud last updated this comment at 2025-02-19 15:21:17 UTC

@oddsson oddsson marked this pull request as ready for review February 18, 2025 11:03
@oddsson oddsson requested a review from a team as a code owner February 18, 2025 11:03
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 (3)
apps/judicial-system/web/src/routes/Prosecutor/components/ProsecutorSection/ProsecutorSection.tsx (1)

16-29: Consider memoizing the setProsecutor function.

The setProsecutor function is recreated on every render. Consider using useCallback to memoize it:

-const setProsecutor = async (prosecutorId: string) => {
+const setProsecutor = useCallback(async (prosecutorId: string) => {
   if (workingCase) {
     const updatedCase = await updateCase(workingCase.id, {
       prosecutorId: prosecutorId,
     })

     const prosecutor = updatedCase?.prosecutor

     setWorkingCase((prevWorkingCase) => ({
       ...prevWorkingCase,
       prosecutor,
     }))
   }
-}
+}, [workingCase, updateCase, setWorkingCase])
apps/judicial-system/web/src/components/ProsecutorSelection/ProsecutorSelection.tsx (2)

77-91: Simplify the onChange handler logic.

The current implementation can be simplified by extracting the prosecutor update logic:

-onChange={(value) => {
-  const id = value?.value
-
-  if (id && typeof id === 'string') {
-    if (!workingCase.id) {
-      const prosecutor = data?.users?.find((p) => p.id === id)
-
-      setWorkingCase((prevWorkingCase) => ({
-        ...prevWorkingCase,
-        prosecutor,
-      }))
-    } else {
-      onChange(id)
-    }
-  }
-}}
+onChange={(value) => {
+  const id = value?.value
+  if (!id || typeof id !== 'string') return
+
+  if (!workingCase.id) {
+    const prosecutor = data?.users?.find((p) => p.id === id)
+    setWorkingCase((prev) => ({ ...prev, prosecutor }))
+    return
+  }
+
+  onChange(id)
+}}

41-64: Optimize eligibleProsecutors memo dependencies.

The eligibleProsecutors memo depends on individual properties from workingCase. Consider creating a separate memo for the institution ID to reduce unnecessary recalculations:

+const institutionId = useMemo(
+  () => (workingCase.id ? workingCase.prosecutorsOffice?.id : currentUser?.institution?.id),
+  [workingCase.id, workingCase.prosecutorsOffice?.id, currentUser?.institution?.id]
+)

 const eligibleProsecutors: Option<string>[] = useMemo(() => {
   if (!data?.users) {
     return []
   }

   return data.users
     .filter(
       (user) =>
         user.role === UserRole.PROSECUTOR &&
-        user.institution?.id === (workingCase.id
-          ? workingCase.prosecutorsOffice?.id
-          : currentUser?.institution?.id),
+        user.institution?.id === institutionId,
     )
     .map(({ id, name }) => ({
       label: name ?? '',
       value: id,
     }))
-}, [currentUser?.institution?.id, data?.users, workingCase.id, workingCase.prosecutorsOffice?.id])
+}, [data?.users, institutionId])
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1b49973 and ff2faf7.

📒 Files selected for processing (9)
  • apps/judicial-system/api/src/app/modules/case/dto/createCase.input.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/dto/createCase.dto.ts (2 hunks)
  • apps/judicial-system/web/src/components/ProsecutorSelection/ProsecutorSelection.tsx (2 hunks)
  • apps/judicial-system/web/src/routes/Court/Indictments/Summary/Summary.tsx (0 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (2 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/components/ProsecutorSection/ProsecutorSection.tsx (2 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCase/index.ts (1 hunks)
  • apps/system-e2e/src/tests/judicial-system/regression/indictment-tests.spec.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • apps/judicial-system/web/src/routes/Court/Indictments/Summary/Summary.tsx
  • apps/system-e2e/src/tests/judicial-system/regression/indictment-tests.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/web/src/utils/hooks/useCase/index.ts
  • apps/judicial-system/backend/src/app/modules/case/dto/createCase.dto.ts
  • apps/judicial-system/web/src/routes/Prosecutor/components/ProsecutorSection/ProsecutorSection.tsx
  • apps/judicial-system/api/src/app/modules/case/dto/createCase.input.ts
  • apps/judicial-system/web/src/components/ProsecutorSelection/ProsecutorSelection.tsx
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
🧠 Learnings (1)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (2)
Learnt from: oddsson
PR: island-is/island.is#17921
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx:457-459
Timestamp: 2025-02-12T08:46:49.953Z
Learning: In the judicial system web app, if a case has been saved (has workingCase.id), it is guaranteed to have a prosecutor set and they cannot be removed. Therefore, prosecutor selection validation is only needed for new cases.
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.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (8)
apps/judicial-system/api/src/app/modules/case/dto/createCase.input.ts (1)

79-82: LGTM! Well-structured field addition.

The new prosecutorId field is properly decorated with GraphQL and validation decorators, following NestJS best practices.

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

95-98: LGTM! Proper validation setup.

The new prosecutorId field is correctly decorated with validation and Swagger decorators, ensuring proper UUID validation and API documentation.

apps/judicial-system/web/src/routes/Prosecutor/components/ProsecutorSection/ProsecutorSection.tsx (1)

12-12: LGTM! Clean component simplification.

The removal of unnecessary props and interface simplifies the component's API, making it more maintainable.

apps/judicial-system/web/src/components/ProsecutorSelection/ProsecutorSelection.tsx (1)

24-34: LGTM! Smart fallback to current user.

The selectedProsecutor logic intelligently falls back to the current user when no prosecutor is selected, aligning with the PR's objective.

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

195-195: LGTM!

The addition of prosecutorId to the case creation input is correct and aligns with the PR objectives.

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (2)

461-461: LGTM!

The simplification of step validation to only check defendant information is correct, as prosecutor selection is now handled automatically.


476-478: LGTM!

The simplified rendering of ProsecutorSection without props is correct, as the prosecutor selection is now controlled internally.

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

742-746: LGTM!

The conditional assignment of prosecutorId is well-implemented:

  • For indictment cases: Uses the provided prosecutorId
  • For other cases: Uses the user's id if they are a prosecutor
  • Otherwise: Remains undefined

This change correctly implements the automatic prosecutor selection for new indictments while maintaining the existing behavior for other case types.

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.

Works! 👌

@oddsson oddsson enabled auto-merge February 19, 2025 09:33
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/case.service.ts (1)

759-763: LGTM! The prosecutor assignment logic is correct.

The conditional assignment of prosecutorId correctly implements the PR objective:

  • For indictment cases, it uses the provided prosecutorId
  • For non-indictment cases, it maintains the existing behavior

Consider improving readability by extracting the condition into a separate variable:

-            prosecutorId: isIndictmentCase(caseToCreate.type)
-              ? caseToCreate.prosecutorId
-              : user.role === UserRole.PROSECUTOR
-              ? user.id
-              : undefined,
+            prosecutorId: isIndictmentCase(caseToCreate.type)
+              ? caseToCreate.prosecutorId
+              : isProsecutor(user)
+              ? user.id
+              : undefined,

And add a helper function at the top of the file:

const isProsecutor = (user: TUser): boolean => user.role === UserRole.PROSECUTOR;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d957d16 and 0c57b1e.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/create.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

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
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
🔇 Additional comments (1)
apps/judicial-system/backend/src/app/modules/case/test/caseController/create.spec.ts (1)

71-71: LGTM! Test coverage looks good.

The test correctly verifies that the prosecutorId is passed to the case creation, aligning with the PR objective of setting the current user as prosecutor in new indictments.

@oddsson oddsson added the skip-nx-cache Skip NX's cache in a pull request label Feb 19, 2025
@oddsson oddsson disabled auto-merge February 19, 2025 14:56
@oddsson oddsson enabled auto-merge February 19, 2025 15:02
@oddsson oddsson added this pull request to the merge queue Feb 19, 2025
Merged via the queue into main with commit 3b0ae2f Feb 19, 2025
30 checks passed
@oddsson oddsson deleted the j-s/prosecutor-section-refactor branch February 19, 2025 15:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
skip-nx-cache Skip NX's cache in a pull request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants