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

Feature/implement risk rule ( WIP ) BAL-2445 #2528

Open
wants to merge 10 commits into
base: dev
Choose a base branch
from

Conversation

Blokh
Copy link
Contributor

@Blokh Blokh commented Jul 16, 2024

  • Create Rule Policy for definition
  • Create Ruleset for policies
  • Create Rule for each engine + Rule
  • modules
  • services
  • controllers
  • schemas
  • CRUD for Rule Policy
  • CRUD for rule set
  • CRUD for rules
  • integrate for rule engine

BAL-2445

Summary by CodeRabbit

  • New Features

    • Introduced new models and enums for managing risk assessment policies and rules in workflow definitions.
    • Implemented repositories for RiskRulePolicy and RiskRuleSet to manage database operations.
    • Added RiskRulePolicyModule, RiskRuleSetModule, and RuleSetModule for structuring risk rule services.
    • Introduced new API endpoints for creating, retrieving, updating, and deleting risk rules and policies.
    • Enhanced the rule engine to support processing of nested rules with hierarchical relationships.
  • Bug Fixes

    • Adjusted RiskRulePlugin to correctly assign databaseId based on rulesSource.
  • Chores

    • Performed a data migration to update the subproject commit hash.
  • Refactor

    • Updated database schemas to support new risk-related models and enums.
  • Documentation

    • Added detailed schema definitions for rule and rule set operations.

Copy link

changeset-bot bot commented Jul 16, 2024

⚠️ No Changeset found

Latest commit: 1d56a23

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

@Blokh Blokh self-assigned this Jul 16, 2024
Copy link
Contributor

coderabbitai bot commented Jul 16, 2024

Walkthrough

The updates significantly enhance the risk management capabilities of the workflow service by expanding the data model with new fields, enums, and models for risk and rule processing. New services, repositories, and controllers provide comprehensive management functionality, while validation schemas ensure structured handling of operations. This structured approach promotes a robust, organized framework for managing compliance and risk assessment within the application.

Changes

File(s) Change Summary
prisma/schema.prisma, prisma/migrations/.../migration.sql Introduced new fields, enums, and models for risk management, including RiskRulesPolicy, RiskRule, and RuleSet. Updated existing models and executed migrations.
src/risk-rules/risk-rule-policy/... Added RiskRulePolicyModule, RiskRulePolicyService, and RiskRulePolicyRepository for managing risk rule policies.
src/risk-rules/risk-rule/... Created RiskRuleModule, RiskRuleService, RiskRuleRepository, and RiskRuleController for managing risk rules.
src/risk-rules/rule-set/... Developed RuleSetModule, RuleSetService, and RuleSetRepository for handling rule sets.
src/rule-engine/core/rule-engine.ts Enhanced runRuleSet and RuleEngine to support RuleSetWithChildren for nested rule processing.
src/rule-engine/risk-rule.service.ts, src/rule-engine/rule-engine.module.ts Updated findAll method for project-specific filtering and integrated RiskRulePolicyModule for expanded functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RiskRulePolicyController
    participant RiskRulePolicyService
    participant RiskRulePolicyRepository
    participant Database

    Client->>+RiskRulePolicyController: Create Policy Request
    RiskRulePolicyController->>+RiskRulePolicyService: Call createRiskRulePolicy
    RiskRulePolicyService->>+RiskRulePolicyRepository: Persist new policy
    RiskRulePolicyRepository->>+Database: Insert policy record
    Database-->>-RiskRulePolicyRepository: Policy record ID
    RiskRulePolicyRepository-->>-RiskRulePolicyService: Policy record ID
    RiskRulePolicyService-->>-RiskRulePolicyController: Policy record ID
    RiskRulePolicyController-->>-Client: Response with Policy ID

    Client->>+RiskRulePolicyController: Add Risk Rule to Policy Request
    RiskRulePolicyController->>+RiskRulePolicyService: Call addRiskRuleToPolicy
    RiskRulePolicyService->>+RiskRulePolicyRepository: Associate risk rule
    RiskRulePolicyRepository->>+Database: Update policy with risk rule
    Database-->>-RiskRulePolicyRepository: Update confirmation
    RiskRulePolicyRepository-->>-RiskRulePolicyService: Association confirmation
    RiskRulePolicyService-->>-RiskRulePolicyController: Association confirmation
    RiskRulePolicyController-->>-Client: Response with association confirmation
Loading

Poem

In a garden of rules, new blooms arise,
With risks dancing 'neath the digital skies.
Policies sprout, and schemas align,
In this code-rich world, all things intertwine.
Rabbits hop through logic so bright,
Celebrating changes that feel just right!
🐰💻✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as PR comments)

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

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@Blokh Blokh requested a review from alonp99 July 16, 2024 17:10
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: 8

Outside diff range, codebase verification and nitpick comments (4)
services/workflows-service/src/helpers/type-box/type-string-enum.ts (1)

1-8: Utility function for dynamic string enums is well-implemented.

The TypeStringEnum function is a useful utility for creating dynamic string enums with TypeBox. It is flexible and correctly uses generics.

Consider documenting the use of Type.Unsafe.

The use of Type.Unsafe might not be immediately clear to all developers. Consider adding detailed comments explaining why it is used here and its implications.

services/workflows-service/src/risk-rules/schemas/create-rule-policy.schema.ts (1)

1-3: Check import paths and module usage.

The import paths use both relative and absolute notations. Ensure consistency in import styles across the project for better maintainability.

services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts (2)

18-22: Consider adding error handling for the findMany method.

Handling cases where no records are found could improve the robustness of the application, perhaps returning an empty array or a custom message.


52-60: Consider adding transactional integrity to the deleteById method.

Implementing transactional checks could prevent partial deletions and ensure data consistency, especially in complex operations involving multiple tables or steps.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 942b559 and f72c12b.

Files selected for processing (21)
  • packages/common/src/rule-engine/types.ts (1 hunks)
  • packages/workflow-core/src/lib/plugins/common-plugin/types.ts (1 hunks)
  • services/workflows-service/plugins/verify-repository-project-scoped/verify-repository-project-scoped.rule.js (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/prisma/migrations/20240716155934_create_rule_policy/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (5 hunks)
  • services/workflows-service/src/app.module.ts (2 hunks)
  • services/workflows-service/src/helpers/type-box/type-string-enum.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/schemas/create-risk-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/schemas/create-rule-policy.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/schemas/create-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/schemas/create-rule.schema.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • services/workflows-service/prisma/data-migrations
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts
Additional comments not posted (19)
services/workflows-service/src/risk-rules/schemas/create-rule-policy.schema.ts (1)

5-10: Review the schema definition for completeness and clarity.

The schema CreateRuleSetSchema is well-defined with descriptions provided for each field. However, ensure that the field names and descriptions accurately reflect their purpose and usage within the system.

services/workflows-service/src/risk-rules/rule/rule.module.ts (1)

1-10: Validate module configuration and dependencies.

The module configuration is correct and follows NestJS best practices. The use of AppLoggerModule and PrismaModule suggests a well-structured approach to logging and database management. However, ensure that these modules are configured correctly elsewhere in the project to avoid integration issues.

services/workflows-service/src/risk-rules/schemas/create-rule.schema.ts (1)

1-14: Assess schema definition for accuracy and extensibility.

CreateRuleSchema includes diverse fields with clear descriptions. The use of enums for operation and engine enhances the schema's robustness. Verify that the enum values from OPERATION and the engines listed are consistent with the system's requirements and documentation.

services/workflows-service/src/risk-rules/schemas/create-rule-set.schema.ts (1)

1-15: Evaluate schema definition for rule sets.

The CreateRuleSetSchema is structured to support complex rule sets with an operator and multiple rules. Ensure that the OPERATOR enum values are correctly implemented and that the integration of CreateRuleSchema within this schema does not introduce any inconsistencies.

services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.module.ts (1)

1-12: Module Configuration Looks Good!

The module is correctly structured with necessary imports and providers. It's important to ensure that this new module integrates well with the rest of the application.

Verification successful

Module Configuration Looks Good!

The RiskRuleSetModule is correctly integrated within the application as evidenced by its imports and usage in other modules.

  • RiskRuleSetModule is declared and exported.
  • It is imported in other modules and used in their imports array.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the RiskRuleSetModule is correctly integrated within the application.

# Test: Search for the module usage in the application. Expect: Correct imports and usage in other modules.
rg --type typescript -A 5 $'RiskRuleSetModule'

Length of output: 80


Script:

#!/bin/bash
# Description: Verify that the RiskRuleSetModule is correctly integrated within the application.

# Find all TypeScript files and search for the usage of RiskRuleSetModule within them.
fd -e ts -x rg 'RiskRuleSetModule' {}

Length of output: 329

packages/common/src/rule-engine/types.ts (1)

35-45: New Type Definitions for Rule Options

The new types TNotionRulesOptions and TDatabaseRulesOptions are well-defined and appropriately structured. Ensure these types are used correctly in the context of rule fetching and processing.

Verification successful

New Type Definitions for Rule Options

The new types TNotionRulesOptions and TDatabaseRulesOptions are well-defined and appropriately structured. They are correctly used through the TFindAllRulesOptions type in the context of rule fetching and processing.

  • packages/workflow-core/src/lib/plugins/common-plugin/types.ts
  • services/workflows-service/src/workflow/workflow.service.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new rule types in the application.

# Test: Search for the usage of `TNotionRulesOptions` and `TDatabaseRulesOptions`. Expect: Correct usage in rule fetching and processing.
rg --type typescript -A 5 $'TNotionRulesOptions|TDatabaseRulesOptions'

Length of output: 106


Script:

#!/bin/bash
# Description: Verify the usage of the new rule types in the application.

# Test: Search for the usage of `TNotionRulesOptions` and `TDatabaseRulesOptions`. Expect: Correct usage in rule fetching and processing.
rg -A 5 'TNotionRulesOptions|TDatabaseRulesOptions'

Length of output: 750


Script:

#!/bin/bash
# Description: Verify the usage of the new rule types in the application.

# Test: Search for the usage of `TNotionRulesOptions` and `TDatabaseRulesOptions` in the codebase.
rg 'TNotionRulesOptions|TDatabaseRulesOptions'

Length of output: 325


Script:

#!/bin/bash
# Description: Verify the usage of the new rule types in the application.

# Test: Search for the usage of `TFindAllRulesOptions` in the codebase.
rg 'TFindAllRulesOptions'

Length of output: 1059

services/workflows-service/plugins/verify-repository-project-scoped/verify-repository-project-scoped.rule.js (1)

13-13: Regex Pattern Adjustment in Repository Verification Rule

The adjustment to the regex pattern to exclude certain repository files is appropriate. Verify that this change does not unintentionally exclude other necessary checks.

services/workflows-service/src/risk-rules/schemas/create-risk-rule.schema.ts (1)

1-38: Comprehensive Schema Definition for Risk Rules

The schema for creating risk rules is well-defined with appropriate constraints and descriptions. Ensure that this schema is correctly integrated into API endpoints and that validation functions as expected.

services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (2)

14-21: Method implementation looks correct.

The createRiskRulePolicy method correctly uses the Prisma client to create a new risk rule policy, passing the necessary arguments.


47-51: Method implementation looks correct.

The findRiskRulePolicyByProjectId method correctly fetches a risk rule policy based on the project ID.

services/workflows-service/prisma/migrations/20240716155934_create_rule_policy/migration.sql (1)

2-2: Comprehensive review of SQL migration script.

This SQL migration script is well-structured and appears to correctly implement the database schema changes required for the new risk rule feature. Here are some specific observations and suggestions:

  1. Enums and Tables Creation:

    • The creation of enums IndicatorRiskLevel and RuleEngine is aligned with the PR objectives to handle risk levels and rule engines.
    • Tables for WorkflowDefinitionRiskRulePolicy, RiskRulesPolicy, RiskRuleSet, and Rule are appropriately defined with primary keys and necessary fields.
  2. Indexes:

    • The creation of unique and non-unique indexes is a good practice for optimizing database queries. However, ensure that the fields indexed are those that will commonly be used in query predicates.
  3. Foreign Keys:

    • The foreign key constraints are set to ON DELETE RESTRICT and ON UPDATE CASCADE, which are sensible defaults to maintain data integrity. Ensure that this behavior is expected and desired in the application logic.
  4. General Best Practices:

    • Consider adding comments to each section of the SQL script for better readability and maintainability.
    • Ensure that all new fields and tables are covered by appropriate unit tests to validate their behavior under various conditions.

Overall, the SQL migration script meets the requirements and follows good practices. No immediate changes are necessary unless specific issues are identified in the context of the entire application.

Also applies to: 5-5, 8-16, 19-26, 29-43, 46-58, 61-71, 73-79, 81-94

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

50-52: Review of module imports and integration.

The addition of RiskRulePolicyModule, RiskRuleSetModule, and RuleModule to the application's main module is consistent with the PR's objectives to enhance the risk management capabilities. Here are a few considerations:

  1. Module Integration:

    • Ensure that these modules do not introduce circular dependencies with other parts of the application.
    • Verify that the services provided by these modules are correctly injected where needed and that they interact seamlessly with existing modules.
  2. Configuration and Initialization:

    • Check if any environment-specific configurations are required for these modules and if they are handled appropriately.
    • Ensure that any initialization code within these modules does not adversely affect the startup time of the application.
  3. Error Handling:

    • Confirm that error handling within these modules is robust, especially in interactions with external services or databases.

The integration of new modules appears correct and well-handled. It is recommended to perform integration testing to ensure that these modules function as expected within the larger application context.

Also applies to: 130-133

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

191-197: Review of Prisma schema changes.

The modifications and additions to the Prisma schema are extensive and align with the objectives to enhance risk management capabilities. Here are specific observations and recommendations:

  1. New Models and Enums:

    • The new enums IndicatorRiskLevel and RuleEngine are correctly defined and used in the models.
    • The new models WorkflowDefinitionRiskRulePolicy, RiskRulesPolicy, RiskRuleSet, and Rule are well-structured with appropriate fields and relationships.
  2. Model Relationships:

    • Ensure that the relationships (e.g., @relation attributes) are correctly configured to enforce integrity and facilitate efficient queries.
    • Verify that optional and mandatory fields are correctly marked, reflecting the business logic and data requirements.
  3. Indexes and Unique Constraints:

    • The use of indexes and unique constraints is appropriate. However, review the chosen fields to ensure they are the most relevant for query optimization.
  4. Migration and Compatibility:

    • Ensure that these schema changes are compatible with existing data and that a migration path is clearly defined for production environments.

The Prisma schema changes are well-implemented and should support the new functionalities as expected. It is advisable to conduct thorough testing, especially focusing on database interactions and performance under load.

Also applies to: 374-374, 811-815, 866-869, 895-962

services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts (2)

9-15: Verify the integrity of input arguments in the create method.

Ensure that createArgs does not already include a riskRulePolicyId which could potentially overwrite the intended value or cause unexpected behavior.


36-49: Verify the uniqueness and correct usage of the compound key in the updateById method.

Ensure that the id_riskRulePolicyId compound key is uniquely defined in the database schema and correctly used here to prevent any potential issues with record identification.

services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.service.ts (3)

45-49: Good error handling in update method.

The method correctly handles the case where an updated risk rule set is not found by throwing a NotFoundException.


52-58: Good error handling in delete method.

The method correctly handles the case where the risk rule set is not found during the delete operation by throwing a NotFoundException.


33-50: Address the TODO and verify complete implementation of update method.

The TODO comment suggests that the update functionality might be incomplete. Ensure that this is addressed before finalizing the PR.

Verification successful

Address the TODO comment in the update method.

The updateById method in risk-rule-set.repository.ts is fully implemented and functional. Ensure that the TODO comment in the update method of risk-rule-set.service.ts is addressed or removed to reflect the complete implementation.

  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.service.ts: Line 37
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the update functionality is complete and integrated properly.

# Test: Search for the TODO comment and related implementation details.
rg --type typescript -A 5 $'TODO update to risk to update module'

Length of output: 101


Script:

#!/bin/bash
# Description: Verify that the update functionality is complete and integrated properly.

# Test: Search for the TODO comment and related implementation details.
rg --type ts -A 5 $'TODO update to risk to update module'

Length of output: 725


Script:

#!/bin/bash
# Description: Verify the implementation of the updateById method in riskRuleSetRepository.

# Test: Search for the updateById method in the repository.
rg --type ts 'updateById'

Length of output: 8074


Script:

#!/bin/bash
# Description: Extract the implementation details of the updateById method in risk-rule-set.repository.ts.

# Test: Extract the implementation of the updateById method in risk-rule-set.repository.ts.
rg --type ts -A 20 'async updateById' services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts

Length of output: 623

packages/workflow-core/src/lib/plugins/common-plugin/types.ts (1)

52-52: Verify the impact of changing rulesSource and document the change.

The change from a specific object structure to TFindAllRulesOptions increases flexibility but may impact existing implementations. Ensure compatibility and document the change in the migration guide.

Would you like me to help document this change in the migration guide?

Comment on lines 1 to 7
import { Injectable } from '@nestjs/common';
import { RuleRepository } from './rule.repository';

@Injectable()
export class RuleService {
constructor(private readonly ruleRepository: RuleRepository) {}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Well-structured service class for rule management.

The RuleService class is correctly set up with dependency injection for the RuleRepository. This follows NestJS best practices.

Consider adding service methods.

Currently, the service class does not contain any methods. Depending on the requirements, you might want to add methods to handle specific business logic related to rules.

Would you like me to help draft some of the service methods based on typical CRUD operations?

Comment on lines 1 to 7
import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/prisma/prisma.service';

@Injectable()
export class RuleRepository {
constructor(protected readonly prisma: PrismaService) {}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Well-structured repository class for rule management.

The RuleRepository class is set up correctly with dependency injection for the PrismaService. This is a good use of the repository pattern in a NestJS project.

Consider adding repository methods.

Currently, the repository class does not contain any methods. You might want to add methods for database interactions such as create, read, update, and delete operations for rules.

Would you like assistance in drafting some of these methods?

Comment on lines 1 to 7
import { Injectable } from '@nestjs/common';
import { RiskRulePolicyRepository } from './risk-rule-policy.repository';

@Injectable()
export class RiskRulePolicyService {
constructor(private readonly riskRuleSetRepository: RiskRulePolicyRepository) {}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Well-structured service class for risk rule policy management.

The RiskRulePolicyService class is correctly set up with dependency injection for the RiskRulePolicyRepository. This follows NestJS best practices.

Consider adding service methods.

Currently, the service class does not contain any methods. Depending on the requirements, you might want to add methods to handle specific business logic related to risk rule policies.

Would you like me to help draft some of the service methods based on typical CRUD operations?

Comment on lines 29 to 44
async findRiskRulePolicyByWorkflowDefinitionId(
workflowDefinitionId: string,
projectIds: TProjectIds,
) {
return this.prisma.riskRulesPolicy.findFirstOrThrow({
where: {
workflowDefinitionRiskRulePolicies: {
some: {
workflowDefinitionId,
},
},
},
select: {
riskRuleSets: true,
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Add project scoping to the query.

The method fetches data based on the workflow definition ID but does not scope the query to specific projects, which might lead to unauthorized data access.

-      where: {
+      where: {
+        projectId: { in: projectIds },
         workflowDefinitionRiskRulePolicies: {
           some: {
             workflowDefinitionId,
           },
         },
+      },
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findRiskRulePolicyByWorkflowDefinitionId(
workflowDefinitionId: string,
projectIds: TProjectIds,
) {
return this.prisma.riskRulesPolicy.findFirstOrThrow({
where: {
workflowDefinitionRiskRulePolicies: {
some: {
workflowDefinitionId,
},
},
},
select: {
riskRuleSets: true,
},
});
async findRiskRulePolicyByWorkflowDefinitionId(
workflowDefinitionId: string,
projectIds: TProjectIds,
) {
return this.prisma.riskRulesPolicy.findFirstOrThrow({
where: {
projectId: { in: projectIds },
workflowDefinitionRiskRulePolicies: {
some: {
workflowDefinitionId,
},
},
},
select: {
riskRuleSets: true,
},
});

Comment on lines 23 to 27
async findRiskRulePolicyById(id: string, projectIds: TProjectIds) {
return this.prisma.riskRulesPolicy.findUnique({
where: { id },
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider scoping the query to specific projects.

The method currently retrieves a risk rule policy by ID without considering the project scope. It might be beneficial to include a filter by projectIds to ensure data access is scoped correctly.

-      where: { id },
+      where: { id, projectId: { in: projectIds } },
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findRiskRulePolicyById(id: string, projectIds: TProjectIds) {
return this.prisma.riskRulesPolicy.findUnique({
where: { id },
});
}
async findRiskRulePolicyById(id: string, projectIds: TProjectIds) {
return this.prisma.riskRulesPolicy.findUnique({
where: { id, projectId: { in: projectIds } },
});
}

Comment on lines 25 to 33
async findById(
id: string,
riskRulePolicyId: string,
args?: Prisma.RiskRuleSetFindFirstOrThrowArgs,
) {
return await this.prisma.riskRuleSet.findFirstOrThrow({
...(args ? args : {}),
where: { ...(args?.where ? { ...args?.where } : {}), id: id, riskRulePolicyId },
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Simplify the conditional logic in the findById method.

The current implementation can be simplified to enhance readability and maintainability.

-      ...(args ? args : {}),
-      where: { ...(args?.where ? { ...args?.where } : {}), id: id, riskRulePolicyId },
+      ...args,
+      where: { ...args?.where, id, riskRulePolicyId },
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findById(
id: string,
riskRulePolicyId: string,
args?: Prisma.RiskRuleSetFindFirstOrThrowArgs,
) {
return await this.prisma.riskRuleSet.findFirstOrThrow({
...(args ? args : {}),
where: { ...(args?.where ? { ...args?.where } : {}), id: id, riskRulePolicyId },
});
return await this.prisma.riskRuleSet.findFirstOrThrow({
...args,
where: { ...args?.where, id, riskRulePolicyId },
});

Comment on lines 11 to 24
async create(policyId: string, createRiskRuleSetData: Static<typeof CreateRiskRuleSchema>) {
return this.riskRuleSetRepository.create(policyId, {
...createRiskRuleSetData,
rules: {
createMany: {
data: createRiskRuleSetData.ruleSet.rules.map(rule => ({
operator: rule.operation,
engine: rule.engine,
comparisonValue: rule.value,
key: rule.key,
})),
},
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for potential undefined properties in create method.

The function assumes createRiskRuleSetData.ruleSet.rules is always defined, which might not be the case. Adding error handling or default values can prevent runtime errors.

- data: createRiskRuleSetData.ruleSet.rules.map(rule => ({
+ data: createRiskRuleSetData.ruleSet?.rules?.map(rule => ({
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async create(policyId: string, createRiskRuleSetData: Static<typeof CreateRiskRuleSchema>) {
return this.riskRuleSetRepository.create(policyId, {
...createRiskRuleSetData,
rules: {
createMany: {
data: createRiskRuleSetData.ruleSet.rules.map(rule => ({
operator: rule.operation,
engine: rule.engine,
comparisonValue: rule.value,
key: rule.key,
})),
},
},
});
async create(policyId: string, createRiskRuleSetData: Static<typeof CreateRiskRuleSchema>) {
return this.riskRuleSetRepository.create(policyId, {
...createRiskRuleSetData,
rules: {
createMany: {
data: createRiskRuleSetData.ruleSet?.rules?.map(rule => ({
operator: rule.operation,
engine: rule.engine,
comparisonValue: rule.value,
key: rule.key,
})),
},
},
});

Comment on lines 27 to 31
async findOne(id: string, policyId: string) {
const riskRuleSet = await this.riskRuleSetRepository.findById(id, policyId);

return riskRuleSet;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling for not found cases in findOne method.

The function does not handle the scenario where riskRuleSet might be null or undefined after the fetch operation.

  const riskRuleSet = await this.riskRuleSetRepository.findById(id, policyId);
+ if (!riskRuleSet) {
+   throw new NotFoundException(`RiskRuleSet with ID "${id}" not found`);
+ }
  return riskRuleSet;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findOne(id: string, policyId: string) {
const riskRuleSet = await this.riskRuleSetRepository.findById(id, policyId);
return riskRuleSet;
}
async findOne(id: string, policyId: string) {
const riskRuleSet = await this.riskRuleSetRepository.findById(id, policyId);
if (!riskRuleSet) {
throw new NotFoundException(`RiskRuleSet with ID "${id}" not found`);
}
return riskRuleSet;
}

@Blokh Blokh changed the title Feature/implement risk rule ( WIP ) Feature/implement risk rule ( WIP ) BAL-2445 Jul 17, 2024
@@ -0,0 +1,94 @@
-- CreateEnum
CREATE TYPE "IndicatorRiskLevel" AS ENUM ('positive', 'moderate', 'critical');
Copy link
Collaborator

Choose a reason for hiding this comment

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

low


model RiskRuleSet {
id String @id @default(cuid())
riskRulePolicyId String
Copy link
Collaborator

Choose a reason for hiding this comment

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

name

Copy link
Collaborator

Choose a reason for hiding this comment

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

operator

// eslint-disable-next-line import/namespace
import { CreateRiskRuleSchema } from './create-risk-rule.schema';

export const CreateRuleSetSchema = Type.Object({
Copy link
Collaborator

Choose a reason for hiding this comment

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

poilicy

}

model Rule {
id String @id @default(cuid())
Copy link
Collaborator

Choose a reason for hiding this comment

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

name

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f72c12b and c27a411.

Files selected for processing (8)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/prisma/migrations/20240717150250_craete_rules_with_ruleset_and_policy/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (5 hunks)
  • services/workflows-service/src/project/project-scope.service.ts (2 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (6)
  • services/workflows-service/prisma/data-migrations
  • services/workflows-service/prisma/schema.prisma
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts
  • services/workflows-service/src/risk-rules/rule/rule.service.ts
Additional comments not posted (1)
services/workflows-service/prisma/migrations/20240717150250_craete_rules_with_ruleset_and_policy/migration.sql (1)

1-162: Comprehensive Review of SQL Migration File

This migration file is well-structured and introduces several new components to the database schema:

  • Enums: IndicatorRiskLevel, RuleEngine, RulesetOperator. These are correctly defined.
  • Tables: Tables for WorkflowDefinitionRiskRulePolicy, RiskRuleSetRule, RiskRulesPolicy, RiskRuleSet, and Rule. Each table is properly defined with primary keys and appropriate data types.
  • Indexes: Various indexes are created to optimize query performance.
  • Foreign Keys: Foreign keys are set up to maintain referential integrity.
  • Checks: Constraints are added to ensure data consistency, such as the public/private status checks.

Overall, the SQL commands appear correct and efficient. However, ensure that:

  • Performance: Indexes are appropriately used to optimize performance, especially for large datasets.
  • Maintainability: The schema is maintainable and aligns with the project's data standards.
  • Best Practices: All SQL practices such as naming conventions and data integrity are followed.

The SQL migration file is well-prepared and aligns with the project's requirements.

Comment on lines 46 to 70
scopeFindManyOrPublic<T>(
args?: Prisma.SelectSubset<T, PrismaGeneralQueryArgs>,
projectIds?: TProjectIds,
): T {
// @ts-expect-error - dynamically typed for all queries
args ||= {};
// @ts-expect-error - dynamically typed for all queries
args!.where = {
// @ts-expect-error - dynamically typed for all queries
...args?.where,
OR: [
{
project: {
id: {in: projectIds},
}
},
{
isPublic: true
}
]
,
};

return args!;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review: New method scopeFindManyOrPublic.

The method scopeFindManyOrPublic dynamically modifies the args object to include conditions for project IDs and public status. While the dynamic nature of the method allows flexibility, it could potentially lead to maintainability issues or bugs due to type mismatches.

  • Correctness: The method correctly adds conditions to the where clause using an OR logic to handle both project-specific and public scopes.
  • Performance: Ensure that the dynamic addition of conditions does not lead to inefficient database queries, especially with large datasets.
  • Best Practices: Consider adding more type safety or documentation to clarify the expected types and behaviors, especially since @ts-expect-error is used extensively.

Enhance type safety and reduce the reliance on @ts-expect-error.

Comment on lines 89 to 110
scopeFindOneOrPublic<T>(
args: Prisma.SelectSubset<T, PrismaGeneralQueryArgs>,
projectIds: TProjectIds,
): T {
// @ts-expect-error
args.where = {
// @ts-expect-error
...args.where,
OR: [
{
project: {
id: {in: projectIds},
}
},
{
isPublic: true
}
],
};

return args as T;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review: New method scopeFindOneOrPublic.

Similar to scopeFindManyOrPublic, this method modifies the args object to handle single project scope retrievals based on conditions. The method uses the same dynamic typing approach.

  • Correctness: The method correctly implements the logic to handle both project-specific and public scopes using an OR condition.
  • Performance: As with the previous method, ensure that the dynamic conditions do not impact the performance of database queries.
  • Best Practices: The extensive use of @ts-expect-error indicates potential type mismatches. Consider improving type safety and documentation.

Improve type safety and documentation to clarify the dynamic behaviors and expected types.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c27a411 and a0d8f96.

Files selected for processing (22)
  • packages/workflow-core/src/lib/plugins/common-plugin/risk-rules-plugin.ts (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/prisma/migrations/20240718140108_create_rule_policy/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (5 hunks)
  • services/workflows-service/src/helpers/type-box/type-string-enum.ts (1 hunks)
  • services/workflows-service/src/project/project-scope.service.ts (2 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-set/schemas/create-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/assign-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/unassign-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/update-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/schemas/create-rule-set.schema.ts (1 hunks)
Files skipped from review as they are similar to previous changes (11)
  • services/workflows-service/prisma/schema.prisma
  • services/workflows-service/src/helpers/type-box/type-string-enum.ts
  • services/workflows-service/src/project/project-scope.service.ts
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.module.ts
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.repository.ts
  • services/workflows-service/src/risk-rules/risk-rule-set/risk-rule-set.service.ts
  • services/workflows-service/src/risk-rules/rule/rule.module.ts
  • services/workflows-service/src/risk-rules/rule/rule.service.ts
  • services/workflows-service/src/risk-rules/schemas/create-rule-set.schema.ts
Additional comments not posted (15)
services/workflows-service/prisma/data-migrations (1)

1-1: Commit hash update approved.

The subproject commit hash was updated to 27c48a7de4204ccb6c780b0d32c84e2822867277.

services/workflows-service/src/risk-rules/rule/schemas/assign-rule.schema.ts (1)

1-9: New schema definition approved.

The AssignRuleSchema is well-defined and uses the TypeBox library for type validation. The description for the riskRuleSetId field is clear.

services/workflows-service/src/risk-rules/rule/schemas/unassign-rule.schema.ts (1)

1-9: New schema definition approved.

The UnassignRuleSchema is well-defined and uses the TypeBox library for type validation. The description for the riskRuleSetId field is clear.

services/workflows-service/prisma/migrations/20240718140108_create_rule_policy/migration.sql (2)

1-7: Verify potential impact of the migration.

The migration includes warnings about dropping the operator column and adding a required operation column without a default value. Ensure that these changes do not cause data loss or issues if the table is not empty.


8-13: Review database migration changes.

The migration drops an index and alters the Rule table by dropping the operator column and adding the operation column. Ensure that these changes are correctly handled in the application logic and that any data migration scripts are in place if needed.

services/workflows-service/src/risk-rules/risk-rule-set/schemas/create-rule-set.schema.ts (2)

1-4: Imports look good.

The imports are necessary and correctly referenced.


6-15: Schema definition is correct.

The CreateRuleSetSchema is well-defined with appropriate types and descriptions.

services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts (2)

1-4: Imports look good.

The imports are necessary and correctly referenced.


5-25: Schema definition is correct.

The CreateRuleSchema is well-defined with appropriate types and descriptions.

services/workflows-service/src/risk-rules/rule/schemas/update-rule.schema.ts (2)

1-4: Imports look good.

The imports are necessary and correctly referenced.


5-32: Schema definition is correct.

The UpdateRuleSchema is well-defined with appropriate types and descriptions.

packages/workflow-core/src/lib/plugins/common-plugin/risk-rules-plugin.ts (1)

55-58: Conditional assignment looks good.

The conditional assignment for databaseId based on the source property is correctly implemented.

services/workflows-service/src/risk-rules/rule/rule.repository.ts (1)

9-12: Well-structured constructor.

The constructor correctly initializes PrismaService and ProjectScopeService using dependency injection.

services/workflows-service/src/risk-rules/risk-rule-set/rule.controller.ts (1)

21-21: Well-structured constructor.

The constructor correctly initializes RuleService using dependency injection.

services/workflows-service/src/risk-rules/rule/rule.controller.ts (1)

21-21: Well-structured constructor.

The constructor correctly initializes RuleService using dependency injection.

Comment on lines 14 to 21
async create(
createArgs: Omit<Prisma.RuleUncheckedCreateInput, 'riskRuleSetId' | 'projectId' | 'isPublic'>,
projectId: string,
) {
return this.prisma.rule.create({
data: { ...createArgs, projectId, isPublic: false },
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The create method lacks error handling, which could lead to unhandled exceptions.

+  try {
    return this.prisma.rule.create({
      data: { ...createArgs, projectId, isPublic: false },
    });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to create rule');
+  }

Committable suggestion was skipped due to low confidence.

Comment on lines 40 to 47
async assignRuleToRuleset(ruleId: string, riskRuleSetId: string) {
return this.prisma.riskRuleSetRule.create({
data: {
riskRuleSetId,
ruleId,
},
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The assignRuleToRuleset method lacks error handling, which could lead to unhandled exceptions.

+  try {
    return this.prisma.riskRuleSetRule.create({
      data: {
        riskRuleSetId,
        ruleId,
      },
    });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to assign rule to ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async assignRuleToRuleset(ruleId: string, riskRuleSetId: string) {
return this.prisma.riskRuleSetRule.create({
data: {
riskRuleSetId,
ruleId,
},
});
}
async assignRuleToRuleset(ruleId: string, riskRuleSetId: string) {
try {
return this.prisma.riskRuleSetRule.create({
data: {
riskRuleSetId,
ruleId,
},
});
} catch (error) {
// Handle error appropriately
throw new Error('Failed to assign rule to ruleset');
}
}

Comment on lines 102 to 113
async deleteById(id: string, projectIds: TProjectIds) {
return this.prisma.riskRuleSet.delete(
this.scopeService.scopeDelete(
{
where: {
id: id,
},
},
projectIds,
),
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The deleteById method lacks error handling, which could lead to unhandled exceptions.

+  try {
    return this.prisma.riskRuleSet.delete(
      this.scopeService.scopeDelete(
        {
          where: {
            id: id,
          },
        },
        projectIds,
      ),
    );
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to delete rule by ID');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async deleteById(id: string, projectIds: TProjectIds) {
return this.prisma.riskRuleSet.delete(
this.scopeService.scopeDelete(
{
where: {
id: id,
},
},
projectIds,
),
);
}
async deleteById(id: string, projectIds: TProjectIds) {
try {
return this.prisma.riskRuleSet.delete(
this.scopeService.scopeDelete(
{
where: {
id: id,
},
},
projectIds,
),
);
} catch (error) {
// Handle error appropriately
throw new Error('Failed to delete rule by ID');
}
}

Comment on lines 50 to 58
async unassignRuleFromRuleset(ruleId: string, riskRuleSetId: string) {
return this.prisma.riskRuleSetRule.delete({
where: {
riskRuleSetId_ruleId: {
ruleId,
riskRuleSetId,
},
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The unassignRuleFromRuleset method lacks error handling, which could lead to unhandled exceptions.

+  try {
    return this.prisma.riskRuleSetRule.delete({
      where: {
        riskRuleSetId_ruleId: {
          ruleId,
          riskRuleSetId,
        },
      },
    });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to unassign rule from ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async unassignRuleFromRuleset(ruleId: string, riskRuleSetId: string) {
return this.prisma.riskRuleSetRule.delete({
where: {
riskRuleSetId_ruleId: {
ruleId,
riskRuleSetId,
},
},
});
async unassignRuleFromRuleset(ruleId: string, riskRuleSetId: string) {
try {
return this.prisma.riskRuleSetRule.delete({
where: {
riskRuleSetId_ruleId: {
ruleId,
riskRuleSetId,
},
},
});
} catch (error) {
// Handle error appropriately
throw new Error('Failed to unassign rule from ruleset');
}

Comment on lines 61 to 71
async findMany(projectIds: TProjectIds, args?: Prisma.RuleFindManyArgs) {
return this.prisma.rule.findMany(
this.scopeService.scopeFindManyOrPublic(
{
...args,
where: { ...args?.where },
},
projectIds,
),
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The findMany method lacks error handling, which could lead to unhandled exceptions.

+  try {
    return this.prisma.rule.findMany(
      this.scopeService.scopeFindManyOrPublic(
        {
          ...args,
          where: { ...args?.where },
        },
        projectIds,
      ),
    );
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to find rules');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findMany(projectIds: TProjectIds, args?: Prisma.RuleFindManyArgs) {
return this.prisma.rule.findMany(
this.scopeService.scopeFindManyOrPublic(
{
...args,
where: { ...args?.where },
},
projectIds,
),
);
}
async findMany(projectIds: TProjectIds, args?: Prisma.RuleFindManyArgs) {
try {
return this.prisma.rule.findMany(
this.scopeService.scopeFindManyOrPublic(
{
...args,
where: { ...args?.where },
},
projectIds,
),
);
} catch (error) {
// Handle error appropriately
throw new Error('Failed to find rules');
}
}

Comment on lines 128 to 142
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});

return rule as TUpdateRule;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The updateRule endpoint lacks error handling, which could lead to unhandled exceptions.

+  try {
    const rule = await this.ruleService.updateRule({
      ruleId,
      ruleData: updateRuleSchema,
      projectId: currentProjectId,
      projectIds,
    });

    return rule as TUpdateRule;
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to update rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});
return rule as TUpdateRule;
}
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});
return rule as TUpdateRule;
} catch (error) {
// Handle error appropriately
throw new Error('Failed to update rule');
}
}

Comment on lines 144 to 157
@Delete('/:ruleId')
@Validate({
request: [
{
type: 'param',
name: 'ruleId',
schema: Type.String(),
},
],
response: Type.Any(),
})
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
await this.ruleService.deleteRule({ ruleId, projectIds });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The deleteRule endpoint lacks error handling, which could lead to unhandled exceptions.

+  try {
    await this.ruleService.deleteRule({ ruleId, projectIds });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to delete rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Delete('/:ruleId')
@Validate({
request: [
{
type: 'param',
name: 'ruleId',
schema: Type.String(),
},
],
response: Type.Any(),
})
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
await this.ruleService.deleteRule({ ruleId, projectIds });
}
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
try {
await this.ruleService.deleteRule({ ruleId, projectIds });
} catch (error) {
// Handle error appropriately
throw new Error('Failed to delete rule');
}
}

Comment on lines 60 to 77
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.riskRuleSetId,
currentProjectId,
projectIds,
);

return {
ruleId: rule.id,
...assignRuleDate,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The assignRuleToRuleset endpoint lacks error handling, which could lead to unhandled exceptions.

+  try {
    const rule = await this.ruleService.assignRuleToRuleset(
      ruleId,
      assignRuleDate.riskRuleSetId,
      currentProjectId,
      projectIds,
    );

    return {
      ruleId: rule.id,
      ...assignRuleDate,
    };
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to assign rule to ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.riskRuleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...assignRuleDate,
};
}
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.riskRuleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...assignRuleDate,
};
} catch (error) {
// Handle error appropriately
throw new Error('Failed to assign rule to ruleset');
}
}

Comment on lines 94 to 111
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.riskRuleSetId,
currentProjectId,
projectIds,
);

return {
ruleId: rule.id,
...unassignRule,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The unassignRule endpoint lacks error handling, which could lead to unhandled exceptions.

+  try {
    const rule = await this.ruleService.unassignRuleFromRuleset(
      ruleId,
      unassignRule.riskRuleSetId,
      currentProjectId,
      projectIds,
    );

    return {
      ruleId: rule.id,
      ...unassignRule,
    };
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to unassign rule from ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.riskRuleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...unassignRule,
};
}
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.riskRuleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...unassignRule,
};
} catch (error) {
// Handle error appropriately
throw new Error('Failed to unassign rule from ruleset');
}
}

Comment on lines 33 to 43
async createRule(
@common.Body() data: TCreateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
return (await this.ruleService.createNewRule({
ruleData: data,
projectId: currentProjectId,
riskRuleSetId: data.riskRuleSetId,
})) as TCreateRule & { id: string };
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

The createRule endpoint lacks error handling, which could lead to unhandled exceptions.

+  try {
    return (await this.ruleService.createNewRule({
      ruleData: data,
      projectId: currentProjectId,
      riskRuleSetId: data.riskRuleSetId,
    })) as TCreateRule & { id: string };
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to create rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async createRule(
@common.Body() data: TCreateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
return (await this.ruleService.createNewRule({
ruleData: data,
projectId: currentProjectId,
riskRuleSetId: data.riskRuleSetId,
})) as TCreateRule & { id: string };
}
async createRule(
@common.Body() data: TCreateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
return (await this.ruleService.createNewRule({
ruleData: data,
projectId: currentProjectId,
riskRuleSetId: data.riskRuleSetId,
})) as TCreateRule & { id: string };
} catch (error) {
// Handle error appropriately
throw new Error('Failed to create rule');
}
}

# Conflicts:
#	packages/common/src/rule-engine/types.ts
#	services/workflows-service/prisma/data-migrations
#	services/workflows-service/src/app.module.ts
#	services/workflows-service/src/project/project-scope.service.ts
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a0d8f96 and 3c2c215.

Files selected for processing (1)
  • packages/common/src/rule-engine/types.ts (1 hunks)
Additional comments not posted (3)
packages/common/src/rule-engine/types.ts (3)

21-24: LGTM! The new type TNotionRulesOptions is well-defined.

The type includes databaseId and source properties, which are essential for Notion-specific rule options.


26-29: LGTM! The new type TDatabaseRulesOptions is well-defined.

The type includes policyId and source properties, which are essential for database-specific rule options.


31-31: LGTM! The redefinition of TFindAllRulesOptions enhances flexibility and clarity.

The union type effectively consolidates the options for finding rules from different sources.

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

Outside diff range, codebase verification and nitpick comments (7)
services/workflows-service/src/risk-rules/rule-set/schemas/assign-rule-set.schema.ts (1)

1-9: Consider improving the naming convention for the type alias.

The type alias TassignToParentRuleSet could be renamed to TAssignToParentRuleSet for consistency with typical TypeScript naming conventions.

- export type TassignToParentRuleSet = Static<typeof AssignRuleSetToParentRuleSet>;
+ export type TAssignToParentRuleSet = Static<typeof AssignRuleSetToParentRuleSet>;
services/workflows-service/src/risk-rules/consts/rule-set-depth-of-3-with-rules.ts (1)

3-48: Consider simplifying or documenting the nested structure.

The deeply nested structure is correct but may impact readability and maintainability. Consider adding comments or documentation to explain the purpose and usage.

services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts (2)

16-28: Consider simplifying or documenting the nested structure.

The deeply nested structure is correct but may impact readability and maintainability. Consider adding comments or documentation to explain the purpose and usage.


30-48: Add comments to clarify the recursive logic.

The recursive logic in extractRiskRulePolicy is correct but could benefit from additional comments to enhance readability and understanding.

services/workflows-service/src/risk-rules/json.json (1)

54-55: Consider specifying allowed values for type.

The type field has a default value of "business". If there are specific allowed values, consider using an enum to enforce this.

- "type": "string",
+ "type": "string",
+ "enum": ["business", "otherAllowedType"]
services/workflows-service/src/risk-rules/risk-rule/rule.controller.ts (2)

23-43: Consider Adding Error Handling in createNewRule Method

The createNewRule method in RuleService relies on the create method of RuleRepository, which does not explicitly handle errors. It would be beneficial to add error handling to manage potential exceptions from the Prisma service.

  • File: services/workflows-service/src/risk-rules/rule/rule.service.ts
  • Method: createNewRule
Analysis chain

createRule method is well-structured.

The method uses appropriate validation and interacts with the service correctly.

Ensure that createNewRule in RuleService handles errors properly and returns the expected data structure.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in `createNewRule` method of `RuleService`.

# Test: Search for the `createNewRule` method implementation. Expect: Proper error handling and return structure.
ast-grep --lang typescript --pattern $'class RuleService {
  $$$
  createNewRule($_) {
    $$$
  }
  $$$  
}'

Length of output: 11044


Script:

#!/bin/bash
# Description: Verify error handling in `create` method of `RuleRepository`.

# Test: Search for the `create` method implementation in `RuleRepository`. Expect: Proper error handling.
ast-grep --lang typescript --pattern $'class RuleRepository {
  $$$
  create($_) {
    $$$
  }
  $$$  
}'

Length of output: 28868


45-77: Add error handling to assignRuleToRuleset in RuleService.

The method currently lacks explicit error handling, which could lead to unhandled exceptions in cases such as rule not found or database operation failures. Consider implementing try-catch blocks or other error handling mechanisms to ensure robustness.

  • Location: services/workflows-service/src/risk-rules/rule/rule.service.ts, lines 30-58
Analysis chain

assignRuleToRuleset method is well-structured.

The method uses appropriate validation and interacts with the service correctly.

Ensure that assignRuleToRuleset in RuleService handles errors properly and returns the expected data structure.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in `assignRuleToRuleset` method of `RuleService`.

# Test: Search for the `assignRuleToRuleset` method implementation. Expect: Proper error handling and return structure.
ast-grep --lang typescript --pattern $'class RuleService {
  $$$
  assignRuleToRuleset($_, $_, $_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 11062


Script:

#!/bin/bash
# Description: Check for error handling in `assignRuleToRuleset` method of `RuleService`.

# Test: Search for try-catch blocks or error handling logic in the `assignRuleToRuleset` method.
rg --context 5 'assignRuleToRuleset' --type=typescript

Length of output: 89


Script:

#!/bin/bash
# Description: Check for error handling in `assignRuleToRuleset` method of `RuleService`.

# Test: Search for try-catch blocks or error handling logic in the `assignRuleToRuleset` method.
rg --context 5 'assignRuleToRuleset' --glob '*.ts'

Length of output: 4400

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3c2c215 and 2b51595.

Files selected for processing (25)
  • services/workflows-service/prisma/migrations/20240808102902_create_risk_ruleset/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (4 hunks)
  • services/workflows-service/src/risk-rules/consts/rule-set-depth-of-3-with-rules.ts (1 hunks)
  • services/workflows-service/src/risk-rules/consts/rule-set-parent-depth-3-with-policies.ts (1 hunks)
  • services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts (1 hunks)
  • services/workflows-service/src/risk-rules/json.json (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/create-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/assign-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/create-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/unassign-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/update-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/assign-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/unassign-ruleset-from-parent.schema.ts (1 hunks)
Additional comments not posted (71)
services/workflows-service/src/risk-rules/rule/schemas/assign-rule.schema.ts (1)

1-9: LGTM!

The schema and type alias are correctly defined for assigning a rule to a rule set.

services/workflows-service/src/risk-rules/rule-set/schemas/unassign-rule-set.schema.ts (1)

1-9: LGTM!

The schema and type alias are correctly defined for unassigning a rule set.

services/workflows-service/src/risk-rules/rule/schemas/unassign-ruleset-from-parent.schema.ts (1)

1-9: Schema Definition Looks Good!

The schema and type definition are correctly implemented using @sinclair/typebox. The use of Type.String for parentRuleSetId is appropriate.

services/workflows-service/src/risk-rules/rule-set/schemas/create-rule-set.schema.ts (1)

1-10: Schema Definition Looks Good!

The schema for creating a ruleset is well-structured. The use of Type.Enum for operator and Type.Optional for parentRuleSetId is appropriate.

services/workflows-service/src/risk-rules/risk-rule/schemas/create-rule-set.schema.ts (1)

1-15: Schema Definition Looks Good!

The schema for creating a rule set is correctly implemented. The use of TypeStringEnum for the operator and Type.Array for rules is appropriate. The description adds clarity to the schema's purpose.

services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts (1)

8-13: Module Configuration Looks Good.

The module is correctly configured with necessary imports and providers. Ensure that all services and repositories are implemented and tested.

services/workflows-service/src/risk-rules/rule-set/rule-set.module.ts (1)

9-15: Module Configuration Looks Good.

The module is well-configured with necessary controllers, imports, and providers. Ensure that the controller and services are properly implemented and tested.

services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts (1)

5-25: Schema Definition Looks Good.

The CreateRuleSchema is well-defined with clear descriptions and examples for each field. Ensure that all fields are validated correctly in the application.

services/workflows-service/src/risk-rules/rule-set/schemas/update-rule-set.schema.ts (6)

6-10: LGTM!

The name field is well-defined with a clear description and example.


12-16: LGTM!

The key field is well-defined with a clear description and example.


18-20: LGTM!

The operation field is well-defined using TypeStringEnum, with a clear description and default value.


21-25: LGTM!

The comparisonValue field is well-defined with a clear description and example.


27-29: LGTM!

The engine field is well-defined using TypeStringEnum, with a clear description and default value.


32-32: LGTM!

The type TUpdateRule is correctly defined using Static from TypeBox.

services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts (3)

4-6: LGTM!

The type RiskRuleWithPolicy is correctly defined and extends RiskRule appropriately.


8-10: LGTM!

The type RiskRuleRuleSetWithRule is correctly defined and extends RiskRuleRuleSet appropriately.


12-14: LGTM!

The type RuleSetWithRiskRules is correctly defined and extends RuleSet appropriately.

services/workflows-service/src/risk-rules/json.json (2)

3-8: Ensure completeness of required fields.

The required array specifies fields that must be present. Verify that all necessary fields for your application logic are included here.


37-39: Validate email format.

The email field uses the format "email". Ensure that any validation logic in your application correctly handles this format.

services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts (6)

19-25: LGTM!

The findManyByRuleset method is well-implemented and correctly uses the repository to fetch data.


27-29: LGTM!

The findMany method is well-implemented, allowing for optional arguments to customize the query.


31-36: LGTM!

The findAssociatedRiskPolcies method is well-implemented, effectively utilizing helper functions to process and return data.


38-43: LGTM!

The assignRuleSetToParentRuleset method is correctly implemented, delegating the task to the repository.


45-53: LGTM!

The unassignRuleFromRuleset method is correctly implemented, using the repository to perform the operation.


99-107: LGTM!

The deleteRule method is correctly implemented, ensuring that public rules cannot be deleted.

services/workflows-service/src/risk-rules/rule/rule.service.ts (4)

14-24: LGTM!

The findManyByRuleset method is well-implemented and correctly uses the repository to fetch data.


26-28: LGTM!

The findMany method is well-implemented, allowing for optional arguments to customize the query.


30-57: Clarify the logic for ruleProjectId.

The logic for checking ruleProjectId in assignRuleToRuleset seems incomplete. Consider verifying if the rule should be connected or created based on ruleProjectId.


117-125: LGTM!

The deleteRule method is correctly implemented, ensuring that public rules cannot be deleted.

services/workflows-service/src/risk-rules/risk-rule/risk-rule.repository.ts (5)

41-65: LGTM!

The findMany method is well-implemented, using the scope service to handle scoped queries effectively.


83-98: LGTM!

The updateById method is well-implemented, ensuring that updates are correctly handled.


101-119: LGTM!

The connectToRuleset method is well-implemented, using Prisma's upsert operation effectively.


123-135: LGTM!

The disconnectFromRuleset method is well-implemented, using Prisma's delete operation effectively.


138-149: LGTM!

The deleteById method is well-implemented, using the scope service to handle scoped deletions effectively.

services/workflows-service/src/risk-rules/rule/rule.repository.ts (7)

14-39: Consider adding error handling to create method.

The create method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


41-54: Consider adding error handling to findMany method.

The findMany method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


56-70: Consider adding error handling to findById method.

The findById method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


72-87: Consider adding error handling to updateById method.

The updateById method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


90-109: Consider adding error handling to connectToRuleset method.

The connectToRuleset method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


112-124: Consider adding error handling to disconnectFromRuleset method.

The disconnectFromRuleset method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.


126-137: Consider adding error handling to deleteById method.

The deleteById method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the Prisma call in a try-catch block.

services/workflows-service/src/risk-rules/rule/rule.controller.ts (1)

34-44: Consider adding error handling to createRule method.

The createRule method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

services/workflows-service/src/risk-rules/risk-rule/rule.controller.ts (3)

1-20: Imports and class declaration look good.

The imports are relevant and well-organized, and the class is correctly set up as a NestJS controller.


113-157: updateRule and deleteRule methods are well-structured.

Both methods use appropriate validation and interact with the service correctly.

Ensure that updateRule and deleteRule in RuleService handle errors properly and return the expected data structure.

Verification successful

Error Handling in updateRule and deleteRule Methods Verified

Both methods in RuleService appropriately handle errors by checking if a rule is public before proceeding with updates or deletions. They throw a BadRequestException when necessary, ensuring that public rules are protected from modification or deletion.

  • updateRule method: Ensures public rules are not updated.
  • deleteRule method: Ensures public rules are not deleted.

These implementations align with expected behavior and error handling practices.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in `updateRule` and `deleteRule` methods of `RuleService`.

# Test: Search for the `updateRule` method implementation. Expect: Proper error handling and return structure.
ast-grep --lang typescript --pattern $'class RuleService {
  $$$
  updateRule($_) {
    $$$
  }
  $$$  
}'

# Test: Search for the `deleteRule` method implementation. Expect: Proper error handling and return structure.
ast-grep --lang typescript --pattern $'class RuleService {
  $$$
  deleteRule($_) {
    $$$
  }
  $$$  
}'

Length of output: 22083


79-111: unassignRule method is well-structured.

The method uses appropriate validation and interacts with the service correctly.

Ensure that unassignRuleFromRuleset in RuleService handles errors properly and returns the expected data structure.

Verification successful

Verification Complete: unassignRuleFromRuleset Method

The unassignRuleFromRuleset method in RuleService correctly handles errors and returns the expected data structure by relying on the disconnectFromRuleset method in RuleRepository, which performs the deletion operation and returns the deleted record. No further issues were found.

  • The disconnectFromRuleset method uses Prisma to delete the association, which will throw an error if the entry does not exist, ensuring proper error handling.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in `unassignRuleFromRuleset` method of `RuleService`.

# Test: Search for the `unassignRuleFromRuleset` method implementation. Expect: Proper error handling and return structure.
ast-grep --lang typescript --pattern $'class RuleService {
  $$$
  unassignRuleFromRuleset($_, $_, $_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 11066


Script:

#!/bin/bash
# Description: Verify the implementation of `disconnectFromRuleset` in `ruleRepository`.

# Test: Search for the `disconnectFromRuleset` method implementation. Expect: Proper return structure.
ast-grep --lang typescript --pattern $'class RuleRepository {
  $$$
  disconnectFromRuleset($_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 28887

services/workflows-service/src/risk-rules/rule-set/rule-set.repository.ts (8)

76-93: findById method is well-structured.

The method uses scoped queries to find a ruleset by ID with optional additional arguments.

Ensure that the scoped queries are correctly implemented and secure.


95-111: findMany method is well-structured.

The method uses scoped queries to find multiple rulesets with optional arguments.

Ensure that the scoped queries are correctly implemented and secure.


114-129: updateById method is well-structured.

The method uses Prisma to update a ruleset by ID.

Ensure that input validation and error handling are implemented in the service layer.


132-157: connectToRuleset and disconnectFromRuleset methods are well-structured.

The methods use Prisma to manage connections between rulesets.

Ensure that input validation and error handling are implemented in the service layer.


159-170: deleteById method is well-structured.

The method uses scoped queries to delete a ruleset by ID.

Ensure that the scoped queries are correctly implemented and secure.


172-209: findAllAssociatedPolicies and findAssociatedRulesetsAndDefinitions methods are well-structured.

The methods use Prisma to find associated policies and rulesets.

Ensure that the queries are correctly implemented and secure.


55-74: findManyByRiskRule method is well-structured.

The method uses scoped queries to find rulesets associated with a specific risk rule.

Ensure that the scoped queries are correctly implemented and secure.

Verification successful

scopeFindOneOrPublic method implementation verified.

The method correctly scopes queries to include projects with specific IDs or public visibility. However, the use of @ts-expect-error should be reviewed to ensure it doesn't mask significant type-checking issues.

  • Location: services/workflows-service/src/project/project-scope.service.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify scoped query implementation for `findManyByRiskRule`.

# Test: Search for the `scopeFindOneOrPublic` method implementation. Expect: Correct and secure implementation.
ast-grep --lang typescript --pattern $'class ProjectScopeService {
  $$$
  scopeFindOneOrPublic($_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 129


Script:

#!/bin/bash
# Description: Search for the `scopeFindOneOrPublic` method to verify its existence and implementation.

# Use `rg` to locate the `scopeFindOneOrPublic` method.
rg 'scopeFindOneOrPublic' --context 5

Length of output: 9183


Script:

#!/bin/bash
# Description: Extract the full implementation of the `scopeFindOneOrPublic` method.

# Use `ast-grep` to extract the method from `project-scope.service.ts`.
ast-grep --lang typescript --pattern $'class ProjectScopeService {
  $$$
  scopeFindOneOrPublic($_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 129


Script:

#!/bin/bash
# Description: Use `rg` to capture the full implementation of `scopeFindOneOrPublic` in `project-scope.service.ts`.

# Search for `scopeFindOneOrPublic` in `project-scope.service.ts` with extended context.
rg 'scopeFindOneOrPublic' --context 20 services/workflows-service/src/project/project-scope.service.ts

Length of output: 820


19-53: create method is well-structured.

The method uses Prisma for database interaction and handles optional associations correctly.

Ensure that input validation and error handling are implemented in the service layer.

services/workflows-service/prisma/migrations/20240808102902_create_risk_ruleset/migration.sql (8)

1-8: ENUM creation statements are well-defined.

The ENUM types IndicatorRiskLevel, RuleEngine, and RulesetOperator are appropriate for the domain.


10-20: RiskRulesPolicy table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that projectId is indexed for performance.


22-41: RiskRule table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that riskRulePolicyId is indexed for performance.


43-52: RiskRuleRuleSet table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that riskRuleId and ruleSetId are indexed for performance.


54-65: RuleSet table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that projectId is indexed for performance.


67-76: RuleSetToRuleSet table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that parentId and childId are indexed for performance.


78-87: RuleSetRule table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that ruleId and ruleSetId are indexed for performance.


89-103: Rule table structure is appropriate.

The table includes necessary fields and a primary key constraint.

Ensure that projectId is indexed for performance.

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

820-824: Enum IndicatorRiskLevel added successfully.

The addition of IndicatorRiskLevel with values positive, moderate, and critical is well-structured and enhances risk categorization.


875-878: Enum RuleEngine added successfully.

The addition of RuleEngine with values Ballerine and JsonLogic provides flexibility in rule engine selection.


880-883: Enum RulesetOperator added successfully.

The addition of RulesetOperator with values and and or is essential for logical rule combinations.


924-937: Model RiskRulesPolicy added successfully.

The RiskRulesPolicy model is well-structured with essential fields and relationships for managing risk rule policies.


939-965: Model RiskRule added successfully.

The RiskRule model is comprehensive, with fields for rule definition and relationships for effective risk assessment.


967-981: Model RiskRuleRuleSet added successfully.

The RiskRuleRuleSet model effectively establishes relationships between risk rules and rule sets, aiding in complex rule management.


983-999: Model RuleSet added successfully.

The RuleSet model is well-structured, supporting hierarchical rule management with necessary fields and relationships.


1001-1014: Model RuleSetToRuleSet added successfully.

The RuleSetToRuleSet model facilitates hierarchical relationships between rule sets, aiding in advanced rule management.


1016-1030: Model RuleSetRule added successfully.

The RuleSetRule model is essential for linking individual rules to rule sets, supporting structured rule management.


1032-1048: Model Rule added successfully.

The Rule model is comprehensive, supporting rule definition with necessary fields and relationships for effective rule processing.

Comment on lines 3 to 64
export const RULESET_PARENT_DEPTH_3_WITH_POLICIES = {
riskRuleRuleSets: {
include: {
riskRule: {
include: {
riskRulePolicy: true
}
}
}
},
parentRuleSets: {
include: {
parent: {
include: {
riskRuleRuleSets: {
include: {
riskRule: {
include: {
riskRulePolicy: true
}
}
}
},
parentRuleSets: {
include: {
parent: {
include: {
riskRuleRuleSets: {
include: {
riskRule: {
include: {
riskRulePolicy: true
}
}
}
},
parentRuleSets: {
include: {
parent: {
include: {
riskRuleRuleSets: {
include: {
riskRule: {
include: {
riskRulePolicy: true
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} satisfies Prisma.RuleSetInclude
Copy link
Contributor

Choose a reason for hiding this comment

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

Review the nesting depth for performance considerations.

The structure is deeply nested, which can impact query performance. Ensure that this depth is necessary for your use case and consider optimizing if possible.

Comment on lines 8 to 55
// async create(policyId: string, createRiskRuleSetData: Static<typeof CreateRiskRuleSchema>) {
// return this.riskRuleSetRepository.create(policyId, {
// ...createRiskRuleSetData,
// rules: {
// createMany: {
// data: createRiskRuleSetData.ruleSet.rules.map(rule => ({
// operator: rule.operation,
// engine: rule.engine,
// comparisonValue: rule.value,
// key: rule.key,
// })),
// },
// },
// });
// }
//
// async findOne(id: string, policyId: string) {
// const riskRuleSet = await this.riskRuleSetRepository.findById(id, policyId);
//
// return riskRuleSet;
// }
//
// async update(
// id: string,
// policyId: string,
// updateRiskRuleSetDto: Static<typeof CreateRiskRuleSchema>,
// ) {
// // TODO update to risk to update module
// const updatedRiskRuleSet = await this.riskRuleSetRepository.updateById(
// id,
// policyId,
// updateRiskRuleSetDto,
// );
//
// if (!updatedRiskRuleSet) {
// throw new NotFoundException(`RiskRuleSet with ID "${id}" not found`);
// }
//
// return updatedRiskRuleSet;
// }
//
// async delete(id: string, policyId: string) {
// const result = await this.riskRuleSetRepository.deleteById(id, policyId);
//
// if (!result?.id) {
// throw new NotFoundException(`RiskRuleSet with ID "${id}" not found`);
// }
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

Implement and test the commented-out methods.

The methods for creating, finding, updating, and deleting risk rule sets are commented out. Ensure these are implemented and tested thoroughly.

Do you want me to help implement these methods or open a GitHub issue to track this task?

Comment on lines +15 to +17
async findById(id: string, projectIds: TProjectIds) {
return await this.ruleSetRepository.findById(id, projectIds);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling for not found cases.

The findById method does not handle cases where the rule set is not found. Consider using findFirstOrThrow or handling the null case explicitly.

async findById(id: string, projectIds: TProjectIds) {
  const ruleSet = await this.ruleSetRepository.findById(id, projectIds);
  if (!ruleSet) {
    throw new NotFoundException(`Rule set with ID ${id} not found.`);
  }
  return ruleSet;
}

Comment on lines 55 to 74
async createRuleSet(
{
ruleSetData,
parentRuleSetId,
projectId,
}: {
ruleSetData: Omit<Prisma.RuleSetUncheckedCreateInput, 'projectId' | 'isPublic'>;
parentRuleSetId?: string;
projectId: TProjectId;
}) {
const ruleSet = await this.ruleSetRepository.create(
{
createArgs: ruleSetData,
parentId: parentRuleSetId,
projectId,
}
);

return ruleSet;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding input validation.

The createRuleSet method lacks validation for ruleSetData, parentRuleSetId, and projectId. Consider adding validation to ensure data integrity.

if (!projectId || !ruleSetData) {
  throw new BadRequestException('Project ID and rule set data are required.');
}

Comment on lines 76 to 97
async updateRuleSet(
{
ruleId,
ruleData,
projectId,
projectIds,
}: {
ruleId: string;
ruleData: Partial<
Omit<Prisma.RuleSetUncheckedCreateInput, 'projectId' | 'isPublic' | 'id'>
>;
projectId: TProjectId;
projectIds: TProjectIds;
}) {
const rule = await this.findById(ruleId, projectIds);

if (rule.isPublic) {
throw new BadRequestException('Cannot delete public rule');
}

return await this.ruleSetRepository.updateById(ruleId, projectId, ruleData);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct the exception message.

The exception message in the updateRuleSet method is misleading. It should indicate that public rules cannot be updated, not deleted.

if (rule.isPublic) {
  throw new BadRequestException('Cannot update public rule');
}

Comment on lines 39 to 50
async createRule(
@common.Body() data: TCreatedRuleset,
@CurrentProject() currentProjectId: TProjectId,
) {
const {parentRuleSetId, ...rulesetCreationData} = data

return await this.ruleSetService.createRuleSet({
ruleSetData: rulesetCreationData,
projectId: currentProjectId,
parentRuleSetId: parentRuleSetId,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling to createRule method.

The createRule method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

+  try {
    const {parentRuleSetId, ...rulesetCreationData} = data;

    return await this.ruleSetService.createRuleSet({
      ruleSetData: rulesetCreationData,
      projectId: currentProjectId,
      parentRuleSetId: parentRuleSetId,
    });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to create rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async createRule(
@common.Body() data: TCreatedRuleset,
@CurrentProject() currentProjectId: TProjectId,
) {
const {parentRuleSetId, ...rulesetCreationData} = data
return await this.ruleSetService.createRuleSet({
ruleSetData: rulesetCreationData,
projectId: currentProjectId,
parentRuleSetId: parentRuleSetId,
});
}
async createRule(
@common.Body() data: TCreatedRuleset,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const {parentRuleSetId, ...rulesetCreationData} = data;
return await this.ruleSetService.createRuleSet({
ruleSetData: rulesetCreationData,
projectId: currentProjectId,
parentRuleSetId: parentRuleSetId,
});
} catch (error) {
// Handle error appropriately
throw new Error('Failed to create rule');
}
}

Comment on lines +156 to +158
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
await this.ruleService.deleteRule({ ruleId, projectIds });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling to deleteRule method.

The deleteRule method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

+  try {
    await this.ruleService.deleteRule({ ruleId, projectIds });
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to delete rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
await this.ruleService.deleteRule({ ruleId, projectIds });
}
async deleteRule(@common.Query() ruleId: string, @ProjectIds() projectIds: TProjectIds) {
try {
await this.ruleService.deleteRule({ ruleId, projectIds });
} catch (error) {
// Handle error appropriately
throw new Error('Failed to delete rule');
}
}

Comment on lines +129 to +142
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});

return rule as TUpdateRule;
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling to updateRule method.

The updateRule method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

+  try {
    const rule = await this.ruleService.updateRule({
      ruleId,
      ruleData: updateRuleSchema,
      projectId: currentProjectId,
      projectIds,
    });

    return rule as TUpdateRule;
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to update rule');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});
return rule as TUpdateRule;
async updateRule(
@common.Query() ruleId: string,
@common.Body() updateRuleSchema: TUpdateRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.updateRule({
ruleId,
ruleData: updateRuleSchema,
projectId: currentProjectId,
projectIds,
});
return rule as TUpdateRule;
} catch (error) {
// Handle error appropriately
throw new Error('Failed to update rule');
}

Comment on lines +61 to +78
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.ruleSetId,
currentProjectId,
projectIds,
);

return {
ruleId: rule.id,
...assignRuleDate,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling to assignRuleToRuleset method.

The assignRuleToRuleset method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

+  try {
    const rule = await this.ruleService.assignRuleToRuleset(
      ruleId,
      assignRuleDate.ruleSetId,
      currentProjectId,
      projectIds,
    );

    return {
      ruleId: rule.id,
      ...assignRuleDate,
    };
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to assign rule to ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.ruleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...assignRuleDate,
};
}
async assignRuleToRuleset(
@common.Query() ruleId: string,
@common.Body() assignRuleDate: TAssignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.assignRuleToRuleset(
ruleId,
assignRuleDate.ruleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...assignRuleDate,
};
} catch (error) {
// Handle error appropriately
throw new Error('Failed to assign rule to ruleset');
}
}

Comment on lines +95 to +112
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.ruleSetId,
currentProjectId,
projectIds,
);

return {
ruleId: rule.id,
...unassignRule,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling to unassignRule method.

The unassignRule method lacks error handling, which could lead to unhandled exceptions. Consider wrapping the service call in a try-catch block.

+  try {
    const rule = await this.ruleService.unassignRuleFromRuleset(
      ruleId,
      unassignRule.ruleSetId,
      currentProjectId,
      projectIds,
    );

    return {
      ruleId: rule.id,
      ...unassignRule,
    };
+  } catch (error) {
+    // Handle error appropriately
+    throw new Error('Failed to unassign rule from ruleset');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.ruleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...unassignRule,
};
}
async unassignRule(
@common.Query() ruleId: string,
@common.Body() unassignRule: TUnassignRule,
@ProjectIds() projectIds: TProjectIds,
@CurrentProject() currentProjectId: TProjectId,
) {
try {
const rule = await this.ruleService.unassignRuleFromRuleset(
ruleId,
unassignRule.ruleSetId,
currentProjectId,
projectIds,
);
return {
ruleId: rule.id,
...unassignRule,
};
} catch (error) {
// Handle error appropriately
throw new Error('Failed to unassign rule from ruleset');
}
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
services/workflows-service/src/risk-rules/risk-rule/schemas/create-risk-rule.schema.ts (1)

1-54: Ensure comprehensive validation in CreateRiskRuleSchema.

The schema is well-defined, but consider adding additional constraints or custom validation logic if necessary to ensure data integrity.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2b51595 and 62b007f.

Files selected for processing (29)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/src/risk-rules/consts/rule-set-depth-of-3-with-rules.ts (1 hunks)
  • services/workflows-service/src/risk-rules/consts/rule-set-parent-depth-3-with-policies.ts (1 hunks)
  • services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts (1 hunks)
  • services/workflows-service/src/risk-rules/json.json (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/schemas/create-risk-rule-policy-schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/schemas/update-risk-rule-policy-schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/connect-risk-rule-to-ruleset.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/copy-risk-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/create-risk-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/disconnect-risk-rule-to-ruleset.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/schemas/update-risk-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/create-rule-set.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/schemas/unassign-ruleset-from-parent.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/unassign-rule-from-rule-set.schema.ts (1 hunks)
Files skipped from review due to trivial changes (5)
  • services/workflows-service/prisma/data-migrations
  • services/workflows-service/src/risk-rules/consts/rule-set-depth-of-3-with-rules.ts
  • services/workflows-service/src/risk-rules/consts/rule-set-parent-depth-3-with-policies.ts
  • services/workflows-service/src/risk-rules/rule-set/schemas/create-rule-set.schema.ts
  • services/workflows-service/src/risk-rules/rule/rule.controller.ts
Files skipped from review as they are similar to previous changes (10)
  • services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts
  • services/workflows-service/src/risk-rules/json.json
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.repository.ts
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.service.ts
  • services/workflows-service/src/risk-rules/rule-set/rule-set.controller.ts
  • services/workflows-service/src/risk-rules/rule-set/rule-set.repository.ts
  • services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts
  • services/workflows-service/src/risk-rules/rule/rule.repository.ts
  • services/workflows-service/src/risk-rules/rule/rule.service.ts
Additional comments not posted (32)
services/workflows-service/src/risk-rules/risk-rule/schemas/update-risk-rule.schema.ts (1)

1-6: LGTM! Verify the CreateRiskRuleSchema definition.

The use of Type.Partial is appropriate for creating an update schema. Ensure that CreateRiskRuleSchema is correctly defined and comprehensive.

Verification successful

CreateRiskRuleSchema is comprehensive and correctly defined.

The CreateRiskRuleSchema includes both required and optional fields, making it suitable for use with Type.Partial in UpdateRiskRuleSchema. The schema is well-structured and covers all necessary aspects for defining a risk rule.

  • The schema includes fields such as name, riskRulePolicyId, operator, domain, indicator, riskLevel, baseRiskScore, additionalRiskScore, and optional fields like minRiskScore, maxRiskScore, and ruleSetId.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition of `CreateRiskRuleSchema`.

# Test: Search for the definition of `CreateRiskRuleSchema`. Expect: A valid schema definition.
ast-grep --lang typescript --pattern 'const CreateRiskRuleSchema = $_'

Length of output: 9662

services/workflows-service/src/risk-rules/rule/schemas/unassign-rule-from-rule-set.schema.ts (1)

1-9: Schema definition looks good.

The UnassignRuleFromRuleSetSchema is well-defined with a clear description for ruleSetId.

services/workflows-service/src/risk-rules/rule-set/schemas/unassign-ruleset-from-parent.schema.ts (1)

1-9: Schema definition looks good.

The UnassignRulesetFromParentSchema is well-defined with a clear description for parentRuleSetId.

services/workflows-service/src/risk-rules/risk-rule/schemas/connect-risk-rule-to-ruleset.schema.ts (1)

1-9: Schema definition looks good.

The schema for connecting a risk rule to a ruleset is well-defined with clear descriptions. The use of Type.String for ruleSetId is appropriate, and the type alias is correctly set up.

services/workflows-service/src/risk-rules/risk-rule-policy/schemas/create-risk-rule-policy-schema.ts (1)

1-10: Schema definition looks good.

The schema for creating a risk rule policy is well-defined with clear descriptions and examples. The use of Type.String for name is appropriate, and the type alias is correctly set up.

services/workflows-service/src/risk-rules/risk-rule/schemas/copy-risk-rule.schema.ts (1)

1-10: Schema definition looks good.

The schema for copying a risk rule is well-defined with clear descriptions and examples. The use of Type.String for newName is appropriate, and the type alias is correctly set up.

services/workflows-service/src/risk-rules/risk-rule/schemas/disconnect-risk-rule-to-ruleset.schema.ts (1)

1-9: Schema definition looks good.

The schema is well-defined with a clear description for ruleSetId. No issues found.

services/workflows-service/src/risk-rules/risk-rule-policy/schemas/update-risk-rule-policy-schema.ts (1)

1-12: Partial schema definition looks good.

The use of Type.Partial is appropriate for update operations, and the field name is well-documented with a description and example. No issues found.

services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts (1)

1-13: Module definition looks good.

The module is well-structured, importing necessary dependencies and correctly providing and exporting the service. No issues found.

services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts (6)

10-12: Ensure input validation for createRiskRulePolicy.

Consider validating the data object before passing it to the repository to prevent invalid data from being persisted.


14-18: Consider handling findById not found scenarios.

Although findFirstOrThrow will throw an error if no policy is found, consider catching this error to provide a more user-friendly message or handle it appropriately.


20-22: Ensure query arguments are validated in findMany.

Validate args and projectIds to ensure they contain valid data before querying the repository.


40-42: Consider handling deleteRiskRulePolicy not found scenarios.

Ensure that a meaningful error message is returned if the policy to be deleted does not exist.


44-46: Ensure validation for addRiskRuleToPolicy.

Validate policyId, riskRuleId, and projectIds to ensure they are correct before proceeding with the repository call.


24-38: Clarify public policy update restrictions in updateRiskRulePolicy.

The method prevents updates to public policies but doesn't log or notify why the update is restricted. Consider adding logging for such cases.

-      throw new BadRequestException('Cannot add risk rule to public policy');
+      throw new BadRequestException('Cannot update a public risk rule policy');

Likely invalid or redundant comment.

services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (4)

14-16: Consider adding validation in create.

Ensure that the data object is validated before attempting to create a new policy to prevent invalid data from being stored.


18-22: Ensure proper error handling in findById.

The method uses findFirstOrThrow, which throws an error if no policy is found. Consider catching this error to provide a more informative response.


24-28: Ensure query arguments are validated in findMany.

Validate args and projectIds to ensure they contain valid data before querying the database.


46-50: Ensure proper error handling in delete.

Ensure that a meaningful error message is returned if the policy to be deleted does not exist.

services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.controller.ts (5)

23-42: LGTM!

The createRiskRulePolicy method is well-implemented with appropriate validation and data handling.


44-57: LGTM!

The getRiskRulePolicy method is correctly implemented with proper validation and service interaction.


59-65: LGTM!

The listRiskRulePolicies method is well-implemented, efficiently retrieving policies with appropriate validation.


67-88: LGTM!

The updateRiskRulePolicy method is correctly implemented with appropriate validation and data handling.


90-105: LGTM!

The deleteRiskRulePolicy method is well-implemented, ensuring proper validation and service interaction for deletion.

services/workflows-service/src/risk-rules/risk-rule/risk-rule.controller.ts (8)

26-45: LGTM!

The createRiskRule method is well-implemented with appropriate validation and data handling.


48-61: LGTM!

The getRiskRule method is correctly implemented with proper validation and service interaction.


63-69: LGTM!

The listRiskRules method is well-implemented, efficiently retrieving rules with appropriate validation.


71-91: LGTM!

The updateRiskRule method is correctly implemented with appropriate validation and data handling.


94-106: LGTM!

The deleteRiskRule method is well-implemented, ensuring proper validation and service interaction for deletion.


109-135: LGTM!

The copyRiskRule method is well-implemented with appropriate validation and data handling for copying rules.


137-157: LGTM!

The connectRiskRuleToRuleset method is well-implemented, ensuring proper validation and service interaction for connecting rules to rulesets.


160-180: LGTM!

The disconnectRiskRuleFromRuleset method is well-implemented, ensuring proper validation and service interaction for disconnecting rules from rulesets.

Comment on lines +48 to +52
Type.String({
minimum: 0,
maximum: 100,
description: 'The ID of the ruleset to connect the risk rule to (optional)',
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

Clarify ruleSetId constraints.

The ruleSetId field has minimum and maximum properties, which are typically used for numbers. Ensure these constraints are intended for a string field.

-    Type.String({
-      minimum: 0,
-      maximum: 100,
-      description: 'The ID of the ruleset to connect the risk rule to (optional)',
-    }),
+    Type.String({
+      description: 'The ID of the ruleset to connect the risk rule to (optional)',
+    }),
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Type.String({
minimum: 0,
maximum: 100,
description: 'The ID of the ruleset to connect the risk rule to (optional)',
}),
Type.String({
description: 'The ID of the ruleset to connect the risk rule to (optional)',
}),

Comment on lines 52 to 69
async addRiskRule(
policyId: string,
riskRuleId: string,
projectIds: TProjectIds,
): Promise<RiskRulesPolicy> {
const policy = await this.findById(policyId, projectIds);
if (policy.isPublic) {
throw new BadRequestException('Cannot add risk rule to public policy');
}
return this.prisma.riskRulesPolicy.update({
where: { id: policyId },
data: {
riskRule: {
connect: { id: riskRuleId },
},
},
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider validation and logging in addRiskRule.

Validate policyId, riskRuleId, and projectIds to ensure they are correct before proceeding with the repository call. Also, consider logging attempts to add rules to public policies.

-      throw new BadRequestException('Cannot add risk rule to public policy');
+      throw new BadRequestException('Cannot add a risk rule to a public policy');

Committable suggestion was skipped due to low confidence.

Comment on lines 30 to 44
async update(
id: string,
data: Prisma.RiskRulesPolicyUncheckedUpdateInput,
projectId: TProjectId,
) {
const policy = await this.findById(id, [projectId]);
if (policy.isPublic) {
throw new BadRequestException('Cannot add risk rule to public policy');
}

return this.prisma.riskRulesPolicy.update({
where: { id },
data: data,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Clarify public policy update restrictions in update.

The method prevents updates to public policies but does not provide feedback on why the update is restricted. Consider adding logging or user feedback.

-      throw new BadRequestException('Cannot add risk rule to public policy');
+      throw new BadRequestException('Cannot update a public risk rule policy');
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async update(
id: string,
data: Prisma.RiskRulesPolicyUncheckedUpdateInput,
projectId: TProjectId,
) {
const policy = await this.findById(id, [projectId]);
if (policy.isPublic) {
throw new BadRequestException('Cannot add risk rule to public policy');
}
return this.prisma.riskRulesPolicy.update({
where: { id },
data: data,
});
}
async update(
id: string,
data: Prisma.RiskRulesPolicyUncheckedUpdateInput,
projectId: TProjectId,
) {
const policy = await this.findById(id, [projectId]);
if (policy.isPublic) {
throw new BadRequestException('Cannot update a public risk rule policy');
}
return this.prisma.riskRulesPolicy.update({
where: { id },
data: data,
});
}

* started mapping logic over rules

* feat: added format risk rule with policy

* feat: finished integration to stripe logic

* feat: fixed recursive types and structure
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 62b007f and ad7fa9c.

Files selected for processing (23)
  • packages/common/src/index.ts (1 hunks)
  • packages/common/src/rule-engine/index.ts (1 hunks)
  • packages/common/src/rule-engine/rules/types.ts (1 hunks)
  • packages/common/src/rule-engine/types.ts (3 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/prisma/migrations/20240813104622_create_risk_policy_and_rules/migration.sql (1 hunks)
  • services/workflows-service/prisma/schema.prisma (4 hunks)
  • services/workflows-service/src/app.module.ts (2 hunks)
  • services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/rule.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts (1 hunks)
  • services/workflows-service/src/risk-rules/types/types.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (3 hunks)
  • services/workflows-service/src/rule-engine/risk-rule.service.intg.test.ts (1 hunks)
  • services/workflows-service/src/rule-engine/risk-rule.service.ts (3 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.module.ts (1 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.service.ts (1 hunks)
  • services/workflows-service/src/workflow/workflow.service.ts (1 hunks)
Files skipped from review due to trivial changes (4)
  • packages/common/src/index.ts
  • packages/common/src/rule-engine/index.ts
  • services/workflows-service/prisma/data-migrations
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.service.ts
Files skipped from review as they are similar to previous changes (8)
  • services/workflows-service/prisma/schema.prisma
  • services/workflows-service/src/risk-rules/helpers/rule-set-search-and-flatten-values.ts
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.repository.ts
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts
  • services/workflows-service/src/risk-rules/rule-set/rule-set.controller.ts
  • services/workflows-service/src/risk-rules/rule-set/rule-set.service.ts
  • services/workflows-service/src/risk-rules/rule/rule.service.ts
  • services/workflows-service/src/risk-rules/rule/schemas/create-rule.schema.ts
Additional comments not posted (27)
services/workflows-service/src/rule-engine/rule-engine.service.ts (1)

7-10: LGTM! Verify compatibility with RuleSetWithChildren.

The change to accept RuleSetWithChildren enhances the flexibility of the run method. Ensure that the RuleEngine can process this new type correctly without issues.

Would you like me to help verify the compatibility of RuleEngine with RuleSetWithChildren?

services/workflows-service/src/rule-engine/rule-engine.module.ts (1)

5-8: LGTM! Verify integration of RiskRulePolicyModule.

The addition of RiskRulePolicyModule to the imports enhances the module's capabilities. Ensure that it is correctly integrated and utilized within the RuleEngineModule.

Would you like me to help verify the integration of RiskRulePolicyModule within the module?

packages/common/src/rule-engine/rules/types.ts (1)

13-17: LGTM! Verify usage of RuleSetWithChildren.

The introduction of RuleSetWithChildren allows for nested rule structures, enhancing the rule engine's expressiveness. Ensure that all parts of the system interacting with rule sets can handle this new structure.

Would you like me to help verify the usage of RuleSetWithChildren across the system?

packages/common/src/rule-engine/types.ts (4)

28-31: LGTM!

The TNotionRulesOptions type is correctly defined with appropriate properties.


33-36: LGTM!

The TDatabaseRulesOptions type is correctly defined with appropriate properties.


38-38: LGTM! Verify the usage of the union type.

The TFindAllRulesOptions type is effectively redefined as a union, improving clarity.

Ensure that the union type is used correctly throughout the codebase.

Verification successful

Usage of TFindAllRulesOptions is Correct Across the Codebase

The TFindAllRulesOptions type is used in several files, indicating that it is integrated into the codebase. Here are some locations where it appears:

  • packages/workflow-core/src/lib/plugins/common-plugin/types.ts: Used in type definitions for rulesSource and ruleOptions.
  • services/workflows-service/src/workflow/workflow.service.ts: Used for ruleStoreServiceOptions.
  • services/workflows-service/src/rule-engine/risk-rule.service.ts: Appears in type definitions.

These usages suggest that the union type is correctly applied in various parts of the codebase, ensuring flexibility and clarity.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `TFindAllRulesOptions` type in the codebase.

# Test: Search for the type usage. Expect: Correct usage of the union type.
rg --type typescript 'TFindAllRulesOptions'

Length of output: 78


Script:

#!/bin/bash
# Description: Verify the usage of `TFindAllRulesOptions` type in the codebase.

# Test: Search for the type usage in TypeScript files.
rg 'TFindAllRulesOptions' --glob '*.ts'

Length of output: 1059


12-16: LGTM! Verify the type usage in the codebase.

The RuleSetWithChildren type is well-defined for nested rule structures.

Ensure that its usage is consistent and correct throughout the codebase.

Verification successful

Verification Successful: Consistent Usage of RuleSetWithChildren

The RuleSetWithChildren type is used consistently across the codebase to handle nested rule structures. Here are some key locations where it is utilized:

  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts
  • services/workflows-service/src/rule-engine/rule-engine.service.ts
  • services/workflows-service/src/rule-engine/core/rule-engine.ts

These usages align with the intended design of the type. No issues were found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `RuleSetWithChildren` type in the codebase.

# Test: Search for the type usage. Expect: Consistent and correct usage.
rg --type typescript 'RuleSetWithChildren'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify the usage of `RuleSetWithChildren` type in the codebase.

# Test: Search for the type usage. Expect: Consistent and correct usage.
rg --type ts 'RuleSetWithChildren'

Length of output: 2060

services/workflows-service/src/risk-rules/types/types.ts (7)

11-13: LGTM!

The RiskRuleWithPolicy type is correctly defined, allowing for an optional policy association.


15-17: LGTM!

The RiskRuleRuleSetWithRule type is correctly defined, enabling associations with risk rules and policies.


19-21: LGTM!

The RuleSetWithRiskRules type is correctly defined, facilitating the linkage of rule sets with risk rules.


23-25: LGTM!

The RiskRuleWithRuleSet type is correctly defined, supporting the association of risk rules with rule sets.


27-30: LGTM!

The RuleSetWithChildrenAndRules type is correctly defined, enabling complex nested structures.


32-34: LGTM!

The RulesetToRuleWithChild type is correctly defined, supporting hierarchical relationships.


40-52: LGTM!

The RuleSetWithParent type is correctly defined, enabling recursive parent-child relationships.

services/workflows-service/src/rule-engine/risk-rule.service.intg.test.ts (1)

20-20: Verify the completeness of the test case with projectIds.

The addition of projectIds as an empty array in the test setup suggests an expansion of test coverage. Ensure that scenarios with non-empty projectIds are also tested if applicable.

Verification successful

Test coverage for projectIds is adequate.

The test suite includes scenarios with non-empty projectIds, ensuring that relevant cases are covered.

  • services/workflows-service/src/workflow/workflow.controller.internal.intg.test.ts contains a test with projectIds: [project.id].
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage and testing of `projectIds` in the codebase.

# Test: Search for other test cases involving `projectIds`. Expect: Comprehensive test coverage.
rg --type typescript 'projectIds'

Length of output: 68


Script:

#!/bin/bash
# Description: Verify the usage and testing of `projectIds` in the codebase.

# Test: Search for other test cases involving `projectIds`. Expect: Comprehensive test coverage.
rg --type ts 'projectIds'

Length of output: 81430


Script:

#!/bin/bash
# Description: Search for test cases that involve non-empty `projectIds`.

# Test: Search for test cases with non-empty `projectIds` to ensure comprehensive test coverage.
rg --type ts 'projectIds: \[.+\]' --glob '*test*.ts'

Length of output: 170

services/workflows-service/src/rule-engine/core/rule-engine.ts (2)

14-16: Ensure type guard correctness.

The isRulesetWithChildren function correctly checks for the presence of the childRuleSet property. This is a simple and effective way to implement a type guard.


47-66: Verify recursive processing logic.

The runRuleSet function now supports RuleSetWithChildren, allowing for recursive processing of nested rule sets. Ensure that this logic is thoroughly tested, especially with complex nested structures, to avoid stack overflow or performance issues.

services/workflows-service/src/rule-engine/risk-rule.service.ts (3)

7-7: New service dependency added.

The RiskRulePolicyService is added as a dependency, which suggests expanded functionality. Ensure that the service is correctly configured and utilized.


46-54: Type definition updated to union type.

The TFindAllRulesOptions has been updated to a union type, allowing for different sources. This change enhances flexibility but ensure that all branches are covered in logic and tests.


Line range hint 66-118: Enhanced filtering in findAll method.

The findAll method now supports filtering by projectIds when the source is 'database'. Ensure that this logic is tested for different scenarios, including edge cases with empty or large lists of project IDs.

services/workflows-service/src/app.module.ts (2)

50-54: New risk-related modules imported.

The imports for RiskRulePolicyModule, RuleModule, RiskRuleModule, and RuleSetModule indicate expanded functionality. Ensure that these modules are correctly configured and integrated into the application.


133-137: Modules integrated into application.

The new risk-related modules are integrated into the AppModule. Verify that their configurations align with the application's overall architecture and dependencies.

Verification successful

Modules are correctly imported and used in the application.

The modules RiskRulePolicyModule, RiskRuleModule, RuleSetModule, and RuleModule are correctly imported and integrated within the application. They are used in various parts of the codebase, indicating proper configuration and usage.

  • The modules are declared as classes, confirming their existence.
  • They are imported into other modules, such as RuleEngineModule, indicating integration into the application's architecture.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct configuration and integration of new modules.

# Test: Search for configurations of the new modules. Expect: Proper configuration and usage.
rg --type typescript -A 5 $'RiskRulePolicyModule|RuleModule|RiskRuleModule|RuleSetModule'

Length of output: 125


Script:

#!/bin/bash
# Description: Verify correct configuration and integration of new modules.

# Find all TypeScript files and search for configurations of the new modules.
fd --extension ts --exec rg -A 5 'RiskRulePolicyModule|RuleModule|RiskRuleModule|RuleSetModule'

Length of output: 1285

services/workflows-service/prisma/migrations/20240813104622_create_risk_policy_and_rules/migration.sql (4)

1-8: Enums Creation Approved.

The enums IndicatorRiskLevel, RuleEngine, and RulesetOperator are well-defined and cover necessary categories.


10-110: Tables Creation Approved.

The tables are well-structured with appropriate primary keys and fields. The use of JSONB in the Rule table is suitable for flexible data storage.


112-152: Indexes Creation Approved.

The indexes are appropriately placed to optimize query performance, especially for foreign keys and unique constraints.


154-185: Foreign Keys Creation Approved.

The foreign key constraints are correctly defined to ensure referential integrity across related tables.

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

1967-1969: Method Signature Update Approved.

The addition of projectIds and shouldThrowOnValidation enhances control over rule retrieval.

Ensure that all calls to findAll in riskRuleService are updated to match the new signature.

Comment on lines +95 to +98
export const RuleEngine = (
ruleSets: RuleSet | RuleSetWithChildren,
helpers?: typeof OperationHelpers,
) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider dependency injection for helpers.

The RuleEngine function mentions a TODO for injecting helpers. Consider using dependency injection to manage helpers, which can improve testability and maintainability.

// Example: Inject helpers using a dependency injection framework or pattern.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ad7fa9c and 1d56a23.

Files selected for processing (6)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.controller.ts (1 hunks)
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts (1 hunks)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.module.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (3 hunks)
Files skipped from review due to trivial changes (1)
  • services/workflows-service/src/risk-rules/rule-set/rule-set.module.ts
Files skipped from review as they are similar to previous changes (5)
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.module.ts
  • services/workflows-service/src/risk-rules/risk-rule-policy/risk-rule-policy.service.ts
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.controller.ts
  • services/workflows-service/src/risk-rules/risk-rule/risk-rule.module.ts
  • services/workflows-service/src/rule-engine/core/rule-engine.ts

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