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

bal 1880 ongoing moitoring alerts #2303

Closed
wants to merge 14 commits into from
Closed

Conversation

liorzam
Copy link
Collaborator

@liorzam liorzam commented Apr 15, 2024

User description

Curl command:

curl --location --globoff 'http://localhost:3000/api/v1/external/alerts/business-report?page[number]=1&page[size]=10' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer secret' 

Type

Enhancement, Tests


Description

  • Introduced new alert definitions for transaction and merchant monitoring in generate-alerts.ts.
  • Updated the seeding script to utilize new alert generation functions for different monitoring types.
  • Added new API endpoints in alert.controller.external.ts for fetching transaction and merchant monitoring alerts.
  • Enhanced alert service in alert.service.ts to handle alert queries based on monitoring type.
  • Created a new business report controller and service methods to support fetching reports with filters.

Changes walkthrough

Relevant files
Enhancement
generate-alerts.ts
Enhance Alert Definitions and Seeding Logic                           

services/workflows-service/scripts/alerts/generate-alerts.ts

  • Introduced new alert definitions for transaction monitoring and
    merchant monitoring.
  • Added new types and constants for monitoring types.
  • Modified functions to support the creation and seeding of alerts based
    on the new definitions.
  • +104/-25
    seed.ts
    Update Seeding Script with New Alert Functions                     

    services/workflows-service/scripts/seed.ts

  • Updated the seeding script to use the new alert seeding function.
  • Removed old alert generation calls and replaced them with new function
    calls for transaction and merchant monitoring alerts.
  • +9/-9     
    alert.controller.external.ts
    Implement API Endpoints for Different Types of Alerts       

    services/workflows-service/src/alert/alert.controller.external.ts

  • Added new API endpoint for business report alerts with specific types
    and response structures.
  • Adjusted existing alert listing endpoint to filter by transaction
    monitoring type.
  • +108/-34
    alert.service.ts
    Refactor Alert Service to Support Monitoring Types             

    services/workflows-service/src/alert/alert.service.ts

  • Modified the getAlerts method to accept a monitoring type parameter to
    differentiate alert queries.
  • Adjusted the alert creation method to include monitoring type and
    additional details.
  • +6/-3     
    business-report.controller.ts
    Add Business Report Controller and Fetch Endpoint               

    services/workflows-service/src/business-report/business-report.controller.ts

  • Created a new controller for handling business reports.
  • Implemented an endpoint to fetch business reports with various
    filters.
  • +54/-0   
    business-report.service.ts
    Implement Business Report Fetching Logic in Service           

    services/workflows-service/src/business-report/business-report.service.ts

  • Implemented service methods to fetch business reports with filtering
    capabilities.
  • +87/-0   

    PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Summary by CodeRabbit

    • New Features

      • Introduced enhanced alert monitoring capabilities, including transaction and business report monitoring.
      • Added new alert response types for more detailed information on transactions and merchants.
    • Enhancements

      • Improved the alert listing method to support new monitoring types and provide more specific alert details.
    • Documentation

      • Updated internal documentation to reflect changes in alert handling and response structures.

    Copy link

    changeset-bot bot commented Apr 15, 2024

    ⚠️ No Changeset found

    Latest commit: e2f6810

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

    This PR includes no changesets

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

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

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

    Copy link
    Contributor

    coderabbitai bot commented Apr 15, 2024

    Walkthrough

    The recent updates focus on enhancing the alert management system in the workflows service. New types for different monitoring scenarios were introduced, along with specific methods to handle transaction and business report alerts. These changes aim to refine data handling and response structuring for better clarity and functionality in alert processing.

    Changes

    File Path Change Summary
    .../src/alert/alert.controller.external.ts Added types and methods for handling transaction and business report alerts.
    .../src/alert/types.ts Introduced new response types and updated existing ones with additional fields.

    🐇💻✨
    In the garden of code, under the moon's glow,
    A rabbit hops along, tweaking as it goes.
    With a flick of its ear, new changes are sown,
    Alerts refined, with clarity now shown.
    Celebrate the craft, for progress we owe! 🌟
    🥕🎉


    Recent Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between 13f68bb and e2f6810.
    Files selected for processing (2)
    • services/workflows-service/src/alert/alert.controller.external.ts (3 hunks)
    • services/workflows-service/src/alert/types.ts (2 hunks)
    Files skipped from review as they are similar to previous changes (1)
    • services/workflows-service/src/alert/alert.controller.external.ts
    Additional comments not posted (2)
    services/workflows-service/src/alert/types.ts (2)

    28-28: LGTM! The addition of counterparty in TAlertTransactionResponse enhances the detail and specificity of transaction-related alerts.


    35-37: LGTM! The structured addition of business in TAlertMerchantResponse aligns well with the intended enhancements for merchant monitoring.


    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.

    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 a review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai help to get help.

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

    CodeRabbit Configration 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.

    @github-actions github-actions bot added enhancement New feature or request Tests labels Apr 15, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (6fe5693)

    Copy link
    Contributor

    github-actions bot commented Apr 15, 2024

    PR Review

    (Review updated until commit 6fe5693)

    ⏱️ Estimated effort to review [1-5]

    4, because the PR introduces significant changes across multiple files including new alert definitions, API endpoints, and data seeding scripts. The complexity and breadth of changes require careful review to ensure functionality and integration with existing systems.

    🧪 Relevant tests

    No

    🔍 Possible issues

    Possible Bug: The generateFakeAlert function in generate-alerts.ts might not correctly handle cases where neither businessIds nor counterpartyIds are provided, potentially leading to incomplete alert data.

    Data Integrity: The changes in alert generation logic and the introduction of new types and constants could affect existing functionalities if not properly integrated and tested.

    🔒 Security concerns

    No

    Code feedback:
    relevant fileservices/workflows-service/scripts/alerts/generate-alerts.ts
    suggestion      

    Consider adding a default case or error handling in the generateFakeAlert function to manage scenarios where neither businessIds nor counterpartyIds are provided. This will enhance the robustness of the alert generation process. [important]

    relevant linelet businessId: { businessId: string } | {} = {};

    relevant fileservices/workflows-service/src/alert/alert.controller.external.ts
    suggestion      

    Refactor the repeated code blocks in the list and listBusniessReportAlerts methods into a private helper method to improve code maintainability and reduce redundancy. [important]

    relevant lineconst alerts = await this.alertService.getAlerts(

    relevant fileservices/workflows-service/src/alert/alert.service.ts
    suggestion      

    Implement input validation for the monitoringType parameter in the getAlerts method to ensure it receives valid enum values, enhancing the method's reliability and security. [important]

    relevant linemonitoringType: MonitoringType,

    relevant fileservices/workflows-service/src/business-report/business-report.service.ts
    suggestion      

    Optimize the findManyWithFilters method by extracting the date manipulation logic into a separate utility function, which can be reused across different services or methods. This change will improve code organization and testing. [medium]

    relevant lineconst pastDate = new Date(now.getTime() - subtractValue);


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible PR issues, security threats and relevant test in the PR. More feedbacks can be added by configuring the tool.

    The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.

    • When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:
    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    
    [pr_reviewer]
    some_config1=...
    some_config2=...
    

    See the review usage page for a comprehensive guide on using this tool.

    Copy link
    Contributor

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Add a meaningful description to the alert definition.

    Ensure that the description field for the MRCNT_RISK alert definition is not left as an
    empty string. Providing a meaningful description can help in understanding the purpose and
    context of the alert.

    services/workflows-service/scripts/alerts/generate-alerts.ts [340]

    -description: '',
    +description: 'Monitors ongoing merchant risk based on specific criteria.',
     
    Make the monitoring type dynamic to increase flexibility.

    Replace the hardcoded monitoring type with a parameter or a more dynamic approach to allow
    flexibility in assigning different monitoring types to different alerts.

    services/workflows-service/scripts/alerts/generate-alerts.ts [364]

    -monitoringType = MonitoringType.transaction_monitoring,
    +monitoringType = defaultMonitoringType,
     
    Enhance validation for query parameters in the getBusinessReport method.

    To enhance API security and usability, consider adding explicit validation rules for all
    query parameters in the getBusinessReport method using class-validator decorators.

    services/workflows-service/src/business-report/business-report.controller.ts [49]

    -@Query() queryParameters: GetBusinessReportDto,
    +@Query() @ValidateNested() @Type(() => GetBusinessReportDto) queryParameters: GetBusinessReportDto,
     
    Reliability
    Add error handling for alert definition generation to improve reliability.

    Consider adding error handling for the generateAlertDefinitions function calls within the
    seedTransactionsAlerts function to manage potential failures in alert definition
    generation.

    services/workflows-service/scripts/alerts/generate-alerts.ts [494]

     const transactionsAlertDef = await generateAlertDefinitions(prisma, {
    +  try {
    +    // existing code
    +  } catch (error) {
    +    console.error('Failed to generate transaction alert definitions:', error);
    +  }
     
    Maintainability
    Refactor the ID generation in generateFakeAlert to improve code modularity.

    Refactor the generateFakeAlert function to separate concerns by creating dedicated
    functions for generating business and counterparty IDs.

    services/workflows-service/scripts/alerts/generate-alerts.ts [446-452]

    -if ('businessIds' in options) {
    +businessId = generateBusinessId(options);
    +counterpartyId = generateCounterpartyId(options);
     
    +function generateBusinessId(options) {
    +  if ('businessIds' in options) {
    +    return faker.helpers.arrayElement(options.businessIds.map(id => ({ businessId: id })));
    +  }
    +  return {};
    +}
    +
    +function generateCounterpartyId(options) {
    +  if ('counterpartyIds' in options) {
    +    return faker.helpers.arrayElement(options.counterpartyIds.map(id => ({ counterpartyId: id })));
    +  }
    +  return {};
    +}
    +
    Refactor the spread operation into a utility function for merging subject entries.

    To improve code readability and maintainability, consider using a type guard or utility
    function to handle the spread operation with the subject array in the
    createExecutionDetails method.

    services/workflows-service/src/alert/alert.service.ts [247]

    -subject: Object.assign({}, ...(subject || [])),
    +subject: mergeSubjects(subject), // Assuming mergeSubjects is a utility function that safely merges subject entries
     
    Use a common base interface for TAlertTransactionResponse and TAlertMerchantResponse to reduce duplication.

    For the TAlertMerchantResponse and TAlertTransactionResponse types, consider adding a
    common base type or interface if there are shared properties or methods to reduce
    duplication and improve maintainability.

    services/workflows-service/src/alert/types.ts [28-37]

    -export type TAlertTransactionResponse = TAlertResponse & {
    -export type TAlertMerchantResponse = TAlertResponse & {
    +interface IAlertResponseBase extends TAlertResponse {
    +  // common properties or methods
    +}
    +export type TAlertTransactionResponse = IAlertResponseBase & {
    +export type TAlertMerchantResponse = IAlertResponseBase & {
     
    Best practice
    Correct the API response type annotation to match the returned data structure.

    Update the API response type annotation to reflect the actual data structure returned by
    the list method, ensuring that the API documentation is accurate.

    services/workflows-service/src/alert/alert.controller.external.ts [55]

    -@swagger.ApiOkResponse({ type: Array<TAlertTransactionResponse> }) // TODO: Set type
    +@swagger.ApiOkResponse({ type: Array<TAlertResponse> })
     
    Add validation for the monitoringType parameter in the getAlerts method.

    Consider validating the monitoringType parameter in the getAlerts method to ensure it is a
    valid enum type of MonitoringType. This can prevent potential issues when invalid values
    are passed to the method.

    services/workflows-service/src/alert/alert.service.ts [74]

    -monitoringType: MonitoringType,
    +monitoringType: MonitoringType, // Ensure monitoringType is a valid enum value
     
    Add error handling in the findManyWithFilters method to improve error management.

    Consider adding error handling for the findManyWithFilters method to manage exceptions
    that may occur during database operations, improving the robustness of the service.

    services/workflows-service/src/business-report/business-report.service.ts [47]

    -return await this.repository.findMany(
    +try {
    +  return await this.repository.findMany(
    +} catch (error) {
    +  this.logger.error('Failed to fetch business reports', { error });
    +  throw new Error('Error fetching business reports');
    +}
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    • When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:
    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    
    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    

    See the improve usage page for a comprehensive guide on using this tool.

    @github-actions github-actions bot added bug_fix and removed Tests labels Apr 15, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (6fe5693)

    @github-actions github-actions bot added the Tests label Apr 15, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (6fe5693)

    Copy link
    Contributor

    Persistent review updated to latest commit 6fe5693

    Copy link
    Contributor

    Persistent review updated to latest commit 6fe5693

    Copy link
    Contributor

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Add a default description for merchant monitoring alerts to enhance clarity.

    Consider adding a default value for the description field in the
    MERCHANT_MONITORING_ALERT_DEFINITIONS to avoid empty descriptions which might not be
    informative for monitoring purposes.

    services/workflows-service/scripts/alerts/generate-alerts.ts [340]

    -description: '',
    +description: 'Default description for merchant risk monitoring',
     
    Ensure alert descriptions are meaningful and not empty.

    Ensure that the description field in the MERCHANT_MONITORING_ALERT_DEFINITIONS is not left
    empty to provide meaningful context about the alert.

    services/workflows-service/scripts/alerts/generate-alerts.ts [340]

    -description: '',
    +description: 'Provides ongoing monitoring of merchant risk levels.',
     
    Include the monitoringType parameter in the query logic of the getAlerts method.

    The monitoringType parameter is added to the getAlerts method but is not used in the
    method's logic. If it's intended to filter alerts by monitoring type, it should be
    included in the query logic.

    services/workflows-service/src/alert/alert.service.ts [74]

     monitoringType: MonitoringType,
    +// Example usage in a query
    +this.alertRepository.findMany({
    +  where: {
    +    monitoringType
    +  }
    +});
     
    Simplify date manipulation using date-fns library in findManyWithFilters.

    The findManyWithFilters method uses a complex logic for date filtering which can be
    simplified using a library like date-fns to handle date manipulations, improving code
    readability and reliability.

    services/workflows-service/src/business-report/business-report.service.ts [81-99]

    -const now = new Date(); // UTC time by default
    -let subtractValue = 0;
    +import { subMonths, subYears } from 'date-fns';
    +const pastDate = subMonths(new Date(), filterParams.timeValue);
     
    Best practice
    Add error handling for database operations in generateAlertDefinitions.

    It's recommended to handle potential exceptions when performing database operations such
    as upsert within generateAlertDefinitions. This can be achieved by wrapping the
    Promise.all call in a try-catch block.

    services/workflows-service/scripts/alerts/generate-alerts.ts [414-417]

    -Promise.all(
    -    Object.entries(alertsDefConfiguration)
    -        .filter(([_, alert]) => 'enabled' in alert && alert.enabled)
    -        .map(([label, data]) =>
    -            prisma.alertDefinition.upsert({
    +try {
    +  await Promise.all(
    +      Object.entries(alertsDefConfiguration)
    +          .filter(([_, alert]) => 'enabled' in alert && alert.enabled)
    +          .map(([label, data]) =>
    +              prisma.alertDefinition.upsert({
    +  ));
    +} catch (error) {
    +  console.error('Failed to upsert alert definitions:', error);
    +}
     
    Replace Object.assign with the spread operator for merging objects.

    The use of Object.assign for merging subject into the executionRow object is redundant
    since the spread operator can achieve the same result with better readability and
    performance.

    services/workflows-service/src/alert/alert.service.ts [247]

    -subject: Object.assign({}, ...(subject || [])),
    +subject: {...(subject || [])},
     
    Add validation to query parameters in the getBusinessReport method.

    The getBusinessReport method uses @Query() to bind query parameters but does not validate
    them. Consider using @Query() queryParameters: GetBusinessReportDto with class-validator
    decorators to ensure the parameters meet expected formats and types.

    services/workflows-service/src/business-report/business-report.controller.ts [49]

     @Query() queryParameters: GetBusinessReportDto,
    +// Ensure GetBusinessReportDto includes necessary validation decorators
     
    Maintainability
    Refactor generateFakeAlert to improve code maintainability and readability.

    To improve the maintainability and readability of the code, consider refactoring the
    generateFakeAlert function to separate the logic for generating businessId and
    counterpartyId into smaller, more focused functions.

    services/workflows-service/scripts/alerts/generate-alerts.ts [443-453]

    -let businessId: { businessId: string } | {} = {};
    -let counterpartyId: { counterpartyId: string } | {} = {};
    -if ('businessIds' in options) {
    -    businessId = faker.helpers.arrayElement(options.businessIds.map(id => ({ businessId: id })));
    -} else if ('counterpartyIds' in options) {
    -    counterpartyId = faker.helpers.arrayElement(
    -        options.counterpartyIds.map(id => ({ counterpartyId: id })),
    -    );
    +let businessId = generateBusinessId(options);
    +let counterpartyId = generateCounterpartyId(options);
    +
    +function generateBusinessId(options) {
    +  return 'businessIds' in options ? faker.helpers.arrayElement(options.businessIds.map(id => ({ businessId: id }))) : {};
     }
     
    +function generateCounterpartyId(options) {
    +  return 'counterpartyIds' in options ? faker.helpers.arrayElement(options.counterpartyIds.map(id => ({ counterpartyId: id }))) : {};
    +}
    +
    Bug
    Initialize arrays to prevent runtime errors due to undefined values.

    To avoid potential runtime errors, ensure that the businessIds and counterpartyIds are
    provided and not undefined before they are used in the seedTransactionsAlerts function.

    services/workflows-service/scripts/alerts/generate-alerts.ts [489-490]

    -businessIds: string[];
    -counterpartyIds: string[];
    +businessIds: string[] = [];
    +counterpartyIds: string[] = [];
     
    Possible issue
    Adjust the inheritance of TAlertTransactionResponse and TAlertMerchantResponse to correctly reflect optional fields.

    The TAlertTransactionResponse and TAlertMerchantResponse types are extended from
    TAlertResponse but do not include the counterparty field which is part of the original
    TAlertResponse. Consider if this field should be optional or removed from the base type if
    not universally applicable.

    services/workflows-service/src/alert/types.ts [28-37]

    -export type TAlertTransactionResponse = TAlertResponse & {
    +export type TAlertTransactionResponse = Omit<TAlertResponse, 'counterparty'> & {
     business: Pick<Business, 'id' | 'companyName'>;
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    • When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:
    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    
    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    

    See the improve usage page for a comprehensive guide on using this tool.

    Copy link
    Contributor

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Initialize the description field with a default value.

    Consider initializing the description field with a meaningful default value instead of an
    empty string to provide more context about the alert definition.

    services/workflows-service/scripts/alerts/generate-alerts.ts [340]

    -description: '',
    +description: 'Default description for ongoing merchant monitoring',
     
    Simplify object merging using the spread operator for better readability and performance.

    Consider using TypeScript's utility types for better type safety and maintainability.
    Instead of using Object.assign({}, ...(subject || [])), you can use the spread operator
    directly if subject is guaranteed to be an array or undefined. This makes the code cleaner
    and avoids unnecessary complexity.

    services/workflows-service/src/alert/alert.service.ts [247]

    -subject: Object.assign({}, ...(subject || [])),
    +subject: {...(subject || {})},
     
    Maintainability
    Use a more descriptive variable name for clarity.

    It's recommended to use a more descriptive variable name than id for the inlineRule to
    enhance code readability and maintainability.

    services/workflows-service/scripts/alerts/generate-alerts.ts [342]

    -id: 'MRCNT_RISK',
    +ruleId: 'MRCNT_RISK',
     
    Extract complex date calculation logic into a utility function to enhance code readability and maintainability.

    The method findManyWithFilters uses a complex logic to adjust the date based on timeUnit
    and timeValue. This logic can be extracted into a separate utility function to improve the
    readability and reusability of the code.

    services/workflows-service/src/business-report/business-report.service.ts [80-105]

     if (filterParams.timeValue && filterParams.timeUnit) {
    -  const now = new Date(); // UTC time by default
    -  let subtractValue = 0;
    -  switch (filterParams.timeUnit) {
    -    case TIME_UNITS.minutes:
    -      subtractValue = filterParams.timeValue * 60 * 1000;
    -      break;
    -    case TIME_UNITS.hours:
    -      subtractValue = filterParams.timeValue * 60 * 60 * 1000;
    -      break;
    -    case TIME_UNITS.days:
    -      subtractValue = filterParams.timeValue * 24 * 60 * 60 * 1000;
    -      break;
    -    case TIME_UNITS.months:
    -      now.setMonth(now.getMonth() - filterParams.timeValue);
    -      break;
    -    case TIME_UNITS.years:
    -      now.setFullYear(now.getFullYear() - filterParams.timeValue);
    -      break;
    -  }
    -  const pastDate = new Date(now.getTime() - subtractValue);
    +  const pastDate = calculatePastDate(filterParams.timeUnit, filterParams.timeValue);
       whereClause.createdAt = { gte: pastDate };
     }
     
    Robustness
    Add validation for empty ID arrays in alert generation.

    To improve the robustness of the alert generation logic, consider adding validation or
    error handling for cases where businessIds or counterpartyIds might be empty arrays.

    services/workflows-service/scripts/alerts/generate-alerts.ts [446-453]

    -if ('businessIds' in options) {
    +if ('businessIds' in options && options.businessIds.length > 0) {
       businessId = faker.helpers.arrayElement(options.businessIds.map(id => ({ businessId: id })));
    -} else if ('counterpartyIds' in options) {
    +} else if ('counterpartyIds' in options && options.counterpartyIds.length > 0) {
       counterpartyId = faker.helpers.arrayElement(
         options.counterpartyIds.map(id => ({ counterpartyId: id })),
       );
    +} else {
    +  throw new Error('No valid IDs provided for alert generation.');
     }
     
    Add null-check for project parameter to prevent runtime errors.

    To avoid potential runtime errors from null or undefined values, ensure that the project
    parameter is validated or handled properly before usage.

    services/workflows-service/scripts/alerts/generate-alerts.ts [396]

    -projectId: project.id,
    +projectId: project?.id ?? 'defaultProjectId',
     
    Best practice
    Require explicit monitoringType for better clarity.

    To ensure that the monitoringType field is always explicitly set and understood, consider
    removing the default value and requiring it to be provided explicitly when creating alert
    definitions.

    services/workflows-service/scripts/alerts/generate-alerts.ts [364]

    -monitoringType = MonitoringType.transaction_monitoring,
    +monitoringType: MonitoringType,
     
    Add error handling in the getBusinessReport method to manage exceptions and improve reliability.

    The getBusinessReport method currently does not handle any potential exceptions that might
    occur during the execution of findManyWithFilters. It's a good practice to add error
    handling, such as try-catch blocks, to manage exceptions and provide meaningful error
    messages to the client.

    services/workflows-service/src/business-report/business-report.controller.ts [48-53]

     async getBusinessReport(
       @Query() queryParameters: GetBusinessReportDto,
       @CurrentProject() projectId: types.TProjectId,
     ) {
    -  return this.service.findManyWithFilters(queryParameters, projectId);
    +  try {
    +    return await this.service.findManyWithFilters(queryParameters, projectId);
    +  } catch (error) {
    +    this.logger.error('Failed to get business report', { error });
    +    throw new HttpException('Failed to fetch business report', HttpStatus.INTERNAL_SERVER_ERROR);
    +  }
     }
     
    Possible issue
    Use more specific type assertions to ensure data integrity and avoid runtime errors.

    The type assertion as InputJsonValue might be too broad and could lead to runtime errors
    if the object structure doesn't match the expected schema. It's better to define a more
    precise type or interface that reflects the expected structure of TExecutionDetails.

    services/workflows-service/src/alert/alert.service.ts [249]

    -} satisfies TExecutionDetails as InputJsonValue,
    +} satisfies TExecutionDetails,
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    • When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:
    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    
    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    

    See the improve usage page for a comprehensive guide on using this tool.

    Comment on lines +24 to +28
    | {
    // since we don't know the other options, we can use never
    fnName: unknown;
    options: never;
    }
    Copy link
    Collaborator

    Choose a reason for hiding this comment

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

    Why? I think it's better to remove it, so we'll have an exhaustive list for now.

    Copy link
    Collaborator Author

    Choose a reason for hiding this comment

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

    same response:
    #2303 (comment)

    Comment on lines -42 to -50
    // Used for exhaustive check
    inlineRule satisfies never;
    Copy link
    Collaborator

    Choose a reason for hiding this comment

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

    This line is important to verify we didn't miss any function. I think it's better you'll revert this line removal.

    Copy link
    Collaborator Author

    @liorzam liorzam May 5, 2024

    Choose a reason for hiding this comment

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

    It just allow TS show the rest of the code as relevant instead of such a gray which it wont get this section
    image

    Copy link
    Collaborator Author

    Choose a reason for hiding this comment

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

    with my type changes its looks like that...
    image

    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

    Out of diff range and nitpick comments (11)
    services/workflows-service/src/alert/dtos/create-alert-definition.dto.ts (2)

    Line range hint 9-9: The example values provided in @ApiProperty should be replaced with actual values before deployment.


    Line range hint 25-25: Consider providing a specific type for options in the evaluateRiskScore case to ensure type safety.

    - options?: undefined;
    + options: RiskScoreOptions;
    services/workflows-service/src/transaction/transaction.service.ts (1)

    Line range hint 38-59: Ensure that the error handling in createBulk method logs all errors, not just unique constraint errors.

    - this.sentry.captureException(errorToLog);
    + this.sentry.captureException(error);
    services/workflows-service/src/transaction/transaction.mapper.ts (3)

    Line range hint 14-14: Consider improving type safety for additionalInfo casting.

    - additionalInfo: (dto.additionalInfo ?? null) as unknown as InputJsonValue,
    + additionalInfo: dto.additionalInfo ? JSON.parse(dto.additionalInfo) : null,

    Line range hint 14-14: Refine error messages for clarity in getCounterpartyCreateInput.

    - throw new HttpException('Counterparty must have either business or end user data.', 400);
    + throw new HttpException('Counterparty must have business data.', 400);
    - throw new HttpException('Counterparty must have either business or end user data.', 400);
    + throw new HttpException('Counterparty must not have both business and end user data.', 400);

    Line range hint 14-14: Add error handling for required fields in altDtoToOriginalDto.

    + if (!altDto.tx_id || !altDto.tx_amount) {
    +   throw new Error('Required fields tx_id and tx_amount are missing.');
    + }
    services/workflows-service/scripts/alerts/generate-alerts.ts (2)

    Line range hint 14-14: Consider externalizing configuration values in TRANSACTIONS_ALERT_DEFINITIONS.


    Line range hint 14-14: Add error handling for Prisma operations in generateAlertDefinitions.

    services/workflows-service/src/transaction/transaction.controller.external.intg.test.ts (3)

    Line range hint 14-14: Add more detailed assertions to verify transaction data in the test case creates a transaction with business originator and end user beneficiary.


    Line range hint 14-14: Expand the test case to cover more types of validation errors in returns 400 when validation fails.


    Line range hint 14-14: Refine the error message for clarity in the test case returns 400 when counterparty is missing from the body.

    - message: 'Originator and beneficiary are required.',
    + message: 'Transaction request must include both originator and beneficiary data.',

    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

    Out of diff range and nitpick comments (1)
    services/workflows-service/scripts/alerts/generate-alerts.ts (1)

    433-445: Add a meaningful description to the MRCNT_RISK alert definition in MERCHANT_MONITORING_ALERT_DEFINITIONS to provide better context and information for users and developers.

    Comment on lines +127 to +129
    const alertDefinitions = await this.getAlertDefinitions({
    type: MonitoringType.transaction_monitoring,
    });
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Consider refactoring the checkAllAlerts method to allow dynamic passing of the monitoringType. Currently, it is hardcoded to MonitoringType.transaction_monitoring, which may limit flexibility given the PR's objectives to handle multiple monitoring types.

    Comment on lines +148 to +156
    private async checkAlert(alertDefinition: AlertDefinition, ...args: any[]) {
    const unknownData: unknown = alertDefinition.inlineRule;

    const inlineRule: InlineRule = unknownData as InlineRule;

    const ruleExecutionResults = await this.dataAnalyticsService.runInlineRule(
    alertDefinition.projectId,
    inlineRule,
    args,
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Add type checks before casting unknownData to InlineRule in the checkAlert method to prevent potential runtime errors if the data does not match the expected 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: 0

    Out of diff range and nitpick comments (5)
    services/workflows-service/src/data-analytics/data-analytics.service.ts (5)

    Line range hint 77-177: Consider using parameterized queries instead of raw SQL to enhance security and prevent potential SQL injection vulnerabilities.


    Line range hint 178-204: Ensure the use of parameterized queries to mitigate the risk of SQL injection in the evaluateHighTransactionTypePercentage method.


    Line range hint 205-238: Adopt parameterized queries in the evaluateTransactionLimitHistoricAverageInbound method to prevent SQL injection risks.


    Line range hint 239-255: Implement parameterized queries in the evaluatePaymentUnexpected method to enhance security against SQL injection.


    Line range hint 256-290: Use parameterized queries in the evaluateDormantAccount method to safeguard against SQL injection vulnerabilities.

    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

    @@ -4,6 +4,7 @@ export type TExecutionDetails = {
    checkpoint: {
    hash: string;
    };
    subject: Array<Record<string, unknown>>;
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Consider specifying more detailed types for subject if possible to enhance type safety.

    @liorzam liorzam closed this May 18, 2024
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    None yet

    4 participants