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(accident-notification): connect new api for accident-notification #15420

Merged
merged 28 commits into from
Oct 9, 2024

Conversation

jonnigs
Copy link
Member

@jonnigs jonnigs commented Jul 2, 2024

What

Connect a new client for accident notifications and stop using the old xml client

Why

To modernize

Checklist:

  • I have performed a self-review of my own code
  • 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

Summary by CodeRabbit

  • New Features

    • Enhanced accident notification status retrieval by incorporating user context for personalized data handling.
    • Streamlined the ApplicationStatus component logic, improving readability and maintainability through the introduction of utility functions.
    • Added new functions for improved attachment management, enabling better handling of accident report submissions and associated data.
  • Bug Fixes

    • Updated error handling in the ApplicationStatus component to provide clearer feedback when data is unavailable.
  • Documentation

    • Improved clarity in method signatures and component props for better developer understanding.
  • Chores

    • Removed unused imports and refactored component logic to reduce redundancy.

Copy link
Contributor

coderabbitai bot commented Jul 2, 2024

Walkthrough

The changes involve updates to the HealthInsuranceAccidentNotificationResolver class in the accident-notification.resolver.ts file, where a new CurrentUser decorator and User type are introduced. The accidentStatus method is modified to accept a new user parameter, enhancing its ability to handle user-specific data. Additionally, the ApplicationStatus component in the index.tsx file is refactored to remove unused imports, simplify logic, and improve readability by integrating a new utility function for status management. A new mock service is also introduced in the test suite for the AccidentNotificationService.

Changes

File Path Change Summary
libs/api/domains/health-insurance/src/lib/graphql/accident-notification.resolver.ts Updated accidentStatus method to include a user parameter annotated with @CurrentUser().
libs/application/templates/accident-notification/src/fields/ApplicationStatus/index.tsx Refactored ApplicationStatus component to remove unused imports, simplify logic, and replace getValueViaPath with getStatusAndApproval.
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts Introduced AccidentreportsApi mock service with methods submitAccidentReportAttachment and addAttachment. Updated tests to use the new mock service.
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts Refactored AccidentNotificationService to replace DocumentApi with AccidentreportsApi, updating methods for report submission and attachment management.
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts Added new functions for attachment management, including getReportId, getNewAttachments, and getReviewApplicationData.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • thorkellmani

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.

@jonnigs jonnigs changed the title feat: connect new api for accident-notification feat(accident-notification): connect new api for accident-notification Oct 1, 2024
@datadog-island-is
Copy link

datadog-island-is bot commented Oct 1, 2024

Datadog Report

All test runs e20c248 🔗

99 Total Test Services: 0 Failed, 97 Passed
🔻 Test Sessions change in coverage: 3 decreased, 8 increased, 189 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-backend 0 0 0 81 0 25.36s N/A Link
air-discount-scheme-web 0 0 0 2 0 9.13s N/A Link
api 0 0 0 4 0 3.27s N/A Link
api-catalogue-services 0 0 0 23 0 10.97s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 20.32s N/A Link
api-domains-assets 0 0 0 3 0 12.43s N/A Link
api-domains-auth-admin 0 0 0 18 0 14.09s N/A Link
api-domains-communications 0 0 0 5 0 29.1s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.74s N/A Link
api-domains-driving-license 0 0 0 23 0 28.74s N/A Link

🔻 Code Coverage Decreases vs Default Branch (3)

  • nest-feature-flags - jest 56.81% (-0.46%) - Details
  • api-domains-health-insurance - jest 36.03% (-0.08%) - Details
  • services-auth-personal-representative-public - jest 40.68% (-0.03%) - Details

@jonnigs jonnigs marked this pull request as ready for review October 1, 2024 10:21
@jonnigs jonnigs requested review from a team as code owners October 1, 2024 10:21
@jonnigs jonnigs added the deploy-feature Deploys features to dev label Oct 1, 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: 18

🧹 Outside diff range and nitpick comments (19)
libs/clients/icelandic-health-insurance/rights-portal/src/lib/providers.ts (1)

28-28: LGTM: AccidentreportsApi correctly added to exportedApis.

The AccidentreportsApi is successfully added to the exportedApis array, ensuring it will be provided with the shared configuration like other APIs.

Consider maintaining alphabetical order in the exportedApis array for consistency. You might want to move AccidentreportsApi to the beginning of the list:

 export const exportedApis = [
+  AccidentreportsApi,
   TherapyApi,
   AidsandnutritionApi,
   DentistApi,
   HealthcenterApi,
   EhicApi,
   InsurancestatementsApi,
   DrugApi,
   OverviewApi,
   PaymentsCopaymentApi,
   PaymentsOverviewApi,
-  AccidentreportsApi,
 ].map((Api) => ({
libs/clients/icelandic-health-insurance/rights-portal/src/clientConfig.json (5)

2419-2452: Improved accident reporting structure

The changes to the AccidentDTO schema enhance the accident reporting process by requiring more specific information. The addition of 'symptoms' and 'dateTimeOfDoctorVisit' fields will provide valuable data for assessment and analysis.

Consider adding a field for 'severity' to further categorize accidents and prioritize responses.

{
  "type": "object",
  "properties": {
    // ... existing properties ...
+   "severity": {
+     "type": "string",
+     "enum": ["minor", "moderate", "severe", "critical"],
+     "description": "The severity level of the accident"
+   }
  }
}

Line range hint 2679-2693: Reconsider making 'phone' optional in InjuredDTO

While adding 'occupation' is valuable for work-related accident analysis, making 'phone' optional might hinder immediate contact in urgent situations.

Consider keeping both 'phone' and 'occupation' as required fields to ensure comprehensive data collection and maintain the ability for quick communication.

{
  "type": "object",
  "properties": {
    // ... existing properties ...
    "occupation": {
      "type": "string",
      "nullable": true
    },
    "phone": {
-     "type": "string",
-     "nullable": true
+     "type": "string"
    }
  },
  "required": [
    "email",
    "name",
    "nationalId",
+   "phone",
+   "occupation"
  ]
}

Line range hint 2577-2592: Improved accountability in accident report confirmations

The addition of 'accepted' and 'party' as required fields in the AccidentReportConfirmationDTO enhances accountability and clarity in the confirmation process. This change will help track the status of each report more effectively.

Consider adding a 'timestamp' field to record when the confirmation was made, further improving the audit trail.

{
  "type": "object",
  "properties": {
    // ... existing properties ...
+   "timestamp": {
+     "type": "string",
+     "format": "date-time",
+     "description": "The date and time when the confirmation was made"
+   }
  },
  "required": [
    "accepted",
    "party",
+   "timestamp"
  ]
}

4288-4308: Enhanced error handling and tracing in InsuranceStatementApplicationResponseDTO

The addition of 'requestId', 'errors', and 'errorStack' fields significantly improves the ability to track and debug issues in insurance statement applications. This will lead to better error resolution and system reliability.

However, be cautious about exposing detailed error information, especially in production environments. Consider implementing a mechanism to control the verbosity of error details based on the environment or user role.

Implement a configuration setting to control error detail exposure:

{
  "errorHandling": {
    "exposeDetailedErrors": false,
    "logDetailedErrors": true
  }
}

Use this configuration to determine whether to include the 'errorStack' in the response or just log it internally.


Line range hint 3753-3801: Improved drug certificate status tracking

The addition of the 'status' field with the DrugCertificateStatusEnum provides a clear and consistent way to represent the state of drug certificates. This enhancement will improve the management and tracking of drug certificates throughout their lifecycle.

To further improve clarity, consider adding descriptions for each enum value in the OpenAPI specification. This will help API consumers understand the meaning of each status.

Enhance the DrugCertificateStatusEnum definition:

"DrugCertificateStatusEnum": {
  "enum": [0, 1, 2, 3],
  "type": "integer",
  "format": "int32",
  "description": "The status of the drug certificate",
  "x-enum-descriptions": [
    "Pending",
    "Approved",
    "Rejected",
    "Expired"
  ]
}

This addition provides clear descriptions for each status value, improving API documentation and usability.

libs/clients/icelandic-health-insurance/rights-portal/src/index.ts (1)

21-36: Ensure exports align with effective tree-shaking practices

Exporting numerous entities may impact bundling and tree-shaking effectiveness. Please review whether all exported items are necessary for external use or if some can remain internal to minimize bundle size.

libs/application/templates/accident-notification/src/types/index.ts (2)

181-236: Evaluate the use of 'V2' suffix in type names for better maintainability

Appending V2 to type names like ApplicantV2 and AccidentDetailsV2 may not scale well as the application evolves. Consider alternative versioning strategies, such as using namespaces or versioning within the API routes, to manage different versions of types without polluting the type names.


181-236: Clarify the necessity of 'string | null' in optional properties

Since the properties are already optional (using ?), including null in the type (string | null) may be redundant unless there's a need to distinguish between undefined and null. If differentiating between these is important due to external API requirements or data handling, consider adding comments to explain the rationale.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (3)

45-52: Standardize naming of accidentReportsApi

There is an inconsistency in naming between the class property and the method. The class property is named accidentReportsApi, but the method is named accidentsReportsApiWithAuth (note the additional 's' in accidents).

Apply this diff to fix the method name for consistency:

- private accidentsReportsApiWithAuth(auth: Auth) {
+ private accidentReportsApiWithAuth(auth: Auth) {
    return this.accidentReportsApi.withMiddleware(new AuthMiddleware(auth))
  }

143-149: Consider removing commented-out code

The code related to sending new attachments is commented out. If this functionality is no longer needed, consider removing the commented-out code to keep the codebase clean and maintainable.


163-181: Remove unused sendAttachment method

The sendAttachment method is entirely commented out. If it's no longer required, it's better to remove it to reduce clutter and improve code readability.

libs/api/domains/application/src/lib/application.service.ts (2)

Line range hint 131-136: Consider refactoring repeated destructuring and API call patterns

The methods update, addAttachment, deleteAttachment, updateExternalData, generatePdfPresignedUrl, requestFileSignature, and uploadSignedFile all follow a similar pattern:

  • Destructuring id from input
  • Spreading the remaining properties into a DTO object
  • Calling the corresponding API method with id and the DTO

To reduce code duplication and improve maintainability, consider creating a helper function or abstraction that encapsulates this pattern.

Also applies to: 138-143, 145-150, 152-158, 170-176, 178-184


Line range hint 186-192: Inconsistent method naming: 'Url' vs 'URL'

The method names presignedUrl and attachmentPresignedURL use different casing for Url/URL. For consistency and readability, consider standardizing the casing. For example, choose either Url or URL consistently across method names.

Also applies to: 194-200

libs/application/templates/accident-notification/src/lib/dataSchema.ts (5)

Line range hint 33-42: Consider adding validation for 'phoneNumber' field in 'representative' schema.

The phoneNumber field is defined as an optional string without validation. To ensure data integrity, consider adding validation to check that the phone number is in the expected format.

Apply this diff to add validation:

const representative = z.object({
  name: z.string().refine((x) => x.trim().length > 0, {
    params: error.invalidValue,
  }),
  nationalId: z.string().refine((x) => (x ? kennitala.isPerson(x) : false), {
    params: error.invalidValue,
  }),
  email: z.string().email(),
- phoneNumber: z.string().optional(),
+ phoneNumber: z
+   .string()
+   .optional()
+   .refine((x) => (x ? isValidPhoneNumber(x) : true), {
+     params: error.invalidValue,
+   }),
})

Note: You'll need to implement or import an isValidPhoneNumber function as appropriate.


148-163: Consider adding validation for 'phoneNumber' field in 'injuredPersonInformation' schema.

In the injuredPersonInformation schema, the phoneNumber field is optional and defined as a string without validation. To ensure data integrity, consider adding validation to check that the phone number is in the expected format.

Apply this diff to add validation:

phoneNumber: z
  .string()
  .optional()
+ .refine((x) => (x ? isValidPhoneNumber(x) : true), {
+   params: error.invalidValue,
+ }),

Note: You need to implement or import an isValidPhoneNumber function as appropriate.


179-186: Consider adding validation for 'name' field in 'childInCustody' schema.

The name field is validated for trimmed length greater than zero. To enhance validation, consider adding checks to ensure the name contains valid characters and does not include numbers or special symbols.

Apply this diff to enhance name validation:

name: z
  .string()
  .refine((x) => x.trim().length > 0, {
    params: error.invalidValue,
  })
+ .regex(/^[A-Za-zÁÉÍÓÚÝÞÆÖáéíóúýþæö\s'-]+$/, {
+   params: error.invalidValue,
+ }),

Note: Adjust the regular expression to match valid characters based on your requirements.


189-189: Ensure 'approveExternalData' has a meaningful error message.

The approveExternalData field uses .refine((v) => v) without specifying an error message. Consider providing a custom error message to inform users why their input was invalid.

Apply this diff to add an error message:

approveExternalData: z
  .boolean()
- .refine((v) => v),
+ .refine((v) => v, {
+   params: error.approvalRequired,
+ }),

Note: Define error.approvalRequired with an appropriate message in your error definitions.


Line range hint 188-267: Confirm adherence to TypeScript best practices and effective tree-shaking.

Since this is part of libs/**/*, ensure that all exported types and schemas are correctly typed and that unused code is eliminated during bundling to support effective tree-shaking.

Consider reviewing the exports and imports to ensure they align with best practices for library code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ff7d751 and 55939e2.

📒 Files selected for processing (12)
  • apps/application-system/api/src/app/app.module.ts (2 hunks)
  • libs/api/domains/application/src/lib/application.service.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (6 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accodent-notification-v2.utils.ts (1 hunks)
  • libs/application/templates/accident-notification/src/lib/AccidentNotificationTemplate.ts (0 hunks)
  • libs/application/templates/accident-notification/src/lib/dataSchema.ts (5 hunks)
  • libs/application/templates/accident-notification/src/types/index.ts (3 hunks)
  • libs/application/ui-shell/src/lib/FormShell.tsx (0 hunks)
  • libs/clients/icelandic-health-insurance/rights-portal/src/clientConfig.json (28 hunks)
  • libs/clients/icelandic-health-insurance/rights-portal/src/index.ts (1 hunks)
  • libs/clients/icelandic-health-insurance/rights-portal/src/lib/providers.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • libs/application/templates/accident-notification/src/lib/AccidentNotificationTemplate.ts
  • libs/application/ui-shell/src/lib/FormShell.tsx
🧰 Additional context used
📓 Path-based instructions (10)
apps/application-system/api/src/app/app.module.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."
libs/api/domains/application/src/lib/application.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accodent-notification-v2.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/lib/dataSchema.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/types/index.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/clients/icelandic-health-insurance/rights-portal/src/clientConfig.json (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/clients/icelandic-health-insurance/rights-portal/src/index.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/clients/icelandic-health-insurance/rights-portal/src/lib/providers.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accodent-notification-v2.utils.ts (1)
Learnt from: HjorturJ
PR: island-is/island.is#16111
File: libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.utils.spec.ts:210-361
Timestamp: 2024-09-25T13:23:39.010Z
Learning: In `accident-notification.utils.spec.ts`, the helper functions `getDefaultAttachments` and `getFullBasicAnswers` should not be modified to accept parameters for customizing returned data.
🪛 Biome
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accodent-notification-v2.utils.ts

[error] 259-260: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 293-295: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (16)
libs/clients/icelandic-health-insurance/rights-portal/src/lib/providers.ts (2)

13-13: LGTM: Import statement for AccidentreportsApi is correct.

The AccidentreportsApi is correctly imported from the '../../gen/fetch' module, following the existing pattern and maintaining consistency with other API imports.


Line range hint 1-34: Overall assessment: Changes are well-implemented and align with project goals.

The addition of AccidentreportsApi to this providers file is well-executed and aligns with the PR objectives of connecting a new API for accident notifications. The changes maintain the existing code structure and follow the established patterns, which supports maintainability and consistency.

The modifications adhere to the coding guidelines for library files:

  1. The file is part of a reusable library for NextJS apps.
  2. TypeScript is used for defining types (as implied by importing from a generated file).
  3. The structure supports effective tree-shaking and bundling practices.

These changes contribute to the modernization of the system as intended in the PR objectives.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (2)

Line range hint 1-52: Overall assessment: Changes are minimal and align with PR objectives.

The modification to replace HealthInsuranceV2ClientModule with RightsPortalClientModule is the only significant change in this file. This update aligns well with the PR's goal of modernizing the system and connecting a new client for accident notifications. The overall structure and functionality of the AccidentNotificationModule remain intact, which is good for maintaining consistency.

The changes adhere to the coding guidelines for files in the libs directory:

  1. The module structure supports reusability across different NextJS apps.
  2. The file uses TypeScript, as evidenced by the .ts extension and type annotations.
  3. The single, specific import of RightsPortalClientModule suggests good tree-shaking practices.

10-10: LGTM: Import change aligns with PR objectives.

The replacement of HealthInsuranceV2ClientModule with RightsPortalClientModule aligns well with the PR objective of connecting a new client for accident notifications. This change appears to be part of the effort to modernize the system as mentioned in the PR summary.

To ensure this change doesn't introduce any issues, let's verify the usage of both modules across the codebase:

This will help us confirm that the old module is not being used elsewhere and that the new module is properly integrated.

Also applies to: 29-29

✅ Verification successful

Verified: Import replacement is correctly implemented and does not affect other modules.

The replacement of HealthInsuranceV2ClientModule with RightsPortalClientModule in accident-notification.module.ts is properly localized. Other modules continue to use HealthInsuranceV2ClientModule without issues, ensuring no conflicts or inconsistencies are introduced by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of old and new modules across the codebase

echo "Checking for any remaining usage of HealthInsuranceV2ClientModule:"
rg "HealthInsuranceV2ClientModule" --type ts

echo "Checking for usage of new RightsPortalClientModule:"
rg "RightsPortalClientModule" --type ts

Length of output: 3587

apps/application-system/api/src/app/app.module.ts (3)

58-58: LGTM: New import statement is correct and follows the existing pattern.

The import of RightsPortalClientConfig is correctly added and aligns with the PR objective of connecting a new client for accident notifications. It follows the established pattern for importing client configurations in this module.


116-116: LGTM: RightsPortalClientConfig correctly added to ConfigModule.

The RightsPortalClientConfig is properly added to the load array in ConfigModule.forRoot(). Its placement maintains the alphabetical order of the configurations, which is consistent with the existing code structure. This addition ensures that the new client configuration will be available throughout the application, supporting the PR's objective of connecting a new API for accident notifications.


58-58: Summary: Changes successfully integrate RightsPortalClientConfig.

The modifications to app.module.ts effectively integrate the new RightsPortalClientConfig into the application. These changes align well with the PR objective of connecting a new client for accident notifications, contributing to the modernization of the system. The code adheres to the existing patterns and TypeScript best practices, maintaining consistency within the module.

Also applies to: 116-116

libs/application/templates/accident-notification/src/types/index.ts (1)

17-18: Addition of 'jobTitle' to 'Applicant' type looks good

The optional jobTitle field enhances the Applicant type by providing additional information without affecting existing functionality.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

194-202: Review commented-out confirmation sending logic

The confirmation sending logic in the reviewApplication method is commented out. Ensure that this is intentional and that the application functions correctly without this code. If the code is temporarily disabled, consider adding a TODO comment explaining when it will be re-enabled or refactored.

libs/api/domains/application/src/lib/application.service.ts (2)

Line range hint 118-122: 'create' method implementation is correct and follows best practices

The method correctly uses TypeScript types and follows the established pattern for interacting with the API.


Line range hint 124-129: 'getApplicationCountByTypeIdAndStatus' method is properly implemented

The method correctly delegates to the API and uses the appropriate types for parameters.

libs/application/templates/accident-notification/src/lib/dataSchema.ts (3)

4-4: LGTM!

The import statement for YES is appropriate and correctly added.


20-22: Enums imported correctly from '../types'.

The additional enums OnBehalf, Status, and ChoiceEnum are properly imported and used.


215-215: Verify the existence and correctness of 'additionalAttachments' schema.

The attachments field is included in the main schema, but there is no validation to ensure that attachments required by additionalAttachments are provided. Ensure that when additionalAttachments.answer is AttachmentsEnum.ADDITIONALNOW, the necessary files are included in the attachments field.

Run the following script to check for references to additionalAttachments:

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accodent-notification-v2.utils.ts (2)

258-261: Verify assignment of locationDescription field

Both description and locationDescription fields are assigned accidentDetails.descriptionOfAccident. Is this intentional? If locationDescription should represent a different piece of data, please verify and correct accordingly.

🧰 Tools
🪛 Biome

[error] 259-260: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1-379: Code adheres to TypeScript practices and promotes reusability

The utility functions are well-defined with appropriate TypeScript types, enhancing type safety and reusability across different applications. The exports are correctly managed, aligning with the coding guidelines for libs/**/* pattern.

🧰 Tools
🪛 Biome

[error] 259-260: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 293-295: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Copy link

codecov bot commented Oct 1, 2024

Codecov Report

Attention: Patch coverage is 30.23952% with 233 lines in your changes missing coverage. Please review.

Project coverage is 36.83%. Comparing base (2c1d7e4) to head (0cc442c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ent-notification/accident-notification-v2.utils.ts 18.29% 134 Missing ⚠️
...fields/ApplicationStatus/applicationStatusUtils.ts 0.00% 43 Missing ⚠️
...plates/accident-notification/src/lib/dataSchema.ts 36.36% 21 Missing ⚠️
...dent-notification/accident-notification.service.ts 60.00% 14 Missing ⚠️
...insurance/src/lib/accident-notification.service.ts 0.00% 6 Missing ⚠️
...otification/src/fields/ApplicationStatus/index.tsx 0.00% 6 Missing ⚠️
...ident-notification/attachments/attachment.utils.ts 73.68% 5 Missing ⚠️
.../src/lib/graphql/accident-notification.resolver.ts 0.00% 2 Missing ⚠️
...health-insurance/src/lib/healthInsurance.module.ts 0.00% 1 Missing ⚠️
...ent-notification/src/fields/FormOverview/index.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #15420      +/-   ##
==========================================
- Coverage   36.84%   36.83%   -0.01%     
==========================================
  Files        6803     6805       +2     
  Lines      140736   140728       -8     
  Branches    40007    40041      +34     
==========================================
- Hits        51853    51840      -13     
- Misses      88883    88888       +5     
Flag Coverage Δ
api 3.37% <ø> (ø)
api-domains-health-insurance 34.72% <0.00%> (-0.11%) ⬇️
application-system-api 41.68% <25.45%> (+0.01%) ⬆️
application-template-api-modules 24.05% <34.45%> (-0.26%) ⬇️
application-templates-accident-notification 29.44% <13.41%> (+<0.01%) ⬆️
application-ui-shell 21.29% <ø> (+0.01%) ⬆️
clients-license-client 1.83% <ø> (ø)
download-service 44.19% <100.00%> (+0.18%) ⬆️
license-api 42.66% <100.00%> (+0.12%) ⬆️

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

Files with missing lines Coverage Δ
apps/application-system/api/src/app/app.module.ts 100.00% <100.00%> (ø)
...ident-notification/accident-notification.module.ts 100.00% <100.00%> (ø)
...cident-notification/accident-notification.utils.ts 76.92% <ø> (-7.25%) ⬇️
...ident-notification/src/forms/InReviewForm/index.ts 0.00% <ø> (ø)
...ation/templates/accident-notification/src/index.ts 100.00% <100.00%> (ø)
...tification/src/lib/AccidentNotificationTemplate.ts 22.78% <ø> (ø)
...templates/accident-notification/src/types/index.ts 100.00% <100.00%> (ø)
libs/application/ui-shell/src/lib/FormShell.tsx 69.44% <ø> (+15.27%) ⬆️
...landic-health-insurance/rights-portal/src/index.ts 100.00% <100.00%> (ø)
...ealth-insurance/rights-portal/src/lib/providers.ts 100.00% <ø> (ø)
... and 10 more

... and 37 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 2c1d7e4...0cc442c. Read the comment docs.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e027617 and 8f213d1.

📒 Files selected for processing (1)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (3)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts (3)

25-25: LGTM: New import for AccidentreportsApi

The import of AccidentreportsApi is consistent with the PR objective of connecting a new API for accident notifications. This change aligns with the modernization effort mentioned in the PR description.


126-132: LGTM: Mock AccidentreportsApi added to test module

The addition of the mock AccidentreportsApi to the test module is well-implemented. The mock methods addAttachment and getAttachmentStatus return resolved promises, which is suitable for testing. This change supports the integration of the new API for accident notifications.


139-139: LGTM: AccidentreportsApi instance added to test setup

The addition of accidentReportsApi = module.get(AccidentreportsApi) is correct and necessary for accessing the mock AccidentreportsApi in the tests. This change is consistent with the previous additions and supports the new API integration.

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: 7

🧹 Outside diff range and nitpick comments (3)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (2)

54-54: LGTM: Successful transition to new API with enhanced security.

The submitApplication method has been successfully updated to use the new AccidentreportsApi with proper authentication. The changes align well with the PR objectives and enhance security.

Consider renaming documentId to reportId in the return object for consistency:

return {
-  documentId: reportId,
+  reportId: reportId,
  sentDocuments: fileHashList,
}

Also applies to: 64-71, 79-79, 93-97, 103-104


163-181: Consider removing unused sendAttachment method.

The entire sendAttachment method has been commented out. If this method is no longer needed with the new API, consider removing it entirely to keep the codebase clean and maintainable.

If there's a reason to keep this code for future reference, please add a TODO comment explaining why it's being kept and any plans for future use or refactoring.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)

122-190: Remove commented-out code to enhance maintainability

The large block of commented-out code between lines 122 and 190 can be removed. Keeping outdated or unused code increases complexity and may cause confusion for future maintainers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bf8deed and 36cac5e.

📒 Files selected for processing (2)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)
Learnt from: HjorturJ
PR: island-is/island.is#16111
File: libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.utils.spec.ts:210-361
Timestamp: 2024-09-25T13:23:39.010Z
Learning: In `accident-notification.utils.spec.ts`, the helper functions `getDefaultAttachments` and `getFullBasicAnswers` should not be modified to accept parameters for customizing returned data.
🔇 Additional comments (12)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (7)

31-32: LGTM: New imports and constructor update align with PR objectives.

The addition of AccidentreportsApi and related imports, along with the constructor update, align well with the PR's objective to connect a new API for accident notifications.

Also applies to: 45-45


50-52: LGTM: Enhanced API security with authentication middleware.

The accidentsReportsApiWithAuth method effectively applies authentication middleware to the API calls, enhancing security and aligning with best practices.


143-149: Clarify the intention behind commented-out attachment logic.

The logic for sending attachments in the addAdditionalAttachment method has been commented out. This change could potentially break the functionality of adding additional attachments. Please clarify the intention behind this change:

  1. Is this a temporary change?
  2. If it's permanent, how will additional attachments be handled going forward?
  3. Should we remove the commented-out code if it's no longer needed?

Consider adding a TODO comment explaining the reason for commenting out this logic and any future plans for handling additional attachments.

Would you like assistance in implementing a solution for handling additional attachments with the new API?

Also applies to: 154-154


194-202: Clarify the intention behind commented-out review confirmation logic.

The logic for sending review confirmation in the reviewApplication method has been commented out. This change could potentially break the review functionality. Please clarify the intention behind this change:

  1. Is this a temporary change?
  2. If it's permanent, how will review confirmations be handled with the new API?
  3. Should we remove the commented-out code if it's no longer needed?

Consider adding a TODO comment explaining the reason for commenting out this logic and any future plans for handling review confirmations.

Would you like assistance in implementing a solution for handling review confirmations with the new API?


Line range hint 1-204: LGTM: Code structure and patterns maintain consistency and adhere to guidelines.

The overall code structure and patterns in this file maintain consistency with the existing codebase and adhere to the coding guidelines. The use of TypeScript for type definitions and the consistent style contribute to the maintainability and reusability of the code.


Line range hint 1-204: LGTM: Security enhancements with authentication middleware.

The changes in this file enhance security by implementing authentication middleware for API calls. Additionally, the transition away from XML processing (as mentioned in the PR objectives) likely reduces potential security risks associated with XML parsing. No obvious security vulnerabilities are present in the changed code.


31-31: ⚠️ Potential issue

Fix typo in import path

There is a typo in the import path for applicationToAccidentReport.

Apply this diff to correct the import path:

- import { applicationToAccidentReport } from './accident-notification-v2.utils'
+ import { applicationToAccidentReport } from './accident-notification-v2.utils'

Likely invalid or redundant comment.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (5)

313-314: Possible duplication in accident descriptions

locationDescription and description are both set to accidentDetails.descriptionOfAccident. Confirm if this is intentional or if locationDescription should refer to a different field.


321-322: Check the return values of getAtWork and getAtSailorWork

Ensure that the functions getAtWork and getAtSailorWork return the expected data structures, especially when optional values are involved.


353-368: Ensure shipLocation is correctly handled in getAtSailorWork

In getAtSailorWork, if shipLocation is falsy, the function returns false. Confirm that this behavior is intended and compatible with the expected return type.


46-431: Adherence to coding guidelines

The code adheres to TypeScript usage for defining types and exporting them. Functions are modular and promote reusability across different applications. Effective tree-shaking and bundling practices are upheld by properly organizing imports and exports.


275-285: Verify that injured.jobTitle is consistently defined

In the getInjured function, injured.jobTitle is used, but it may not be defined for all injury cases. Ensure that jobTitle exists on the injured object to avoid undefined values.

Run the following script to check if jobTitle is present in all relevant cases:

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: 3

🧹 Outside diff range and nitpick comments (2)
libs/application/templates/accident-notification/src/lib/dataSchema.ts (2)

87-186: New schemas enhance data structure - Consider updating documentation.

The addition of new schemas (attachments, accidentDetails, fishingShipInfo, homeAccident, injuredPersonInformation, juridicalPerson, and childInCustody) significantly improves the structure and type safety of the accident notification data. These schemas cover various aspects of the accident reporting process, which aligns with the PR objective of modernizing the system.

To maintain code quality and ease of use:

  1. Ensure these new schemas are used consistently throughout the application.
  2. Consider updating the documentation to reflect these new data structures and their purposes.
  3. Verify that these additions don't introduce unnecessary complexity to the codebase.

Would you like assistance in generating documentation for these new schemas?


Line range hint 1-272: Enhance documentation for exported types to improve reusability.

The file adheres well to the coding guidelines for the libs directory, using TypeScript for defining props and exporting types. To further improve reusability across different NextJS apps:

  1. Consider adding JSDoc comments to the AccidentNotificationSchema and its exported type AccidentNotification.
  2. Ensure that all exported types and enums (including those imported from ../types) are well-documented.
  3. If not already present, consider adding a README.md file in this directory explaining the purpose and usage of these schemas.

These documentation improvements will facilitate easier integration and usage of these schemas across different parts of the application.

Would you like assistance in generating JSDoc comments for the exported types?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 36cac5e and 6c8fdb9.

📒 Files selected for processing (2)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (6 hunks)
  • libs/application/templates/accident-notification/src/lib/dataSchema.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/lib/dataSchema.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (10)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (6)

31-33: LGTM! Import statements are correct and aligned with the new API integration.

The new imports for applicationToAccidentReport, AccidentreportsApi, and authentication modules are appropriate for the PR's objective. The previously reported typo in the import path has been correctly addressed.


45-45: LGTM! Constructor updated to use the new AccidentreportsApi.

The constructor change aligns with the PR objective of replacing the XML client with a new API. The use of TypeScript for defining the injected dependency adheres to the coding guidelines.


50-52: LGTM! New method enhances security and reusability.

The accidentsReportsApiWithAuth method is a good addition that ensures authenticated API calls. This aligns with the PR objective of modernizing the system and enhances the overall security of the service. The method's reusability across different API calls within the service is a plus.


Line range hint 1-204: Overall, good progress on API transition, but clarification needed on some changes.

The file has been successfully updated to integrate the new AccidentreportsApi, aligning with the PR objective of connecting a new API for accident notifications and modernizing the system. The changes adhere to TypeScript usage and promote reusability, as per the coding guidelines.

However, several methods related to attachments and review confirmation have been commented out, which raises some questions about the transition strategy.

Could you please provide a high-level explanation of:

  1. The overall transition strategy from the old XML client to the new API.
  2. The status of attachment handling and review confirmation in the new system.
  3. Any pending tasks or future plans for reimplementing commented-out functionality.

This information will help ensure that all necessary functionality is accounted for in the new implementation and that the transition is smooth and complete.


163-181: Clarification needed: sendAttachment method is entirely commented out.

The sendAttachment method has been entirely commented out. This is consistent with the changes in the addAdditionalAttachment method and further suggests that the attachment functionality is being removed or significantly refactored.

Please provide clarification on:

  1. The reason for removing this method.
  2. How attachment functionality will be handled in the new system, if at all.
  3. Any plans for reimplementing this functionality with the new API.

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

This will help identify any other parts of the codebase that might be affected by the removal of this method.

✅ Verification successful

Verification Incomplete: Shell script encountered errors. Please run the corrected script below to continue verification.


sendAttachment Method Removal is Consistent with New Attachment Handling Implementations

The sendAttachment method has been entirely commented out in accident-notification.service.ts. Additionally, new methods like sendEmailWithAttachment have been introduced across various services to handle attachments. This indicates that the attachment functionality has been refactored to a more standardized approach.

  • Removed Method:

    • sendAttachment in accident-notification.service.ts
  • New Attachment Handling Methods:

    • sendEmailWithAttachment in:
      • children-residence-change.service.ts
      • shared.service.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for references to sendAttachment in the codebase

# Search for references to sendAttachment
echo "Searching for references to sendAttachment:"
rg "sendAttachment" --type ts

# Search for potential new methods handling attachments
echo "\nSearching for potential new methods handling attachments:"
rg "send.*ttachment|attach.*end" --type ts

Length of output: 7036


Script:

#!/bin/bash
# Description: Check for references to sendAttachment in the codebase

# Search for references to sendAttachment
echo "Searching for references to sendAttachment:"
rg "sendAttachment" --type ts

# Search for potential new methods handling attachments
echo -e "\nSearching for potential new methods handling attachments:"
rg "send.*ttachment|attach.*end" --type ts

Length of output: 3719


194-202: Clarification needed: Review confirmation logic is commented out.

The logic for sending confirmation in the reviewApplication method has been commented out. This suggests that the review confirmation process is being modified or removed.

Please provide clarification on:

  1. The reason for commenting out this logic.
  2. How the review confirmation process will work with the new API.
  3. Any plans for reimplementing this functionality.

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

This will help identify any other parts of the codebase that might be affected by this change and potentially reveal any new implementation of the review confirmation process.

libs/application/templates/accident-notification/src/lib/dataSchema.ts (4)

Line range hint 33-55: LGTM: Improved validation and consistency in schemas.

The updates to the representative and companyInfo schemas enhance type safety and validation. The companyInfo schema is now correctly marked as optional, addressing the previous inconsistency. These changes contribute to better code quality and maintainability.


57-85: Verify consistent usage of the new externalData schema.

The newly added externalData schema suggests integration with external data sources, which aligns with the PR objective. To ensure consistency and proper implementation:

  1. Verify that this schema is used correctly in the AccidentNotificationService or any other relevant services.
  2. Ensure that the data fetched from the new API matches this schema structure.
  3. Check for any necessary data transformations between the API response and this schema.
#!/bin/bash
# Search for usage of externalData in relevant files
rg -n "externalData" --type ts $(fd -t d "accident-notification" --max-depth 3)

Line range hint 188-267: Verify backwards compatibility with updated AccidentNotificationSchema.

The AccidentNotificationSchema has been significantly updated to incorporate new sub-schemas and improve type safety through the use of nativeEnum. While these changes align with the PR objective of modernizing the system, it's crucial to ensure they don't break existing functionality.

To maintain system integrity:

  1. Verify that these changes are backwards compatible with existing data and API calls.
  2. Ensure that any services or components using this schema are updated accordingly.
  3. Consider adding or updating unit tests to cover the new schema structure.
✅ Verification successful

To gather more information about the usage of AccidentNotificationSchema and related components, I'll search for partial matches of "AccidentNotification" in the codebase.


Verify changes within the accident-notification template to ensure backwards compatibility.

Based on the analysis of the codebase, the AccidentNotificationSchema is primarily used within its own template directory and doesn't appear to be directly imported or used outside of the accident-notification template. This suggests that the risk of breaking existing functionality in other parts of the system is low.

To ensure backwards compatibility and maintain system integrity:

  1. Review all files within the libs/application/templates/accident-notification/ directory that import and use the AccidentNotificationSchema to ensure they are updated to work with the new schema structure.

  2. Pay special attention to the following files:

    • libs/application/templates/accident-notification/src/lib/AccidentNotificationTemplate.ts
    • libs/application/templates/accident-notification/src/utils/ directory files
    • libs/application/templates/accident-notification/src/fields/ directory files
  3. Update any unit tests related to the accident-notification template to reflect the new schema structure and ensure they pass.

  4. Consider adding integration tests that cover the entire accident-notification application flow to verify that the changes don't introduce any unexpected behavior.

  5. If there are any API endpoints that directly interact with the accident-notification template, ensure they are compatible with the updated schema.

While the changes appear to be localized, it's important to thoroughly test the accident-notification template to ensure that all existing functionality remains intact with the new schema structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of AccidentNotificationSchema in the codebase
rg -n "AccidentNotificationSchema" --type ts

Length of output: 589708


Script:

#!/bin/bash
# Search for partial matches of "AccidentNotification" in the codebase
rg "AccidentNotification" --type ts

Length of output: 31876


20-22: Verify export of new types in the referenced file.

The newly imported types (OnBehalf, Status, and ChoiceEnum) are used throughout the schema definitions. Ensure that these types are properly exported from the ../types file and are well-documented to maintain code clarity and type safety across the application.

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 (5)
libs/application/templates/accident-notification/src/index.ts (2)

Line range hint 9-13: LGTM! Consider adding a comment for the type alias.

The export statements look good and maintain backwards compatibility. The new type alias AccidentNotificationAnswers is a good practice for potential future refactoring.

Consider adding a brief comment explaining the purpose of the AccidentNotificationAnswers type alias for better code documentation:

+// Alias for backwards compatibility and future refactoring
export type AccidentNotificationAnswers = AccidentNotification

Line range hint 1-18: LGTM! Consider grouping related imports for better readability.

The overall structure of the file is excellent, promoting reusability and allowing for effective tree-shaking. The use of TypeScript for type definitions and exports is consistent and aligns with our coding guidelines.

For improved readability, consider grouping related imports together:

 import AccidentNotificationTemplate from './lib/AccidentNotificationTemplate'
 import { AccidentNotification } from './lib/dataSchema'
-import * as appMessages from './lib/messages'
 import { OnBehalf } from './types'
+import * as appMessages from './lib/messages'
 import * as appUtils from './utils'

This groups the type imports together and the utility imports together.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (3)

108-114: Approve getReportId function with minor suggestion

The getReportId function is well-implemented, type-safe, and focused on a single responsibility. It correctly retrieves the document ID from the application's external data.

Consider adding a null check or providing a default value to handle cases where the path doesn't exist:

export const getReportId = (application: ApplicationWithAttachments) => {
  const externalData = application.externalData
  return getValueViaPath(
    externalData,
    'submitApplication.data.documentId',
  ) as number | undefined
}

This change would make the function more robust against potential data inconsistencies.


116-127: Approve getNewAttachments function with error handling suggestion

The getNewAttachments function is well-structured and effectively retrieves new attachments. However, it lacks error handling for potential issues during asynchronous operations.

Consider wrapping the function body in a try-catch block:

export const getNewAttachments = async (
  application: ApplicationWithAttachments,
  attachmentProvider: AccidentNotificationAttachmentProvider,
) => {
  try {
    const attachmentStatus = getApplicationAttachmentStatus(application)
    const requests = attachmentStatusToAttachmentRequests(attachmentStatus)
    const attachments = await attachmentProvider.getFiles(requests, application)

    return filterOutAlreadySentDocuments(attachments, application)
  } catch (error) {
    console.error('Error getting new attachments:', error)
    throw new Error('Failed to retrieve new attachments')
  }
}

This change would improve error handling and make the function more robust.


129-147: Approve getReviewApplicationData function with type safety suggestion

The getReviewApplicationData function is well-implemented, extracting relevant review data from the application. To further improve type safety, consider defining an interface for the return type:

interface ReviewApplicationData {
  documentId: number;
  isRepresentativeOfCompanyOrInstitute: boolean;
  reviewApproval: ReviewApprovalEnum;
  reviewComment: string;
}

export const getReviewApplicationData = (application: Application): ReviewApplicationData => {
  // ... existing implementation ...
}

This change would make the function's return type explicit and improve type checking for consumers of this function.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ed9016d and 00e3116.

📒 Files selected for processing (2)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (3 hunks)
  • libs/application/templates/accident-notification/src/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/index.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (1)
Learnt from: HjorturJ
PR: island-is/island.is#16111
File: libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.utils.spec.ts:210-361
Timestamp: 2024-09-25T13:23:39.010Z
Learning: In `accident-notification.utils.spec.ts`, the helper functions `getDefaultAttachments` and `getFullBasicAnswers` should not be modified to accept parameters for customizing returned data.
🔇 Additional comments (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (2)

3-9: Improved type safety with new imports

The addition of ApplicationWithAttachments, AccidentNotificationAnswers, and ReviewApprovalEnum imports enhances type safety and specificity in handling accident notifications. This aligns well with the PR objective and promotes better code quality.


25-27: Enhanced modularity with new utility imports

The addition of AccidentNotificationAttachmentProvider, getApplicationDocumentId, and utils imports improves modularity and code reuse. This change aligns with the PR objective and promotes better code organization.

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

🧹 Outside diff range and nitpick comments (7)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (7)

68-106: LGTM: Comprehensive accident type mappings with room for improvement

The accidentTypeMap, workAccidentSubtypeMap, and studiesAccidentSubtypeMap provide clear and comprehensive mappings for various accident types and subtypes. The comments offer valuable context for the numeric codes.

Consider using an enum or constant object for the numeric codes to improve readability and maintainability. For example:

const AccidentTypes = {
  SPORTS: 4,
  WORK: 6,
  HOME_ACTIVITIES: 7,
  // ... other types
} as const;

const accidentTypeMap = {
  [AccidentTypeEnum.SPORTS]: { type: AccidentTypes.SPORTS },
  [AccidentTypeEnum.WORK]: { type: AccidentTypes.WORK },
  // ... other mappings
};

This approach would make the code more self-documenting and reduce the reliance on comments for understanding the numeric codes.


108-137: LGTM: Comprehensive accident type conversion with room for improvement

The accidentTypeToDTO function effectively converts accident types from application answers to the DTO format, handling both base types and subtypes for work and studies accidents.

Consider adding a comment or adjusting the logic for the fallback case:

const baseType = accidentTypeMap[accidentType] || { type: 6 } // Fallback to general work accident if type is not found

This would clarify the intention behind defaulting to type 6 when an unknown accident type is encountered.


139-173: LGTM: Clear location conversion functions with potential for refactoring

The locationToDTO and shipLocationToDTO functions effectively convert location enums to numeric codes, handling all cases and providing default values for unexpected inputs.

Consider refactoring these functions to use a mapping object for consistency with other parts of the code and to potentially reduce duplication:

const generalLocationMap = {
  [GeneralWorkplaceAccidentLocationEnum.ATTHEWORKPLACE]: 0,
  [GeneralWorkplaceAccidentLocationEnum.TOORFROMTHEWORKPLACE]: 1,
  [GeneralWorkplaceAccidentLocationEnum.OTHER]: 2,
};

const shipLocationMap = {
  [FishermanWorkplaceAccidentLocationEnum.ONTHESHIP]: 1,
  [FishermanWorkplaceAccidentLocationEnum.TOORFROMTHEWORKPLACE]: 2,
  [FishermanWorkplaceAccidentLocationEnum.OTHER]: 3,
};

const locationToDTO = (answers: AccidentNotificationAnswers) => {
  const accidentLocation = getValueViaPath(
    answers,
    'accidentLocation.answer'
  ) as GeneralWorkplaceAccidentLocationEnum;
  return generalLocationMap[accidentLocation] ?? 2;
};

const shipLocationToDTO = (answers: AccidentNotificationAnswers) => {
  const accidentLocation = getValueViaPath(
    answers,
    'accidentLocation.answer'
  ) as FishermanWorkplaceAccidentLocationEnum;
  return shipLocationMap[accidentLocation] ?? 3;
};

This approach would make the code more consistent with other parts of the file and potentially easier to maintain.


175-198: LGTM: Robust reporter information extraction with room for improvement

The getReporter function effectively extracts reporter information from the application answers, handling potential missing data well.

Consider adding basic validation for email and phone number to ensure data integrity:

const isValidEmail = (email: string): boolean => {
  // Basic email regex
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};

const isValidPhoneNumber = (phone: string): boolean => {
  // Adjust regex based on expected phone number format
  return /^\+?[\d\s-]{7,}$/.test(phone);
};

// In getReporter function:
email: isValidEmail(applicant.email ?? '') ? applicant.email : '',
phoneNumber: isValidPhoneNumber(applicant.phoneNumber ?? '') ? applicant.phoneNumber : '',

This would ensure that only valid email addresses and phone numbers are included in the report.


200-226: LGTM: Effective injured person information extraction with potential for improvement

The getInjured function correctly extracts information about the injured person, handling different scenarios based on who the notification is for.

Consider adding similar email and phone number validation as suggested for the getReporter function:

// Add isValidEmail and isValidPhoneNumber functions if not already present

// In getInjured function:
email: isValidEmail(injured.email ?? '') ? injured.email : '',
phone: isValidPhoneNumber(injured.phoneNumber ?? '') ? injured.phoneNumber : '',

This would ensure consistency in data validation across different parts of the application.


264-312: LGTM: Well-structured location-specific detail extraction

The getAtHome, getAtWork, and getAtSailorWork functions effectively extract specific details based on the accident location, handling potential missing data appropriately.

For consistency, consider adjusting the getAtHome function to match the structure of the other two:

const getAtHome = (answers: AccidentNotificationAnswers) => {
  const homeAccident = getValueViaPath(
    answers,
    'homeAccident'
  ) as HomeAccidentV2

  if (!homeAccident) {
    return undefined
  }

  return {
    address: homeAccident.address ?? '',
    city: homeAccident.community ?? '',
    postcode: homeAccident.postalCode ?? '',
    comment: homeAccident.moreDetails ?? '',
  }
}

This change removes the redundant check and makes the function structure more consistent with getAtWork and getAtSailorWork.


377-392: LGTM: Clear attachment type mapping with potential for refactoring

The mapAttachmentTypeToAccidentReportType function provides a clear mapping between attachment types and effectively handles unknown types by throwing an error.

Consider refactoring this function to use an object mapping for consistency with other parts of the code:

const attachmentTypeMap = {
  [AttachmentTypeEnum.INJURY_CERTIFICATE]: MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum.NUMBER_1,
  [AttachmentTypeEnum.POWER_OF_ATTORNEY]: MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum.NUMBER_2,
  [AttachmentTypeEnum.POLICE_REPORT]: MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum.NUMBER_3,
  [AttachmentTypeEnum.ADDITIONAL_FILES]: MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum.NUMBER_4,
};

export const mapAttachmentTypeToAccidentReportType = (
  attachmentType: AttachmentTypeEnum
): MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum => {
  const mappedType = attachmentTypeMap[attachmentType];
  if (mappedType === undefined) {
    throw new Error('Unknown attachment type');
  }
  return mappedType;
};

This approach is more declarative and easier to maintain if new attachment types are added in the future.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 00e3116 and 86d95a6.

📒 Files selected for processing (1)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)
Learnt from: HjorturJ
PR: island-is/island.is#16111
File: libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.utils.spec.ts:210-361
Timestamp: 2024-09-25T13:23:39.010Z
Learning: In `accident-notification.utils.spec.ts`, the helper functions `getDefaultAttachments` and `getFullBasicAnswers` should not be modified to accept parameters for customizing returned data.
🔇 Additional comments (5)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (5)

1-34: LGTM: Well-organized imports

The import statements are comprehensive and well-structured, covering all necessary types, enums, and utilities for handling accident notification data transformation.


36-48: LGTM: Well-structured main function

The applicationToAccidentReport function is well-organized, using helper functions to modularize the data transformation process. This structure enhances readability and maintainability.


50-59: LGTM: Clear and comprehensive enum mapping

The reportingForMap provides a clear and concise mapping between WhoIsTheNotificationForEnum and MinarsidurAPIModelsAccidentReportsReporterDTOReportingForEnum. All enum values are covered, ensuring completeness.


61-66: LGTM: Robust enum conversion function

The whoIsTheNotificationForToDTO function efficiently converts WhoIsTheNotificationForEnum to the corresponding DTO enum value. It handles potential missing mappings and provides a fallback value, ensuring robustness.


359-375: ⚠️ Potential issue

Effective attachment transformation with areas for improvement

The getAttachments function successfully maps the attachments to the DTO format, but there are a few areas that could be enhanced:

  1. The content type extraction from the file name is simple but may not always be accurate. Consider using a more robust method or library for determining file types.

  2. The hack for handling additional files (type 4) is a temporary solution that needs to be addressed properly.

Consider implementing proper support for additional files or handling this scenario more elegantly. For example:

type: mapAttachmentTypeToAccidentReportType(attachment.attachmentType),

And then update the mapAttachmentTypeToAccidentReportType function to handle the additional files case appropriately.

To check the impact of this hack, run the following script:

#!/bin/bash
# Search for attachment type 4 usage in the codebase
rg --type typescript "attachmentType.*===.*4" -C 3

This will help identify other parts of the codebase that might be affected by this temporary solution.

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 (3)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

54-54: LGTM with a minor suggestion: Updated to use new API and enhanced security

The changes to the submitApplication method align well with the PR objective of connecting a new API for accident notifications. The addition of authentication enhances security.

However, there's a minor inconsistency in the returned object:

Consider renaming the documentId key to reportId in the returned object for consistency:

return {
-  documentId: reportId,
+  reportId: reportId,
  sentDocuments: fileHashList,
}

This change will make the code more consistent with the new API terminology and prevent potential confusion.

Also applies to: 64-71, 79-79, 93-97, 103-103

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (2)

1-34: Consider organizing imports for better readability

The imports are comprehensive but could be organized better for improved readability. Consider grouping imports by their source:

  1. External libraries
  2. Application-specific imports
  3. Type imports

This organization can help developers quickly understand the dependencies of the file.


68-86: Improve documentation for accident types and subtypes

The comment block explaining accident types and subtypes is helpful but could be improved. Consider using JSDoc format for better integration with IDE tooling and documentation generators. For example:

/**
 * Accident types:
 * 4 - Íþróttaslys (Sports accident)
 * 6 - Vinnuslys (Work accident)
 * 7 - Heimilistrygging (Home insurance)
 * 8 - Björgunarmenn (Rescue workers)
 * 9 - Nemendur við iðnnám (Vocational students)
 *
 * Subtypes for type 6 (Work accident):
 * 1 - Almenn vinna á landi (General work on land)
 * 2 - Vinna sjómanna (Seamen's work)
 * 3 - Atvinnumennska í íþróttum (Professional sports)
 * 4 - Vinna við landbúnað (Agricultural work)
 *
 * Subtypes for type 9 (Vocational students):
 * 5 - Starfsnám (Internship)
 * 6 - Verknám við háskóla (University practical training)
 * 7 - Iðnám í löggildum iðngreinum (Apprenticeship in licensed trades)
 */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 86d95a6 and 019e133.

📒 Files selected for processing (3)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts (3 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
📓 Learnings (1)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (1)
Learnt from: HjorturJ
PR: island-is/island.is#16111
File: libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.utils.spec.ts:210-361
Timestamp: 2024-09-25T13:23:39.010Z
Learning: In `accident-notification.utils.spec.ts`, the helper functions `getDefaultAttachments` and `getFullBasicAnswers` should not be modified to accept parameters for customizing returned data.
🔇 Additional comments (10)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (7)

11-11: LGTM: New imports align with PR objectives

The new imports, including utility functions, AccidentreportsApi, and authentication-related imports, align well with the PR objective of connecting a new API for accident notifications. These changes contribute to the modernization of the system and support better TypeScript usage.

Also applies to: 22-24, 28-32


45-45: LGTM: Constructor updated for new API

The replacement of documentApi with accidentReportsApi in the constructor is consistent with the PR objective of replacing the existing XML client with a new API for accident notifications.


50-52: LGTM: Enhanced security with authenticated API calls

The new private method accidentsReportsApiWithAuth is a valuable addition that ensures all API calls are authenticated. This enhancement aligns with best practices for security and supports the modernization effort mentioned in the PR objectives.


127-174: LGTM: Improved attachment handling with new API and better error management

The changes to the addAdditionalAttachment method are well-implemented and align with the PR objectives. Key improvements include:

  1. Integration with the new API, including proper authentication.
  2. Enhanced error handling, particularly the check for reportId.
  3. Improved type mapping for attachments.

These changes contribute to a more robust and secure implementation of the attachment handling process.


184-200: LGTM: Streamlined review process with new API integration

The reviewApplication method has been successfully updated to work with the new API. Notable improvements include:

  1. Integration of authentication for API calls.
  2. Streamlined data extraction using the getReviewApplicationData utility.
  3. Updated data structure for submitting the review confirmation, which better represents the review process.

These changes align well with the PR objectives and contribute to a more modern and efficient implementation.


Line range hint 1-200: LGTM: Consistent structure and improved patterns

The overall structure of the AccidentNotificationService demonstrates several improvements:

  1. Consistent use of authenticated API calls, enhancing security.
  2. Improved error handling throughout, contributing to code robustness.
  3. Maintained TypeScript usage for defining types and interfaces, aligning with coding guidelines for the libs directory.

These changes not only meet the PR objectives but also contribute to the overall quality and maintainability of the codebase.


Line range hint 1-200: LGTM: Successful refactoring aligns with PR objectives and coding guidelines

The AccidentNotificationService has been successfully refactored to integrate with the new API for accident notifications. Key improvements include:

  1. Consistent use of authenticated API calls across all public methods, enhancing security.
  2. Improved error handling and type safety, contributing to code robustness.
  3. Maintained reusability and TypeScript usage, adhering to coding guidelines for the libs directory.

These changes not only meet the PR objectives of connecting a new API and modernizing the system but also contribute to the overall quality, security, and maintainability of the codebase. The refactoring demonstrates a thoughtful approach to modernizing the accident notification system while maintaining good coding practices.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification-v2.utils.ts (3)

1-402: Summary of review findings

Overall, the accident-notification-v2.utils.ts file provides a comprehensive set of utilities for handling accident notifications. However, there are several areas where improvements can be made:

  1. Organize imports for better readability.
  2. Add error handling and input validation to the main applicationToAccidentReport function.
  3. Improve documentation for accident types and subtypes using JSDoc format.
  4. Simplify some functions, such as getAccidentTypes, for better readability.
  5. Enhance error handling and data validation in DTO creation functions.
  6. Address the inconsistency in accessing accidentType in getEmployer and getClub functions.
  7. Properly handle additional files in the getAttachments function instead of using a temporary hack.
  8. Refactor the mapAttachmentTypeToAccidentReportType function to use an object mapping approach.

Addressing these points will improve the overall quality, maintainability, and robustness of the code.


369-385: ⚠️ Potential issue

Address the temporary solution for additional files

The comment "Hack since additional files are not supported yet..." indicates a temporary solution that needs to be properly addressed. This hack could lead to incorrect categorization of attachments. Please implement proper support for additional files or handle this scenario more elegantly.

Additionally, consider adding error handling for cases where the file name doesn't have an extension or the attachment type is unknown.

Example improvement:

const getAttachments = (
  attachments: Array<AccidentNotificationAttachment>,
): Array<MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentDTO> => {
  return attachments.map((attachment) => {
    const fileNameParts = attachment.name.split('.');
    const contentType = fileNameParts.length > 1 ? fileNameParts.pop() : undefined;
    
    let type = attachment.attachmentType;
    if (type === AttachmentTypeEnum.ADDITIONAL_FILES) {
      // TODO: Implement proper handling for additional files
      console.warn('Additional files are not fully supported yet');
      type = MinarsidurAPIModelsAccidentReportsAccidentReportAttachmentTypeEnum.NUMBER_2;
    }

    return {
      type,
      document: {
        fileName: attachment.name,
        contentType,
        data: attachment.content,
      },
    };
  });
};

To check for occurrences of attachment type 4 and references to additional files in the codebase, run:

#!/bin/bash
# Search for attachment type 4 usage
echo "Searching for attachment type 4 usage:"
rg --type typescript "attachmentType.*===.*4" -C 3

# Search for references to additional files
echo "\nSearching for references to additional files:"
rg --type typescript "additional.*files" -i -C 3

238-272: ⚠️ Potential issue

Improve error handling and remove commented-out code in getAccident

The getAccident function could benefit from improved error handling and data validation. Additionally, there are commented-out properties that should be addressed:

  1. Consider adding null checks for critical fields and throw meaningful errors if they're missing.
  2. The use of new Date() as a fallback for missing dates might lead to inaccurate data. Consider using null or a specific placeholder date instead.
  3. Remove or implement the commented-out properties dockName and dockGps. If they're not needed, remove the comments to keep the code clean.

Example improvement:

dateTimeOfDoctorVisit: accidentDetails.dateOfDoctorVisit
  ? new Date(accidentDetails.dateOfDoctorVisit)
  : null,

To check if dockName and dockGps are used elsewhere in the codebase, run:

✅ Verification successful

Confirm dockName and dockGps are not used elsewhere

The dockName and dockGps properties are only present as commented-out lines in the accident-notification-v2.utils.ts file and are not used elsewhere in the codebase. It is safe to remove the commented-out code to keep the codebase clean.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for dockName and dockGps usage in TypeScript files
rg --type typescript "dockName|dockGps" -C 3

Length of output: 365


Script:

#!/bin/bash
# Search for dockName and dockGps usage in TypeScript files using glob patterns
rg "dockName|dockGps" -g "*.ts" -g "*.tsx" -C 3

Length of output: 1379

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: 5

🧹 Outside diff range and nitpick comments (2)
libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (1)

Line range hint 91-94: Avoid using spread syntax in reducers to improve performance

Similar to the previous comment, using the spread operator ... in this reducer can lead to performance issues due to O(n^2) time complexity.

Refactor the reducer to mutate the accumulator directly:

  receivedConfirmations: accidentStatus.confirmations
    ?.map((x) => ({
      [mapConfirmationType(x.party)]: !!x.received,
    }))
-   .reduce(
-     (prev, curr) => ({ ...prev, ...curr }),
-     {},
-   ) as AccidentNotificationConfirmation,
+   .reduce((acc, curr) => {
+     Object.assign(acc, curr)
+     return acc
+   }, {} as AccidentNotificationConfirmation),

Or combine the map and reduce into a single reduce function:

  receivedConfirmations: accidentStatus.confirmations
-   ?.map((x) => ({
-     [mapConfirmationType(x.party)]: !!x.received,
-   }))
-   .reduce((acc, curr) => {
-     Object.assign(acc, curr)
-     return acc
-   }, {} as AccidentNotificationConfirmation),
+   ?.reduce((acc, x) => {
+     acc[mapConfirmationType(x.party)] = !!x.received
+     return acc
+   }, {} as AccidentNotificationConfirmation),
🧰 Tools
🪛 Biome

[error] 84-84: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


[error] 92-92: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

libs/application/templates/accident-notification/src/fields/ApplicationStatus/index.tsx (1)

163-163: Address the TODO to add Sentry logging and design improvements.

The TODO comment indicates that Sentry logging and design updates are pending. Please implement the necessary error handling and design enhancements.

Would you like assistance in implementing Sentry logging or updating the design? I can help generate the necessary code or open a GitHub issue to track this task.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 019e133 and 1438de9.

📒 Files selected for processing (5)
  • libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (3 hunks)
  • libs/api/domains/health-insurance/src/lib/healthInsurance.module.ts (2 hunks)
  • libs/application/templates/accident-notification/src/fields/ApplicationStatus/applicationStatusUtils.ts (1 hunks)
  • libs/application/templates/accident-notification/src/fields/ApplicationStatus/index.tsx (5 hunks)
  • libs/application/templates/accident-notification/src/forms/InReviewForm/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/health-insurance/src/lib/healthInsurance.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/fields/ApplicationStatus/applicationStatusUtils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/fields/ApplicationStatus/index.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/accident-notification/src/forms/InReviewForm/index.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/api/domains/health-insurance/src/lib/accident-notification.service.ts

[error] 84-84: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (7)
libs/api/domains/health-insurance/src/lib/healthInsurance.module.ts (3)

9-9: LGTM: Import statement for AccidentreportsApi

The import statement for AccidentreportsApi is correctly added and aligns with the PR objective of connecting a new client for accident notifications.


18-18: LGTM: Addition of AccidentreportsApi to providers

The AccidentreportsApi is correctly added to the providers array, making it available for dependency injection within the module. This change is consistent with the PR objective of connecting a new client for accident notifications.


Line range hint 1-24: Verification: Compliance with coding guidelines

The module adheres to the coding guidelines for libs/**/* files:

  1. It's designed for reusability across different NextJS apps.
  2. It uses TypeScript for defining and exporting types.
  3. The module structure allows for effective tree-shaking and bundling.

To further verify the module's usage across different NextJS apps, you can run the following script:

This script will help identify where the HealthInsuranceModule is being used across different NextJS applications.

libs/application/templates/accident-notification/src/forms/InReviewForm/index.ts (1)

Line range hint 19-30: Approve the addition of AssigneeReview with suggestions for improvement

The addition of AssigneeReview looks good and follows the existing pattern, promoting reusability across different NextJS apps. Here are some suggestions to enhance the code:

  1. Consider adding a comment explaining the purpose of the true argument passed to each section function in AssigneeReview. This will improve code readability and maintainability.

  2. It might be beneficial to use an enum or constant for the form IDs ('applicantReviewForm' and 'assigneeReviewForm') to avoid potential typos and improve maintainability.

  3. Ensure that the implementation of applicationStatusSection, addAttachmentsSection, and inReviewOverviewSection correctly handles the boolean parameter passed in AssigneeReview.

To verify the correct implementation of the section functions, please run the following script:

This will help ensure that the boolean parameter is properly utilized in each section function.

libs/application/templates/accident-notification/src/fields/ApplicationStatus/applicationStatusUtils.ts (1)

142-142: ⚠️ Potential issue

Verify that 'currentAccidentStatus' has a 'status' property

In the fourthStep function, currentAccidentStatus.status is accessed at lines 142 and 145. Please ensure that currentAccidentStatus is an object containing a status property. If currentAccidentStatus is already a status value (e.g., an enum or string), accessing .status may result in an undefined value or a runtime error.

Also applies to: 145-145

libs/application/templates/accident-notification/src/fields/ApplicationStatus/index.tsx (2)

26-31: Good use of destructuring in the function signature to improve readability.

Destructuring the props directly in the function signature simplifies the component and enhances readability.


164-164: ⚠️ Potential issue

Localize the error message using formatMessage.

Avoid hardcoding error messages; instead, use formatMessage to support localization and maintain consistency.

Apply this refactor:

-      <Text>Ekki tókst að sækja stöðu umsóknar, eitthvað fór úrskeiðis.</Text>
+      <Text>{formatMessage(inReview.error.couldNotFetchStatus)}</Text>

If inReview.error.couldNotFetchStatus does not exist in your localization messages, please add the appropriate message to your localization files.

Likely invalid or redundant comment.

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 (1)
libs/api/domains/health-insurance/src/lib/graphql/accident-notification.resolver.ts (1)

36-41: LGTM: Method signature update improves functionality and follows TypeScript best practices.

The addition of the user parameter with the @CurrentUser() decorator enhances the method by providing user context. This change is well-implemented and typed correctly.

Consider adding error handling for cases where the user might be undefined:

if (!user) {
  throw new Error('User not authenticated');
}

This would improve the robustness of the function.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1438de9 and 97886bc.

📒 Files selected for processing (3)
  • libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (2 hunks)
  • libs/api/domains/health-insurance/src/lib/graphql/accident-notification.resolver.ts (2 hunks)
  • libs/api/domains/health-insurance/src/lib/healthInsurance.module.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/api/domains/health-insurance/src/lib/healthInsurance.module.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/health-insurance/src/lib/graphql/accident-notification.resolver.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/api/domains/health-insurance/src/lib/accident-notification.service.ts

[error] 89-89: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (6)
libs/api/domains/health-insurance/src/lib/graphql/accident-notification.resolver.ts (2)

5-11: LGTM: Import changes are appropriate and follow best practices.

The new imports from '@island.is/auth-nest-tools' are necessary for the changes made to the accidentStatus method. They are specific imports, which is good for tree-shaking and bundling practices. The use of internal packages also promotes code reusability across different NextJS apps.


Line range hint 1-50: Excellent adherence to coding guidelines for library code.

This file demonstrates good practices for library code:

  1. It's designed for reusability across different NextJS apps.
  2. TypeScript is used effectively for type definitions and prop types.
  3. Imports are specific, which is good for tree-shaking and bundling.

The changes maintain these good practices, ensuring the code remains maintainable and efficient.

libs/api/domains/health-insurance/src/lib/accident-notification.service.ts (4)

14-15: Imports are correctly updated to use the new API client and authentication tools.

The inclusion of AccidentreportsApi and AuthMiddleware aligns with the migration to the new API and ensures that API calls are authenticated properly.


59-59: Constructor correctly updated to inject the new AccidentreportsApi.

Replacing the old DocumentApi with AccidentreportsApi in the constructor is appropriate for integrating the new accident notification API.


69-69: Method signature updated appropriately to include auth: Auth.

Adding the auth parameter to getAccidentNotificationStatus ensures that API calls are made with the necessary authentication.


74-78: Correct usage of the new API client with authentication.

The call to getAccidentReportStatus using accidentReportsApiWithAuth demonstrates proper integration with the new API and authentication middleware.

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 (4)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (1)

126-143: LGTM: Well-structured getReviewApplicationData function.

The getReviewApplicationData function effectively extracts review-related data from the application. It follows the single responsibility principle and uses appropriate utility functions.

Consider using optional chaining and nullish coalescing for a more concise reviewComment assignment:

const reviewComment = getValueViaPath(application.answers, 'reviewComment') as string ?? ''

This change would simplify the logic and make it more resilient to undefined values.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (3)

45-45: LGTM: Constructor updated to use new API

The constructor has been updated to use AccidentreportsApi instead of DocumentApi, which aligns with the PR objective of connecting a new API for accident notifications.

For consistency, consider renaming accidentReportsApi to accidentreportsApi to match the import name:

- private readonly accidentReportsApi: AccidentreportsApi,
+ private readonly accidentreportsApi: AccidentreportsApi,

This minor change would improve naming consistency throughout the file.


54-54: LGTM with a minor suggestion: submitApplication updated to use new API

The submitApplication method has been successfully updated to use the new AccidentreportsApi, aligning with the PR objectives. The addition of the auth parameter and the use of utility functions like applicationToAccidentReport improve security and code modularity.

For consistency, consider renaming the documentId key in the returned object to reportId:

return {
-  documentId: reportId,
+  reportId,
  sentDocuments: fileHashList,
}

This change would make the code more consistent with the new API terminology.

Also applies to: 64-71, 79-79, 93-97, 103-103


127-173: LGTM with a suggestion: addAdditionalAttachment updated with improved error handling

The addAdditionalAttachment method has been successfully updated to use the new AccidentreportsApi and includes improved error handling. The addition of the auth parameter and the use of utility functions enhance security and code modularity.

Consider adding more specific error handling for the API call:

 } catch (e) {
-  this.logger.error('Error adding additional attachment', e)
+  this.logger.error('Error adding additional attachment', { error: e, reportId })
   throw new Error('Villa kom upp við að bæta við viðbótarskjali.')
 }

This change would provide more context in the error logs, making debugging easier.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dd1f66b and 9c62f14.

📒 Files selected for processing (3)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts (6 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (5 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.spec.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (7)
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/attachments/attachment.utils.ts (3)

3-9: LGTM: New imports enhance type safety.

The addition of Application, ApplicationWithAttachments, and ReviewApprovalEnum imports is appropriate for the new functions introduced in this file. These imports contribute to improved type safety and provide access to necessary types and enums.


25-27: LGTM: New imports support new functionality.

The addition of AccidentNotificationAttachmentProvider, getApplicationDocumentId, and utils imports is appropriate for the new functions introduced in this file. These imports provide access to necessary types and utility functions required for the new attachment handling logic.


105-111: LGTM: Correct implementation of getReportId.

The getReportId function correctly retrieves the document ID from the application's external data. This implementation addresses the issue mentioned in the past review comment by properly accessing the externalData property of the application.

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.service.ts (4)

11-11: LGTM: New imports align with PR objectives

The new imports, including utility functions, AccidentreportsApi, and Auth-related imports, align well with the PR objective of connecting a new API for accident notifications. These changes enhance type safety and support better code reusability, which is crucial for files in the libs directory.

Also applies to: 22-24, 28-33


50-52: LGTM: New method enhances security and reusability

The new private method accidentsReportsApiWithAuth is a great addition. It enhances security by ensuring authenticated API calls and improves code reusability across different API calls in the service. This aligns well with the coding guidelines for the libs directory.


183-199: LGTM: reviewApplication successfully updated to use new API

The reviewApplication method has been effectively updated to use the new AccidentreportsApi. The addition of the auth parameter enhances security, while the use of the getReviewApplicationData utility function improves code modularity. These changes align well with the PR objectives and the coding guidelines for the libs directory.


Line range hint 1-199: Overall LGTM: Successful implementation of new AccidentreportsApi

The AccidentNotificationService has been successfully updated to use the new AccidentreportsApi, aligning perfectly with the PR objectives. Key improvements include:

  1. Enhanced security through the use of authenticated API calls.
  2. Improved error handling and logging.
  3. Better code modularity with the introduction of utility functions.
  4. Consistent use of TypeScript best practices.

These changes not only modernize the system as intended but also improve the overall code quality and maintainability. The refactoring adheres well to the coding guidelines for the libs directory, ensuring reusability across different NextJS apps.

Minor suggestions for naming consistency have been provided in previous comments. Addressing these would further enhance the code quality.

Copy link
Contributor

@norda-gunni norda-gunni left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@thordurhhh thordurhhh left a comment

Choose a reason for hiding this comment

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

Client changes LGTM 🚀

@jonnigs jonnigs added the automerge Merge this PR as soon as all checks pass label Oct 9, 2024
@kodiakhq kodiakhq bot merged commit 386d587 into main Oct 9, 2024
53 checks passed
@kodiakhq kodiakhq bot deleted the feat/new-accident-notification-client branch October 9, 2024 13:03
busla pushed a commit that referenced this pull request Oct 10, 2024
#15420)

* feat: connect new api for accident-notification

* feat: map and send attachments to new api

* chore: remove unused code

* feat: codegen for api changes and fix dataSchema

* chore: nx format:write update dirty files

* fix: remove test

* chore: nx format:write update dirty files

* fix: add null test to pass build

* chore: lint

* fix: Coderabbit comments

* feat: connect review application and addAditionalAttachment

* fix: pr comments and add test back in

* chore: use switch instead of if

* fix: getReportId

* fix: codegen backend schema

* chore: consistent early return

* chore: simplify accidentTypeDTO

* fix: lint

* feat: connect getAccidentReportStatus

* feat: add auth to getAccidentNotificationStatus

* fix: import

* chore: add test back in

* fix: test

* chore: remove console.log

---------

Co-authored-by: andes-it <[email protected]>
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 deploy-feature Deploys features to dev
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants