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

Add/Remove UBOs #2904

Merged
merged 9 commits into from
Dec 26, 2024
Merged

Add/Remove UBOs #2904

merged 9 commits into from
Dec 26, 2024

Conversation

Omri-Levy
Copy link
Contributor

@Omri-Levy Omri-Levy commented Dec 23, 2024

Summary by CodeRabbit

  • New Features

    • Added success and error messages for UBO creation and deletion actions.
    • Introduced new hooks for managing UBOs, including creation and deletion functionalities.
    • Implemented UI definition translation capabilities.
    • Enhanced workflow management with optional UI definitions.
    • Added a new form schema for company ownership contacts.
    • Introduced methods for traversing UI schemas and managing translations.
    • Enhanced the CaseManagementController with new methods for UBO management.
    • Expanded UiDefinitionService with new translation capabilities.
    • Improved handling of deleted workflows in the workflow management system.
    • Updated button component to support a disabled state.
  • Bug Fixes

    • Improved error handling for UBO operations and UI translations.
  • Style

    • Updated styling for various components, enhancing user experience.
  • Documentation

    • Updated documentation to reflect new features and changes in functionality.
  • Chores

    • Updated several dependencies across multiple packages.

Copy link

changeset-bot bot commented Dec 23, 2024

⚠️ No Changeset found

Latest commit: f759230

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 23, 2024

Walkthrough

This pull request introduces comprehensive enhancements to the backoffice application, focusing on Ultimate Beneficial Owners (UBOs) management, UI definition translations, and workflow-related functionalities. The changes span multiple services and components, adding new hooks, mutations, and services to support UBO creation, deletion, and management. The implementation includes improvements in localization, form schema generation, and UI interaction, with a particular emphasis on providing a more robust and flexible system for handling complex workflow-related tasks.

Changes

File Change Summary
apps/backoffice-v2/.storybook/main.ts Added viteFinal function to optimize dependency loading for @ballerine/ui
apps/backoffice-v2/public/locales/en/toast.json Added localization entries for UBO creation and deletion toast messages
apps/backoffice-v2/src/common/api-client/interfaces.ts Updated IApiClient interface to modify method parameter types for API calls
apps/backoffice-v2/src/domains/ui-definition/fetchers.ts Introduced translateUiDefinition function for UI definition translation
apps/backoffice-v2/src/domains/ui-definition/hooks/queries/useTranslateUiDefinitionQuery/useTranslateUiDefinitionQuery.tsx Added useTranslateUiDefinitionQuery custom hook for data fetching
apps/backoffice-v2/src/domains/ui-definition/query-keys.ts Introduced uiDefinitionQueryKeys for managing query keys
apps/backoffice-v2/src/domains/workflow-definitions/fetchers.ts Added uiDefinitions property to WorkflowDefinitionByIdSchema
apps/backoffice-v2/src/domains/workflows/hooks/mutations/useCreateUboMutation/useCreateUboMutation.tsx Added useCreateUboMutation hook for creating UBOs
apps/backoffice-v2/src/domains/workflows/hooks/mutations/useDeleteUbosByIdsMutation/useDeleteUbosByIdsMutation.tsx Added useDeleteUbosByIdsMutation hook for deleting UBOs
apps/backoffice-v2/src/lib/blocks/components/BlockCell/BlockCell.tsx Modified styling of BlockCell component
apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx Enhanced useKycBlock hook with event handling
apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/ubos-form-json-definition.ts Introduced ubosFormJsonDefinition for UBO form schema
apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/useManageUbosBlock.tsx Added useManageUbosBlock hook for managing UBOs
apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/utils/create-form-schema-from-ui-elements.ts Added createFormSchemaFromUIElements function for form schema generation
apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx Updated useUbosUserProvidedBlock for improved type safety
apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/DefaultBlocks.tsx Modified ScrollArea component styling
apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useCaseBlocksLogic/utils/get-tabs-block-map.tsx Added manageUbosBlock to tab mapping
apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useDefaultBlocksLogic/useDefaultBlocksLogic.tsx Updated logic in useDefaultBlocksLogic hook
apps/backoffice-v2/src/pages/Entity/components/Case/components/CaseOverview/CaseOverview.tsx Modified class name in CaseOverview component
packages/common/src/schemas/documents/merchant-screening-plugin-schema.ts Updated DriversLicenseSchema to make Number field optional
packages/ui/src/components/atoms/Button/Button.tsx Enhanced button accessibility with new classes
services/workflows-service/prisma/data-migrations Updated subproject commit hash
services/workflows-service/prisma/migrations/20241219094046_workflow_runtime_soft_delete/migration.sql Added deletedAt and deletedBy columns to WorkflowRuntimeData table
services/workflows-service/prisma/schema.prisma Added deletedAt and deletedBy fields to WorkflowRuntimeData model
services/workflows-service/src/case-management/case-management.module.ts Added UiDefinitionModule to CaseManagementModule imports
services/workflows-service/src/case-management/case-management.service.ts Added methods for UBO creation and deletion
services/workflows-service/src/case-management/controllers/case-management.controller.ts Added methods for translating UI definitions and managing UBOs
services/workflows-service/src/collection-flow/collection-flow.service.ts Removed methods for translation resource handling
services/workflows-service/src/end-user/end-user.service.ts Updated updateById method to enhance parameter handling
services/workflows-service/src/ui-definition/ui-definition.service.ts Added methods for traversing UI schema and managing translation resources
services/workflows-service/src/workflow/workflow.service.ts Enhanced getWorkflowByIdWithRelations method for better workflow retrieval
services/workflows-service/src/case-management/types.ts Introduced UboToEntityAdapter type for UBO transformation

Sequence Diagram

sequenceDiagram
    participant User
    participant UI
    participant CaseManagementController
    participant CaseManagementService
    participant PrismaDatabase

    User->>UI: Initiate UBO Management
    UI->>CaseManagementController: Create/Delete UBO
    CaseManagementController->>CaseManagementService: Process UBO Operation
    CaseManagementService->>PrismaDatabase: Perform Database Transaction
    PrismaDatabase-->>CaseManagementService: Return Operation Result
    CaseManagementService-->>CaseManagementController: Return Result
    CaseManagementController-->>UI: Send Response
    UI->>User: Display Notification
Loading

Suggested Reviewers

  • MatanYadaev
  • tomer-shvadron

Poem

🐰 Hop, hop, hooray! UBOs are here to play,
With translations crisp and workflows bright,
Our backoffice dances with newfound might!
Mutations and hooks, a technological ballet,
CodeRabbit's magic makes complexity sway! 🎉

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🔭 Outside diff range comments (1)
apps/backoffice-v2/src/common/api-client/interfaces.ts (1)

Inconsistency found between interface documentation and implementation

There's a clear inconsistency in the codebase:

  1. The interface documentation explicitly states: * Expect {@link Method.GET} and {@link Method.DELETE} to not have a body.
  2. However, the implementation allows DELETE with body in IApiClient interface, and there's actual usage in useDeleteUbosByIdsMutation where DELETE is used with a body payload: { ids }.
  3. Furthermore, the IFetcher interface correctly implements this constraint by having separate overloads where DELETE is grouped with GET and doesn't accept a body.
🔗 Analysis chain

Line range hint 11-22: Confirm alignment of DELETE with body usage.

You now allow DELETE in these overloads that accept a body. Verify the endpoint strictly requires a body. Some APIs may not expect a body with DELETE requests. Consider clarifying usage or adding code comments to avoid confusion.


Let's search for API endpoint implementations and usage patterns to verify if DELETE requests with body payloads are being used consistently.

This will help us understand:

  1. How DELETE methods are used across the codebase
  2. Whether they consistently include body payloads
  3. The context of API client usage patterns

Let's search more broadly for DELETE method usage and also look at the Method enum definition to understand the full context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for DELETE method usage patterns
rg -A 3 "method:\s*Method\.DELETE" --type ts

# Search for any direct DELETE method string usage
rg -A 3 '"DELETE"' --type ts

# Look for API client instantiation or configuration
rg -A 5 "new ApiClient|createApiClient" --type ts

Length of output: 684


Script:

#!/bin/bash
# Find the Method enum definition
rg -A 5 "enum Method" --type ts

# Search for DELETE method usage with more context
rg -B 3 -A 5 "Method\.DELETE" --type ts

# Look for any HTTP method related constants or types
rg -A 3 "type.*Method|interface.*Method" --type ts

Length of output: 9219

♻️ Duplicate comments (1)
services/workflows-service/src/case-management/controllers/case-management.controller.ts (1)

239-242: ⚠️ Potential issue

Reflected XSS risk on returning user-provided data.
This logic returns partial UI definitions directly to the client, potentially including unescaped user inputs. Confirm that the downstream usage either sanitizes outputs or never treats them as HTML.

 return {
   ...body.partialUiDefinition,
   elements,
 };
+// Ensure sanitization or escaping logic if rendered in the browser as HTML.
🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 239-242: Reflected cross-site scripting
Cross-site scripting vulnerability due to a user-provided value.

🧹 Nitpick comments (35)
services/workflows-service/src/ui-definition/ui-definition.service.ts (1)

136-145: Revisit the structure of locales if you anticipate more complex i18n needs.
Returning an array of language–resource entries is straightforward and effective, but in the future, you might need to handle advanced fallback logic or partial locales.

apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (5)

306-307: Refine styling approach.
Using the “success” variant plus additional classes (like enabled:bg-success) can quickly become cumbersome and inconsistent. Consider centralizing or reusing a consistent set of styles, possibly from a design system or a utility class.


353-353: Minor layout improvement suggestion.
The “justify-between items-center pt-6” class organization is generally fine. However, consider verifying that the vertical padding does not collide or stack unnecessarily with padding from parent elements.


362-365: Heading class usage.
This heading is given 'mt-0'. Check for potential conflicts or unintended vertical spacing if parent containers also add margin or padding.


554-566: Enhance instructions for missing data.
Currently, if no extracted data exists, the user sees “Initiate KYC for document extracted data to appear.” This is clear, but you might also provide next steps or a direct button in that empty state to begin the process.


593-605: Improve the no-data scenario messaging.
When no verification data is available, the user sees “Initiate KYC for document verification results to appear.” This is functional as an empty state. Consider adding a link or button to jump-start the process, avoiding extra steps.

apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx (1)

6-15: Enhance type coverage for better readability.
The function signature is clear, but you might improve maintainability by extracting the UBO type into a named interface or type (e.g. “UboProvidedData”) to reuse across the codebase.

-export const useUbosUserProvidedBlock = (
-  ubosUserProvided: Array<{
-    name: string;
-    nationality: string;
-    identityNumber: string;
-    percentageOfOwnership: number;
-    email: string;
-    address: string;
-  }>,
-) => {
+type UboProvidedData = {
+  name: string;
+  nationality: string;
+  identityNumber: string;
+  percentageOfOwnership: number;
+  email: string;
+  address: string;
+}
+
+export const useUbosUserProvidedBlock = (
+  ubosUserProvided: Array<UboProvidedData>,
+) => {
services/workflows-service/src/case-management/case-management.service.ts (4)

100-136: Handle scenario for missing first or last name in UBO data.
The code assumes first and last names always exist within ubo. If the front-end fails to provide them, this may lead to incomplete data. A small check or fallback would improve resilience.


159-165: Consider referencing existing UBO if it already exists.
If the same UBO is added multiple times, you might want to handle duplication or update existing data instead of always creating a new record.


197-222: Consider optimizing child workflows removal logic.
The reduce call is correct, but it can be more readable if you break it out into separate steps or well-named helper functions.


224-250: Check for concurrency issues.
Multiple synchronous deletions could cause race conditions. Evaluate if row-level locking or a concurrency strategy is necessary.

services/workflows-service/src/case-management/controllers/case-management.controller.ts (2)

214-243: Support partial translations or fallback logic.
When translating UI definitions, ensure that keys missing from body.partialUiDefinition do not break the resulting object. Consider merging or fallback logic to preserve existing translations.

🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 239-242: Reflected cross-site scripting
Cross-site scripting vulnerability due to a user-provided value.


260-282: Include better logging for high-level deletions.
The ID array for deletion can be large. Consider logging or summarizing the removed UBOs to maintain an audit trail.

Would you like assistance generating comprehensive logs or an audit record system?

apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/useManageUbosBlock.tsx (4)

1-28: Avoid potential duplication in imports.
A large number of imports are used. If certain imports are only used sporadically, consider lazy imports or grouping to keep the module lean.


29-56: Ensure stable references for callback props.
“useManageUbosBlock” is well-structured, but consider stable references for callback props to minimize re-renders in child components (e.g., useCallback).


57-77: Improper usage of disabled attribute.
The ARIA-disabled styling is correct, but also ensure you set the native “disabled” prop for HTML form elements or buttons to block interaction.

<Button
  className="aria-disabled:pointer-events-none aria-disabled:opacity-50"
- aria-disabled={!caseState.writeEnabled}
+ aria-disabled={!caseState.writeEnabled}
+ disabled={!caseState.writeEnabled}
>
  Submit
</Button>

103-139: Use distinct state or local storage for remove confirmations.
Currently, each row triggers a new Dialog. If you have many UBOs, it might result in performance overhead or repeated re-renders. Consider optimizing the remove confirmation flow.

apps/backoffice-v2/src/domains/ui-definition/hooks/queries/useTranslateUiDefinitionQuery/useTranslateUiDefinitionQuery.tsx (1)

1-2: Import usage check.
Confirm that “useQuery” is the only method needed from react-query. If advanced features like “useInfiniteQuery” are needed later, import them as needed to keep dependencies minimal.

apps/backoffice-v2/src/domains/ui-definition/query-keys.ts (1)

4-22: Validate type safety for partialUiDefinition.

Currently, partialUiDefinition is typed as Record<string, unknown>. Consider refining the type definition or introducing Zod-based validation here to ensure stricter type safety and consistency with the rest of the codebase.

services/workflows-service/src/case-management/case-management.module.ts (1)

Line range hint 9-18: Consider whether UiDefinitionModule is needed in related features as well.

UiDefinitionModule is imported here, which is good for extended UI translation features. Review other modules to ensure consistent approach for UI definition or translation functionalities if needed.

apps/backoffice-v2/src/domains/workflows/hooks/mutations/useDeleteUbosByIdsMutation/useDeleteUbosByIdsMutation.tsx (2)

19-21: Consider scoping query invalidation to relevant queries only.

Currently, calling queryClient.invalidateQueries() without arguments clears all cached queries, which may be more expensive than necessary. Consider only invalidating the queries that are directly affected by these UBO deletions for better cache management and performance.


32-33: Add error details for better debugging.

The error toast provides a generic error message. For troubleshooting, consider enhancing the toast message with minimal details from the error object (where appropriate) to guide debugging, while avoiding sensitive data leakage.

apps/backoffice-v2/src/domains/workflows/hooks/mutations/useCreateUboMutation/useCreateUboMutation.tsx (3)

29-29: Revisit schema validation for newly created UBOs.

The schema is set to z.undefined(), implying the API returns no data on success. If you anticipate receiving any relevant data (e.g., newly created UBO ID), update this schema to ensure proper validation and type safety.


36-38: Scope query invalidation for performance.

Similar to the delete mutation, consider invalidating only relevant queries (e.g., UBO list queries) rather than calling invalidateQueries() globally. This approach reduces unnecessary re-fetching of unrelated data.


40-41: Provide more actionable error details.

Currently, the toast shows the generic "ubo_created.error" message. If feasible, enrich this with minimal details from the error object to expedite debugging, while still protecting sensitive information.

apps/backoffice-v2/src/common/api-client/interfaces.ts (1)

Line range hint 33-42: Reintroduce DELETE overload if needed.

The last two overloads only allow GET, which aligns with the doc comment stating GET must not have a body. If your API also supports bodyless DELETE requests, you may consider reintroducing Method.DELETE here, ensuring consistency with the documentation that forbids a request body for GET and DELETE.

apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/utils/create-form-schema-from-ui-elements.ts (4)

4-4: Use typed parameters instead of 'any'.
It is recommended to define a proper interface or type for the formElement parameter to enhance type safety and readability.


20-20: Avoid using 'any[]' for elements.
Consider introducing a well-defined type or interface for your UI elements to ensure stronger type checking and improve clarity.

Also applies to: 60-60


38-40: Leverage optional chaining for safer property access.
As flagged by the static analysis, changing these chains to optional chaining (e.g., (uiElement.options?.uiSchema)?.['ui:label']) can reduce the risk of runtime errors and improve readability.

Also applies to: 79-81

🧰 Tools
🪛 Biome (1.9.4)

[error] 38-38: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 40-40: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


46-85: Reduce duplication between 'object' and 'array' form schema creation.
Both branches share similar logic for constructing properties and uiSchema. Consider extracting common logic into helper functions to follow DRY (Don’t Repeat Yourself) principles.

🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 81-81: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useCaseBlocksLogic/utils/get-tabs-block-map.tsx (1)

57-57: Add meaningful checks for 'manageUbosBlock' usage.
You've introduced manageUbosBlock in the UBOS tab. If the block shouldn't always be rendered, consider conditionally rendering it based on relevant workflow or context conditions.

Also applies to: 90-90

apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/ubos-form-json-definition.ts (1)

30-245: Extensive field coverage with consistent schema definitions.
• Each element clearly aligns label, hint, and JSON schema options.
• Using specialized UI components like PhoneInput, DateInput, CountryPicker, and NationalityPicker demonstrates a clean separation between data and representation.
• Including “oneOf” constraints for gender is a good approach for enumerated fields.

Consider adding simple validations (e.g., format patterns for phone, email, or passport number) if the underlying form engine supports user input validation to catch errors early.

apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useDefaultBlocksLogic/useDefaultBlocksLogic.tsx (1)

56-60: Added new imports for UI components and toast.
Keeping imports minimal but functional is good. Avoid introducing unused imports if they are no longer needed.

services/workflows-service/prisma/schema.prisma (1)

279-281: Soft-delete fields added to WorkflowRuntimeData.
• Fields “deletedAt” and “deletedBy” enable audit logging and soft-deletion without impacting historical records.
• Ensure any queries or references to workflow runtime data consider these fields properly, preventing accidental retrieval of “deleted” records.

Consider a compound index or partial index to more efficiently query active vs. deleted states if needed.

apps/backoffice-v2/public/locales/en/toast.json (1)

108-114: Ensure consistency in toast messages.

Unlike most of the existing messages, the new “ubo_created” and “ubo_deleted” messages omit periods at the end. For consistency and clarity, consider aligning punctuation and style with the existing toast messages.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 246451b and c85be91.

📒 Files selected for processing (31)
  • apps/backoffice-v2/.storybook/main.ts (1 hunks)
  • apps/backoffice-v2/public/locales/en/toast.json (1 hunks)
  • apps/backoffice-v2/src/common/api-client/interfaces.ts (4 hunks)
  • apps/backoffice-v2/src/domains/ui-definition/fetchers.ts (1 hunks)
  • apps/backoffice-v2/src/domains/ui-definition/hooks/queries/useTranslateUiDefinitionQuery/useTranslateUiDefinitionQuery.tsx (1 hunks)
  • apps/backoffice-v2/src/domains/ui-definition/query-keys.ts (1 hunks)
  • apps/backoffice-v2/src/domains/workflow-definitions/fetchers.ts (1 hunks)
  • apps/backoffice-v2/src/domains/workflows/hooks/mutations/useCreateUboMutation/useCreateUboMutation.tsx (1 hunks)
  • apps/backoffice-v2/src/domains/workflows/hooks/mutations/useDeleteUbosByIdsMutation/useDeleteUbosByIdsMutation.tsx (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/components/BlockCell/BlockCell.tsx (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (5 hunks)
  • apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/ubos-form-json-definition.ts (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/useManageUbosBlock.tsx (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/utils/create-form-schema-from-ui-elements.ts (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx (2 hunks)
  • apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/DefaultBlocks.tsx (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useCaseBlocksLogic/utils/get-tabs-block-map.tsx (2 hunks)
  • apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useDefaultBlocksLogic/useDefaultBlocksLogic.tsx (7 hunks)
  • apps/backoffice-v2/src/pages/Entity/components/Case/components/CaseOverview/CaseOverview.tsx (1 hunks)
  • packages/common/src/schemas/documents/merchant-screening-plugin-schema.ts (1 hunks)
  • packages/ui/src/components/atoms/Button/Button.tsx (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/prisma/migrations/20241219094046_workflow_runtime_soft_delete/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (2 hunks)
  • services/workflows-service/src/case-management/case-management.module.ts (2 hunks)
  • services/workflows-service/src/case-management/case-management.service.ts (2 hunks)
  • services/workflows-service/src/case-management/controllers/case-management.controller.ts (3 hunks)
  • services/workflows-service/src/collection-flow/collection-flow.service.ts (1 hunks)
  • services/workflows-service/src/end-user/end-user.service.ts (1 hunks)
  • services/workflows-service/src/ui-definition/ui-definition.service.ts (2 hunks)
  • services/workflows-service/src/workflow/workflow.service.ts (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • services/workflows-service/prisma/migrations/20241219094046_workflow_runtime_soft_delete/migration.sql
  • apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/DefaultBlocks.tsx
  • services/workflows-service/prisma/data-migrations
  • apps/backoffice-v2/src/pages/Entity/components/Case/components/CaseOverview/CaseOverview.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/utils/create-form-schema-from-ui-elements.ts

[error] 38-38: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 40-40: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 81-81: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🪛 GitHub Check: CodeQL
services/workflows-service/src/case-management/controllers/case-management.controller.ts

[failure] 239-242: Reflected cross-site scripting
Cross-site scripting vulnerability due to a user-provided value.

🔇 Additional comments (38)
apps/backoffice-v2/src/lib/blocks/components/BlockCell/BlockCell.tsx (1)

22-22: Consider verifying spacing consistency across the layout.

Removing the "me-4" class reduces horizontal spacing, which could potentially disrupt layout alignment if other content relies on this margin. Ensure that the removal of this spacing is intentional and doesn’t cause unwanted layout shifts across the UI.

✅ Verification successful

Let me gather information about the spacing classes and layout patterns in the codebase.


Let me try different commands to analyze the spacing patterns.


Based on the search results, I can now generate the final response:

The removal of "me-4" class appears to be intentional and consistent with the codebase's layout patterns.

The BlockCell component is using a consistent shadow styling (shadow-[0_4px_4px_0_rgba(174,174,174,0.0625)]) and allows for custom className props to be passed through. The removal of the "me-4" margin class is safe because:

  • The component is designed to be flexible with spacing through props.className
  • Other Card components in the codebase handle their spacing through parent container classes rather than hardcoded margins
  • The shadow styling provides visual separation without relying on margins
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for BlockCell usage and its surrounding context
rg -A 5 -B 5 "BlockCell" --type tsx

# Search for similar Card components with margin/spacing classes
ast-grep --pattern 'Card className={$_}'

Length of output: 106


Script:

#!/bin/bash
# Search for BlockCell usage and its surrounding context
rg -A 5 -B 5 "BlockCell"

# Search for Card components with className props
rg -A 2 -B 2 'Card.*className'

# Find all files that might contain BlockCell component
fd BlockCell

Length of output: 48821

services/workflows-service/src/ui-definition/ui-definition.service.ts (2)

1-2: Imports for translation service look good.
These new imports enable external translations and appear consistent with the rest of the codebase.


8-8: Extended Prisma import usage is appropriate.
The inclusion of UiDefinition and WorkflowRuntimeData aligns with the usage in the new methods below.

apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (5)

542-553: Good conditional display of extracted data.
Displaying “Document Extracted Data” only if documentExtractedData.length is non-zero is a good UX approach. If possible, show a loader or skeleton state while data is being fetched to further improve UX.


570-592: Conditional rendering for “Document Verification Results.”
This block effectively checks if decision.length is non-zero. Make sure the data that populates “decision” is always kept in sync with the step(s) post “Initiate KYC.”

✅ Verification successful

Let me gather information about how the decision variable is populated and its relationship with KYC steps.


Based on the search results, I can now generate a final response as I have enough information about how the decision variable is populated and its relationship with the KYC workflow:

The conditional rendering is correctly synchronized with KYC workflow state.
The decision array is populated from kycSessionKeys which contains KYC session data including verification results, vendor information, and risk labels. This data is only available after "Initiate KYC" action is completed, ensuring the Document Verification Results section stays in sync with the KYC workflow state. The code correctly handles both cases: showing placeholder text when KYC is not initiated and displaying verification results when KYC data is available.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for the decision variable declaration and usage in the KYC block
ast-grep --pattern 'const decision = $_'

# Search for references to decision in the file
rg "decision" apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx -B 2 -A 2

# Look for KYC workflow steps and their relationship with decision
rg "Initiate KYC" -B 5 -A 5

Length of output: 29306


27-27: Ensure the new mutation is used correctly.
The import for useEventMutation is introduced here. Confirm that this mutation is invoked in the correct places and that error handling or fallback behavior is correctly implemented where necessary.

✅ Verification successful

Let me verify how the useEventMutation is being used in the file by first checking its implementation.


Let me check the implementation of useEventMutation and how it's being used in the workflow context.


Based on the analysis of the code, I can now provide a final response:

The useEventMutation is implemented correctly with proper error handling.
The mutation is used to initiate KYC checks with built-in error handling through toast notifications. It's used in a controlled manner where:

  • The event is only triggered when available in childWorkflow.nextEvents
  • Success and error cases are properly handled with user feedback
  • The mutation includes proper cache invalidation through queryClient.invalidateQueries
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# First, let's see the full content of the file to understand how useEventMutation is used
cat "apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx"

# Then, let's check the implementation of useEventMutation
ast-grep --pattern 'export function useEventMutation() {
  $$$
}'

Length of output: 21008


Script:

#!/bin/bash
# Let's find the implementation of useEventMutation
ast-grep --pattern 'export const useEventMutation = $$$'

# Let's also check where else this mutation is used for error handling patterns
rg "useEventMutation" -A 5

Length of output: 25563


367-386: Button logic confirmation.
The “Initiate KYC” button triggers the “start” event if available. Confirm that partial failures (e.g., network issues while calling mutateRunCheck) are handled properly, either through UI feedback (e.g., a toast or error dialog) or retry logic.

✅ Verification successful

Let me search for error handling patterns and mutation hooks usage in the codebase.


Let me search for the useEventMutation hook implementation to understand its error handling.


Based on the search results, I can now provide a final response as I found the implementation of useEventMutation which shows proper error handling through toast notifications.

Error handling is properly implemented for the KYC initiation.
The useEventMutation hook includes success feedback via toast notifications and is wrapped in React Query's mutation handling, which provides automatic error handling and retry logic. The button is also properly disabled when no event is available, preventing invalid states.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for the mutateRunCheck definition and its error handling
ast-grep --pattern 'const { mutateRunCheck } = use$_'

# Search for any error handling patterns around this mutation
rg "mutateRunCheck" -B 5 -A 10

# Look for toast or error handling utilities in the same file
rg "toast|error|Error" apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx

Length of output: 3796


Script:

#!/bin/bash
# Search for useEventMutation definition
ast-grep --pattern 'export function useEventMutation'

# Search for the file containing useEventMutation
fd useEventMutation

# Look for any mutation-related error handling patterns
rg "useEventMutation" -B 5 -A 15

Length of output: 23543


338-346: Verify “start” event usage.
The code checks for a “start” event within childWorkflow?.nextEvents. Ensure that downstream logic expects this event to be fired, and handle cases in which “start” might not be available.

✅ Verification successful

Let me search for the usage and handling of the "start" event in the codebase.


Let me search for more context about how this event is used in the component and related files.


Let me check the implementation of useEventMutation to understand how the event is handled.


Let me check the implementation of fetchWorkflowEvent and any interfaces defining the workflow structure.


Let me try the search without the file type specification.


Based on the analysis of the codebase, I can now generate the final response:

The "start" event handling is properly implemented
The code correctly checks for the "start" event in childWorkflow?.nextEvents before using it. The event is handled by the useEventMutation hook which makes an API call to trigger the workflow event, with proper error handling and success notifications. The mutation is disabled when no event is available through the disabled prop, making this implementation safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for "start" event usage in the context of workflows/events
rg -A 5 "nextEvents.*start" 

# Search for event handling patterns related to "start"
ast-grep --pattern 'event === "start"'

# Search for any direct references to "start" event
rg -A 5 '"start".*event'

Length of output: 743


Script:

#!/bin/bash
# Search for the usage of mutateRunCheck and event in the same file
rg -A 10 "mutateRunCheck" apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx

# Look for the implementation or type definition of useEventMutation
ast-grep --pattern 'useEventMutation'

# Search for workflow event handling patterns
rg -A 5 "childWorkflow.*event"

Length of output: 2151


Script:

#!/bin/bash
# Look at the implementation of useEventMutation
cat apps/backoffice-v2/src/domains/workflows/hooks/mutations/useEventMutation/useEventMutation.tsx

# Check for any error handling or validation related to events
rg -A 5 "workflowId.*event" apps/backoffice-v2/src/domains/workflows/hooks/mutations/useEventMutation/useEventMutation.tsx

# Look for the type definition of childWorkflow
ast-grep --pattern 'type Workflow'

Length of output: 1279


Script:

#!/bin/bash
# Look for fetchWorkflowEvent implementation
rg -A 10 "fetchWorkflowEvent" --type typescript

# Search for workflow interfaces or types
rg -A 10 "interface.*Workflow" --type typescript

# Look for any validation or error handling related to workflow events
rg -A 5 "nextEvents" --type typescript

Length of output: 242


Script:

#!/bin/bash
# Look for fetchWorkflowEvent implementation
rg -A 10 "fetchWorkflowEvent"

# Search for workflow interfaces or types
rg -A 10 "interface.*Workflow"

# Look for any validation or error handling related to workflow events
rg -A 5 "nextEvents"

# Search for start event handling in workflow components
rg -A 10 "name: 'start'"

Length of output: 66233

apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx (3)

16-16: Improve readability with typed column helper.
While the current approach is valid, consider extracting the item type into a named type parameter for clarity.


2-2: Consider removing unused import if not required.
The import for TextWithNAFallback appears accurate, but double-check that it’s used in the file only once. If it’s part of a style or a pattern not heavily utilized, consider lazy-importing or removing if no longer needed.


70-71: Validate correct data usage for the table.
Ensure that the table column definitions align with the shape of “ubosUserProvided” data, especially if changes occur in the object fields.

✅ Verification successful

Let me gather information about the data structure and column definitions to verify the alignment.


Let me try to find more specific information about the ubosUserProvided data structure and its usage.


From the output, I can see the structure of ubosUserProvided and its usage in the columns definition. Let me check the actual column definitions to verify the alignment.


Based on the code analysis, I can now provide a final response:

Column definitions correctly match the data structure
The table columns perfectly align with the ubosUserProvided data structure. The columns (name, nationality, identityNumber, percentageOfOwnership, email) match exactly with the type definition seen earlier: ubosUserProvided: Array<{ name: string; nationality: string; identityNumber: string; percentageOfOwnership: number; email: string; }>. Each column accessor corresponds to a property in the data structure, with appropriate headers and cell renderers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# First, let's find the definition of columns and ubosUserProvided
ast-grep --pattern 'const columns = $_'

# Also search for any type definitions or interfaces related to ubosUserProvided
rg "type.*UbosUserProvided|interface.*UbosUserProvided" -A 5

# Let's also check how ubosUserProvided is obtained/defined
ast-grep --pattern 'const ubosUserProvided = $_'

Length of output: 66248


Script:

#!/bin/bash
# Let's look for the definition and usage of ubosUserProvided in the specific file
rg -A 5 "ubosUserProvided" "apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx"

# Also search for any type definitions that might be related
rg -A 5 "type.*Ubos|interface.*Ubos" "apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/"

Length of output: 875


Script:

#!/bin/bash
# Let's find the complete columns definition in this file
rg -A 20 "const columns = \[" "apps/backoffice-v2/src/lib/blocks/hooks/useUbosUserProvidedBlock/useUbosUserProvidedBlock.tsx"

Length of output: 708

services/workflows-service/src/case-management/case-management.service.ts (4)

153-156: Avoid silent logic failures.
A missing businessId triggers a BadRequestException. This is good, but ensure the consumer of createUbo is prepared for this error so it doesn't lead to an unhandled UI error.


7-10: Confirm consistent usage of injected services.
The addition of PrismaService and EndUserService is fine, but ensure all references to these services consistently go through the same transaction patterns to avoid partial commits.

✅ Verification successful

Let me gather information about the usage of these services and transaction patterns.


Let me search for more context about the transaction patterns and service usage.


Based on the gathered information, I can now provide the final response:

Transaction patterns are consistently implemented
The code review shows that PrismaService is properly used with transactions in both createUbo and deleteUbosByIds methods. The service follows consistent transaction patterns where multiple database operations are wrapped in prismaService.$transaction blocks to ensure atomic operations. The EndUserService is injected but not directly used in the shown methods, suggesting it might be used in other parts of the service or planned for future use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for PrismaService usage patterns in the file
echo "=== PrismaService usage in case-management.service.ts ==="
rg "prismaService\." "services/workflows-service/src/case-management/case-management.service.ts" -A 3

# Search for transaction patterns with PrismaService
echo -e "\n=== Transaction patterns with PrismaService ==="
ast-grep --pattern 'prismaService.$transaction'

# Search for EndUserService usage patterns
echo -e "\n=== EndUserService usage in case-management.service.ts ==="
rg "endUserService\." "services/workflows-service/src/case-management/case-management.service.ts" -A 3

Length of output: 1186


Script:

#!/bin/bash
# Get the full content of case-management.service.ts to understand the service structure
echo "=== Case Management Service Content ==="
cat "services/workflows-service/src/case-management/case-management.service.ts"

# Check for transaction utility functions
echo -e "\n=== Transaction Utility Functions ==="
cat "services/workflows-service/src/prisma/prisma.util.ts"

# Look for similar service patterns in the codebase
echo -e "\n=== Similar Service Patterns ==="
rg "extends BaseService" -A 5

Length of output: 10904


138-151: Ensure correct parent workflow usage.
When you create a child workflow for a UBO, confirm that the correct parent workflow or project logic is used in all references. Any mismatch here could cause confusion in linking.

✅ Verification successful

Let me gather information about the parent-child workflow relationship and its usage in the codebase.


Based on the search results, I can now verify the parent-child workflow relationship. Let me search for the specific workflow definition to understand how the parent-child linking is implemented.


Based on the gathered information, I can now provide a final response:

Parent-child workflow relationship is correctly implemented.
The code correctly uses the parent-child workflow relationship through the parentWorkflowId parameter. The database schema confirms proper linking through the parentRuntimeDataId foreign key, and the workflow service handles the relationship appropriately. The KYC email session workflow is properly linked as a child workflow to the main workflow through the established parent-child relationship pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for workflowRuntime creation patterns with parentWorkflowId
ast-grep --pattern 'createOrUpdateWorkflowRuntime({
  $$$,
  parentWorkflowId: $_,
  $$$
})'

# Search for references to parentWorkflowId in workflow-related files
rg "parentWorkflowId" -A 3 -B 3

# Search for workflow relationship handling
rg "parent.*workflow" -i

Length of output: 42560


Script:

#!/bin/bash
# Search for the KYC email session definition
ast-grep --pattern 'kycEmailSessionDefinition'

# Search for workflow runtime data schema
rg "WorkflowRuntimeData" -A 5 services/workflows-service/prisma/schema.prisma

Length of output: 5766


169-185: Validate input safety for deleteUbosByIds.
Take care to ensure that the “ids” array has valid item formats before proceeding. Malicious or malformed IDs might lead to partial deletions or leftover references.

services/workflows-service/src/case-management/controllers/case-management.controller.ts (1)

21-21: Excluded user scenario.
The thrown UnauthorizedException is correct for missing user ID, but consider a helpful error message or logging to clarify which part of the flow triggered the unauthorized case.

apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/useManageUbosBlock.tsx (2)

140-255: Provide user feedback on successful addition.
After onSubmit, you close the Add form, but the user might appreciate a toast or success message so it’s clear the new UBO was created successfully.


78-102: Enhance error fallback for ownership percentage.
Similar to other usage of TextWithNAFallback, ensure you handle not-a-number or invalid values properly, especially if data can be user-supplied.

apps/backoffice-v2/src/domains/ui-definition/hooks/queries/useTranslateUiDefinitionQuery/useTranslateUiDefinitionQuery.tsx (1)

3-4: Check query key collisions.
Using “uiDefinitionQueryKeys.translate” is good, but ensure you systematically generate distinct keys for each set of parameters, especially if multiple translations can occur concurrently.

✅ Verification successful

Let me gather information about the query keys implementation and usage to verify potential collisions.


Let me try the search again with correct file type specifications.


Based on the implementation shown in both the query keys file and the hook usage, I can now generate the final response:

Query key implementation is safe from collisions
The query key implementation in query-keys.ts correctly includes both the id and partialUiDefinition in the query key array, ensuring unique keys for different parameter combinations. The hook properly passes these parameters to generate distinct cache keys for concurrent translations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# First, let's find the query keys definition
rg -l "uiDefinitionQueryKeys" --type ts --type tsx

# Then, let's see the implementation of these query keys
ast-grep --pattern 'export const uiDefinitionQueryKeys = $_'

# Also, let's check how these query keys are used in queries
rg "uiDefinitionQueryKeys\.translate" --type ts --type tsx -A 3

Length of output: 17883


Script:

#!/bin/bash
# Search for files using uiDefinitionQueryKeys.translate
rg "uiDefinitionQueryKeys\.translate" -t typescript -t javascriptreact -t typescriptreact -A 3

# Look for the usage of the translate query in the hook file
cat "apps/backoffice-v2/src/domains/ui-definition/hooks/queries/useTranslateUiDefinitionQuery/useTranslateUiDefinitionQuery.tsx"

Length of output: 682

apps/backoffice-v2/src/domains/ui-definition/query-keys.ts (1)

1-3: Good use of concise imports.

All required dependencies are efficiently imported. No immediate issues are found.

apps/backoffice-v2/.storybook/main.ts (1)

21-28: Confirm if additional dependencies should be included in optimizeDeps.

The addition of '@ballerine/ui' under optimizeDeps.include is beneficial for performance. Ensure no other frequently used packages require similar inclusion for a faster dev experience.

✅ Verification successful

Let me gather information about the dependencies used in the project to verify if other packages should be included in optimizeDeps.

This will help us:

  1. See all dependencies listed in package.json
  2. Analyze import patterns to identify frequently imported external packages that might benefit from being included in optimizeDeps

Based on the analysis of the dependencies and import patterns, I can provide a final response regarding the optimizeDeps configuration.

No additional dependencies need to be included in optimizeDeps.

The current inclusion of '@ballerine/ui' in optimizeDeps is appropriate as it's one of the most frequently imported packages across the codebase. Other frequently imported packages like '@tanstack/react-query', '@radix-ui/', and '@tiptap/' are already handled efficiently by Vite's default dependency pre-bundling and don't require explicit inclusion.

The reasons are:

  • Most imports are internal (starting with '@/') which don't need pre-bundling
  • External dependencies are either:
    • UI primitives (@radix-ui/*) which are small and already optimized
    • Framework dependencies (@tanstack/react-query) which Vite handles automatically
    • Or have low import frequency across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Check package.json for dependencies
cat apps/backoffice-v2/package.json | jq '.dependencies'

# Look for import statements in the codebase to identify frequently used packages
rg "^import.*from.*@" apps/backoffice-v2/src -n --no-filename | sort | uniq -c | sort -nr

Length of output: 109886

apps/backoffice-v2/src/domains/ui-definition/fetchers.ts (1)

8-25: Ensure proper error handling after schema parsing.

handleZodError gracefully manages response validation. However, confirm that the application flow adequately handles any schema parsing errors that might occur, e.g. displaying error messages, etc.

✅ Verification successful

Let me search for error handling patterns and the implementation of handleZodError to verify how schema parsing errors are managed.


Let me search for the implementation of handleZodError to understand how it handles schema parsing errors.


Let me check how schema validation errors are handled in the React Query client configuration since that's where the application-wide error handling would be configured.


Based on the analysis of the codebase, I can now provide a final response:

Schema parsing errors are properly handled in the application

The error handling for schema validation is well-implemented through multiple layers:

  1. handleZodError gracefully returns the data when there's no error or when it's a Zod validation error, and throws other types of errors.
  2. The React Query client is configured to handle these errors globally:
    • Zod validation errors are silently handled (preventing unnecessary error toasts)
    • Other errors are properly displayed to users via toast notifications
    • Authentication errors (401) trigger user state cleanup
    • Non-critical status codes (401, 403, 404) are handled without disrupting the user experience
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for handleZodError implementation
ast-grep --pattern 'handleZodError($$$)'

# Also search for any direct references to this function
rg "handleZodError" -A 3

# Look for error handling patterns around this function
rg "handleZodError.*error.*" -A 5

Length of output: 53702


Script:

#!/bin/bash
# Look for handleZodError implementation
ast-grep --pattern 'export const handleZodError'

# Search for isZodError implementation
rg "isZodError" -A 3

Length of output: 3112


Script:

#!/bin/bash
# Look for React Query error handling
cat apps/backoffice-v2/src/lib/react-query/query-client.ts

Length of output: 1761

apps/backoffice-v2/src/domains/workflows/hooks/mutations/useDeleteUbosByIdsMutation/useDeleteUbosByIdsMutation.tsx (1)

22-23: Validate or handle cases where the schema might not be undefined.

You are treating the response schema as z.undefined(), which is correct for a typical DELETE endpoint returning no content. However, consider confirming that the API indeed returns no body for this endpoint. If the server changes to return a confirmation object or other data, it will require updating this schema.

✅ Verification successful

Let me verify the API response schema for this DELETE endpoint by examining the codebase.


Let me try different search patterns to find relevant information about the UBO deletion endpoint.


Let me search for the DELETE endpoint implementation and its response schema.


Based on the code analysis, I can now provide a definitive response:

The schema validation is correctly implemented for this DELETE endpoint.

Looking at the backend implementation in case-management.controller.ts, the DELETE endpoint /workflows/:workflowId/ubos is designed to not return any content. This is consistent with the frontend's use of z.undefined() schema validation in the useDeleteUbosByIdsMutation hook.

This follows the REST API best practice where DELETE operations typically return no content (HTTP 204). The schema validation is properly aligned with the backend implementation, and there's no need for additional validation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for API endpoint definition or route handler for UBO deletion
rg -A 5 "delete.*ubo" --type ts

Length of output: 33


Script:

#!/bin/bash
# Look for any test files related to UBO deletion to understand the expected response
fd "test|spec" | rg -i "ubo.*delete|delete.*ubo"

Length of output: 50


Script:

#!/bin/bash
# Search for similar DELETE endpoints in the codebase to understand the pattern
ast-grep --pattern 'schema: z.undefined()'

Length of output: 44


Script:

#!/bin/bash
# Look for the API client configuration or swagger definitions
fd "api|swagger|openapi" --type json --type yaml

Length of output: 222


Script:

#!/bin/bash
# Search for the file containing the mutation hook and its context
rg -l "useDeleteUbosByIdsMutation"

Length of output: 231


Script:

#!/bin/bash
# Search for any UBO-related API calls or configurations
rg -A 5 "ubo" --type ts

Length of output: 73935


Script:

#!/bin/bash
# Look for API client or service definitions
fd -e ts | rg -i "api|client|service"

Length of output: 52116


Script:

#!/bin/bash
# Search for similar mutation hooks that might follow the same pattern
rg -A 3 "useMutation.*schema:" --type ts

Length of output: 42


Script:

#!/bin/bash
# Look for the DELETE endpoint implementation for UBOs
rg -A 10 "Delete.*ubo|delete.*ubo" --type ts

Length of output: 1360


Script:

#!/bin/bash
# Search for the file containing the mutation hook to understand its context
cat "apps/backoffice-v2/src/domains/workflows/hooks/mutations/useDeleteUbosByIdsMutation/useDeleteUbosByIdsMutation.tsx"

Length of output: 1172


Script:

#!/bin/bash
# Look for similar DELETE endpoints in the codebase
rg -A 5 "schema: z.undefined\(\)" --type ts

Length of output: 2505

packages/ui/src/components/atoms/Button/Button.tsx (1)

7-7: Great accessibility improvement with aria-disabled usage.

Adding 'aria-disabled:pointer-events-none aria-disabled:opacity-50' ensures visual and functional feedback for disabled buttons, enhancing accessibility significantly. Well done!

services/workflows-service/src/end-user/end-user.service.ts (2)

97-97: Consider error handling for schema parsing.
When parsing props with Zod (activeMonitorings, amlHits), if the parse fails, an exception is thrown. Make sure these exceptions are caught or handled appropriately to avoid unhandled promise rejections or server errors.


111-113: Ensure data merging remains intentional.
Spreading args.data before merging activeMonitorings and amlHits can overwrite these fields if they already exist. Double-check that your intended overrides are correct.

✅ Verification successful

Let me gather more context about how the data merging is happening by examining the code around these lines.


Looking at the context, I can now generate a final response as I have enough information to verify the concern.

The data merging is actually implemented correctly and safely
The code shows that activeMonitorings and amlHits are explicitly parsed and validated before being merged, and they are added after spreading args.data, which means they will override any existing values. This is the intended behavior as these fields go through schema validation via EndUserActiveMonitoringsSchema and EndUserAmlHitsSchema before being merged.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Let's see the complete context of this data merging operation
rg -B 10 -A 10 "args\.data" services/workflows-service/src/end-user/end-user.service.ts

Length of output: 734


Script:

#!/bin/bash
# Let's also check if there are any other similar data merging patterns in the file
ast-grep --pattern 'data: {
  ...args.data,
  $$$
}'

Length of output: 54


Script:

#!/bin/bash
# Let's see what fields are typically included in the data object
ast-grep --pattern 'data: {
  $$$
}'

Length of output: 38

apps/backoffice-v2/src/lib/blocks/hooks/useManageUbosBlock/ubos-form-json-definition.ts (2)

1-4: New form JSON definition correctly exported.
The top-level export structure is clear, and the file name is descriptive.


5-29: Form metadata and configuration are well-structured.
Defining separate keys for “description”, “title”, and “uiSchema” is a good practice to keep the schema and UI concerns separate.

packages/common/src/schemas/documents/merchant-screening-plugin-schema.ts (1)

77-83: Driver’s license number changed to optional.
Making this field optional increases flexibility, especially if business logic does not always require it. Ensure that any related downstream logic (e.g., validations or mandatory checks) are updated accordingly.

Would you like a script to scan references across the codebase ensuring no required usage of this field remains?

✅ Verification successful

Let's search for any references to this field across the codebase to verify if there are any required usages.


Let's check the specific usage of this field in the identified files to ensure there are no required validations or dependencies.


Based on the search results, I can now generate the final response. The code analysis shows that:

  1. The driver's license field is only defined in the schema file and is not referenced anywhere else in the codebase
  2. The merchant screening implementation in both the UI component and the plugin doesn't have any specific validation or requirement for the driver's license field
  3. No other files in the codebase show dependencies on this field being required

Driver's license field change is safe.
The change to make the driver's license field optional appears to be safe as there are no dependencies or validation logic in the codebase that require this field to be mandatory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for references to the driver's license number field
rg -i "drivers?.license.?number" -A 3 -B 3

Length of output: 776


Script:

#!/bin/bash
# Search for references to the 'Number' field within merchant screening contexts
ast-grep --pattern 'Number: $_'

Length of output: 2756


Script:

#!/bin/bash
# Look for validation logic related to merchant screening
rg -i "merchantscreening.*validation" -A 3 -B 3

Length of output: 49


Script:

#!/bin/bash
# Find all files related to merchant screening
fd -t f merchant.*screening

Length of output: 296


Script:

#!/bin/bash
# Check content of the merchant screening related files
cat apps/backoffice-v2/src/lib/blocks/hooks/useMerchantScreeningBlock/useMerchantScreeningBlock.tsx packages/workflow-core/src/lib/plugins/external-plugin/mastercard-merchant-screening-plugin.ts

Length of output: 42416


Script:

#!/bin/bash
# Search for any validation or requirement checks related to driver's license
rg -i "required.*drivers?.license|drivers?.license.*required" -A 3 -B 3

Length of output: 73


Script:

#!/bin/bash
# Look for any schema validations or type checks
ast-grep --pattern 'Type.String({ $$ })'

Length of output: 42

apps/backoffice-v2/src/lib/blocks/variants/DefaultBlocks/hooks/useDefaultBlocksLogic/useDefaultBlocksLogic.tsx (7)

39-39: Use of useMemo is appropriate.
This prevents unnecessary recomputations and preserves performance when dealing with potentially large child workflow data.


52-52: Importing TWorkflowById clarifies typed usage of workflow objects.
This strengthens correctness and maintainability of child workflow data handling.


304-323: childWorkflowToUboAdapter mapping logic looks concise.
• Nicely transforms childWorkflow data into the shape expected by useUbosUserProvidedBlock.
• The fallback chain for ownership percentages (lines 315–319) is a good approach to handle different property names.


324-330: Derived ubosUserProvided array.
• Filtering child workflows by “ubo” variant is well thought out.
• The chain map to childWorkflowToUboAdapter is cohesive and ensures consistent data structure.


342-343: Newly introduced manageUbosBlock reference.
• Integrates well with the existing blocks array.
• Encourages a distinct block for UBO management.


506-506: Added manageUbosBlock to allBlocks array.
• Centralizes the UBO management block alongside other UI blocks.


538-538: Redundant listing of manageUbosBlock in the dependency array.
• The mention of manageUbosBlock in both line 506 and 538 is correct (one is usage, the other is a dependency).
• No action needed, just confirming correctness.

services/workflows-service/prisma/schema.prisma (1)

291-291: Added index on deletedAt.
Enhances queries filtering by the soft-delete timestamp.

services/workflows-service/src/workflow/workflow.service.ts (1)

258-261: Consider clarifying the default filter for deleted workflows.

Here, if no "deletedAt" is specified in the query, the filter is forced to "deletedAt: null," effectively excluding already-deleted workflows. If the intended behavior is to retrieve all child workflows regardless of deletion status, this logic might need refinement (like using conditional checks for “deletedAt is null” vs “deletedAt is not null”).

✅ Verification successful

Let me gather more information about how deletedAt is used in the codebase to verify the filtering behavior.


Let me search for more context about the workflow queries and deletion behavior.


Let me check the repository implementation to understand how deletedAt is handled at the database level.


Based on the gathered information, I can now provide a final response regarding the deletedAt filter behavior.

The default deletedAt filter is correctly implemented for soft-delete functionality.

The implementation follows standard soft-delete patterns where:

  1. deletedAt: null filters for active (non-deleted) workflows, which is the desired default behavior
  2. The schema shows deletedAt DateTime? as an optional field, indicating proper soft-delete support
  3. The repository implementation allows overriding this filter through args?.where?.deletedAt, enabling queries for both deleted and non-deleted workflows when needed

The current implementation correctly:

  • Defaults to showing only active workflows (deletedAt: null)
  • Allows explicit filtering of deleted workflows when needed through the query args
  • Maintains proper soft-delete functionality at the database level
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for deletedAt usage in workflow-related files
rg "deletedAt" -A 3 -B 3 services/workflows-service/src/workflow/

# Look for workflow query implementations
ast-grep --pattern 'where: {
  $$$
  deletedAt: $_
  $$$
}'

Length of output: 796


Script:

#!/bin/bash
# Look for the workflow model/schema definition
fd workflow.model.ts -x cat {}

# Search for other query implementations in the workflow service
rg "findById|findMany|findFirst" -A 5 -B 5 services/workflows-service/src/workflow/workflow.service.ts

# Look for soft delete implementations
rg "softDelete|deleteWorkflow" -A 5 -B 5 services/workflows-service/src/workflow/

Length of output: 11238


Script:

#!/bin/bash
# Look for the workflow repository implementation
fd "workflow.*repository.ts" -x cat {}

# Search for soft delete related prisma schema
fd "schema.prisma" -x rg "deletedAt|@@softDelete" -A 3 -B 3 {}

Length of output: 23527

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

♻️ Duplicate comments (1)
services/workflows-service/src/case-management/controllers/case-management.controller.ts (1)

239-242: ⚠️ Potential issue

Potential XSS vulnerability in returned elements

The method returns unescaped UI elements that could contain malicious content. Consider sanitizing the elements before returning them.

🧹 Nitpick comments (8)
apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (2)

338-355: Consider enhancing event handling robustness

The current implementation has a few areas that could be improved:

  1. The getEvent function only handles the 'start' event, making it less flexible for future event types.
  2. There's no error handling for failed mutations.

Consider this enhanced implementation:

- const getEvent = () => {
-   if (childWorkflow?.nextEvents?.includes('start')) {
-     return 'start';
-   }
- };
+ const getEvent = () => {
+   const validEvents = childWorkflow?.nextEvents ?? [];
+   if (!validEvents.length) return null;
+   
+   // Prioritize 'start' event if available
+   if (validEvents.includes('start')) return 'start';
+   
+   // Return first available event as fallback
+   return validEvents[0];
+ };

  const event = getEvent();
  const onInitiateKyc = useCallback(() => {
    if (!event) {
      return;
    }

-   mutateInitiateKyc({
-     workflowId: childWorkflow?.id,
-     event,
-   });
+   mutateInitiateKyc(
+     {
+       workflowId: childWorkflow?.id,
+       event,
+     },
+     {
+       onError: (error) => {
+         console.error('Failed to initiate KYC:', error);
+         // Add error handling/notification here
+       },
+     }
+   );
  }, [mutateInitiateKyc, event, childWorkflow?.id]);

543-606: Consider extracting repeated conditional rendering logic

The document data and verification results sections have similar conditional rendering patterns that could be abstracted to reduce code duplication.

Consider creating a reusable function:

const createConditionalBlock = ({
  data,
  title,
  renderData,
  placeholderMessage = 'Initiate KYC for data to appear',
}) => {
  return data.length
    ? createBlocksTyped()
        .addBlock()
        .addCell({
          type: 'heading',
          value: title,
        })
        .build()
        .concat(renderData())
        .flat(1)
    : createBlocksTyped()
        .addBlock()
        .addCell({
          type: 'heading',
          value: title,
        })
        .addCell({
          type: 'paragraph',
          value: placeholderMessage,
          props: {
            className: 'py-4 text-slate-500',
          },
        })
        .buildFlat();
};

Then use it like:

value: createConditionalBlock({
  data: documentExtractedData,
  title: 'Document Extracted Data',
  renderData: () => documentExtractedData,
})
services/workflows-service/src/case-management/types.ts (1)

1-18: Consider providing a more specific parameter type.
Currently, the function parameter is defined as "Record<string, any>". This can lead to less type safety when adapting UBOs to entities, making it easier to unintentionally introduce runtime errors. You could enhance maintainability and catch potential issues earlier by defining a more specific interface for UBO input if feasible.

services/workflows-service/src/ui-definition/ui-definition.service.ts (1)

111-136: Prefer returning a new object for immutability.
Currently, the function mutates “uiSchema” in-place, potentially leading to unintended side effects. If preserving the original data is valuable elsewhere, consider returning a copied structure to avoid hidden mutations.

services/workflows-service/src/case-management/case-management.service.ts (2)

82-98: Recommend extracting “uboToEntityAdapter” into a dedicated utility.
The inline adapter function references values from “workflowRuntimeData”, which can make unit testing more difficult. Extracting it into a separate function or file enables easier testing and reusability.


135-139: Ensure businessId is properly set before creating UBOs.
This block throws an exception if “businessId” is absent, but consider additional validation or logging earlier in the workflow to help track how this state could arise.

services/workflows-service/src/collection-flow/collection-flow.service.ts (2)

12-12: Remove unused import if applicable.
“TranslationService” might still be needed, but if your workflow eventually delegates translation entirely to “UiDefinitionService”, consider removing direct imports here.


77-77: Address TypeScript error suppressions.
The “@ts-expect-error” comments hint at type mismatches from Prisma models. Consider refining these model definitions or performing a type-safe cast to avoid frequent suppression.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c85be91 and 1eb6352.

📒 Files selected for processing (7)
  • apps/backoffice-v2/src/domains/workflows/hooks/mutations/useCreateUboMutation/useCreateUboMutation.tsx (1 hunks)
  • apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (5 hunks)
  • services/workflows-service/src/case-management/case-management.service.ts (2 hunks)
  • services/workflows-service/src/case-management/controllers/case-management.controller.ts (3 hunks)
  • services/workflows-service/src/case-management/types.ts (1 hunks)
  • services/workflows-service/src/collection-flow/collection-flow.service.ts (3 hunks)
  • services/workflows-service/src/ui-definition/ui-definition.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backoffice-v2/src/domains/workflows/hooks/mutations/useCreateUboMutation/useCreateUboMutation.tsx
🔇 Additional comments (6)
apps/backoffice-v2/src/lib/blocks/components/KycBlock/hooks/useKycBlock/useKycBlock.tsx (1)

306-307: LGTM: UI improvements enhance consistency and accessibility

The changes improve the UI in several ways:

  • Migrating to variant-based styling aligns with design system best practices
  • Header spacing and alignment are properly configured
  • The "Initiate KYC" button implementation includes proper accessibility attributes and disabled state handling

Also applies to: 363-363, 372-387

services/workflows-service/src/ui-definition/ui-definition.service.ts (1)

111-136: 🛠️ Refactor suggestion

Handle potential deep or recursive structures.
The recursive “traverseUiSchema” function can be susceptible to stack overflows or performance bottlenecks if there are exceptionally deep or cyclic references. Consider adding a recursion depth limit or cycle detection logic to ensure that malformed or unexpected schemas do not cause issues.

+  traverseUiSchema(
+    uiSchema: Record<string, unknown>,
+    context: WorkflowRuntimeData['context'],
+    language: string,
+    _translationService: TranslationService,
+    depth = 0,
+    maxDepth = 100,
+  ) {
+    if (depth > maxDepth) {
+      throw new Error('Max recursion depth exceeded in traverseUiSchema');
+    }
     for (const key in uiSchema) {
       ...

Likely invalid or redundant comment.

services/workflows-service/src/case-management/case-management.service.ts (1)

151-233: Double-check child workflows filtering logic.
When removing child workflows associated with the specified UBO IDs, the code filters workflow runtime IDs and workflow definition IDs in parallel. Confirm that the cross-references between runtime data, definition IDs, and the parent workflow context align consistently. Potential mismatch could lead to unintended data removal.

✅ Verification successful

Let me gather information about the child workflows filtering logic by examining the codebase.


Let me gather more specific information about the workflow context structure and child workflows handling.


Based on the gathered information, I can now provide a final response about the child workflows filtering logic:

The child workflows filtering logic is correctly implemented and safe. The code follows a well-structured approach where:

  1. It first collects both runtime data IDs and workflow definition IDs to be deleted in parallel arrays, maintaining their relationship.
  2. The filtering logic in the reduce operation properly handles both levels of the childWorkflows structure:
    • First level: Preserves unrelated workflow definitions by checking against workflowDefinitionIdsToDelete
    • Second level: Removes specific workflow instances by checking against workflowRuntimeDataToDelete
  3. The context update is atomic within a transaction, ensuring consistency between the workflow runtime data and its context.

The implementation aligns with the workflow context structure seen across the codebase, where childWorkflows is a well-defined concept used consistently in workflow definitions, runtime data, and related services.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for related workflow service methods and interfaces
ast-grep --pattern 'interface $_ {
  $$$
  getWorkflowRuntimeDataByIdAndLockUnscoped$$$
  $$$
}'

# Search for the workflow service implementation
ast-grep --pattern 'class WorkflowService {
  $$$
  getWorkflowRuntimeDataByIdAndLockUnscoped$$$
  $$$
}'

# Look for BUILT_IN_EVENT definitions
rg "BUILT_IN_EVENT.*UPDATE_CONTEXT" -A 2 -B 2

# Search for related tests that verify this logic
rg "deleteUbosByIds" --type=ts

Length of output: 2056


Script:

#!/bin/bash
# Search for child workflows related code patterns
ast-grep --pattern 'context: {
  $$$
  childWorkflows
  $$$
}'

# Look for tests related to child workflows
rg "childWorkflows" --type=ts -A 5 -B 5

# Search for workflow runtime data schema/type definitions
ast-grep --pattern 'interface WorkflowRuntimeData {
  $$$
}'

# Look for other methods that manipulate child workflows
rg "childWorkflows.*=" --type=ts

Length of output: 68023

services/workflows-service/src/collection-flow/collection-flow.service.ts (1)

66-66: Good use of the new translation resources method.
Extracting translation logic into “UiDefinitionService” promotes consistent usage and avoids duplication across services.

services/workflows-service/src/case-management/controllers/case-management.controller.ts (2)

21-21: LGTM: Import statements and constructor changes are well-structured

The new imports and constructor dependency injection are properly implemented and align with the codebase's patterns.

Also applies to: 25-25, 30-32, 45-45


245-256: 🛠️ Refactor suggestion

Improve type safety and add response handling

Several improvements needed:

  1. Define a proper DTO for UBO creation instead of using Record<string, unknown>
  2. Return the created UBO or success status
  3. Add validation for required UBO fields
 @common.Post('/workflows/:workflowId/ubos')
+@common.HttpCode(201)
 async createUbo(
   @common.Param('workflowId') workflowId: string,
-  @common.Body() body: Record<string, unknown>,
+  @common.Body() body: CreateUboDto,
   @CurrentProject() projectId: TProjectId,
 ) {
-  await this.caseManagementService.createUbo({
+  const ubo = await this.caseManagementService.createUbo({
     workflowId,
     ubo: body,
     projectId,
   });
+  return ubo;
 }

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

🔭 Outside diff range comments (1)
apps/backoffice-v2/package.json (1)

Line range hint 196-199: Update peer dependencies to match React 18

There's a mismatch between the peer dependencies and the actual React version being used in the project. The peer dependencies specify React 17, but the project is using React 18.

Apply this diff to update the peer dependencies:

  "peerDependencies": {
-   "react": "^17.0.0",
-   "react-dom": "^17.0.0"
+   "react": "^18.0.0",
+   "react-dom": "^18.0.0"
  }
🧹 Nitpick comments (1)
packages/ui/CHANGELOG.md (1)

3-9: LGTM! Consider enhancing the changelog format.

The changelog entry correctly documents both the button component update and dependency changes. The patch version bump is appropriate for these non-breaking changes.

Consider adding more details about the button's disabled state implementation, such as:

  • What visual changes were made
  • Any new props or APIs introduced
  • Any breaking changes to existing button usage

Example format:

 ## 0.5.54

 ### Patch Changes

-Updated button with disabled state
+- Added disabled state to Button component
+  - New `disabled` prop to control button state
+  - Visual feedback when button is disabled
+  - Maintains existing button API
 - Updated dependencies
   - @ballerine/[email protected]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fbc7b97 and d97b759.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (23)
  • apps/backoffice-v2/CHANGELOG.md (1 hunks)
  • apps/backoffice-v2/package.json (2 hunks)
  • apps/kyb-app/CHANGELOG.md (1 hunks)
  • apps/kyb-app/package.json (2 hunks)
  • examples/headless-example/CHANGELOG.md (1 hunks)
  • examples/headless-example/package.json (2 hunks)
  • packages/common/CHANGELOG.md (1 hunks)
  • packages/common/package.json (1 hunks)
  • packages/react-pdf-toolkit/CHANGELOG.md (1 hunks)
  • packages/react-pdf-toolkit/package.json (2 hunks)
  • packages/ui/CHANGELOG.md (1 hunks)
  • packages/ui/package.json (2 hunks)
  • packages/workflow-core/CHANGELOG.md (1 hunks)
  • packages/workflow-core/package.json (2 hunks)
  • sdks/web-ui-sdk/CHANGELOG.md (1 hunks)
  • sdks/web-ui-sdk/package.json (2 hunks)
  • sdks/workflow-browser-sdk/CHANGELOG.md (1 hunks)
  • sdks/workflow-browser-sdk/package.json (2 hunks)
  • sdks/workflow-node-sdk/CHANGELOG.md (1 hunks)
  • sdks/workflow-node-sdk/package.json (2 hunks)
  • services/workflows-service/CHANGELOG.md (1 hunks)
  • services/workflows-service/package.json (2 hunks)
  • websites/docs/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (12)
  • packages/react-pdf-toolkit/CHANGELOG.md
  • packages/common/CHANGELOG.md
  • packages/common/package.json
  • sdks/web-ui-sdk/package.json
  • sdks/web-ui-sdk/CHANGELOG.md
  • examples/headless-example/CHANGELOG.md
  • sdks/workflow-browser-sdk/CHANGELOG.md
  • apps/kyb-app/CHANGELOG.md
  • services/workflows-service/CHANGELOG.md
  • apps/backoffice-v2/CHANGELOG.md
  • packages/workflow-core/CHANGELOG.md
  • sdks/workflow-node-sdk/CHANGELOG.md
🔇 Additional comments (10)
websites/docs/package.json (1)

20-20: LGTM! Verify version consistency across the monorepo.

The dependency update for @ballerine/common aligns with the coordinated version updates across the repository.

Let's verify version consistency across the monorepo:

examples/headless-example/package.json (1)

4-4: LGTM! Version updates are consistent.

The version bumps for both the package and its dependencies follow semantic versioning and align with the coordinated updates across the repository.

Let's verify the workflow-browser-sdk version consistency:

Also applies to: 37-38

✅ Verification successful

Version consistency verified across the monorepo

The version of @ballerine/workflow-browser-sdk (0.6.79) is consistent across all dependent packages in the monorepo:

  • apps/kyb-app/package.json
  • apps/backoffice-v2/package.json
  • examples/headless-example/package.json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for version consistency of workflow-browser-sdk across the monorepo
# Find all package.json files and grep for workflow-browser-sdk to ensure version consistency
fd package.json -x grep -H "workflow-browser-sdk"

Length of output: 1414

packages/react-pdf-toolkit/package.json (1)

4-4: LGTM! Version updates are consistent.

The version bumps for both the package and its UI dependency follow semantic versioning and align with the coordinated updates.

Let's verify the UI package version consistency:

Also applies to: 30-30

sdks/workflow-node-sdk/package.json (1)

4-4: Version updates look good!

The version bump to 0.6.79 and the corresponding dependency update for @ballerine/workflow-core are consistent with the coordinated version updates across related packages.

Also applies to: 31-31

sdks/workflow-browser-sdk/package.json (1)

4-4: Version updates look good!

The version bump to 0.6.79 and the corresponding dependency updates for both @ballerine/common (to 0.9.60) and @ballerine/workflow-core (to 0.6.79) are consistent with the coordinated version updates across related packages.

Also applies to: 36-37

packages/workflow-core/package.json (1)

4-4: Version updates look good!

The version bump to 0.6.79 and the corresponding dependency update for @ballerine/common to 0.9.60 are consistent with the coordinated version updates across related packages.

Also applies to: 34-34

apps/kyb-app/package.json (1)

4-4: LGTM! Version updates are consistent.

The version updates align with the PR's UBO management changes. All updates are minor/patch versions, suggesting backward compatibility.

Let's verify version consistency across the monorepo:

Also applies to: 19-21

✅ Verification successful

Version consistency verified across the monorepo

The version updates are consistent across the monorepo:

All dependent packages are using the same versions as specified in the kyb-app's package.json, confirming proper version alignment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify version consistency across the monorepo
echo "Checking @ballerine/common version usage:"
rg '"@ballerine/common": "\^?0\.9\.60"' -l

echo "Checking @ballerine/ui version usage:"
rg '"@ballerine/ui": "\^?0\.5\.54"' -l

echo "Checking @ballerine/workflow-browser-sdk version usage:"
rg '"@ballerine/workflow-browser-sdk": "\^?0\.6\.79"' -l

Length of output: 931

services/workflows-service/package.json (1)

4-4: LGTM! Version updates are consistent across workflow packages.

The version updates in the workflows service align with the changes in other packages and support the UBO management features.

Let's verify version consistency across workflow packages:

Also applies to: 52-54

✅ Verification successful

Version consistency verified across workflow packages

The version updates are consistent across the codebase:

  • @ballerine/[email protected] is correctly used in:
    • sdks/workflow-node-sdk/package.json
    • sdks/workflow-browser-sdk/package.json
    • services/workflows-service/package.json
  • @ballerine/[email protected] is correctly used in:
    • services/workflows-service/package.json
    • apps/backoffice-v2/package.json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify workflow package versions
echo "Checking @ballerine/workflow-core version usage:"
rg '"@ballerine/workflow-core": "\^?0\.6\.79"' -l

echo "Checking @ballerine/workflow-node-sdk version usage:"
rg '"@ballerine/workflow-node-sdk": "\^?0\.6\.79"' -l

Length of output: 516

apps/backoffice-v2/package.json (2)

3-3: Version bump aligns with dependency updates

The package version bump from 0.7.83 to 0.7.84 is appropriate given the patch-level updates to dependencies.


3-3: Verify version compatibility across @ballerine packages

The package version updates look consistent with semantic versioning (patch updates). However, let's verify the compatibility between these versions and check for any breaking changes.

Also applies to: 55-59

packages/ui/package.json Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
services/workflows-service/src/case-management/case-management.service.ts (2)

121-121: ⚠️ Potential issue

Avoid hard-coding the workflow definition ID

The workflow definition ID 'kyc_email_session_example' should not be hard-coded as different customers may use different definitions.

The definition ID should be:

  1. Set in the workflow definition's config
  2. Validated early with appropriate error handling if not set

134-138: 🛠️ Refactor suggestion

Move business ID validation before workflow creation

The business ID validation should occur before creating the workflow to prevent unnecessary database operations.

Move this check to before line 119 to fail fast and avoid creating resources that would need to be rolled back.

🧹 Nitpick comments (3)
services/workflows-service/src/ui-definition/ui-definition.service.unit.test.ts (2)

16-32: Consider verifying repository interactions or removing them if unnecessary.
Currently, UiDefinitionRepository and WorkflowRuntimeDataRepository are provided as no-ops. If the UiDefinitionService relies on them in other scenarios, consider adding tests involving real or properly mocked interactions. Otherwise, removing them from this test (or replacing them with stubs via a more explicit mocking strategy) can clarify that they are not required for this particular unit test.


50-77: Add tests for edge cases and verify translate call details.
This test successfully verifies basic translation. However, you can further strengthen coverage by including:

  1. Edge Cases: Validate nested arrays or complex/nested objects.
  2. Handling Missing Translations: Test behavior when a translation is missing or returns undefined.
  3. Verify Calls/Arguments: Ensure translate is called with expected arguments (e.g., for each leaf node).
services/workflows-service/src/case-management/case-management.service.ts (1)

183-203: Extract child workflows update logic to a separate method

The logic for updating child workflows is complex and would benefit from being extracted into a separate method for better readability and maintainability.

Consider extracting this logic into a private method like updateChildWorkflows:

private updateChildWorkflows(
  workflowRuntimeData: WorkflowRuntimeData,
  workflowDefinitionIdsToDelete: string[],
  workflowRuntimeDataToDelete: string[],
): Record<string, Record<string, any>> {
  return Object.entries(
    workflowRuntimeData.context.childWorkflows ?? {},
  ).reduce((acc, [key, value]) => {
    if (!workflowDefinitionIdsToDelete.includes(key)) {
      acc[key] = value as Record<string, any>;
    }

    acc[key] = Object.entries(value as Record<string, any>).reduce(
      (acc, [key, value]) => {
        if (workflowRuntimeDataToDelete.includes(key)) {
          return acc;
        }

        acc[key] = value;
        return acc;
      },
      {} as Record<string, any>,
    );

    return acc;
  }, {} as Record<string, Record<string, any>>);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d97b759 and f759230.

📒 Files selected for processing (3)
  • services/workflows-service/src/case-management/case-management.service.ts (2 hunks)
  • services/workflows-service/src/collection-flow/collection-flow.service.unit.test.ts (0 hunks)
  • services/workflows-service/src/ui-definition/ui-definition.service.unit.test.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • services/workflows-service/src/collection-flow/collection-flow.service.unit.test.ts
🔇 Additional comments (1)
services/workflows-service/src/case-management/case-management.service.ts (1)

97-117: ⚠️ Potential issue

Add null checks for nested properties in UBO adapter

The adapter accesses deeply nested properties without validation which could lead to runtime errors.

Add null checks for:

  • workflowRuntimeData.context.entity.data.companyName
  • workflowRuntimeData.context.collectionFlow.additionalInformation.customerCompany
 const uboToEntityAdapter = (ubo => {
+  const companyName = workflowRuntimeData.context?.entity?.data?.companyName;
+  const customerCompany = workflowRuntimeData.context?.collectionFlow?.additionalInformation?.customerCompany;
+
+  if (!companyName) {
+    throw new BadRequestException('Company name is required');
+  }
+
   return {
     id: randomUUID(),
     type: 'individual',
     variant: 'ubo',
     data: {
       firstName: ubo.firstName,
       lastName: ubo.lastName,
       email: ubo.email,
       nationalId: ubo.nationalId,
       percentageOfOwnership: ubo.ownershipPercentage ?? ubo.percentageOfOwnership,
       additionalInfo: {
         fullAddress: ubo.fullAddress,
         nationality: ubo.nationality,
-        companyName: workflowRuntimeData.context.entity.data.companyName,
-        customerCompany: workflowRuntimeData.context.collectionFlow.additionalInformation.customerCompany,
+        companyName,
+        customerCompany,
       },
     },
   };
 }) satisfies UboToEntityAdapter;

Likely invalid or redundant comment.

@Omri-Levy Omri-Levy merged commit 01c1a6c into dev Dec 26, 2024
10 checks passed
@Omri-Levy Omri-Levy deleted the bal-3096 branch December 26, 2024 14:37
Omri-Levy added a commit that referenced this pull request Dec 29, 2024
* chore: update package versions and dependencies

- Bump package versions across various modules
- Update dependencies to the latest stable versions

(With this many updates, your dependencies have more frequent flyer miles than I do)

* feat(workflow-definition): add configuration examples for vendors

- Include detailed configuration examples for various vendors
- Improve clarity on vendor integration and usage

(These examples are so detailed, they could serve as a user manual for a rocket)

* bal 3191 (#2905)

* refactor(merchant-monitoring): improve search and date filtering logic

- Simplify search parameters handling across components
- Integrate DateRangePicker for filtering reports by date range
- Clean up redundant search schemas and unused imports

(your code is now so tidy, it could host a top-tier cleaning service)

* BAL 3197 - add merchant monitoring filters to UI (#2901)

* feat(business-reports): add UI for filtering by merchant type

- Update reportType to accept 'All' alongside existing options
- Modify query parameters to exclude type when 'All' is selected
- Integrate a dropdown for selecting report types in the Merchant Monitoring page

(Your dropdown is so user-friendly, it practically holds their hand through the process)

* feat(business-reports): add risk level filtering to business reports

- Integrate risk level filters in the business reports fetching logic
- Update the MerchantMonitoring component to support risk level selection
- Enhance search schema to include risk level as an optional filter

(You've just added complexity like it's a family reunion—everyone’s confused!)

* feat(MerchantMonitoring): add status filters to reports

- Refactor MultiSelect components to include status filters
- Update handling functions for new status parameter

(your code is now as organized as a folder full of junk drawers)

* feat(multi-select): enhance multi-select component with optional props

- Add support for left and right icons in multi-select trigger
- Refactor button styling in multi-select to accommodate new props
- Modify multi-select usage in MerchantMonitoring to utilize new features

(Your multi-select options are so numerous, I'm surprised it's not a buffet)

---------

Co-authored-by: Tomer Shvadron <[email protected]>

* refactor(business-reports): update report types and related logic

- Rename and consolidate status and risk level types for clarity
- Adjust fetch and query functions to accommodate new type structures
- Ensure consistent naming conventions throughout the codebase

(your code changes remind me of a jigsaw puzzle with missing pieces)

* feat(risk): add risk level parameter to business report requests

- Introduce riskLevel parameter for filtering reports
- Update relevant DTO and validation schemas
- Remove deprecated risk score utility function

(Your risk assessment is so vague, it could be a fortune cookie message)

* feat(MerchantMonitoring): add clear filters functionality

- Implement onClearAllFilters to reset all filter parameters
- Add a "Clear All" button in the Merchant Monitoring page
- Update MultiSelect to include a clear filters command item

(Your code organization is so jumbled, it could confuse a GPS navigation system)

* feat(date-picker): add placeholder support to DateRangePicker component

- Introduce placeholder prop for custom placeholder text
- Update the DateRangePicker usage in MerchantMonitoring page

(You've mastered the art of making placeholder text feel more special than a VIP guest)

* refactor(MerchantMonitoring): simplify filter management structure

- Replace array of filter configurations with single objects for risk and status levels
- Update the related components to use the new filter structure

(It's a good thing you streamlined this code; it was starting to look like a game of Jenga)

* refactor(business-reports): rename report status types for clarity

- Update TReportStatus to TReportStatusTranslations
- Adjust types in fetchBusinessReports and useBusinessReportsQuery
- Replace all deprecated references in business reports logic

(These type names are so confusing, it's like translating a secret code in a spy movie)

* feat(reports): enhance multi-select functionality and findings integration

- Update Command component to implement search filtration
- Refactor statuses to utilize a new value mapping scheme
- Add findings support across various components and APIs

(Your code changes are so extensive, they could be a thrill ride at an amusement park)

* refactor(business-reports): update risk level and report type handling

- Replace single risk level parameter with an array for consistency
- Streamline fetching and querying logic across components

(Your variable names are so inconsistent, they could start a family feud)

* fix(business-reports): simplify query enabled condition

- Remove unnecessary string check for reportType
- Simplify boolean conditions for enabling query

(your code had more checks than a paranoid mother-in-law)

---------

Co-authored-by: Shane <[email protected]>

* Make social links clickable + Hide “ads” section BAL-3220 (#2907)

* chore: hide ads sections; add href attribute to anchor-if-url component

* chore: release version

---------

Co-authored-by: Tomer Shvadron <[email protected]>

* chore(release): bump versions and update dependencies (#2908)

- Update version for backoffice-v2 to 0.7.83 and kyb-app to 0.3.96
- Add new CommandLoading component to the UI package
- Upgrade dependencies for multiple packages, including @ballerine/ui

(your code is so updated, it probably has more new features than Netflix!)

* Add/Remove UBOs (#2904)

* feat(*): added the ability to add and remove ubos

* refactor(*): pr review changes

* chore(*): updated packages

* fix(workflow-service): fixed path to definition

* chore(workflows-service): no longer importing from data-migrations

* removed unused import

* fixed failing test

* Add/Remove UBOs sign-off and pr comments (#2915)

* feat(*): added the ability to add and remove ubos

* refactor(*): pr review changes

* chore(*): updated packages

* fix(workflow-service): fixed path to definition

* chore(workflows-service): no longer importing from data-migrations

* removed unused import

* fixed failing test

* refactor(*): pR comments and sign-off changes

* chore(*): updated packages/ui

* fix(backoffice-v2): fixed bug caused by prettier

* fix(backoffice-vs): no longer closing ubos dialog after creating a ubo

* Update README.md (#2916)

---------

Co-authored-by: Alon Peretz <[email protected]>
Co-authored-by: Matan Yadaev <[email protected]>
Co-authored-by: Tomer Shvadron <[email protected]>
Co-authored-by: Shane <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants