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): add slack lock for daily court hearing arrangements #17468

Merged
merged 14 commits into from
Jan 14, 2025

Conversation

thorhildurt
Copy link
Member

@thorhildurt thorhildurt commented Jan 10, 2025

Betri yfirsýn fyrir fyrirtökur dagsins

What

  • Create a summary log to post in Slack for the daily court hearing arrangements

Why

  • Helps the team to plan manual deployments

Screenshots / Gifs

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

    • Added functionality to post hearing arrangements for a specific date.
    • Introduced new methods for handling daily hearing arrangement events and archiving cases.
  • Improvements

    • Enhanced case management and event tracking capabilities.
    • Improved scheduler service with more modular and robust error handling.
  • Maintenance

    • Removed unused import in limited access case controller.
    • Refactored application service methods for better code organization.

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Warning

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

🔧 eslint

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

warning [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/[email protected]: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/[email protected]: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > [email protected]: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning jest > @jest/core > @jest/reporters > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-config > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-runtime > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/transform > babel-plugin-istanbul > test-exclude > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning storybook > @storybook/cli > tempy > del > [email protected]: Rimraf versions prior to v4 are no longer supported
warning react-native > @react-native/codegen > [email protected]: Glob versions prior to v9 are no longer supported
warning react-native > @react-native-community/cli > @react-native-community/cli-tools > [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
warning react-native > @react-native/community-cli-plugin > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning react-native > @react-native/community-cli-plugin > @react-native/dev-middleware > @rnx-kit/chromium-edge-launcher > [email protected]: Rimraf versions prior to v4 are no longer supported
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-numeric-separator instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-async-generator-functions instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-logical-assignment-operators instead.
warning react-native > @react-native/community-cli-plugin > @react-native/metro-babel-transformer > @react-native/babel-preset > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-catch-binding instead.
warning next-auth > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning next-auth > [email protected]: this version is no longer supported
warning next-auth > @next-auth/typeorm-legacy-adapter > typeorm > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > stylus > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > webpack-dev-server > [email protected]: Rimraf versions prior to v4 are no longer supported
warning @nx/next > @nx/webpack > fork-ts-checker-webpack-plugin > [email protected]: this will be v4
warning @nx/next > @nx/webpack > webpack-dev-server > webpack-dev-middleware > [email protected]: this will be v4
warning workspace-aggregator-fdaa74db-20fb-4617-99a8-5123522960f6 > [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.

Walkthrough

This pull request introduces new functionality for handling court hearing arrangements in the judicial system backend. A new method postHearingArrangements is added to the InternalCaseController, which retrieves cases with court hearing arrangements for a specific date. The InternalCaseService includes a corresponding method getCaseHearingArrangements to fetch these cases. An additional method in the EventService allows posting daily hearing arrangement events, and the scheduler's AppService is updated to incorporate these new features into its run cycle.

Changes

File Change Summary
apps/judicial-system/backend/src/app/modules/case/internalCase.controller.ts Added postHearingArrangements method to handle POST requests for court hearing arrangements.
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts Added getCaseHearingArrangements method to retrieve cases with hearing arrangements for a specific date.
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts Removed unused DefendantEventType import.
apps/judicial-system/backend/src/app/modules/event/event.service.ts Added postDailyHearingArrangementEvents method to send events for daily hearing arrangements.
apps/judicial-system/scheduler/src/app/app.service.ts Added new private methods for handling case-related tasks and updated run method.
apps/judicial-system/scheduler/src/app/test/run.spec.ts Updated test cases to reflect changes in the expected behavior of fetch calls.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb
  • oddsson

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34903bd and 42e9bd7.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/event/event.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/event/event.service.ts

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

@thorhildurt thorhildurt changed the title J s/add slack log for hearing arrangements chore(j-s): add slack lock for daily court hearing arrangements Jan 10, 2025
…github.com/island-is/island.is into j-s/add-slack-log-for-hearing-arrangements

# Conflicts:
#	apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
@thorhildurt thorhildurt self-assigned this Jan 10, 2025
@thorhildurt thorhildurt marked this pull request as ready for review January 10, 2025 10:04
@thorhildurt thorhildurt requested a review from a team as a code owner January 10, 2025 10:04
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: 2

🧹 Nitpick comments (2)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

105-113: Consider parallel execution for independent tasks

The tasks appear to be independent and could be executed in parallel using Promise.all() for better performance.

Apply this diff:

   async run() {
     this.logger.info('Scheduler starting')
 
-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])
 
     this.logger.info('Scheduler done')
   }
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

523-544: Add input validation and consider performance optimization

The method needs input validation and could benefit from performance optimization.

  1. Add input validation:
   async getCaseHearingArrangements(date: Date): Promise<Case[]> {
+    if (!(date instanceof Date) || isNaN(date.getTime())) {
+      throw new BadRequestException('Invalid date provided')
+    }
  1. Consider adding an index on the date_type and date columns for better query performance:
CREATE INDEX idx_date_logs_type_date ON date_logs (date_type, date);
  1. Consider adding a limit to prevent excessive memory usage:
   return this.caseModel.findAll({
     include: [...],
     order: [...],
+    limit: 1000, // Adjust based on requirements
   })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1364f19 and b4afe11.

📒 Files selected for processing (5)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (0 hunks)
  • apps/judicial-system/backend/src/app/modules/event/event.service.ts (1 hunks)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts
🧰 Additional context used
📓 Path-based instructions (4)
apps/judicial-system/backend/src/app/modules/event/event.service.ts (1)

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

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

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/scheduler/src/app/app.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."
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (3)
apps/judicial-system/scheduler/src/app/app.service.ts (2)

Line range hint 27-41: Well-structured message queue handling!

Good job extracting this functionality into a separate method with proper error handling and logging.


Line range hint 43-79: Well-implemented archiving logic!

Good implementation of retry mechanism with proper time limit and error handling.

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

176-219: Add JSDoc documentation for better maintainability

The method would benefit from JSDoc documentation explaining its purpose, parameters, and return type.

Add documentation:

+  /**
+   * Posts a summary of daily hearing arrangements to Slack
+   * @param date The date for which to post hearing arrangements
+   * @param cases Array of cases with hearing arrangements
+   * @returns Promise<void>
+   */
   async postDailyHearingArrangementEvents(date: Date, cases: Case[]) {

Also, consider adding unit tests to verify the formatting logic and error handling.

✅ Verification successful

Add JSDoc documentation and unit tests for better maintainability

The original suggestion for adding JSDoc documentation is valid. Additionally, the verification confirms that there are no direct unit tests for the EventService, despite its important role in posting hearing arrangements. The service is only referenced in test setup modules.

  • Add the suggested JSDoc documentation
  • Create a dedicated test file (event.service.spec.ts) to cover:
    • Message formatting logic
    • Error handling
    • Empty case list handling
    • Date formatting
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing test coverage
fd -e spec.ts -e test.ts | grep -l "event.service"

Length of output: 50


Script:

#!/bin/bash
# Try multiple search strategies to find test files
echo "=== Searching for EventService tests ==="
rg -l "EventService" --type ts

echo -e "\n=== Searching for event.service tests ==="
rg -l "event.service" --type ts

echo -e "\n=== Looking for spec files in event module ==="
fd -e ts . src/app/modules/event

Length of output: 3898

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

Attention: Patch coverage is 39.53488% with 26 lines in your changes missing coverage. Please review.

Project coverage is 35.65%. Comparing base (4785092) to head (f7ba653).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...tem/backend/src/app/modules/event/event.service.ts 0.00% 16 Missing ⚠️
...nd/src/app/modules/case/internalCase.controller.ts 33.33% 4 Missing ⚠️
...ckend/src/app/modules/case/internalCase.service.ts 0.00% 4 Missing ⚠️
...s/judicial-system/scheduler/src/app/app.service.ts 88.23% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17468      +/-   ##
==========================================
+ Coverage   35.61%   35.65%   +0.04%     
==========================================
  Files        7015     6976      -39     
  Lines      150294   149937     -357     
  Branches    42969    42907      -62     
==========================================
- Hits        53529    53464      -65     
+ Misses      96765    96473     -292     
Flag Coverage Δ
application-templates-new-primary-school ?
judicial-system-backend 55.81% <7.69%> (-0.06%) ⬇️
judicial-system-scheduler 71.36% <88.23%> (+0.11%) ⬆️

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

Files with missing lines Coverage Δ
...c/app/modules/case/limitedAccessCase.controller.ts 97.50% <ø> (ø)
...s/judicial-system/scheduler/src/app/app.service.ts 95.55% <88.23%> (-4.45%) ⬇️
...nd/src/app/modules/case/internalCase.controller.ts 94.79% <33.33%> (-2.21%) ⬇️
...ckend/src/app/modules/case/internalCase.service.ts 83.29% <0.00%> (-0.80%) ⬇️
...tem/backend/src/app/modules/event/event.service.ts 24.71% <0.00%> (-5.42%) ⬇️

... and 97 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 4785092...f7ba653. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Jan 10, 2025

Datadog Report

All test runs 7a456df 🔗

6 Total Test Services: 0 Failed, 6 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.05%), 1 increased (+0.01%), 8 no change

Test 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.44s 1 no change Link
application-system-api 0 0 0 46 0 2m 12.06s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 3.86s 1 no change Link
application-ui-shell 0 0 0 74 0 31.1s 1 no change Link
judicial-system-backend 0 0 0 21053 0 18m 39.21s 1 decreased (-0.05%) Link
judicial-system-scheduler 0 0 0 4 0 3.85s 1 increased (+0.01%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • judicial-system-backend - jest 59.48% (-0.05%) - 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 comments (1)
apps/judicial-system/scheduler/src/app/test/run.spec.ts (1)

Line range hint 79-91: Improve test clarity for the new fetch call.

The test now expects 4 fetch calls instead of 3, presumably due to the new hearing arrangements functionality. However, the test description and mock responses don't clearly indicate the purpose of this additional call.

Consider:

  1. Adding a descriptive comment explaining what each fetch call is for
  2. Including mock responses for hearing arrangement data
  3. Adding assertions to verify the hearing arrangement API call
     beforeEach(async () => {
       mockFetch
+        // Mock response for hearing arrangements
+        .mockResolvedValueOnce({
+          ok: true,
+          json: () => Promise.resolve({ hearingArrangements: [] }),
+        })
+        // Mock responses for case archiving
         .mockResolvedValue({
           ok: true,
           json: () => Promise.resolve({ caseArchived: false }),
         })
         .mockResolvedValueOnce({
           ok: true,
           json: () => Promise.resolve({ caseArchived: true }),
         })
         .mockResolvedValueOnce({
           ok: true,
           json: () => Promise.resolve({ caseArchived: true }),
         })

       await givenWhenThen()
     })

-    it('should continue until done', () => {
+    it('should fetch hearing arrangements and continue archiving until done', () => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b4afe11 and 239f60e.

📒 Files selected for processing (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/test/run.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."
🔇 Additional comments (1)
apps/judicial-system/scheduler/src/app/test/run.spec.ts (1)

31-31: LGTM!

The added empty line improves code readability.

apps/judicial-system/scheduler/src/app/test/run.spec.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
apps/judicial-system/scheduler/src/app/app.service.ts (4)

Line range hint 27-41: Consider adding retry logic for better resilience

While the error handling logs failures, adding retry logic would improve reliability for transient failures.

Consider implementing exponential backoff:

   private addMessagesForIndictmentsWaitingForConfirmationToQueue() {
+    const maxRetries = 3;
+    const retry = async (attempt = 0): Promise<void> => {
+      try {
         return this.messageService
           .sendMessagesToQueue([
             {
               type: MessageType.NOTIFICATION_DISPATCH,
               body: {
                 type: NotificationDispatchType.INDICTMENTS_WAITING_FOR_CONFIRMATION,
               },
             },
           ])
-          .catch((reason) =>
-            // Tolerate failure, but log
-            this.logger.error('Failed to dispatch notifications', { reason }),
-          )
+      } catch (error) {
+        if (attempt < maxRetries) {
+          const delay = Math.pow(2, attempt) * 1000;
+          this.logger.warn(`Retry attempt ${attempt + 1} after ${delay}ms`, { error });
+          await new Promise(resolve => setTimeout(resolve, delay));
+          return retry(attempt + 1);
+        }
+        this.logger.error('Failed to dispatch notifications after retries', { error });
+      }
+    };
+    return retry();
   }

Line range hint 43-79: Well-implemented retry mechanism and error handling

The implementation shows good practices with:

  • Time-bounded retries
  • Proper error handling
  • Secure authorization header usage

Consider extracting the content-type header to a constant:

+const JSON_CONTENT_TYPE = 'application/json';
+
   private async archiveCases() {
     // ...
           headers: {
-            'Content-Type': 'application/json',
+            'Content-Type': JSON_CONTENT_TYPE,
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },

81-103: Improve error handling and URL construction

While the timezone-insensitive date handling is intentional (as per previous discussion), there are some improvements possible:

   private async postDailyHearingArrangementSummary() {
     const today = now()
+    const url = new URL(`api/internal/cases/postHearingArrangements/${today}`, this.config.backendUrl);
     try {
       const res = await fetch(
-        `${this.config.backendUrl}/api/internal/cases/postHearingArrangements/${today}`,
+        url.toString(),
         {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },
         },
       )

       if (!res.ok) {
+        const errorBody = await res.text();
         throw new BadGatewayException(
-          'Unexpected error occurred while fetching cases',
+          `Unexpected error occurred while fetching cases: ${errorBody}`,
         )
       }
     } catch (error) {
+      if (error instanceof BadGatewayException) {
+        throw error;
+      }
       throw new BadGatewayException(`Failed to fetch cases: ${error.message}`)
     }
   }

105-111: Consider parallel execution for independent operations

The sequential execution is clear, but independent operations could be executed in parallel for better performance.

   async run() {
     this.logger.info('Scheduler starting')

-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])

     this.logger.info('Scheduler done')
   }

Note: Only implement this if these operations are truly independent and can be executed concurrently without side effects.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 239f60e and d792494.

📒 Files selected for processing (2)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/app.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."
📓 Learnings (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)
Learnt from: thorhildurt
PR: island-is/island.is#17468
File: apps/judicial-system/scheduler/src/app/app.service.ts:81-103
Timestamp: 2025-01-10T11:23:01.559Z
Learning: In the judicial system backend, court hearing arrangements and their date handling (including in `postDailyHearingArrangementSummary`) are designed to be timezone-insensitive, using native Date objects without specific timezone handling.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

3-3: LGTM: Import follows NestJS best practices

The BadGatewayException import is appropriately added and used for error handling.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
apps/judicial-system/scheduler/src/app/app.service.ts (3)

Line range hint 27-41: Consider adding retry logic for resilience

While the error handling is appropriate for a scheduler task, consider implementing retry logic to improve reliability, similar to the archiveCases method.

 private addMessagesForIndictmentsWaitingForConfirmationToQueue() {
+    const startTime = now()
+    const retry = async () => {
     return this.messageService
       .sendMessagesToQueue([
         {
           type: MessageType.NOTIFICATION_DISPATCH,
           body: {
             type: NotificationDispatchType.INDICTMENTS_WAITING_FOR_CONFIRMATION,
           },
         },
       ])
       .catch((reason) => {
-        // Tolerate failure, but log
-        this.logger.error('Failed to dispatch notifications', { reason }),
+        this.logger.error('Failed to dispatch notifications', { reason })
+        if (minutesBetween(startTime, now()) < this.config.timeToLiveMinutes) {
+          return retry()
+        }
       })
+    }
+    return retry()
   }

81-103: Consider enhancing error handling and retry logic

While the error handling is good, consider these improvements:

  1. Add retry logic similar to archiveCases for consistency
  2. Include more specific error details in the BadGatewayException message
   private async postDailyHearingArrangementSummary() {
     const today = now()
+    const startTime = now()
+    
+    const attemptPost = async () => {
     try {
       const res = await fetch(
         `${this.config.backendUrl}/api/internal/cases/postHearingArrangements/${today}`,
         {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
             authorization: `Bearer ${this.config.backendAccessToken}`,
           },
         },
       )

       if (!res.ok) {
+        const errorBody = await res.text()
         throw new BadGatewayException(
-          'Unexpected error occurred while fetching cases',
+          `Unexpected error occurred while fetching cases: ${res.status} - ${errorBody}`,
         )
       }
     } catch (error) {
-      throw new BadGatewayException(`Failed to fetch cases: ${error.message}`)
+      if (minutesBetween(startTime, now()) < this.config.timeToLiveMinutes) {
+        return attemptPost()
+      }
+      throw new BadGatewayException(
+        `Failed to fetch cases after retries: ${error.message}`
+      )
     }
+    }
+    return attemptPost()
   }

105-112: Consider parallel execution for independent tasks

The run method executes tasks sequentially, which is safe but might not be optimal. Consider running independent tasks in parallel using Promise.all() if they don't have dependencies.

   async run() {
     this.logger.info('Scheduler starting')
 
-    await this.addMessagesForIndictmentsWaitingForConfirmationToQueue()
-    await this.archiveCases()
-    await this.postDailyHearingArrangementSummary()
+    await Promise.all([
+      this.addMessagesForIndictmentsWaitingForConfirmationToQueue(),
+      this.archiveCases(),
+      this.postDailyHearingArrangementSummary(),
+    ])
 
     this.logger.info('Scheduler done')
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d792494 and 27e2ecf.

📒 Files selected for processing (2)
  • apps/judicial-system/scheduler/src/app/app.service.ts (4 hunks)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/scheduler/src/app/test/run.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/scheduler/src/app/app.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."
📓 Learnings (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)
Learnt from: thorhildurt
PR: island-is/island.is#17468
File: apps/judicial-system/scheduler/src/app/app.service.ts:81-103
Timestamp: 2025-01-10T11:23:01.559Z
Learning: In the judicial system backend, court hearing arrangements and their date handling (including in `postDailyHearingArrangementSummary`) are designed to be timezone-insensitive, using native Date objects without specific timezone handling.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: prepare
🔇 Additional comments (2)
apps/judicial-system/scheduler/src/app/app.service.ts (2)

3-3: LGTM: Import addition is well-placed

The BadGatewayException import is appropriately grouped with other NestJS imports and is used correctly in the error handling.


Line range hint 43-79: LGTM: Well-implemented retry mechanism

The archiveCases method implements a robust retry mechanism with proper time limiting and error handling.

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

🧹 Nitpick comments (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)

Line range hint 43-79: Enhance error logging context

The implementation is robust with proper retry mechanism and timeout. Consider enhancing the error logging by including more context about the failure.

-          this.logger.error('Failed to archive cases', { reason })
+          this.logger.error('Failed to archive cases', { 
+            reason,
+            attemptNumber: minutesBetween(startTime, now()),
+            maxAttempts: this.config.timeToLiveMinutes
+          })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27e2ecf and 34903bd.

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/scheduler/src/app/app.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."
📓 Learnings (1)
apps/judicial-system/scheduler/src/app/app.service.ts (1)
Learnt from: thorhildurt
PR: island-is/island.is#17468
File: apps/judicial-system/scheduler/src/app/app.service.ts:81-103
Timestamp: 2025-01-10T11:23:01.559Z
Learning: In the judicial system backend, court hearing arrangements and their date handling (including in `postDailyHearingArrangementSummary`) are designed to be timezone-insensitive, using native Date objects without specific timezone handling.
🔇 Additional comments (3)
apps/judicial-system/scheduler/src/app/app.service.ts (2)

3-3: LGTM!

The addition of BadGatewayException import is appropriate for handling gateway errors in the new functionality.


Line range hint 27-41: LGTM! Well-structured queue message handling

The implementation follows good practices with proper error handling and logging. The method gracefully handles failures without breaking the execution flow.

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

80-92: 🛠️ Refactor suggestion

Add API documentation, input validation, and error handling

The endpoint implementation needs several improvements:

  1. Missing API documentation
  2. No input validation for the date parameter
  3. Basic error handling
  4. Unsafe date conversion
+  @ApiOkResponse({
+    description: 'Successfully posted hearing arrangements summary',
+  })
   @Post('cases/postHearingArrangements')
   async postHearingArrangements(
-    @Body() { date }: { date: Date },
+    @Body(new ValidationPipe({
+      transform: true,
+      whitelist: true,
+    }))
+    body: { date: string },
   ): Promise<void> {
     this.logger.debug(
-      `Post internal summary of all cases that have court hearing arrangement at ${date}`,
+      'Posting internal summary of court hearing arrangements',
+      { date: body.date }
     )
 
-    const cases = await this.internalCaseService.getCaseHearingArrangements(
-      new Date(date),
-    )
-    await this.eventService.postDailyHearingArrangementEvents(date, cases)
+    try {
+      const parsedDate = new Date(body.date)
+      if (isNaN(parsedDate.getTime())) {
+        throw new BadRequestException('Invalid date format')
+      }
+
+      const cases = await this.internalCaseService.getCaseHearingArrangements(parsedDate)
+      await this.eventService.postDailyHearingArrangementEvents(parsedDate, cases)
+    } catch (error) {
+      this.logger.error('Failed to post hearing arrangements', { error, date: body.date })
+      if (error instanceof BadRequestException) {
+        throw error
+      }
+      throw new InternalServerErrorException('Failed to process hearing arrangements')
+    }
   }

Likely invalid or redundant comment.

@thorhildurt thorhildurt added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Jan 14, 2025
@kodiakhq kodiakhq bot merged commit 006bb01 into main Jan 14, 2025
37 checks passed
@kodiakhq kodiakhq bot deleted the j-s/add-slack-log-for-hearing-arrangements branch January 14, 2025 16:28
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