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): Enable setting civil claimants #15996

Merged
merged 111 commits into from
Sep 25, 2024
Merged

feat(j-s): Enable setting civil claimants #15996

merged 111 commits into from
Sep 25, 2024

Conversation

oddsson
Copy link
Member

@oddsson oddsson commented Sep 13, 2024

Enable setting civil claimants

Asana

What

  • Enable setting civil claimants and their legal advocates.
  • Refactor the component responsible for setting defender info. We now talk about advocates. This is more flexible some legal advocates in our system are not defending anyone, but rather act as a spokesperson or legal rights protectors.

Screenshots / Gifs

Screenshot 2024-09-24 at 11 04 05

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

Release Notes

  • New Features

    • Introduced InputAdvocate component to replace the previous DefenderInput for enhanced advocate information handling.
    • Added support for multiple advocate types, including 'defender', 'spokesperson', and 'legal rights protector'.
    • Implemented new GraphQL mutations for creating, updating, and deleting civil claimants.
  • Enhancements

    • Improved civil claimant management with new state variables and rendering logic in the processing workflow.
    • Expanded input fields and validation for civil claimants, ensuring better data handling.
    • Added new error messages for civil claimant operations to enhance user feedback.
  • Bug Fixes

    • Simplified logic in various components for better performance and maintainability.
  • Documentation

    • Updated message strings to support new civil claimant functionalities.

Copy link
Contributor

coderabbitai bot commented Sep 13, 2024

Walkthrough

The changes involve the refactoring of components and the introduction of new functionalities related to advocates and civil claimants within the judicial system application. The DefenderInput component has been replaced with InputAdvocate, which supports multiple advocate types. Additionally, new GraphQL mutations for creating, updating, and deleting civil claimants have been introduced, along with enhancements to the handling of civil claimants in the processing workflow.

Changes

File Change Summary
apps/judicial-system/web/src/components/DefenderInfo/DefenderInfo.tsx Replaced DefenderInput with InputAdvocate, updated props accordingly.
apps/judicial-system/web/src/components/Inputs/Input.strings.ts Renamed exported constant from defenderInput to strings, added new message entries for spokesperson labels.
apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx Refactored DefenderInput to InputAdvocate, modified props for advocate types, and added new properties.
apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx Simplified logic in useEffect to handle undefined values.
apps/judicial-system/web/src/components/index.ts Removed export of DefenderInput, added exports for InputAdvocate, InputName, and InputNationalId.
apps/judicial-system/web/src/routes/Court/Indictments/Defender/SelectDefender.tsx Replaced DefenderInput with InputAdvocate, updated props.
apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx Removed import of core from @island.is/judicial-system-web/messages.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx Enhanced handling of civil claimants with new state variables and functions.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/processing.strings.ts Removed and added message definitions related to civil claims.
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/createCivilClaimant.graphql Introduced CreateCivilClaimant mutation.
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/deleteCivilClaimant.graphql Introduced DeleteCivilClaimant mutation.
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts Introduced useCivilClaimants hook for managing civil claimants.
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/updateCivilClaimant.graphql Introduced UpdateCivilClaimant mutation.
apps/judicial-system/web/src/utils/hooks/index.ts Added export for useCivilClaimants.
apps/judicial-system/web/messages/Core/errors.ts Added new error messages for civil claimant operations.

Possibly related PRs

  • feat(j-s): Civil Demands #16010: This PR introduces a new field for civil demands within the indictment process, which is directly related to the management of civil claimants in the judicial system.
  • feat(j-s): Data structure for civil claimants #16059: This PR establishes a data structure for civil claimants, including the creation of a new model and associated functionalities, which aligns with the changes made in the main PR regarding civil claims.
  • feat(j-s): Civil Claimants Info Card #16113: This PR focuses on displaying information about civil claimants on an info card, enhancing the visibility and management of civil claims, which is a key aspect of the main PR's objectives.

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

codecov bot commented Sep 13, 2024

Codecov Report

Attention: Patch coverage is 2.06612% with 237 lines in your changes missing coverage. Please review.

Project coverage is 36.64%. Comparing base (23d2dbd) to head (7da5d73).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...s/Prosecutor/Indictments/Processing/Processing.tsx 0.00% 113 Missing ⚠️
...system/web/src/components/Inputs/InputAdvocate.tsx 1.49% 66 Missing ⚠️
...tem/web/src/utils/hooks/useCivilClaimants/index.ts 2.12% 46 Missing ⚠️
apps/judicial-system/web/src/utils/validate.ts 25.00% 6 Missing ⚠️
...-system/web/src/utils/hooks/useDefendants/index.ts 0.00% 5 Missing ⚠️
...stem/web/src/components/Inputs/InputNationalId.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #15996      +/-   ##
==========================================
- Coverage   36.72%   36.64%   -0.08%     
==========================================
  Files        6765     6764       -1     
  Lines      139147   139273     +126     
  Branches    39531    39591      +60     
==========================================
- Hits        51096    51040      -56     
- Misses      88051    88233     +182     
Flag Coverage Δ
judicial-system-web 28.20% <2.06%> (-0.38%) ⬇️

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

Files with missing lines Coverage Δ
apps/judicial-system/web/messages/Core/errors.ts 100.00% <ø> (ø)
...m/web/src/components/DefenderInfo/DefenderInfo.tsx 2.22% <ø> (ø)
...-system/web/src/components/Inputs/Input.strings.ts 100.00% <100.00%> (ø)
...utes/Court/Indictments/Defender/SelectDefender.tsx 0.00% <ø> (ø)
...src/routes/Court/Indictments/Subpoena/Subpoena.tsx 0.00% <ø> (ø)
...cutor/Indictments/Processing/processing.strings.ts 0.00% <ø> (ø)
...stem/web/src/components/Inputs/InputNationalId.tsx 3.22% <0.00%> (+0.19%) ⬆️
...-system/web/src/utils/hooks/useDefendants/index.ts 2.38% <0.00%> (+0.20%) ⬆️
apps/judicial-system/web/src/utils/validate.ts 40.69% <25.00%> (-0.51%) ⬇️
...tem/web/src/utils/hooks/useCivilClaimants/index.ts 2.12% <2.12%> (ø)
... and 2 more

... and 17 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 23d2dbd...7da5d73. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 13, 2024

Datadog Report

All test runs d1965da 🔗

43 Total Test Services: 0 Failed, 41 Passed
🔻 Test Sessions change in coverage: 2 decreased, 3 increased, 165 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
air-discount-scheme-web 0 0 0 2 0 8.94s 1 no change Link
api 0 0 0 4 0 2.72s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 12.38s 1 no change Link
api-domains-communications 0 0 0 5 0 30.22s 1 no change Link
api-domains-license-service 0 0 0 0 0 563.76ms 1 no change Link
application-api-files 0 0 0 12 0 6.16s 1 no change Link
application-core 0 0 0 90 0 19.84s 1 no change Link
application-system-api 0 0 0 111 2 3m 55.39s 1 no change Link
application-template-api-modules 0 0 0 109 0 1m 55.22s 1 no change Link
application-templates-accident-notification 0 0 0 98 0 19.14s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • judicial-system-api - jest 20.1% (-0.48%) - Details
  • judicial-system-web - jest 32.71% (-0.26%) - Details

@oddsson oddsson marked this pull request as ready for review September 24, 2024 11:46
@oddsson oddsson requested a review from a team as a code owner September 24, 2024 11:46
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: 16

Outside diff range and nitpick comments (17)
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/createCivilClaimant.graphql (1)

1-5: LGTM! Consider returning additional fields for flexibility.

The CreateCivilClaimant mutation is well-structured and aligns with GraphQL best practices and the PR objectives. It's correctly placed within the NextJS project structure.

Consider returning additional fields beyond just the id. This could provide more flexibility for client-side operations without requiring additional queries. For example:

mutation CreateCivilClaimant($input: CreateCivilClaimantInput!) {
  createCivilClaimant(input: $input) {
    id
    name
    type
    # Add other relevant fields
  }
}

This change would allow clients to immediately use more information about the newly created civil claimant without needing a separate query.

apps/judicial-system/web/src/components/Inputs/Input.strings.ts (2)

27-31: Approve spokesperson email label, but update description

The addition of spokespersonEmailLabel is consistent with the PR objectives and follows the existing pattern. However, the description seems to be copied from the name label.

Consider updating the description to be more specific to the email field:

   spokespersonEmailLabel: {
     id: 'judicial.system.core:defender_input.spokesperson_email_label',
     defaultMessage: 'Netfang réttargæslumanns',
-    description: 'Notaður sem titill á inputi fyrir skipaðan verjanda.',
+    description: 'Notaður sem titill á inputi fyrir netfang réttargæslumanns.',
   },

45-49: Approve spokesperson phone number label, but update description

The addition of spokespersonPhoneNumberLabel is consistent with the PR objectives and follows the existing pattern. However, the description seems to be copied from the name label.

Consider updating the description to be more specific to the phone number field:

   spokespersonPhoneNumberLabel: {
     id: 'judicial.system.core:defender_input.spokesperson_phone_number_label',
     defaultMessage: 'Símanúmer réttargæslumanns',
-    description: 'Notaður sem titill á inputi fyrir skipaðan verjanda.',
+    description: 'Notaður sem titill á inputi fyrir símanúmer réttargæslumanns.',
   },
apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx (1)

79-79: Simplification improves code, but consider consistency and performance

The change simplifies the code and ensures setInputValue always receives a defined value, which is good. However, consider the following points:

  1. Ensure this change doesn't alter the intended behavior if the previous condition was purposeful.
  2. For consistency, consider updating the InputMask component's value prop to use the same pattern: value={inputValue ?? ''}.
  3. For performance, you could potentially move the value ?? '' logic outside the useEffect to avoid unnecessary re-renders.

Consider refactoring to improve consistency and potentially performance:

const [inputValue, setInputValue] = useState<string>('')

useEffect(() => {
  setErrorMessage(undefined)
  if (value !== undefined) {
    setInputValue(value)
  }
}, [value])

// ...

<InputMask
  // ...
  value={inputValue}
  // ...
>
  {/* ... */}
</InputMask>

This approach ensures consistency between the useEffect and the InputMask component, and potentially reduces unnecessary re-renders.

apps/judicial-system/web/src/routes/Court/Indictments/Defender/SelectDefender.tsx (2)

99-102: Approve changes with a suggestion for consistency

The InputAdvocate component usage has been updated correctly to align with the PR objectives. The prop changes from onDefenderNotFound to onAdvocateNotFound and from defendantId to clientId are appropriate and consistent with the new terminology.

However, for full consistency, consider renaming the setDefenderNotFound function to setAdvocateNotFound.

Consider applying this change for consistency:

- const [defenderNotFound, setDefenderNotFound] = useState<boolean>(false)
+ const [advocateNotFound, setAdvocateNotFound] = useState<boolean>(false)

  // ... (later in the code)

  <InputAdvocate
    disabled={defendant.defenderChoice === DefenderChoice.WAIVE}
-   onAdvocateNotFound={setDefenderNotFound}
+   onAdvocateNotFound={setAdvocateNotFound}
    clientId={defendant.id}
  />

Review Remaining "Defender" Terminology for Consistency

The verification revealed multiple instances of "defender" throughout the codebase, including variable names, component names, and string literals. To ensure consistency and fully align with the PR objectives, please review and update these instances where appropriate:

  • Utility Files

    • apps/judicial-system/web/src/utils/validate.ts
  • Components

    • DefenderNotFound
    • DefenderInfo
  • Hooks

    • useDefendants
  • Routes and Pages

    • SelectDefender.tsx
    • Various routes under apps/judicial-system/web/src/routes/Court/Indictments/Defender/
  • Tests

    • Multiple test files referencing "defender"

Note: The term "defendant" is used extensively and represents a legal term that may not require changes. Please confirm whether "defendant" should remain unchanged based on its legal context.

Analysis chain

Line range hint 1-110: Consider reviewing remaining "defender" terminology

While the main changes have been made to transition from "defender" to "advocate", there are still instances of "defender" terminology in the code, such as:

  1. The useDefendants hook
  2. The DefenderChoice enum
  3. Variable names like defenderNotFound and defendantWaivesRightToCounsel
  4. Comments and string literals containing "defender"

For consistency and to fully align with the PR objectives, consider reviewing these instances and updating them if appropriate. However, if these terms are still used in other parts of the system (e.g., backend, database), it might be necessary to keep them as is for now.

To help identify remaining instances of "defender" terminology, you can run the following command:

This will help you locate any remaining instances that might need to be updated.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for "defender" terminology in the codebase
rg --type typescript --type tsx -i 'defender|defendant' apps/judicial-system/web/src

Length of output: 121


Script:

#!/bin/bash
# Search for "defender" and "defendant" terminology in TypeScript and TSX files
rg --type ts --type tsx -i 'defender|defendant' apps/judicial-system/web/src

Length of output: 106


Script:

#!/bin/bash
# Search for "defender" and "defendant" terminology in TypeScript and TSX files
rg -i 'defender|defendant' -g "*.ts" -g "*.tsx" apps/judicial-system/web/src

Length of output: 199602

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

53-56: Improved error handling and code simplification

The changes in the deleteDefendant function are good improvements:

  1. The simplified return statement enhances readability.
  2. Adding a toast notification for errors improves user feedback.

Consider adding more specific error handling:

} catch (error) {
  console.error('Error deleting defendant:', error);
  toast.error(formatMessage(errors.deleteDefendant));
  return false;
}

This will help with debugging by logging the specific error while maintaining the user-friendly toast message.


71-74: Improved error handling and code simplification

The changes in the updateDefendant function are good improvements:

  1. The simplified return statement enhances readability.
  2. Adding a toast notification for errors improves user feedback.

Consider adding more specific error handling:

} catch (error) {
  console.error('Error updating defendant:', error);
  toast.error(formatMessage(errors.updateDefendant));
  return false;
}

This will help with debugging by logging the specific error while maintaining the user-friendly toast message.


Line range hint 1-124: Good adherence to NextJS and TypeScript best practices

The overall structure of this custom hook adheres well to NextJS best practices and makes good use of TypeScript:

  1. Custom hook pattern is used effectively for reusable logic.
  2. GraphQL mutations are used for efficient state management.
  3. TypeScript is applied for type safety in function parameters and return types.

Consider using more specific types for the data object in GraphQL mutation responses. For example:

interface DeleteDefendantResponse {
  deleteDefendant?: {
    deleted: boolean;
  };
}

const { data } = await deleteDefendantMutation<DeleteDefendantResponse>({
  variables: { input: { caseId, defendantId } },
});

This would provide better type safety and autocompletion when working with mutation responses.

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/processing.strings.ts (3)

70-76: LGTM with a minor suggestion: Update description for accuracy

The civilClaimantShareFilesWithDefender message is well-defined and uses a select statement to handle different defender types, which is good for localization. However, there's a minor inconsistency in the description.

Consider updating the description to accurately reflect this message:

- 'Notaður sem texti fyrir kröfuhafi í "Kröfuhafi er ekki með íslenska kennitölu" í einkaréttarkröfu á Málsmeðferðarskjánum.',
+ 'Notaður sem texti fyrir valmöguleika að deila gögnum með lögmanni eða réttargæslumanni kröfuhafa í einkaréttarkröfu á Málsmeðferðarskjánum.',

89-94: LGTM with a suggestion: Clarify the purpose of the 'remove' message

The remove message is well-defined, but its purpose might be confused with removeDefender. To improve clarity:

Consider updating the message ID and description to be more specific:

-  id: 'judicial.system.indictments:processing.remove',
+  id: 'judicial.system.indictments:processing.remove_claimant',
   defaultMessage: 'Eyða',
   description:
-    'Notaður sem texti í takka til að eyða kröfuhafa í einkaréttarkröfu á Málsmeðferðarskjánum.',
+    'Notaður sem texti í takka til að eyða kröfuhafa (ekki lögmanni kröfuhafa) í einkaréttarkröfu á Málsmeðferðarskjánum.',

113-119: LGTM with a suggestion: Enhance consistency in the tooltip message

The civilClaimantShareFilesWithDefenderTooltip message is well-defined and provides helpful context for users. However, there's a minor inconsistency with the earlier civilClaimantShareFilesWithDefender message.

Consider updating the default message to account for both lawyer and legal rights protector roles:

   defaultMessage:
-    'Ef hakað er í þennan reit fær lögmaður kröfuhafa aðgang að gögnum málsins',
+    'Ef hakað er í þennan reit fær lögmaður eða réttargæslumaður kröfuhafa aðgang að gögnum málsins',

This change would make the tooltip consistent with the flexibility provided in the civilClaimantShareFilesWithDefender message.

apps/judicial-system/web/src/components/DefenderInfo/DefenderInfo.tsx (2)

96-96: LGTM: InputAdvocate component integrated correctly

The InputAdvocate component has been correctly integrated, maintaining the same functionality as the previous DefenderInput component. This change aligns with the PR objectives of generalizing the concept from defenders to advocates.

Consider updating the state variable name defenderNotFound to advocateNotFound for consistency with the new terminology. This would involve changing:

-const [defenderNotFound, setDefenderNotFound] = useState<boolean>(false)
+const [advocateNotFound, setAdvocateNotFound] = useState<boolean>(false)

-<InputAdvocate onAdvocateNotFound={setDefenderNotFound} />
+<InputAdvocate onAdvocateNotFound={setAdvocateNotFound} />

This change would improve the consistency of the terminology throughout the component.


Line range hint 1-205: LGTM: Implementation is compatible with NextJS best practices

The component follows React best practices which align well with NextJS recommendations. The use of functional components and hooks is consistent with modern React and NextJS development patterns.

Consider memoizing the DefenderInfo component using React.memo if it's likely to re-render frequently due to parent component updates. This can potentially improve performance in a NextJS application:

import React, { memo } from 'react'

// ... rest of the imports

const DefenderInfo: FC<Props> = memo(({ workingCase, setWorkingCase }) => {
  // ... component implementation
})

export default DefenderInfo

This optimization can help prevent unnecessary re-renders and improve the overall performance of your NextJS application.

apps/judicial-system/web/src/utils/validate.ts (2)

274-282: LGTM with suggestions for improvement

The addition of allCivilClaimantsAreValid enhances the validation process for civil claimants, which aligns well with the PR objectives. However, I have a few suggestions for improvement:

  1. Consider using a more robust method for validating the national ID. The current implementation assumes a 10-digit format without hyphens, which might not cover all valid cases.

  2. Add a type annotation for better type safety:

const allCivilClaimantsAreValid: boolean = workingCase.hasCivilClaims
  ? workingCase.civilClaimants?.every(
      (civilClaimant) =>
        civilClaimant.name &&
        (civilClaimant.noNationalId ||
          (civilClaimant.nationalId &&
            civilClaimant.nationalId.replace('-', '').length === 10)),
    ) ?? false
  : true
  1. Consider adding a comment explaining the purpose of this validation:
// Validate all civil claimants have a name and either a valid national ID or no national ID
const allCivilClaimantsAreValid: boolean = ...

274-288: Overall assessment: Well-implemented feature addition

The changes to the isProcessingStepValidIndictments function effectively implement the new feature for validating civil claimants. The implementation is focused, adheres to TypeScript best practices, and aligns well with the PR objectives. The new validation logic is properly integrated into the existing function without introducing side effects to other parts of the file.

Consider implementing the suggested improvements for robustness and clarity. Additionally, ensure that corresponding updates are made to the documentation as mentioned in the PR summary.

To further enhance the modularity and reusability of the validation logic, consider extracting the civil claimant validation into a separate function. This would make it easier to test and potentially reuse in other parts of the application if needed.

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

96-99: Avoid unnecessary type assertion with 'as CivilClaimant'

The type assertion as CivilClaimant may mask underlying type issues and reduces the benefits of TypeScript's type checking.

Ensure that the object conforms to the CivilClaimant type without requiring an explicit type assertion:

            newCivilClaimants[indexOfCivilClaimantToUpdate] = {
              ...newCivilClaimants[indexOfCivilClaimantToUpdate],
              ...update,
-           } as CivilClaimant
+           }

If TypeScript raises a type error, consider refining the types of update or adjusting the CivilClaimant interface to accurately represent the data structure.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 52fc588 and 146c775.

Files selected for processing (15)
  • apps/judicial-system/web/src/components/DefenderInfo/DefenderInfo.tsx (2 hunks)
  • apps/judicial-system/web/src/components/Inputs/Input.strings.ts (3 hunks)
  • apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (13 hunks)
  • apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx (1 hunks)
  • apps/judicial-system/web/src/components/index.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Court/Indictments/Defender/SelectDefender.tsx (2 hunks)
  • apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (5 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/processing.strings.ts (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/createCivilClaimant.graphql (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/deleteCivilClaimant.graphql (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/updateCivilClaimant.graphql (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useDefendants/index.ts (2 hunks)
  • apps/judicial-system/web/src/utils/validate.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx
Additional context used
Path-based instructions (14)
apps/judicial-system/web/src/components/DefenderInfo/DefenderInfo.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/Inputs/Input.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/web/src/components/Inputs/InputAdvocate.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/Inputs/InputNationalId.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/index.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/routes/Court/Indictments/Defender/SelectDefender.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/Prosecutor/Indictments/Processing/Processing.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/Prosecutor/Indictments/Processing/processing.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/web/src/utils/hooks/useCivilClaimants/createCivilClaimant.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/utils/hooks/useCivilClaimants/deleteCivilClaimant.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/utils/hooks/useCivilClaimants/index.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/updateCivilClaimant.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/utils/hooks/useDefendants/index.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/utils/validate.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/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (1)
Learnt from: gudjong
PR: island-is/island.is#15421
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx:55-61
Timestamp: 2024-07-03T15:43:13.884Z
Learning: The `updateCase` method in the `apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx` file has its own error handling, and additional error handling in the `initialize` function is not necessary.
Additional comments not posted (20)
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/updateCivilClaimant.graphql (1)

1-5: LGTM! The mutation structure looks good.

The mutation follows GraphQL naming conventions and has a clear purpose. Good job on keeping the input type name consistent with the "Input" suffix convention.

Consider returning more fields for flexibility.

Currently, the mutation only returns the id of the updated civil claimant. While this might be sufficient for basic use cases, consider returning more fields (e.g., name, status) to provide more information to the client without requiring additional queries.

Reminder: Ensure proper error handling is implemented.

While error handling isn't visible in this GraphQL schema, it's crucial to implement proper error handling in the resolver function. Make sure to catch and handle potential errors, such as validation failures or database errors, and return appropriate error messages to the client.

apps/judicial-system/web/src/utils/hooks/useCivilClaimants/deleteCivilClaimant.graphql (1)

1-5: The GraphQL mutation looks well-structured and aligns with the PR objectives.

The DeleteCivilClaimant mutation is correctly defined and follows GraphQL best practices:

  1. It uses a clear, descriptive name that indicates its purpose.
  2. It accepts an input object, which is a good practice for mutations with multiple parameters.
  3. The response includes a deleted field, which provides a clear indication of the operation's success.

This mutation aligns well with the PR objective of enhancing the system to manage civil claimants. It provides the necessary functionality to remove a civil claimant from the system.

To ensure this mutation is properly integrated and used within the NextJS application, let's verify its usage:

This will help us confirm that the mutation is being imported and used correctly in the NextJS components or hooks.

Verification successful

Mutation DeleteCivilClaimant is properly integrated and used across the codebase.

The search results indicate that DeleteCivilClaimant is correctly imported and utilized within the following files:

  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx

This confirms that the mutation is correctly integrated and operational within the NextJS application.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the usage of DeleteCivilClaimant mutation in the codebase

# Search for import or usage of DeleteCivilClaimant
rg --type typescript --type tsx "DeleteCivilClaimant|deleteCivilClaimant" apps/judicial-system/web/src

Length of output: 139


Script:

#!/bin/bash
# Description: Check for the usage of DeleteCivilClaimant mutation in the codebase

# Search for import or usage of DeleteCivilClaimant in .ts and .tsx files
rg "DeleteCivilClaimant|deleteCivilClaimant" -g "*.ts" -g "*.tsx" apps/judicial-system/web/src

Length of output: 1663

apps/judicial-system/web/src/components/Inputs/Input.strings.ts (3)

10-14: New spokesperson name label looks good

The addition of spokespersonNameLabel aligns with the PR objectives and follows the existing pattern for label definitions. The ID, default message, and description are appropriately set.


Line range hint 1-56: Overall consistency and adherence to guidelines

The changes in this file maintain consistency with the existing code structure and adhere to the provided coding guidelines. The use of TypeScript and react-intl for internationalization follows NextJS best practices.


3-3: Approve export name change, but verify imports

The change from defenderInput to strings makes the export more generic, which is good for reusability. However, ensure that all imports of this constant in other files are updated accordingly.

To verify the impact of this change, run the following script:

Verification successful

Import verification successful

All imports of defenderInput have been updated to strings, ensuring consistency across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all imports of the previous constant name 'defenderInput'

# Test: Search for imports of 'defenderInput'. Expect: No results if all imports have been updated.
rg --type typescript "import.*defenderInput.*from.*Input\.strings"

Length of output: 103


Script:

#!/bin/bash
# Description: Find all imports of the previous constant name 'defenderInput'

# Test: Search for imports of 'defenderInput'. Expect: No results if all imports have been updated.
rg --type ts "import.*defenderInput.*from.*Input\.strings"

Length of output: 60

apps/judicial-system/web/src/routes/Court/Indictments/Defender/SelectDefender.tsx (2)

11-11: LGTM: Import statement updated correctly

The import statement has been updated from DefenderInput to InputAdvocate, which aligns with the PR objectives of transitioning terminology from "defenders" to "advocates". This change is consistent with the component usage later in the file.


Line range hint 1-110: Summary: Changes align with PR objectives, minor improvements suggested

The changes in this file successfully implement the transition from "defender" to "advocate" terminology as per the PR objectives. The code adheres to NextJS and React best practices, and the modifications are consistent with the intended functionality.

A few minor suggestions have been made for further improving consistency:

  1. Renaming the setDefenderNotFound function to setAdvocateNotFound.
  2. Reviewing and potentially updating remaining instances of "defender" terminology throughout the file.

These suggestions are not critical and don't impact the overall functionality of the component. Great job on implementing the required changes!

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/processing.strings.ts (9)

52-57: LGTM: Appropriate replacement for hasCivilClaims

The new isCivilClaim message is a suitable replacement for the removed hasCivilClaims. It maintains consistency with the existing style and aligns with the PR objectives of refactoring terminology.


58-63: LGTM: New message for civil claimant

The civilClaimant message is well-defined and consistent with the existing style. It supports the PR objectives by providing a label for civil claimants in the UI.


64-69: LGTM: Handling claimants without Icelandic national ID

The civilClaimantNoNationalId message is well-defined and addresses a specific case for claimants without an Icelandic national ID. This addition enhances the flexibility of the system in handling various claimant scenarios.


77-82: LGTM: New message for adding a claimant's lawyer

The addDefender message is well-defined and consistent with the existing style. It supports the PR objectives by providing a label for adding a lawyer for the civil claimant in the UI.


83-88: LGTM: New message for removing a claimant's lawyer

The removeDefender message is well-defined and consistent with the existing style. It complements the addDefender message, providing a complete set of actions for managing a claimant's legal representation.


95-100: LGTM: New message for adding a civil claimant

The addCivilClaimant message is well-defined and consistent with the existing style. It directly supports the PR objectives by providing a label for adding civil claimants in the UI.


101-106: LGTM: New message for lawyer label

The lawyer message is well-defined and consistent with the existing style. It supports the PR objectives by providing a label for lawyers in the UI, aligning with the terminology refactor from "defenders" to "advocates".


107-112: LGTM: New message for legal rights protector label

The legalRightsProtector message is well-defined and consistent with the existing style. It supports the PR objectives by providing a label for legal rights protectors in the UI, enhancing the system's flexibility in representing different types of legal advocates.


Line range hint 1-119: Overall assessment: Well-implemented changes supporting PR objectives

The changes in this file effectively support the PR objectives of enabling the setting of civil claimants and refactoring terminology from "defenders" to "advocates". The new messages are well-structured, consistent with the existing style, and provide the necessary language support for the enhanced functionality.

Key points:

  1. All new messages align with the PR objectives.
  2. The changes maintain consistency with the existing code style.
  3. The new messages provide flexibility in handling different types of legal advocates.
  4. A few minor suggestions were made to improve clarity and consistency.

These changes significantly enhance the system's ability to handle civil claimants and their legal representatives, improving the overall functionality of the judicial system application.

apps/judicial-system/web/src/components/index.ts (1)

45-47: LGTM! Changes align with PR objectives and improve component granularity.

The addition of InputAdvocate, InputName, and InputNationalId exports aligns well with the PR objective of transitioning from "defenders" to "advocates" terminology. This more granular approach to input components can improve reusability and maintainability.

To ensure the removal of DefenderInput doesn't cause issues, let's verify its usage:

apps/judicial-system/web/src/components/DefenderInfo/DefenderInfo.tsx (2)

20-21: LGTM: Import statements updated correctly

The import statements have been updated to reflect the replacement of DefenderInput with InputAdvocate. This change is consistent with the PR objectives and maintains the correct module structure.


Line range hint 1-205: LGTM: TypeScript usage is correct and follows best practices

The TypeScript implementation in this file is well-done. Props are properly typed using an interface, and imported types are used appropriately throughout the component. This ensures type safety and improves code maintainability.

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

288-288: LGTM: Proper integration of new validation

The addition of allCivilClaimantsAreValid to the return statement's Boolean check is appropriate. It ensures that the processing step is only considered valid when all civil claimants are valid, in addition to the existing checks. This change is consistent with the function's purpose and aligns well with the PR objectives.

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

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

I like where you are going with this PR, creating a shared component to handle lawyer lookups. However, I feel the shared component knows too much about the components that use it. A better approach would be to make the component oblivious of the using components and inject all relevant update methods.

I think the component works as is and the changes suggested above chould be done later as part of a cooldown week.

@oddsson oddsson added the automerge Merge this PR as soon as all checks pass label Sep 24, 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: 4

Outside diff range and nitpick comments (9)
apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts (4)

25-46: LGTM with a minor suggestion: createCivilClaimant function

The createCivilClaimant function is well-implemented with proper error handling and performance optimization using useCallback. The function now returns a value in all code paths, addressing a previous concern.

Consider adding an explicit return type annotation to the function for improved type safety:

  const createCivilClaimant = useCallback(
-   async (civilClaimant: CreateCivilClaimantInput) => {
+   async (civilClaimant: CreateCivilClaimantInput): Promise<string | null> => {
    // ... function body ...
  },
  [createCivilClaimantMutation, formatMessage, isCreatingCivilClaimant],
)

48-62: LGTM with a suggestion: deleteCivilClaimant function

The deleteCivilClaimant function is well-implemented with proper error handling and consistent return values. The use of useCallback for performance optimization is commendable.

Consider adding an explicit return type annotation to the function for improved type safety:

  const deleteCivilClaimant = useCallback(
-   async (caseId: string, civilClaimantId: string) => {
+   async (caseId: string, civilClaimantId: string): Promise<boolean> => {
    // ... function body ...
  },
  [deleteCivilClaimantMutation, formatMessage],
)

64-80: LGTM with a suggestion: updateCivilClaimant function

The updateCivilClaimant function is well-implemented with proper error handling and consistent return values. The use of useCallback for performance optimization is appropriate.

Consider adding an explicit return type annotation to the function for improved type safety:

  const updateCivilClaimant = useCallback(
-   async (updateCivilClaimant: UpdateCivilClaimantInput) => {
+   async (updateCivilClaimant: UpdateCivilClaimantInput): Promise<boolean> => {
    // ... function body ...
  },
  [formatMessage, updateCivilClaimantMutation],
)

1-133: Overall assessment: Well-implemented custom hook with minor improvements needed

The useCivilClaimants hook is generally well-implemented, adhering to React and TypeScript best practices. Key strengths include:

  1. Proper use of useCallback for performance optimization.
  2. Consistent error handling with user-friendly notifications.
  3. Clean and intuitive API for consumers.

Main points to address:

  1. Verify the existence of generated mutation hook files.
  2. Add explicit return type annotations to functions for improved type safety.
  3. Update setAndSendCivilClaimantToServer to properly handle the asynchronous updateCivilClaimant function.

Addressing these points will further enhance the quality and reliability of the implementation.

Consider adding unit tests for this custom hook to ensure its reliability and ease of maintenance as the application evolves.

apps/judicial-system/web/messages/Core/errors.ts (1)

15-20: LGTM with a minor suggestion.

The new updateCivilClaimant error message is well-structured and consistent with other error messages in the file. It follows the established pattern and provides a clear message in Icelandic.

Consider updating the description to be more specific:

- 'Notaður sem villuskilaboð þegar ekki gengur að uppfæra kröfuhafa',
+ 'Notaður sem villuskilaboð þegar ekki gengur að uppfæra upplýsingar um kröfuhafa',

This change would make the description slightly more precise about what is being updated.

apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (4)

30-43: LGTM! Consider using an enum for advocate types.

The changes to the imports and the Props interface effectively support the expanded functionality of the InputAdvocate component. The addition of advocateType and isCivilClaim props provides the necessary flexibility to handle different types of advocates and cases.

Consider defining an enum for the advocateType prop to improve type safety and maintainability:

enum AdvocateType {
  Defender = 'defender',
  Spokesperson = 'spokesperson',
  LegalRightsProtector = 'legal_rights_protector'
}

// Then update the Props interface:
advocateType?: AdvocateType;

This change would make it easier to manage and extend advocate types in the future.


Line range hint 120-196: LGTM! Consider extracting the lawyer update logic.

The handleLawyerChange function has been effectively updated to handle both defenders and spokespersons, including new logic for civil claimants. The use of the isCivilClaim prop to determine the appropriate action is a good approach.

Consider extracting the lawyer update logic into a separate function to improve readability and maintainability:

const updateLawyerInfo = (selectedOption: SingleValue<ReactSelectOption>) => {
  if (!selectedOption) return { lawyer: {}, spokesperson: {} };

  const { label, value, __isNew__: defenderNotFound } = selectedOption;
  const lawyer = lawyers.find((l: Lawyer) => l.email === (value as string));

  return {
    lawyer: {
      defenderName: lawyer ? lawyer.name : label,
      defenderNationalId: lawyer ? lawyer.nationalId : '',
      defenderEmail: lawyer ? lawyer.email : '',
      defenderPhoneNumber: lawyer ? lawyer.phoneNr : '',
    },
    spokesperson: {
      spokespersonName: lawyer ? lawyer.name : label,
      spokespersonNationalId: lawyer ? lawyer.nationalId : '',
      spokespersonEmail: lawyer ? lawyer.email : '',
      spokespersonPhoneNumber: lawyer ? lawyer.phoneNr : '',
    },
    defenderNotFound,
  };
};

// Then in handleLawyerChange:
const { lawyer: updatedLawyer, spokesperson: updatedSpokesperson, defenderNotFound } = updateLawyerInfo(selectedOption);
onAdvocateNotFound?.(defenderNotFound || false);

This refactoring would make the handleLawyerChange function more concise and easier to understand.

Tools
Biome

[error] 143-143: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 244-311: LGTM! Consider using a strategy pattern for advocate updates.

The handleLawyerPropertyChange and handleLawyerPropertyBlur functions have been effectively updated to handle both civil claimants and defendants. The use of the isCivilClaim prop to determine the appropriate action is a good approach, and the error handling and validation logic remain consistent.

To further improve the code's maintainability and extensibility, consider implementing a strategy pattern for advocate updates:

const advocateUpdateStrategies = {
  civilClaimant: {
    updateState: updateCivilClaimantState,
    update: updateCivilClaimant,
    getIdProp: () => 'civilClaimantId',
  },
  defendant: {
    updateState: updateDefendantState,
    update: updateDefendant,
    getIdProp: () => 'defendantId',
  },
};

const getStrategy = (isCivilClaim) => 
  isCivilClaim ? advocateUpdateStrategies.civilClaimant : advocateUpdateStrategies.defendant;

// Then in handleLawyerPropertyChange:
const strategy = getStrategy(isCivilClaim);
strategy.updateState(
  { ...update, caseId: workingCase.id, [strategy.getIdProp()]: clientId },
  setWorkingCase,
);

// Similarly in handleLawyerPropertyBlur:
const strategy = getStrategy(isCivilClaim);
strategy.update({ ...update, caseId, [strategy.getIdProp()]: clientId });

This approach would make it easier to add new types of advocates in the future and reduce the need for conditional statements.


Line range hint 315-496: LGTM! Consider extracting label logic for improved readability.

The render logic has been effectively updated to handle different types of advocates, using conditional rendering based on advocateType and isCivilClaim props. The dynamic labels and placeholders provide the necessary flexibility for different scenarios.

To improve readability, consider extracting the label logic into separate functions:

const getNameLabel = (advocateType, sessionArrangements) => {
  if (advocateType === 'legal_rights_protector') {
    return formatMessage(strings.spokespersonNameLabel);
  }
  return formatMessage(strings.nameLabel, { sessionArrangements });
};

const getEmailLabel = (advocateType, sessionArrangements) => {
  if (advocateType === 'legal_rights_protector') {
    return formatMessage(strings.spokespersonEmailLabel);
  }
  return formatMessage(strings.emailLabel, { sessionArrangements });
};

// Similar function for phone number label

// Then in the render:
label={getNameLabel(advocateType, workingCase.sessionArrangements)}
// ...
label={getEmailLabel(advocateType, workingCase.sessionArrangements)}

This refactoring would make the JSX more concise and easier to read, while keeping the label logic centralized and maintainable.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 146c775 and 0678a90.

Files selected for processing (5)
  • apps/judicial-system/web/messages/Core/errors.ts (1 hunks)
  • apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (13 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (5 hunks)
  • apps/judicial-system/web/src/utils/hooks/index.ts (1 hunks)
  • apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts (1 hunks)
Additional context used
Path-based instructions (5)
apps/judicial-system/web/messages/Core/errors.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/Inputs/InputAdvocate.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/Prosecutor/Indictments/Processing/Processing.tsx (1)

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

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

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Learnings (1)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (1)
Learnt from: gudjong
PR: island-is/island.is#15421
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx:55-61
Timestamp: 2024-07-03T15:43:13.884Z
Learning: The `updateCase` method in the `apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx` file has its own error handling, and additional error handling in the `initialize` function is not necessary.
Biome
apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx

[error] 143-143: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Additional comments not posted (9)
apps/judicial-system/web/src/utils/hooks/index.ts (1)

31-31: LGTM! The new export aligns with the PR objectives and existing code structure.

The addition of useCivilClaimants export is consistent with the existing code style and structure in this index file. This change aligns well with the PR objective of enhancing the system to allow setting civil claimants.

A few points to consider:

  1. The export follows NextJS best practices for file structure and module organization.
  2. The use of TypeScript for type safety is maintained, assuming useCivilClaimants is properly typed in its implementation file.
  3. This new hook likely contributes to efficient state management for civil claimant data.

To ensure the useCivilClaimants hook is properly implemented and typed, let's verify its implementation:

Verification successful

Verified: The useCivilClaimants hook is correctly implemented and properly integrated.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of useCivilClaimants hook

# Test: Check if the useCivilClaimants file exists and its content
fd --type file --full-path "apps/judicial-system/web/src/utils/hooks/useCivilClaimants.ts" --exec cat {}

Length of output: 106


Script:

#!/bin/bash
# Description: Verify the existence of useCivilClaimants.ts hook

# Search for the useCivilClaimants.ts file in the repository
fd "useCivilClaimants.ts"

Length of output: 25


Script:

#!/bin/bash
# Description: Search for useCivilClaimants implementation across the repository

# Use ripgrep to find any instances of useCivilClaimants
rg "useCivilClaimants" --type ts

Length of output: 746


Script:

#!/bin/bash
# Description: Display the contents of useCivilClaimants hook implementation

# Display the contents of useCivilClaimants/index.ts
cat "apps/judicial-system/web/src/utils/hooks/useCivilClaimants/index.ts"

Length of output: 4125

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

17-23: LGTM: Hook initialization

The initialization of the useCivilClaimants hook follows React best practices. The use of useIntl for internationalization and the proper initialization of mutation hooks are commendable.


82-111: LGTM: updateCivilClaimantState function

The updateCivilClaimantState function is well-implemented, following React best practices for state updates. It properly handles edge cases, including when civilClaimants doesn't exist and when the civil claimant ID is not found. The use of immutable update patterns with spread operators is commendable.

apps/judicial-system/web/messages/Core/errors.ts (3)

27-32: LGTM! Well-structured error message.

The new createCivilClaimant error message is correctly implemented and consistent with the existing error messages in the file. It follows the established pattern, uses appropriate Icelandic text, and provides a clear description of its usage.


15-44: Summary: Excellent addition of civil claimant error messages.

The new error messages for civil claimants (updateCivilClaimant, createCivilClaimant, and deleteCivilClaimant) have been successfully implemented. These additions:

  1. Enhance the error handling capabilities for civil claimant operations.
  2. Maintain consistency with existing error message structures.
  3. Use appropriate Icelandic language for user-facing messages.
  4. Provide clear descriptions for developers.

These changes align well with the PR objectives of enabling the setting of civil claimants and their legal advocates. The new error messages will improve the user experience by providing specific feedback for civil claimant-related operations.

To ensure full alignment with the PR objectives, consider the following actions:

  1. Update relevant documentation to reflect these new error messages.
  2. Ensure that the components using these error messages are properly implemented.
  3. Add appropriate unit tests to cover scenarios where these error messages would be triggered.

39-44: LGTM! Consistent implementation with a suggestion for verification.

The new deleteCivilClaimant error message is well-structured and follows the established pattern in the file. It uses appropriate Icelandic text and provides a clear description of its usage.

Please verify that "kröfuhafa" is the correct term for "civil claimant" in this context. It might be beneficial to consult with the product owner or a domain expert to ensure the terminology aligns with the specific legal context of the application.

To assist in this verification, you can run the following script to check for consistency in terminology usage across the codebase:

This script will help identify if there are any inconsistencies in the terminology used for civil claimants across the codebase.

Verification successful

[/run_scripts]


Verified: Terminology Consistent

The term "kröfuhafa" is consistently used across the codebase for "civil claimant," ensuring uniform terminology throughout the application.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of "kröfuhafa" and related terms

echo "Checking for 'kröfuhafa' usage:"
rg --type typescript --type javascript "kröfuhafa"

echo "\nChecking for 'civil claimant' usage:"
rg --type typescript --type javascript "civil.?claimant"

echo "\nChecking for other potential translations:"
rg --type typescript --type javascript "stefnandi|sóknaraðili|málshefjandi"

Length of output: 573


Script:

#!/bin/bash
# Description: Check for consistent usage of "kröfuhafa" and related terms in .ts and .js files

echo "Checking for 'kröfuhafa' usage:"
rg "kröfuhafa" -g "*.ts" -g "*.js"

echo "\nChecking for 'civil claimant' usage:"
rg "civil.?claimant" -g "*.ts" -g "*.js"

echo "\nChecking for other potential translations:"
rg "stefnandi|sóknaraðili|málshefjandi" -g "*.ts" -g "*.js"

Length of output: 7060

apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (3)

69-107: LGTM! Good use of hooks and clear logic.

The updates to the component function and its hooks effectively support the new functionality for handling different types of advocates. The use of separate hooks for defendants and civil claimants (useDefendants and useCivilClaimants) promotes good separation of concerns. The logic for finding defendants and civil claimants is concise and clear.


Line range hint 201-241: LGTM! Clear and maintainable property handling.

The updates to the propertyValidations and formatUpdate functions effectively support the new functionality for different types of advocates. The inclusion of spokesperson-related properties in propertyValidations and the expanded switch statement in formatUpdate are clear and easy to maintain.


499-499: LGTM! Correct export of the renamed component.

The export statement has been correctly updated to export InputAdvocate, which aligns with the component's new name and expanded functionality.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0678a90 and 7da5d73.

📒 Files selected for processing (2)
  • apps/judicial-system/web/src/components/index.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/web/src/components/index.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.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."
📓 Learnings (1)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (1)
Learnt from: gudjong
PR: island-is/island.is#15421
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx:55-61
Timestamp: 2024-07-03T15:43:13.884Z
Learning: The `updateCase` method in the `apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx` file has its own error handling, and additional error handling in the `initialize` function is not necessary.
🔇 Additional comments not posted (3)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (3)

146-156: Ensure civilClaimants is always an array

The previous review comment about initializing the civilClaimants array when it's undefined is still applicable. If prevWorkingCase.civilClaimants is null or undefined, the current logic may set civilClaimants to undefined, causing issues when rendering or manipulating the array.


217-222: Avoid exiting the loop prematurely in removeAllCivilClaimants

In the removeAllCivilClaimants function, if civilClaimant.id is undefined, the function returns, which stops the deletion process for remaining civil claimants. This could result in some civil claimants not being deleted as expected.


472-474: Avoid resetting nationalIdNotFound prematurely

Calling setNationalIdNotFound(false) when the input length is less than 11 may reset the nationalIdNotFound flag before the national ID has been validated. This could lead to incorrect validation states.

@kodiakhq kodiakhq bot merged commit 621b5bb into main Sep 25, 2024
30 checks passed
@kodiakhq kodiakhq bot deleted the j-s/civil-claimant branch September 25, 2024 08:57
thoreyjona pushed a commit that referenced this pull request Oct 2, 2024
* Started working on extracting nationalId input to component

* Use InputNationalId in DefendantInfo

* Create name input

* Checkpoint

* Add AddDefender button to Claimant section

* Add defender info

* Refactor

* feat(j-s): Added controller and service for civilclaimant

* Checkpoint

* fix(j-s): Dtos

* feat(j-s): Civil claimant API layer

* Add addClaimant functionality

* fix(j-s): backend usage

* Checkpoint

* Revert framer motion update

* fix(j-s): Remove defendant and rename defender to spokesperson

* Cleanup

* feat(j-s): Connect civil claimant to case

* fix(j-s): Remove required from name

* Remove unused imports

* Layout

* feat(j-s): Add hasCivilClaims

* feat(j-s): Fix boolean

* chore(j-s): Add update civil claimant mutation to resolver

* chore(j-s): Added role guards and write guards to civil claimant controller

* chore(j-s): Added delete civil claimant to resolver

* Save hasCivilClaims choise to server

* Create new civil claimant when needd

* CRUD operations on civil claimant

* Fix lint

* chore: nx format:write update dirty files

* Create and delete civil claimant

* Create and delete civil claimant

* Lookup nationalId with national registry

* Checkpoint

* Autofill name when national id is set

* Prevent double civil claimant creation

* Implement noNationalId

* Remove redunant boolean check

* Checkpoint

* Rename defendantId to clientId in DefenderInput component to make it more generic

* Enable lawyer lookup

* Add ability to share case files with defender

* Reset lawyer when he is deleted

* Remove unused code

* Remove unused code

* Remove unused code

* Remove unused code

* Remove unused code

* Remove unused code

* Remove unused code

* Merge

* Merge

* Refactor DefenderInput

* Clear nationalId when noNationalId is selcted

* Checkpoint

* Clear nationalId

* Refactor DefenderInput

* Fix lint

* Allow clear defender

* Validation

* Remove console.log

* Reset caseFilesSharedWithSpokesperson when advocate is set

* Add tooltip

* Validate name

* Validate

* Fix input name bug

* Remove DefenderInput

* Reorder imports

* Remove commented out code

* Validate

* Fix strings

* Cleanup

* Cleanup

* Cleanup

* Cleanup

* Cleanup

* Use barrel file for import

* Fix typo

---------

Co-authored-by: unakb <una@kolibri.is>
Co-authored-by: andes-it <builders@andes.is>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants