Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

chore(j-s): Indictment Case Arrignment Date #16156

Merged
merged 7 commits into from
Sep 27, 2024

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Sep 25, 2024

Indictment Case Arrignment Date

Höndla tilkynningar og skil á fyrirkalli í bakenda

What

  • Sendir tilkynningar um fyrirkall frá bakenda í stað framenda.

Why

  • Öruggari staður fyrir þessa virkni og undirbúningur undir flóknari fyrirkalls virkni.

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 messaging functionality for court and arraignment date changes, ensuring accurate notifications are sent.
    • Improved handling of arraignment date changes with notifications for each defendant.
    • Updated logic for handling changes in both arraignment and court dates for indictment cases.
  • Bug Fixes

    • Removed unnecessary notification logic for defendants, simplifying notification construction.
  • Tests

    • Expanded test coverage for the CaseController to include updates for both arraignment and court dates under the indictment case type.

@gudjong gudjong requested a review from a team as a code owner September 25, 2024 13:56
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The changes involve modifications to the CaseService class, specifically enhancing the methods that handle messaging related to court and arraignment date updates. The addMessagesForNewCourtDateToQueue method now accepts an additional boolean parameter to indicate if the arraignment date has changed. The addMessagesForUpdatedCaseToQueue method has been updated to check for changes in both arraignment and court dates for indictment cases. Corresponding test cases in the CaseController have also been updated to reflect these changes.

Changes

File Path Change Summary
apps/judicial-system/backend/src/app/modules/case/case.service.ts The addMessagesForNewCourtDateToQueue method now includes an arraignmentDateChanged boolean parameter. The addMessagesForUpdatedCaseToQueue method checks for changes in both arraignment and court dates for indictment cases.
apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts Added a new test suite for handling updates to arraignment dates, ensuring correct messaging for both arraignment and court date updates under the indictment case type. Modified existing tests to align with the new structure.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • oddsson
  • 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/backend/src/app/modules/subpoena/subpoena.service.ts (2)

Line range hint 129-133: Implement error handling improvement instead of TODO

The TODO comment highlights an important improvement for error handling. However, it's better to implement the suggestion rather than leaving it as a TODO in the code.

Consider implementing the error handling improvement as follows:

const [affectedRows] = await this.subpoenaModel.update(
  { subpoenaId: createdSubpoena.subpoenaId },
  { where: { id: subpoena.id } },
);

if (affectedRows === 0) {
  this.logger.error('Failed to update subpoena with police subpoenaId');
  // Consider throwing an error or handling this case appropriately
  return { delivered: false };
}

If you prefer to address this in a separate PR, I can create a GitHub issue to track this improvement. Would you like me to do that?


Line range hint 1-145: Enhance overall robustness and consistency of SubpoenaService

While the SubpoenaService class is well-structured, consider the following improvements to enhance its robustness and consistency:

  1. Implement consistent error handling across all methods. For example, the update method could benefit from more detailed error handling similar to findBySubpoenaId.

  2. Use transactions for operations that involve multiple database updates, such as in the update method when both subpoena and defendant are updated.

  3. Enhance logging throughout the class. Add more detailed log messages for important operations and their outcomes.

Here's an example of how you could improve the update method:

async update(
  subpoena: Subpoena,
  update: UpdateSubpoenaDto,
  transaction?: Transaction,
): Promise<Subpoena> {
  const t = transaction || await this.sequelize.transaction();
  try {
    const [subpoenaAffectedRows] = await this.subpoenaModel.update(update, {
      where: { subpoenaId: subpoena.subpoenaId },
      returning: true,
      transaction: t,
    });

    if (subpoenaAffectedRows === 0) {
      throw new Error(`Failed to update subpoena with id ${subpoena.subpoenaId}`);
    }

    if (update.defenderChoice || update.defenderNationalId) {
      const defendantUpdate: Partial<Defendant> = {
        defenderChoice: update.defenderChoice,
        defenderNationalId: update.defenderNationalId,
        defenderName: update.defenderName,
        defenderEmail: update.defenderEmail,
        defenderPhoneNumber: update.defenderPhoneNumber,
      };

      const [defenderAffectedRows] = await this.defendantModel.update(
        defendantUpdate,
        {
          where: { id: subpoena.defendantId },
          transaction: t,
        },
      );

      if (defenderAffectedRows === 0) {
        throw new Error(`Failed to update defendant with id ${subpoena.defendantId}`);
      }
    }

    if (!transaction) await t.commit();

    const updatedSubpoena = await this.findBySubpoenaId(subpoena.subpoenaId);
    this.logger.info(`Successfully updated subpoena with id ${subpoena.subpoenaId}`);
    return updatedSubpoena;
  } catch (error) {
    if (!transaction) await t.rollback();
    this.logger.error(`Error updating subpoena: ${error.message}`, error);
    throw error;
  }
}

This refactored version includes better error handling, use of transactions, and enhanced logging.

apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx (4)

42-42: LGTM: Improved arraignment status check

The change from isArraignmentDone to isArraignmentScheduled better aligns with the PR objectives. It correctly focuses on whether an arraignment date is set rather than if it's completed.

Consider using nullish coalescing for a more explicit check:

const isArraignmentScheduled = workingCase.arraignmentDate != null

This makes the intention clearer and handles both null and undefined explicitly.


Line range hint 46-78: LGTM: Updated navigation logic and removed frontend notifications

The changes in the handleNavigationTo function align well with the PR objectives:

  1. The condition now correctly checks if an arraignment is scheduled rather than completed.
  2. The removal of frontend notification logic supports the shift to backend-handled notifications.

Consider adding a comment explaining why the navigation logic differs based on isArraignmentScheduled. This would improve code readability and maintainability.

// If arraignment is already scheduled, we can navigate directly.
// Otherwise, we need to send the court date and update defendants before navigation.
if (isArraignmentScheduled) {
  // ... existing code ...
}

150-155: LGTM: Updated navigation logic in FormFooter

The changes in the onNextButtonClick prop correctly use isArraignmentScheduled to determine the navigation behavior. This is consistent with the earlier changes and PR objectives.

To improve code clarity, consider extracting the navigation path to a constant:

const NEXT_ROUTE = `${constants.INDICTMENTS_DEFENDER_ROUTE}/${workingCase.id}`;

onNextButtonClick={() => {
  if (isArraignmentScheduled) {
    router.push(NEXT_ROUTE);
  } else {
    setNavigateTo(constants.INDICTMENTS_DEFENDER_ROUTE);
  }
}}

This reduces repetition and makes the code more maintainable.


157-160: LGTM: Updated next button text logic

The change to use isArraignmentScheduled for determining the nextButtonText is consistent with the earlier modifications and PR objectives. Using undefined when the arraignment is scheduled is a good practice, allowing the component to use its default text.

To improve readability, consider using an early return:

nextButtonText={
  isArraignmentScheduled
    ? undefined
    : formatMessage(strings.nextButtonText)
}

This makes the conditional logic more explicit and easier to understand at a glance.

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

1342-1346: Simplify code by removing unnecessary Boolean() wrapper

Since arraignmentDateChanged is now a boolean after fixing the date comparisons, wrapping it with Boolean() is redundant.

Apply this diff:

          await this.addMessagesForNewCourtDateToQueue(
            updatedCase,
            user,
-            Boolean(arraignmentDateChanged),
+            arraignmentDateChanged,
          )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between aae6610 and cf631db.

📒 Files selected for processing (4)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/notification/notification.service.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1 hunks)
  • apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx (5 hunks)
💤 Files not reviewed due to no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/notification/notification.service.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.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."
🔇 Additional comments not posted (4)
apps/judicial-system/web/src/routes/Court/Indictments/Subpoena/Subpoena.tsx (2)

24-24: LGTM: New import for useDefendants hook

The addition of the useDefendants hook import is appropriate and aligns with the PR objectives. It follows NextJS best practices for importing custom hooks.


115-116: LGTM: Consistent disabling of court arrangements

The update to use isArraignmentScheduled for both dateTimeDisabled and courtRoomDisabled props is consistent with the overall changes and PR objectives. This ensures that court arrangements cannot be modified once an arraignment is scheduled, maintaining data integrity.

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

1146-1168: Changes to addMessagesForNewCourtDateToQueue look good

The addition of the arraignmentDateChanged parameter and the conditional logic for sending additional messages are correctly implemented.


1146-1146: Ensure all calls to addMessagesForNewCourtDateToQueue include the new parameter

Verify that all calls to addMessagesForNewCourtDateToQueue have been updated to include the new arraignmentDateChanged parameter to prevent runtime errors.

Run the following script to check for any outdated method calls:

Copy link

codecov bot commented Sep 25, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.71%. Comparing base (1494343) to head (4cb27a9).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16156      +/-   ##
==========================================
+ Coverage   36.69%   36.71%   +0.01%     
==========================================
  Files        6776     6774       -2     
  Lines      139590   139547      -43     
  Branches    39678    39662      -16     
==========================================
+ Hits        51226    51237      +11     
+ Misses      88364    88310      -54     
Flag Coverage Δ
judicial-system-backend 54.83% <100.00%> (+0.02%) ⬆️
judicial-system-web 28.16% <ø> (+0.01%) ⬆️
portals-admin-regulations-admin 1.93% <ø> (ø)

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

Files with missing lines Coverage Δ
...ystem/backend/src/app/modules/case/case.service.ts 90.85% <100.00%> (+0.21%) ⬆️
...c/app/modules/notification/notification.service.ts 94.44% <ø> (+2.33%) ⬆️
...ckend/src/app/modules/subpoena/subpoena.service.ts 0.00% <ø> (ø)
...src/routes/Court/Indictments/Subpoena/Subpoena.tsx 0.00% <ø> (ø)

... and 12 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 1494343...4cb27a9. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 25, 2024

Datadog Report

All test runs 6cf3260 🔗

15 Total Test Services: 0 Failed, 15 Passed
🔻 Test Sessions change in coverage: 2 decreased, 2 increased, 26 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.96s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 13.65s 1 no change Link
application-system-api 0 0 0 111 2 3m 12.58s 1 no change Link
application-template-api-modules 0 0 0 109 0 1m 50.5s 1 no change Link
auth-api-lib 0 0 0 20 0 25.32s 1 no change Link
judicial-system-backend 0 0 0 21126 0 19m 37.44s 1 increased (+0.02%) Link
judicial-system-web 0 0 0 338 0 1m 10.6s 1 no change Link
services-auth-admin-api 0 0 0 125 0 3m 12.32s 1 no change Link
services-auth-delegation-api 0 0 0 256 0 2m 47.14s 1 decreased (-0.19%) Link
services-auth-ids-api 0 0 0 152 0 1m 5.61s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • services-auth-delegation-api - jest 51.26% (-0.19%) - Details
  • services-auth-personal-representative-public - jest 40.7% (-0.02%) - Details

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 (1)
apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts (1)

906-907: Ensure consistent use of caseId in message objects

In the sendMessagesToQueue calls, you're using caseId: theCase.id for some messages and caseId for others. Since caseId and theCase.id are the same, for consistency and clarity, consider using caseId directly in all message objects.

Apply this diff to make the change:

            {
              type: MessageType.DELIVERY_TO_POLICE_SUBPOENA,
              user,
-             caseId: theCase.id,
+             caseId,
              elementId: defendantId1,
            },
            {
              type: MessageType.DELIVERY_TO_POLICE_SUBPOENA,
              user,
-             caseId: theCase.id,
+             caseId,
              elementId: defendantId2,
            },

Also applies to: 912-913

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cf631db and 9192246.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/case/test/caseController/update.spec.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)

1149-1171: LGTM! Consider adding a comment for clarity.

The changes to addMessagesForNewCourtDateToQueue align well with the PR objectives. The new parameter arraignmentDateChanged allows for more specific handling of arraignment date changes, improving the notification process.

Consider adding a brief comment explaining the purpose of the new conditional block:

 if (arraignmentDateChanged) {
+  // Send subpoena messages for each defendant when the arraignment date changes
   theCase.defendants?.forEach((defendant) => {
     messages.push({
       type: MessageType.DELIVERY_TO_POLICE_SUBPOENA,
       user,
       caseId: theCase.id,
       elementId: defendant.id,
     })
   })
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9192246 and f3a4c67.

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (1)
apps/judicial-system/backend/src/app/modules/case/case.service.ts (1)

1330-1352: Great job addressing the date comparison issue!

The changes to addMessagesForUpdatedCaseToQueue significantly improve the accuracy of date change detection for indictment cases. The use of getTime() for date comparisons resolves the issue mentioned in the past review comments. The addition of the arraignmentDateChanged parameter to addMessagesForNewCourtDateToQueue allows for more specific handling of arraignment date changes.

These changes align well with the PR objectives and enhance the notification system for indictment case arraignment dates.

Copy link
Member

@unakb unakb left a comment

Choose a reason for hiding this comment

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

Nice 😊

@gudjong gudjong added the automerge Merge this PR as soon as all checks pass label Sep 27, 2024
@kodiakhq kodiakhq bot merged commit 5efe4fd into main Sep 27, 2024
36 checks passed
@kodiakhq kodiakhq bot deleted the j-s/indictment-case-arraignment-date branch September 27, 2024 11:12
@coderabbitai coderabbitai bot mentioned this pull request Sep 30, 2024
6 tasks
thoreyjona pushed a commit that referenced this pull request Oct 2, 2024
* Locks subpoena fields when arraignment date has been set

* Move arraignment date message handling to the server side

* Updates tests and fixes date comparison

---------

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

Successfully merging this pull request may close these issues.

2 participants