Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(j-s): Fix ServiceAnnouncement component for defenders #16840

Merged
merged 31 commits into from
Nov 13, 2024

Conversation

oddsson
Copy link
Member

@oddsson oddsson commented Nov 13, 2024

Fix ServiceAnnouncement component for defenders

Asana

What

We are now showing the service status to defenders. When a service is done electronically, servedBy is set to the nationalId of the defendant. This PR shows "Served electronically" message instead of that.

Why

It's a bug

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Enhanced display logic for defendant information, including clearer messaging when no defender is present.
    • Added a new message for documents served electronically in the Indictment Overview.
    • Improved service status messaging for subpoenas.
  • Bug Fixes

    • Corrected assertions in test cases for the DefendantInfo component to enhance specificity.
  • Refactor

    • Streamlined rendering logic and state management in the Overview component for better clarity and efficiency.

oddsson and others added 27 commits November 5, 2024 15:25
…d-is/island.is into j-s/service-announcement-defenders
@oddsson oddsson requested a review from a team as a code owner November 13, 2024 11:00
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request involve modifications to several components within the judicial system application. Key updates include enhancements to the rendering logic and data handling in the DefendantInfo.tsx file, adjustments to test cases in InfoCard.spec.tsx, and refinements in the Overview.tsx component's state management. Additionally, new message definitions were added in IndictmentOverview.strings.ts, and the getMessage function was updated in IndictmentOverview.tsx to include a new parameter for service status. These changes aim to improve clarity and maintainability across the components.

Changes

File Path Change Summary
apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx Introduced hasDefender and defenderLabel variables for improved conditional rendering; refactored display logic for defender information; adjusted layout.
apps/judicial-system/web/src/components/InfoCard/InfoCard.spec.tsx Modified assertions in tests for DefendantInfo; corrected nesting issue in one test case; enhanced assertion specificity for "no defender" message.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx Updated InfoCardActiveIndictment prop for clarity; refined modal state handling in handleNextButtonClick; maintained existing rendering logic.
apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.strings.ts Added new message servedToElectronically for electronic service notifications.
apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx Updated getMessage function to include serviceStatus parameter for conditional message formatting based on service status.

Possibly related PRs

Suggested labels

automerge, high priority

Suggested reviewers

  • unakb

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (7)
apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.strings.ts (1)

26-30: LGTM! Consider adding English translations in descriptions.

The new message definition follows the established pattern and aligns with the PR objective to show "Served electronically" instead of national ID. The message ID, default message, and description are consistent with other entries.

Consider adding English translations in the description to help non-Icelandic speaking developers:

  servedToElectronically: {
    id: 'judicial.system.core:overview.served_electronically',
    defaultMessage: 'Rafrænt pósthólf island.is',
-   description: 'Notaður sem texti þegar birt var í pósthólfi.',
+   description: 'Notaður sem texti þegar birt var í pósthólfi. (EN: Used as text when served to electronic mailbox)',
  },
apps/judicial-system/web/src/components/InfoCard/InfoCard.spec.tsx (2)

Line range hint 89-130: Fix duplicate nested render calls in test case

There's a critical structural issue where the render function is incorrectly nested within another render call. This will cause test failures.

Apply this fix to remove the nested render:

test('should display the assigned defender name, email and phonenumber if that info is provided', async () => {
  // Arrange
  render(
    <MockedProvider>
      <LocaleProvider locale="is" messages={{}}>
-       render(
-       <MockedProvider>
-         <LocaleProvider locale="is" messages={{}}>
          <InfoCard
            sections={[
              {
                id: 'sec_id',
                items: [
                  {
                    id: 'itm_id',
                    title: 'Titill',
                    values: [
                      <DefendantInfo
                        defendant={{
                          id: 'def_id',
                          defenderName: 'Joe',
                          defenderEmail: '[email protected]',
                          defenderPhoneNumber: '455-5544',
                        }}
                      />,
                    ],
                  },
                ],
              },
            ]}
          />
-         </LocaleProvider>
-       </MockedProvider>
-       , )
      </LocaleProvider>
    </MockedProvider>,
  )

152-155: Consider using translation keys instead of hardcoded strings

While the assertion logic is good, the test is using a hardcoded Icelandic string. Consider using the translation system for better maintainability and consistency.

Example approach:

expect(
  await screen.findByText(
    (_, element) =>
-     element?.textContent === 'Verjandi: Hefur ekki verið skráður',
+     element?.textContent === messages.defender.notAssigned,
  ),
).toBeTruthy()

This assumes you've defined the translation key in your messages object. You'll need to:

  1. Import the messages from your translation files
  2. Pass them to the LocaleProvider in the test setup
apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx (2)

78-87: LGTM! Consider adding type assertions for better type safety.

The new variables are well-structured and provide clear fallback handling. The code is readable and maintainable, which aligns with the team's preferences.

Consider adding type assertions to ensure type safety:

- const hasDefender = defendant.defenderName || defender?.name
+ const hasDefender = Boolean(defendant.defenderName || defender?.name)

Further servedBy usages detected that may display national IDs. Please update all instances to display "Served electronically":

  • apps/judicial-system/xrd-api/src/app/app.service.ts
  • apps/judicial-system/xrd-api/src/app/dto/subpoena.dto.ts
  • apps/judicial-system/web/src/components/ServiceAnnouncement/ServiceAnnouncement.tsx
  • apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx
  • apps/judicial-system/api/src/app/modules/police/models/subpoenaStatus.model.ts
  • apps/judicial-system/api/src/app/modules/defendant/models/subpoena.model.ts
  • apps/judicial-system/backend/src/app/modules/police/police.service.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/models/subpoena.model.ts
  • apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts
  • apps/judicial-system/web/src/components/ServiceAnnouncement/ServiceAnnouncement.strings.ts
  • apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.strings.ts
🔗 Analysis chain

Line range hint 1-147: Verify handling of servedBy field across the codebase.

To ensure complete implementation of the PR objective (replacing national ID with "Served electronically"), let's verify all usages of the servedBy field.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of servedBy field that might still display national IDs
rg -g '*.{ts,tsx}' -A 3 'servedBy'

# Search for translations or messages related to electronic service
rg -g '*.strings.{ts,tsx}' -A 3 'electronic.*service|served.*electronic'

Length of output: 7794

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

71-80: LGTM with a type safety enhancement suggestion

The function correctly implements the electronic service display logic while maintaining backwards compatibility. Good use of i18n for internationalization.

Consider adding type narrowing for better type safety:

  const getMessage = (
    servedBy?: string | null,
    serviceDate?: string | null,
    serviceStatus?: ServiceStatus | null,
  ): string => {
    const processServer =
-     serviceStatus === ServiceStatus.ELECTRONICALLY
+     serviceStatus && serviceStatus === ServiceStatus.ELECTRONICALLY
        ? formatMessage(strings.servedToElectronically)
        : servedBy
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx (1)

Line range hint 1-450: Consider adding JSDoc documentation

Given the complexity of this component (handling multiple states, transitions, and user roles), consider adding JSDoc documentation to describe:

  • Component's purpose and responsibilities
  • Key props and state management
  • Available transitions and their conditions
  • Modal types and their triggers

Example:

/**
 * Overview component for managing indictment cases.
 * 
 * Handles:
 * - Case state transitions
 * - Document management
 * - Indictment confirmation/denial
 * - Case cancellation requests
 * 
 * @component
 * @example
 * return (
 *   <Overview />
 * )
 */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between af03eb5 and f1f1810.

📒 Files selected for processing (5)
  • apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx (2 hunks)
  • apps/judicial-system/web/src/components/InfoCard/InfoCard.spec.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.strings.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.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/InfoCard/InfoCard.spec.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/Overview/Overview.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/Shared/IndictmentOverview/IndictmentOverview.strings.ts (1)

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
📓 Learnings (2)
apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx (4)
Learnt from: oddsson
PR: island-is/island.is#15461
File: apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx:36-62
Timestamp: 2024-11-12T15:15:20.157Z
Learning: The user prefers readability over optimization in the `getAppealExpirationInfo` function within `DefendantInfo.tsx`.
Learnt from: oddsson
PR: island-is/island.is#15461
File: apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx:36-62
Timestamp: 2024-11-12T15:15:11.835Z
Learning: The user prefers readability over optimization in the `getAppealExpirationInfo` function within `DefendantInfo.tsx`.
Learnt from: unakb
PR: island-is/island.is#14922
File: apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx:43-49
Timestamp: 2024-11-12T15:15:20.157Z
Learning: The `getAppealExpirationInfo` function in `DefendantInfo.tsx` correctly uses `today < expiryDate` to determine if the current date is before the appeal expiration date.
Learnt from: unakb
PR: island-is/island.is#14922
File: apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx:43-49
Timestamp: 2024-11-12T15:15:26.274Z
Learning: The `getAppealExpirationInfo` function in `DefendantInfo.tsx` correctly uses `today < expiryDate` to determine if the current date is before the appeal expiration date.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx (5)
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.
Learnt from: unakb
PR: island-is/island.is#14712
File: apps/judicial-system/web/src/routes/PublicProsecutor/Indictments/Overview/IndictmentOverview.tsx:0-0
Timestamp: 2024-11-12T15:15:11.835Z
Learning: The judicial system application uses a toaster notification system to handle errors globally.
Learnt from: unakb
PR: island-is/island.is#14712
File: apps/judicial-system/web/src/routes/PublicProsecutor/Indictments/Overview/IndictmentOverview.tsx:0-0
Timestamp: 2024-11-12T15:15:11.835Z
Learning: The judicial system application uses a toaster notification system to handle errors globally.
Learnt from: unakb
PR: island-is/island.is#15378
File: apps/judicial-system/web/src/routes/Court/Indictments/Summary/Summary.tsx:86-100
Timestamp: 2024-11-12T15:15:11.835Z
Learning: User unakb prefers explicit case handling in switch statements for key functionalities like `getRulingDecisionTagColor` to ensure clarity and avoid assumptions that a case was overlooked.
Learnt from: unakb
PR: island-is/island.is#15378
File: apps/judicial-system/web/src/routes/Court/Indictments/Summary/Summary.tsx:86-100
Timestamp: 2024-11-12T15:15:11.835Z
Learning: User unakb prefers explicit case handling in switch statements for key functionalities like `getRulingDecisionTagColor` to ensure clarity and avoid assumptions that a case was overlooked.
🔇 Additional comments (5)
apps/judicial-system/web/src/components/InfoCard/DefendantInfo/DefendantInfo.tsx (1)

Line range hint 140-147: LGTM! The conditional rendering is well-implemented.

The additional serviceRequirement check improves the rendering logic by ensuring the verdict view date is only shown when necessary. The implementation is type-safe and follows React best practices.

apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx (3)

41-41: LGTM: Clean import addition

The ServiceStatus import is properly added and grouped with related schema types.


87-91: LGTM: Clean props update

The AlertMessage component correctly implements the new serviceStatus parameter while maintaining the existing structure.


71-91: Verify the presence of required translation strings

Let's ensure the required translation string is properly defined in the strings file.

✅ Verification successful

Required translation string 'servedToElectronically' is properly defined.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the required translation string exists
# Expected: Find the servedToElectronically string definition

rg "servedToElectronically" --type ts

Length of output: 557

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx (1)

228-228: LGTM! Clean boolean prop syntax

The simplified boolean prop syntax follows modern React best practices.

Copy link

codecov bot commented Nov 13, 2024

Codecov Report

Attention: Patch coverage is 0% with 5 lines in your changes missing coverage. Please review.

Project coverage is 36.44%. Comparing base (2401e53) to head (23414b1).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...s/Shared/IndictmentOverview/IndictmentOverview.tsx 0.00% 4 Missing ⚠️
...omponents/InfoCard/DefendantInfo/DefendantInfo.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #16840   +/-   ##
=======================================
  Coverage   36.44%   36.44%           
=======================================
  Files        6852     6852           
  Lines      143527   143471   -56     
  Branches    40961    40932   -29     
=======================================
- Hits        52303    52289   -14     
+ Misses      91224    91182   -42     
Flag Coverage Δ
judicial-system-web 27.12% <0.00%> (-0.01%) ⬇️

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

Files with missing lines Coverage Δ
...d/IndictmentOverview/IndictmentOverview.strings.ts 0.00% <ø> (ø)
...omponents/InfoCard/DefendantInfo/DefendantInfo.tsx 75.60% <0.00%> (ø)
...s/Shared/IndictmentOverview/IndictmentOverview.tsx 0.00% <0.00%> (ø)

... and 7 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 2401e53...23414b1. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 13, 2024

Datadog Report

Branch report: j-s/fix-served-bu
Commit report: 100172b
Test service: judicial-system-web

✅ 0 Failed, 333 Passed, 0 Skipped, 1m 9.93s Total Time
➡️ Test Sessions change in coverage: 1 no change

@unakb unakb added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 13, 2024
@kodiakhq kodiakhq bot merged commit 8cf924e into main Nov 13, 2024
23 checks passed
@kodiakhq kodiakhq bot deleted the j-s/fix-served-bu branch November 13, 2024 17:57
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
* Checkpoint

* Refactor AlertMessage

* Format date

* Cleanup

* Cleanup

* Merge

* Add key

* Refactor

* Remove console.log

* Refactoring

* Merge

* Show to prosecutors

* Fix tests

* Handle served by electronically

* Checkpoint

* Remove console.log

---------

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

Successfully merging this pull request may close these issues.

3 participants