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(application-system): On delete template api #16605

Merged
merged 4 commits into from
Oct 29, 2024
Merged

feat(application-system): On delete template api #16605

merged 4 commits into from
Oct 29, 2024

Conversation

obmagnusson
Copy link
Member

@obmagnusson obmagnusson commented Oct 29, 2024

Asana Task

What

Added an onDelete template Api handler for Application States.
Error toast for application delete
Added audit log for application delete

Why

There Is a need for applications to notify 3rd parties on their deletion.

Checklist:

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced application deletion process with improved error handling and logging.
    • Added support for executing defined actions upon application deletion.
    • Integrated toast notifications in the Application List for better user feedback.
  • Bug Fixes

    • Improved error handling during application deletion, providing localized messages.
  • Documentation

    • Updated method signatures and interface definitions for clarity on new functionalities.

@obmagnusson obmagnusson added the automerge Merge this PR as soon as all checks pass label Oct 29, 2024
@obmagnusson obmagnusson requested a review from a team as a code owner October 29, 2024 09:47
Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The pull request introduces several enhancements to the application deletion process within the ApplicationController. A new locale parameter is added to the delete method, improving localization handling. The deletion logic is refined to include checks for application templates and on-delete actions, with appropriate error handling mechanisms. Additionally, modifications are made to the ApplicationTemplateHelper and ApplicationStateMeta to support these changes. UI components are updated to include toast notifications for user feedback, and the useDeleteApplication hook is enhanced for better error management.

Changes

File Change Summary
apps/application-system/api/src/app/modules/application/application.controller.ts Updated delete method to include @CurrentLocale() parameter and enhanced deletion logic with template checks and error handling.
libs/application/core/src/lib/ApplicationTemplateHelper.ts Added getOnDeleteStateAPIAction method to retrieve on-delete actions for application states.
libs/application/types/src/lib/StateMachine.ts Introduced optional onDelete property in ApplicationStateMeta interface to specify actions for application state deletions.
libs/application/ui-components/src/components/ApplicationList/ApplicationList.tsx Added ToastContainer for toast notifications; no changes to existing logic or structure.
libs/application/ui-components/src/hooks/useDeleteApplication.ts Enhanced error handling in useDeleteApplication hook by integrating localized error messaging and modifying mutation configuration.

Possibly related PRs

Suggested reviewers

  • thorkellmani
  • HjorturJ
  • GunnlaugurG

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
libs/application/ui-components/src/components/ApplicationList/ApplicationList.tsx (1)

Line range hint 64-71: Add error handling to onApplicationDelete

The deletion callback should handle potential errors to ensure proper state management and user feedback through the newly added toast notifications.

-  const onApplicationDelete = () => {
+  const onApplicationDelete = async () => {
+    try {
       if ((applications.length - 1) % pageSize === 0 && page > 1) {
         setPage(page - 1)
       }
       if (refetch) {
-        refetch()
+        await refetch()
       }
+    } catch (error) {
+      console.error('Failed to handle application deletion:', error)
+      // Assuming toast is from react-toastify
+      toast.error('Failed to update application list')
+    }
   }
libs/application/types/src/lib/StateMachine.ts (1)

134-134: Add JSDoc documentation for the onDelete property.

The new onDelete property looks good and follows the existing pattern of lifecycle hooks. However, consider adding JSDoc documentation to match other properties and improve maintainability.

+  /**
+   * Represents actions to be executed when an application is deleted.
+   * Can be either a single TemplateApi action or an array of actions.
+   */
   onDelete?: TemplateApi<R>[] | TemplateApi<R>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d3b3f0c and 99090a5.

📒 Files selected for processing (5)
  • apps/application-system/api/src/app/modules/application/application.controller.ts (2 hunks)
  • libs/application/core/src/lib/ApplicationTemplateHelper.ts (1 hunks)
  • libs/application/types/src/lib/StateMachine.ts (1 hunks)
  • libs/application/ui-components/src/components/ApplicationList/ApplicationList.tsx (2 hunks)
  • libs/application/ui-components/src/hooks/useDeleteApplication.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/application-system/api/src/app/modules/application/application.controller.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/application/core/src/lib/ApplicationTemplateHelper.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/types/src/lib/StateMachine.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/ui-components/src/components/ApplicationList/ApplicationList.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/ui-components/src/hooks/useDeleteApplication.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 (5)
libs/application/ui-components/src/hooks/useDeleteApplication.ts (1)

3-4: LGTM! Good separation of concerns with error handling.

The addition of localization support and error handling utilities improves the hook's reusability across different NextJS apps while maintaining proper TypeScript typing.

Let's verify the error handling utility implementation:

Also applies to: 7-7

✅ Verification successful

Let me gather more information about the error handling implementation and its dependencies.


Error handling implementation is well-structured and properly integrated

The handleServerError utility follows good practices:

  • Properly handles Apollo GraphQL errors using shared utilities (findProblemInApolloError)
  • Integrates with the localization system via FormatMessage type
  • Uses standardized error handling from @island.is/application/core and @island.is/shared/problem
  • Provides user-friendly error messages through the UI toast system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handleServerError utility implementation
# Expected: The utility should handle GraphQL errors and support localization

# Check the implementation
rg -A 10 "export.*handleServerError" libs/application/ui-components/src/utilities/

Length of output: 1245


Script:

#!/bin/bash
# Check the findProblemInApolloError and getErrorReasonIfPresent implementations
rg -A 5 "findProblemInApolloError|getErrorReasonIfPresent" libs/application/ui-components/src/utilities/

# Check the types used in handleServerError
ast-grep --pattern 'type $_'

Length of output: 2313

libs/application/ui-components/src/components/ApplicationList/ApplicationList.tsx (1)

2-7: LGTM! Import changes follow best practices

The ToastContainer import is properly grouped with other UI components and maintains effective tree-shaking.

libs/application/types/src/lib/StateMachine.ts (1)

134-134: Verify the usage of onDelete property.

Let's verify how this property is being used in the application templates.

✅ Verification successful

The onDelete property is used for template API actions during application deletion

The property is correctly implemented in the codebase. It's used by ApplicationTemplateHelper to execute template-specific API actions when an application is being deleted. The implementation in application.controller.ts shows that these actions are properly handled and can be either a single action or an array of actions.

Key findings:

  • Used in ApplicationTemplateHelper.getOnDeleteStateAPIAction() to retrieve deletion-specific API actions
  • Properly handled in the application controller to support both single and multiple API actions
  • Follows the same pattern as other template API actions (onEntry, onExit)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usage of onDelete in application templates and state definitions
# Expected: Find implementations showing how onDelete is configured in templates

# Test 1: Look for direct usage of onDelete in state definitions
rg -t typescript "onDelete.*TemplateApi" -A 5

# Test 2: Look for state machine configurations that might use this property
ast-grep --pattern 'meta: {
  $$$
  onDelete: $_
  $$$
}'

Length of output: 142


Script:

#!/bin/bash
# Let's try different search patterns to find onDelete usage

# Search for onDelete in TypeScript/JavaScript files
rg "onDelete" --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}' -t ts -t js -C 3

# Search for state machine configurations
rg "StateMachine" --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}' -t ts -t js -C 3

# Look for template definitions that might use onDelete
ast-grep --pattern 'const $_ = {
  $$$
  onDelete: $_,
  $$$
}'

Length of output: 98192


Script:

#!/bin/bash
# Let's search for usage of onDelete in application templates and state machine configurations

# Look for state machine configurations with onDelete
ast-grep --pattern 'states: {
  $$$
  meta: {
    $$$
    onDelete: $_
    $$$
  }
  $$$
}'

# Search for ApplicationTemplateHelper usage of onDelete
rg "getOnDeleteStateAPIAction" --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}' -t ts -t js -C 3

Length of output: 1630

libs/application/core/src/lib/ApplicationTemplateHelper.ts (1)

121-128: LGTM! The implementation follows established patterns.

The new getOnDeleteStateAPIAction method:

  • Maintains consistency with existing state action retrieval methods
  • Uses TypeScript effectively with proper return type definition
  • Follows best practices for null handling using optional chaining and nullish coalescing
  • Is properly placed in the core library for reuse across different NextJS apps

Let's verify the usage of this new method:

✅ Verification successful

Implementation follows established patterns and is correctly used

The getOnDeleteStateAPIAction method:

  • Follows the same pattern as getOnExitStateAPIAction and getOnEntryStateAPIAction
  • Is properly used in the application controller for handling application deletion
  • Correctly uses the shared getTemplateAPIAction helper method for consistent API action handling
  • Has proper TypeScript typing and null handling with optional chaining

The implementation is verified to be consistent with the codebase's patterns and is being used appropriately in the deletion flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of onDelete actions across the codebase
# Expected: Find references to onDelete in state machine configurations and its usage

# Test 1: Look for state machine configurations defining onDelete actions
rg -A 3 "onDelete:\s*{" 

# Test 2: Look for usages of getOnDeleteStateAPIAction
rg "getOnDeleteStateAPIAction"

Length of output: 350


Script:

#!/bin/bash
# Let's try a different approach to find onDelete configurations and usages

# Search for onDelete in state machine configurations
rg "onDelete" -A 3

# Search for template configurations with onDelete
fd "template.json" --exec rg "onDelete" {} -A 3 \;

# Look at the implementation in the controller to understand usage
rg -A 5 "getOnDeleteStateAPIAction" "apps/application-system/api/src/app/modules/application/application.controller.ts"

Length of output: 51186


Script:

#!/bin/bash
# Let's check for state machine configurations to understand onDelete usage

# Look for state machine configurations
ast-grep --pattern 'stateMachineConfig = {
  $$$
}'

# Search for meta configurations with onDelete
rg -B 2 -A 2 "meta:\s*{[^}]*onDelete" 

# Look at the template helper implementation
rg -B 5 -A 5 "getTemplateAPIAction" "libs/application/core/src/lib/ApplicationTemplateHelper.ts"

Length of output: 1480

apps/application-system/api/src/app/modules/application/application.controller.ts (1)

1082-1082: Addition of 'locale' parameter is appropriate and correctly implemented

The new parameter @CurrentLocale() locale: Locale is properly added to the delete method and utilized within the method.

Copy link
Member

@HjorturJ HjorturJ 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

codecov bot commented Oct 29, 2024

Codecov Report

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

Project coverage is 36.78%. Comparing base (b86cd04) to head (c3edb3e).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../app/modules/application/application.controller.ts 0.00% 18 Missing ⚠️
...on/ui-components/src/hooks/useDeleteApplication.ts 0.00% 5 Missing ⚠️
...lication/core/src/lib/ApplicationTemplateHelper.ts 0.00% 4 Missing ⚠️
...src/components/ApplicationList/ApplicationList.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16605      +/-   ##
==========================================
- Coverage   36.79%   36.78%   -0.01%     
==========================================
  Files        6855     6855              
  Lines      142285   142311      +26     
  Branches    40576    40590      +14     
==========================================
- Hits        52348    52347       -1     
- Misses      89937    89964      +27     
Flag Coverage Δ
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
application-api-files 56.78% <ø> (ø)
application-core 71.49% <0.00%> (+0.14%) ⬆️
application-system-api 41.32% <0.00%> (-0.02%) ⬇️
application-template-api-modules 27.78% <0.00%> (-0.02%) ⬇️
application-templates-accident-notification 29.24% <0.00%> (-0.07%) ⬇️
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.30% <0.00%> (-0.13%) ⬇️
application-templates-driving-license 18.40% <0.00%> (-0.06%) ⬇️
application-templates-estate 12.25% <0.00%> (-0.02%) ⬇️
application-templates-example-payment 25.20% <0.00%> (-0.12%) ⬇️
application-templates-financial-aid 15.50% <0.00%> (-0.04%) ⬇️
application-templates-general-petition 23.42% <0.00%> (-0.11%) ⬇️
application-templates-inheritance-report 6.51% <0.00%> (-0.01%) ⬇️
application-templates-marriage-conditions 15.18% <0.00%> (-0.07%) ⬇️
application-templates-mortgage-certificate 43.55% <0.00%> (-0.07%) ⬇️
application-templates-parental-leave 29.94% <0.00%> (-0.03%) ⬇️
application-types 6.62% <ø> (ø)
application-ui-components 1.27% <0.00%> (-0.01%) ⬇️
application-ui-shell 21.22% <0.00%> (-0.02%) ⬇️
clients-charge-fjs-v2 24.11% <ø> (ø)
services-university-gateway 49.35% <ø> (-0.15%) ⬇️
web 1.79% <ø> (ø)

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

Files with missing lines Coverage Δ
libs/application/types/src/lib/StateMachine.ts 95.00% <ø> (ø)
...src/components/ApplicationList/ApplicationList.tsx 6.25% <0.00%> (ø)
...lication/core/src/lib/ApplicationTemplateHelper.ts 78.23% <0.00%> (-2.19%) ⬇️
...on/ui-components/src/hooks/useDeleteApplication.ts 7.14% <0.00%> (-3.97%) ⬇️
.../app/modules/application/application.controller.ts 77.94% <0.00%> (-4.22%) ⬇️

... and 1 file 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 b86cd04...c3edb3e. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 29, 2024

Datadog Report

All test runs d2b8fa4 🔗

21 Total Test Services: 0 Failed, 20 Passed
🔻 Test Sessions change in coverage: 17 decreased, 1 increased (+0.04%), 84 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-web 0 0 0 2 0 7.03s 1 no change Link
api 0 0 0 4 0 2.98s 1 no change Link
application-api-files 0 0 0 12 0 5.32s 1 no change Link
application-core 0 0 0 92 0 14.42s 1 increased (+0.04%) Link
application-system-api 0 0 0 120 2 3m 18.42s 1 no change Link
application-template-api-modules 0 0 0 123 0 2m 1.8s 1 decreased (-0.01%) Link
application-templates-accident-notification 0 0 0 148 0 16.18s 1 decreased (-0.06%) Link
application-templates-criminal-record 0 0 0 2 0 9.96s 1 decreased (-0.11%) Link
application-templates-driving-license 0 0 0 13 0 12.98s 1 decreased (-0.05%) Link
application-templates-example-payment 0 0 0 2 0 10.2s 1 decreased (-0.1%) Link

🔻 Code Coverage Decreases vs Default Branch (17)

This report shows up to 5 code coverage decreases.

  • application-templates-criminal-record - jest 32.9% (-0.11%) - Details
  • application-templates-example-payment - jest 31.76% (-0.1%) - Details
  • application-templates-general-petition - jest 27.96% (-0.09%) - Details
  • application-templates-social-insurance-administration-additional-support-for-the-elderly - jest 31% (-0.07%) - Details
  • application-templates-mortgage-certificate - jest 52.65% (-0.07%) - Details

@obmagnusson obmagnusson changed the title feat(application-stystem): On delete template api feat(application-system): On delete template api Oct 29, 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: 1

🧹 Outside diff range and nitpick comments (3)
apps/application-system/api/src/app/modules/application/application.controller.ts (3)

1110-1146: Enhance error handling for delete actions

While the error handling is good, consider these improvements:

  1. Add timeout handling for external API calls
  2. Implement retry logic for transient failures
  3. Add more detailed error logging for debugging
       const result =
         deletingApplication.externalData[api.externalDataId || api.action]

+      if (!result) {
+        this.logger.error(
+          `No result found for action ${api.action} on ${JSON.stringify(
+            template.name,
+          )}`,
+        )
+        throw new TemplateApiError('Action execution failed', 500)
+      }

       this.logger.debug(

Line range hint 1147-1162: Implement transaction-like behavior for resource cleanup

The sequential deletion of resources could leave the system in an inconsistent state if one operation fails. Consider implementing a rollback mechanism or using a transaction-like pattern.

Consider implementing a cleanup service that:

  1. Tracks the status of each deletion step
  2. Implements retry logic for failed operations
  3. Provides rollback capabilities
  4. Logs detailed cleanup status

Would you like me to help create a new cleanup service implementation?


1163-1168: Enhance audit logging for deletion process

Consider adding more metadata to the audit log to track the complete deletion process:

     this.auditService.audit({
       auth: user,
       action: 'delete',
       resources: existingApplication.id,
-      meta: { type: existingApplication.typeId },
+      meta: {
+        type: existingApplication.typeId,
+        deletedResources: {
+          charges: true,
+          payments: true,
+          attachments: true,
+          history: true
+        },
+        onDeleteActionsExecuted: onDeleteActions ? onDeleteActions.length : 0
+      },
     })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 99090a5 and 8af4797.

📒 Files selected for processing (1)
  • apps/application-system/api/src/app/modules/application/application.controller.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/application-system/api/src/app/modules/application/application.controller.ts (1)

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

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

1082-1082: LGTM: Locale parameter addition

The addition of the locale parameter enables proper internationalization support for delete actions and error messages.

@obmagnusson obmagnusson added automerge Merge this PR as soon as all checks pass and removed automerge Merge this PR as soon as all checks pass labels Oct 29, 2024
@kodiakhq kodiakhq bot merged commit e50ded3 into main Oct 29, 2024
92 checks passed
@kodiakhq kodiakhq bot deleted the as-ondelete branch October 29, 2024 14:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants