ballerine icon indicating copy to clipboard operation
ballerine copied to clipboard

Bal 1644 - report in case management

Open alonp99 opened this issue 9 months ago • 10 comments

User description

  • Added Ongoing Monitoring alerts page
  • Added Ongoing monitoring analysis sheet

Screenshots

image image

Checklist

  • [] I have read the contribution guidelines of this project
  • [] I have read the style guidelines of this project
  • [] I have performed a self-review of my own code
  • [] I have commented my code, particularly in hard-to-understand areas
  • [] I have made corresponding changes to the documentation
  • [] My changes generate no new warnings and errors
  • [] New and existing tests pass locally with my changes

PR Type

enhancement, tests


Changes walkthrough 📝

Relevant files
Enhancement
58 files
Router.tsx
Add routes for Businesses and Businesses Alerts                   

apps/backoffice-v2/src/Router/Router.tsx

  • Added new routes for Businesses and Businesses Alerts.
  • Reorganized imports and routes for better readability.
  • +39/-17 
    MultiSelect.tsx
    Adjust icon sizes and import order                                             

    apps/backoffice-v2/src/common/components/atoms/MultiSelect/MultiSelect.tsx

    • Adjusted icon sizes and import order.
    +6/-6     
    useNavbarLogic.tsx
    Add Ongoing Monitoring link to navbar                                       

    apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx

    • Added Ongoing Monitoring link under Businesses in the navbar.
    +12/-6   
    useFilter.tsx
    Add onClear method to clear filters                                           

    apps/backoffice-v2/src/common/hooks/useFilter/useFilter.tsx

    • Added onClear method to clear filters.
    +12/-1   
    save-base64-as-file.ts
    Add utility to save base64 as file                                             

    apps/backoffice-v2/src/common/utils/save-base64-as-file/save-base64-as-file.ts

    • Added utility function to save base64 string as a file.
    +8/-0     
    fetchers.ts
    Add entityType parameter and refactor alert schemas           

    apps/backoffice-v2/src/domains/alerts/fetchers.ts

  • Added entityType parameter to fetchAlerts.
  • Refactored alert schemas.
  • +36/-28 
    get-alerts-search-schema.ts
    Add type field to alert search schema                                       

    apps/backoffice-v2/src/domains/alerts/helpers/get-alerts-search-schema.ts

    • Added type field to alert search schema.
    +4/-2     
    useAlertsQuery.tsx
    Add entityType parameter to alerts query                                 

    apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx

    • Added entityType parameter to alerts query.
    +5/-2     
    fetchers.ts
    Add fetchers for business alerts                                                 

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts

    • Added fetchers for business alerts.
    +118/-0 
    useAlertsDecisionByIdsMutation.tsx
    Add mutation hook for updating alert decisions                     

    apps/backoffice-v2/src/domains/business-alerts/hooks/mutations/useAlertsDecisionByIdsMutation/useAlertsDecisionByIdsMutation.tsx

    • Added mutation hook for updating alert decisions.
    +50/-0   
    useAssignAlertsMutation.tsx
    Add mutation hook for assigning alerts                                     

    apps/backoffice-v2/src/domains/business-alerts/hooks/mutations/useAssignAlertsMutation/useAssignAlertsMutation.tsx

    • Added mutation hook for assigning alerts.
    +84/-0   
    useAlertDefinitionByAlertIdQuery.tsx
    Add query hook for fetching alert definition by ID             

    apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useAlertDefinitionByAlertIdQuery/useAlertDefinitionByAlertIdQuery.tsx

    • Added query hook for fetching alert definition by ID.
    +13/-0   
    useAlertLabelsQuery.tsx
    Add query hook for fetching alert labels                                 

    apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useAlertLabelsQuery/useAlertLabelsQuery.tsx

    • Added query hook for fetching alert labels.
    +13/-0   
    useBusinessAlertsQuery.tsx
    Add query hook for fetching business alerts                           

    apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useBusinessAlertsQuery/useBusinessAlertsQuery.tsx

    • Added query hook for fetching business alerts.
    +36/-0   
    query-keys.ts
    Add query keys for business alerts                                             

    apps/backoffice-v2/src/domains/business-alerts/query-keys.ts

    • Added query keys for business alerts.
    +43/-0   
    fetchers.ts
    Add fetchers for business reports                                               

    apps/backoffice-v2/src/domains/business-reports/fetchers.ts

    • Added fetchers for business reports.
    +27/-5   
    useGetBusinessReportsQuery.ts
    Add query hook for fetching business reports                         

    apps/backoffice-v2/src/domains/business-reports/hooks/queries/useGetBusinessReportsQuery/useGetBusinessReportsQuery.ts

    • Added query hook for fetching business reports.
    +15/-0   
    query-keys.ts
    Add query keys for business reports                                           

    apps/backoffice-v2/src/domains/business-reports/query-keys.ts

    • Added query keys for business reports.
    +9/-2     
    Businesses.tsx
    Add Businesses page component                                                       

    apps/backoffice-v2/src/pages/Businesses/Businesses.tsx

    • Added Businesses page component.
    +6/-0     
    BusinessesAlerts.page.tsx
    Add Businesses Alerts page component                                         

    apps/backoffice-v2/src/pages/BusinessesAlerts/BusinessesAlerts.page.tsx

    • Added Businesses Alerts page component.
    +55/-0   
    BusinessAlertsTable.tsx
    Add Business Alerts Table component                                           

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/BusinessAlertsTable.tsx

    • Added Business Alerts Table component.
    +22/-0   
    columns.tsx
    Define columns for Business Alerts Table                                 

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx

    • Defined columns for Business Alerts Table.
    +182/-0 
    useBusinessAlertsTableLogic.tsx
    Add logic hook for Business Alerts Table                                 

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/hooks/useBusinessAlertsTableLogic/useBusinessAlertsTableLogic.tsx

    • Added logic hook for Business Alerts Table.
    +37/-0   
    index.ts
    Export Business Alerts Table component                                     

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/index.ts

    • Exported Business Alerts Table component.
    +1/-0     
    interfaces.ts
    Add interfaces for Business Alerts Table                                 

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/interfaces.ts

    • Added interfaces for Business Alerts Table.
    +5/-0     
    get-severity-from-risk-score.ts
    Add utility to get severity from risk score                           

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/utils/get-severity-from-risk-score.ts

    • Added utility to get severity from risk score.
    +17/-0   
    useBusinessAlertsLogic.tsx
    Add logic hook for Business Alerts                                             

    apps/backoffice-v2/src/pages/BusinessesAlerts/hooks/useBusinessAlertsLogic/useBusinessAlertsLogic.tsx

    • Added logic hook for Business Alerts.
    +57/-0   
    BusinessesAlertsAnalysis.page.tsx
    Add Businesses Alerts Analysis page component                       

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/BusinessesAlertsAnalysis.page.tsx

    • Added Businesses Alerts Analysis page component.
    +13/-0   
    OngoingMonitoringRiskSheet.tsx
    Add Ongoing Monitoring Risk Sheet component                           

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringRiskSheet/OngoingMonitoringRiskSheet.tsx

    • Added Ongoing Monitoring Risk Sheet component.
    +38/-0   
    index.ts
    Export Ongoing Monitoring Risk Sheet component                     

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringRiskSheet/index.ts

    • Exported Ongoing Monitoring Risk Sheet component.
    +1/-0     
    OngoingMonitoringTable.tsx
    Add Ongoing Monitoring Table component                                     

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/OngoingMonitoringTable.tsx

    • Added Ongoing Monitoring Table component.
    +93/-0   
    columns.tsx
    Define columns for Ongoing Monitoring Table                           

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/columns.tsx

    • Defined columns for Ongoing Monitoring Table.
    +80/-0   
    DownloadReportButton.tsx
    Add Download Report Button component                                         

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/DownloadReportButton.tsx

    • Added Download Report Button component.
    +22/-0   
    useDownloadReportButtonLogic.ts
    Add logic hook for Download Report Button                               

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts

    • Added logic hook for Download Report Button.
    +37/-0   
    index.ts
    Export Ongoing Monitoring Table component                               

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/index.ts

    • Exported Ongoing Monitoring Table component.
    +1/-0     
    useBusinessAlertsAnalysisLogic.tsx
    Add logic hook for Business Alerts Analysis                           

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx

    • Added logic hook for Business Alerts Analysis.
    +32/-0   
    SignIn.page.tsx
    Reorganize imports and add console log                                     

    apps/backoffice-v2/src/pages/SignIn/SignIn.page.tsx

  • Reorganized imports and added console log for authentication status.
  • +15/-13 
    TransactionMonitoringAlerts.page.tsx
    Reorganize imports and add NoAlerts component                       

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/TransactionMonitoringAlerts.page.tsx

    • Reorganized imports and added NoAlerts component.
    +4/-4     
    AlertsFilters.tsx
    Adjust correlationIds mapping for undefined values             

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsFilters/AlertsFilters.tsx

    • Adjusted correlationIds mapping to handle undefined values.
    +5/-5     
    AlertsHeader.tsx
    Reorganize imports and adjust alert decision logic             

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsHeader/AlertsHeader.tsx

    • Reorganized imports and adjusted alert decision logic.
    +9/-9     
    AlertsTable.tsx
    Reorganize imports for AlertsTable component                         

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/AlertsTable.tsx

    • Reorganized imports for AlertsTable component.
    +3/-3     
    interfaces.ts
    Update interface to use TBusinessAlertsList                           

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts

    • Updated interface to use TBusinessAlertsList.
    +2/-2     
    severity-to-class-name.tsx
    Add severityToTextClassName mapping                                           

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/severity-to-class-name.tsx

    • Added severityToTextClassName mapping.
    +12/-1   
    useTransactionMonitoringAlertsLogic.tsx
    Add entityType parameter to alerts query                                 

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx

    • Added entityType parameter to alerts query.
    +7/-6     
    AlertAnalysisSheet.tsx
    Reorganize imports for AlertAnalysisSheet component           

    apps/backoffice-v2/src/pages/TransactionMonitoringAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx

    • Reorganized imports for AlertAnalysisSheet component.
    +2/-2     
    generate-alerts.ts
    Reorganize imports and constants                                                 

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

    • Reorganized imports and constants.
    +12/-12 
    seed-business-reports.ts
    Add script to seed business reports                                           

    services/workflows-service/scripts/business-reports/seed-business-reports.ts

    • Added script to seed business reports.
    +57/-0   
    seed.ts
    Reorganize imports and add seeding for transactions alerts

    services/workflows-service/scripts/seed.ts

    • Reorganized imports and added seeding for transactions alerts.
    +20/-20 
    alert.controller.external.ts
    Reorganize imports for alert controller                                   

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

    • Reorganized imports for alert controller.
    +4/-4     
    alert.service.ts
    Reorganize imports and add new methods for alert service 

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

    • Reorganized imports and added new methods for alert service.
    +6/-6     
    business-report.controller.internal.ts
    Reorganize imports for business report controller               

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

    • Reorganized imports for business report controller.
    +9/-7     
    business-report.repository.ts
    Add findFirst method to business report repository             

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

    • Added findFirst method to business report repository.
    +9/-0     
    business-report.service.ts
    Add findFirst method to business report service                   

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

    • Added findFirst method to business report service.
    +7/-0     
    business.controller.external.ts
    Reorganize imports and adjust authentication guards           

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

    • Reorganized imports and adjusted authentication guards.
    +16/-15 
    app-logger.service.ts
    Reorganize imports for app logger service                               

    services/workflows-service/src/common/app-logger/app-logger.service.ts

    • Reorganized imports for app logger service.
    +1/-1     
    data-analytics.service.ts
    Reorganize imports for data analytics service                       

    services/workflows-service/src/data-analytics/data-analytics.service.ts

    • Reorganized imports for data analytics service.
    +7/-15   
    types.ts
    Adjust InlineRule type to include alert labels                     

    services/workflows-service/src/data-analytics/types.ts

    • Adjusted InlineRule type to include alert labels.
    +3/-2     
    prisma.service.ts
    Add transaction parameter to lock methods                               

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

    • Added transaction parameter to lock methods.
    +15/-6   
    Tests
    1 files
    alert.service.intg.test.ts
    Add integration tests for ongoing monitoring alerts           

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

    • Added integration tests for ongoing monitoring alerts.
    +329/-16

    💡 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

      • Added new enum type MonitoringType for alerts and extended AlertDefinition to include monitoringType.
      • Introduced new alert definitions for merchant monitoring.
      • Added businessId to Alert for associating alerts with businesses.
      • New columns reportId and riskScore added to BusinessReport table.
    • Bug Fixes

      • Adjusted alert generation functions to handle different alert types based on business or counterparty IDs.
    • Enhancements

      • Updated Jest configuration and dependencies for improved testing.
      • Enhanced BusinessReportService with new filtering and pagination capabilities.
      • Improved TransactionService error handling and logging.
    • Refactor

      • Replaced AlertService with AlertDefinitionService in controllers.
      • Renamed various DTOs and methods for better clarity.
    • Documentation

      • Updated routing configuration and page components in the backoffice app for better navigation and new features.
    • Chores

      • Added new data seeding scripts for business reports and alerts.

    alonp99 avatar May 05 '24 14:05 alonp99

    ⚠️ No Changeset found

    Latest commit: c6a0f236752011004e2d0ebebc05cc18e5480275

    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

    changeset-bot[bot] avatar May 05 '24 14:05 changeset-bot[bot]

    Walkthrough

    The changes span configuration updates, schema migrations, and feature enhancements for the workflows service. Key updates include Jest configuration adjustments, database schema modifications to support new alert types and business reports, and enhancements to alert generation and business report seeding scripts. Additionally, the backoffice application routing has been restructured to include new pages and components.

    Changes

    File(s) Change Summary
    services/workflows-service/jest.config.ts Reorganized Jest settings, updated module paths, added TypeScript transform configuration, changed export
    services/workflows-service/package.json Added @jest/types v29.6.3, updated @types/jest to v26.0.24
    services/workflows-service/prisma/migrations/.../migration.sql Added new enum MonitoringType, altered AlertDefinition and Alert tables, added businessId and reportId columns, added riskScore column, added additionalInfo JSONB column
    services/workflows-service/prisma/schema.prisma Added fields to Business, AlertDefinition, and Alert models, reorganized BusinessReport fields
    services/workflows-service/scripts/alerts/generate-alerts.ts, services/workflows-service/scripts/seed.ts Updated alert generation scripts, added merchant monitoring alert definitions, modified seeding process
    services/workflows-service/scripts/business-reports/seed-business-reports.ts Added functions to seed business reports and files using faker data and Prisma ORM
    services/workflows-service/src/alert/... Replaced AlertService with AlertDefinitionService, added MonitoringType, updated alert handling methods
    services/workflows-service/src/alert-definition/alert-definition.module.ts Included AlertDefinitionRepository in exports
    services/workflows-service/src/alert/types.ts Added types CheckRiskScoreOptions and CheckRiskScorePayload
    services/workflows-service/src/business-report/... Added methods for filtering and updating business reports, renamed some DTOs and methods
    services/workflows-service/src/collection-flow/collection-flow.module.ts, services/workflows-service/src/data-analytics/data-analytics.module.ts Added new module imports for alert and business report functionalities
    services/workflows-service/src/data-analytics/... Added risk score evaluation method, updated error message formatting
    services/workflows-service/src/transaction/transaction.service.ts Introduced correlationId, updated error handling, reordered dependencies
    apps/backoffice-v2/src/Router/Router.tsx Restructured routing configuration, added new page components
    services/workflows-service/prisma/data-migrations Updated subproject commit reference

    In code and schema, we weave our tale, With enums and alerts that now prevail. Business reports, they grow and seed, In Jest we trust, our tests proceed. Routing paths, a new array, For workflows bright as a spring day. 🌸

    [!WARNING]

    Review ran into problems

    Problems (1)
    • Git: Failed to clone repository. Please contact CodeRabbit support.

    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 full the 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 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.

    coderabbitai[bot] avatar May 05 '24 14:05 coderabbitai[bot]

    PR Description updated to latest commit (https://github.com/ballerine-io/ballerine/commit/4828e8c54e545a1423003952140da115969b2bde)

    github-actions[bot] avatar May 05 '24 14:05 github-actions[bot]

    PR Review 🔍

    (Review updated until commit https://github.com/ballerine-io/ballerine/commit/9452a571364764ca6f09d226594576a9103af4d0)

    ⏱️ Estimated effort to review [1-5]

    5, because the PR introduces a significant amount of changes across multiple files and functionalities, including backend logic, database interactions, and scheduled tasks. The complexity and potential impact of these changes on the system's behavior require a thorough review to ensure correctness, performance, and maintainability.

    🧪 Relevant tests

    No

    ⚡ Possible issues

    Possible Bug: The method handleCron in ongoing-monitoring.cron.ts uses a lock mechanism to prevent concurrent executions, but it does not handle the case where the lock is not successfully released due to an error or crash, which could lead to deadlock situations.

    Performance Concern: The handleCron method in ongoing-monitoring.cron.ts could potentially process a large number of businesses sequentially, which might lead to long execution times and delays, especially if the operations performed for each business are also time-consuming.

    🔒 Security concerns

    No

    Code feedback:
    relevant filesrc/workflow/cron/ongoing-monitoring.cron.ts
    suggestion      

    Consider implementing error handling for the lock release process in the handleCron method to ensure that the lock is always released even if errors occur during the execution of the cron job. This change will prevent potential deadlocks and ensure that subsequent executions of the cron job can proceed without issues. [important]

    relevant lineconst lockReleased = await this.prisma.releaseLock(transaction, this.lockKey);

    relevant filesrc/workflow/cron/ongoing-monitoring.cron.ts
    suggestion      

    To improve performance and responsiveness of the handleCron method, consider processing businesses in parallel using asynchronous operations or by batching them to reduce the total execution time. This approach can help in scaling the system more effectively and reduce the impact of processing large datasets. [important]

    relevant linefor (const business of businesses) {

    relevant filesrc/common/app-logger/app-logger.service.ts
    suggestion      

    Ensure that sensitive information is not logged by the AppLoggerService. Review the logging statements throughout the application to confirm that no personal data or sensitive business information is being exposed in the logs. This is crucial for maintaining security and compliance with data protection regulations. [important]

    relevant linethis.logger.error(`Failed to Invoke Ongoing Report for businessId: ${

    relevant filesrc/prisma/prisma.service.ts
    suggestion      

    Optimize the database queries and indexes in the PrismaService to improve performance, especially for operations that are executed frequently or involve large amounts of data. Consider analyzing the query performance using a tool like the Prisma Studio or directly via SQL EXPLAIN plans. [medium]

    relevant lineconst result = await transaction.$queryRaw

    github-actions[bot] avatar May 05 '24 14:05 github-actions[bot]

    PR Code Suggestions ✨

    CategorySuggestions                                                                                                                                                       
    Maintainability
    Use a constant for repeated route path segments to improve maintainability.

    Consider using a constant for the repeated string '/:locale' in the route paths to ensure
    consistency and reduce the risk of typos.

    apps/backoffice-v2/src/Router/Router.tsx [115-139]

    -path: '/:locale/businesses',
    -path: '/:locale/businesses/alerts',
    -path: '/:locale/businesses/alerts/:alertId',
    -path: '/:locale/ongoing-monitoring',
    -path: '/:locale/ongoing-monitoring/alerts',
    +const LOCALE_PATH = '/:locale';
    +path: `${LOCALE_PATH}/businesses`,
    +path: `${LOCALE_PATH}/businesses/alerts`,
    +path: `${LOCALE_PATH}/businesses/alerts/:alertId`,
    +path: `${LOCALE_PATH}/ongoing-monitoring`,
    +path: `${LOCALE_PATH}/ongoing-monitoring/alerts`,
     
    
    Refactor URL construction into a separate function for better code organization.

    Refactor the URL construction logic into a separate function to improve readability and
    maintainability.

    apps/backoffice-v2/src/domains/alerts/fetchers.ts [113-116]

    -let url = `${getOriginUrl(env.VITE_API_URL)}/api/v1/external/alerts?${queryParams}`;
    -if (params.entityType === 'business') {
    -    url = `${getOriginUrl(env.VITE_API_URL)}/api/v1/external/alerts/business-report?${queryParams}`;
    -}
    +const constructAlertsUrl = (entityType: AlertEntityType, queryParams: string) => {
    +    const baseUrl = `${getOriginUrl(env.VITE_API_URL)}/api/v1/external/alerts`;
    +    return entityType === 'business' ? `${baseUrl}/business-report?${queryParams}` : `${baseUrl}?${queryParams}`;
    +};
    +const url = constructAlertsUrl(params.entityType, queryParams);
     
    
    Replace magic strings with constants or enums to improve code maintainability and prevent errors.

    Avoid using magic strings and instead use a constant or enum for the decision types.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsDecisionDropdown/AlertsDecisionDropdown.tsx [22]

    -Decision
    +DECISION_LABEL
     
    
    Extract complex configurations into separate functions or files to improve code maintainability.

    Extract the filter configuration into a separate function or file to improve readability
    and maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsFilters/AlertsFilters.tsx [38-66]

    -const filters = [
    -  {
    -    title: 'Assignee',
    -    accessor: 'assigneeId',
    -    options: [
    -      {
    -        label: 'Unassigned',
    -        value: null,
    -      },
    -      ...assigneeOptions,
    -    ],
    -  },
    -  {
    -    title: 'Alert Type',
    -    accessor: 'alertType',
    -    options: alertTypeOptions,
    -  },
    -  {
    -    title: 'Status',
    -    accessor: 'status',
    -    options: statusOptions,
    -  },
    -  {
    -    title: 'Label',
    -    accessor: 'label',
    -    options: labels.map(label => ({
    -      label,
    -      value: label,
    -    })),
    -  },
    -];
    +const filters = createFilterOptions(assigneeOptions, alertTypeOptions, statusOptions, labels);
     
    
    Improve readability by renaming ctw to combineClassNames.

    Use a more descriptive variable name instead of ctw for the function that combines class
    names. This will improve code readability and maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsTable/columns.tsx [94-99]

    -className={ctw(
    +className={combineClassNames(
       severityToClassName[
         (severity?.toUpperCase() as keyof typeof severityToClassName) ?? 'DEFAULT'
       ],
       'w-20 py-0.5 font-bold',
     )}
     
    
    Reduce code duplication by creating a reusable function for null checks and fallback rendering.

    Refactor the repeated pattern of checking for null values and returning <TextWithNAFallback> into a reusable
    function to reduce code duplication and improve maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsTable/columns.tsx [31-32]

    -if (!dataTimestamp) {
    -  return <TextWithNAFallback>{dataTimestamp}</TextWithNAFallback>;
    +function renderWithFallback(value) {
    +  if (!value) {
    +    return <TextWithNAFallback>{value}</TextWithNAFallback>;
    +  }
    +  // Additional logic can be added here if needed
     }
     
    
    Use theme variables or CSS classes for colors to enhance maintainability and consistency.

    Replace the hardcoded color code with a theme variable or a CSS class to improve
    maintainability and theming consistency.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx [28]

    -<div className="max-w-[88ch] text-sm text-[#64748B]">{summary}</div>
    +<div className="max-w-[88ch] text-sm text-theme-secondary">{summary}</div>
     
    
    Extract inline styles to a CSS module for better readability and maintainability.

    Extract the inline styles into a separate CSS module to improve code readability and
    separation of concerns.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx [23]

    -<div className="flex flex-col p-4">
    +<div className={styles.alertAnalysisContainer}>
     
    
    Best practice
    Remove debug logging from production code.

    Remove the console.log statement to avoid exposing potentially sensitive data and to
    maintain clean production code.

    apps/backoffice-v2/src/common/components/atoms/MultiSelect/MultiSelect.tsx [49]

    -console.log('title', { title });
    +// Removed console.log statement
     
    
    Use optional chaining to safely access properties of potentially undefined objects.

    Consider using optional chaining when accessing properties of potentially undefined
    objects to prevent runtime errors.

    apps/backoffice-v2/src/pages/BusinessesAlerts/BusinessesAlerts.page.tsx [30-32]

     assignees={assignees ?? []}
     labels={labels ?? []}
    -authenticatedUser={authenticatedUser}
    +authenticatedUser={authenticatedUser ?? {}}
     
    
    Improve type safety by using more specific types.

    Use a more specific type for the id parameter in the onAssigneeSelect function to ensure
    type safety.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsAssignDropdown/AlertsAssignDropdown.tsx [11]

    -onAssigneeSelect: (id: string | null, isAssignedToMe: boolean) => () => void;
    +onAssigneeSelect: (id: string, isAssignedToMe: boolean) => () => void;
     
    
    Use CSS classes instead of inline styles to improve code readability and maintainability.

    Replace inline styles with class names defined in CSS files to separate concerns and
    improve maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsHeader/AlertsHeader.tsx [86]

    -className={'leading-0 min-h-[16px] pb-7 text-xs font-bold'}
    +className={'headerStyles'}
     
    
    Move inline styles to CSS for better maintainability.

    Avoid using inline styles for setting colors directly in the JSX. Instead, define these
    styles in a CSS or SCSS file to improve maintainability and separation of concerns.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsTable/columns.tsx [41]

    -<span className={`text-xs text-[#999999]`}>{time}</span>
    +<span className="text-xs text-secondary">{time}</span>
     
    
    Use optional chaining to safely access properties on potentially null or undefined objects.

    Consider using optional chaining (?.) when accessing properties on transactions to prevent
    runtime errors if transactions is null or undefined.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx [32]

    -<AlertAnalysisTable transactions={transactions ?? []} />
    +<AlertAnalysisTable transactions={transactions?.transactionsList ?? []} />
     
    
    Use descriptive prop names to improve code readability and maintainability.

    Use a more descriptive prop name than heading to enhance code readability and
    maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx [25]

    -<h2 className="text-2xl font-bold">{heading}</h2>
    +<h2 className="text-2xl font-bold">{alertTitle}</h2>
     
    
    Use specific types for props to ensure type safety and clarity.

    Consider using a more specific type than ReactNode for heading and summary to ensure the
    components receive the expected type of content.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx [10-11]

    -heading: ReactNode;
    -summary: ReactNode;
    +heading: string;
    +summary: string;
     
    
    Enhancement
    Improve error messages for better debugging and user experience.

    Add error handling for unsupported filter types to prevent runtime errors and improve user
    feedback.

    apps/backoffice-v2/src/common/components/organisms/Filters/Filters.Input.tsx [12]

    -throw new Error(`Filter input for type ${type} not implemented.`);
    +throw new Error(`Filter input for type ${type} is not implemented. Please check the configuration.`);
     
    
    Enhance conditional rendering to handle non-string and non-JSX elements gracefully.

    Use conditional rendering to handle different types of titles more explicitly, ensuring
    that non-string JSX elements are handled properly.

    apps/backoffice-v2/src/common/components/organisms/Filters/Filters.Header.tsx [5-9]

     return typeof title === 'string' ? (
         <h4 className={'leading-0 min-h-[16px] pb-7 text-xs font-bold'}>{title}</h4>
    -) : (
    +) : React.isValidElement(title) ? (
         title
    -);
    +) : null;
     
    
    Improve type specificity for the decisionToTextColor mapping.

    Consider using a more specific type for the decisionToTextColor mapping instead of using
    ComponentProps<typeof TextWithNAFallback>['className']. This will ensure that the types
    are more aligned with the actual values expected by the TextWithNAFallback component,
    improving type safety and maintainability.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsTable/columns.tsx [158-164]

    -const decisionToTextColor = {
    +const decisionToTextColor: Record<'CLEARED' | 'REJECTED', string> = {
       CLEARED: 'text-success',
       REJECTED: 'text-destructive',
    -} as const satisfies Record<
    -  Extract<Uppercase<SnakeCase<TAlertState>>, 'CLEARED' | 'REJECTED'>,
    -  ComponentProps<typeof TextWithNAFallback>['className']
    ->;
    +};
     
    
    Performance
    Optimize date formatting by reducing redundant calls to dayjs.

    Replace the repeated calls to dayjs(dataTimestamp).format('MMM DD, YYYY') and
    dayjs(dataTimestamp).format('hh:mm') with a single call to dayjs and store the result in a
    variable to avoid redundant processing.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/AlertsTable/columns.tsx [35-36]

    -const date = dayjs(dataTimestamp).format('MMM DD, YYYY');
    -const time = dayjs(dataTimestamp).format('hh:mm');
    +const formattedDate = dayjs(dataTimestamp);
    +const date = formattedDate.format('MMM DD, YYYY');
    +const time = formattedDate.format('hh:mm');
     
    

    github-actions[bot] avatar May 05 '24 14:05 github-actions[bot]

    PR Description updated to latest commit (https://github.com/ballerine-io/ballerine/commit/b1e439250065509f3b96362260417ece9ee16d29)

    github-actions[bot] avatar May 16 '24 10:05 github-actions[bot]

    Persistent review updated to latest commit https://github.com/ballerine-io/ballerine/commit/b1e439250065509f3b96362260417ece9ee16d29

    github-actions[bot] avatar May 16 '24 10:05 github-actions[bot]

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Replace .catch with .default for setting default values in Zod schemas

    Replace the use of .catch with .default in Zod schemas to set default values for the
    fields. .catch is typically used for error handling, not for setting default values.

    apps/backoffice-v2/src/pages/BusinessesAlerts/get-alerts-search-schema.ts [12]

     sortBy: z
       .enum(['dataTimestamp', 'status'] as const satisfies ReadonlyArray<
         Extract<keyof TAlertsList[number], 'dataTimestamp' | 'status'>
       >)
    -  .catch('dataTimestamp'),
    +  .default('dataTimestamp'),
     
    
    Suggestion importance[1-10]: 10

    Why: The suggestion correctly identifies a misuse of .catch for setting default values in Zod schemas, where .default should be used instead. This is a significant improvement for correct schema usage.

    10
    Replace console logging with proper error handling or logging

    Replace the direct console logging with a more robust error handling or debugging
    mechanism, especially in production code.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/BusinessAlertsTable.tsx [71-75]

    -console.log(
    -  `/${locale}/businesses/alerts/${itemId}${search}&businessId=${
    -    item?.additionalInfo?.businessId ?? ''
    -  }`,
    -);
    +// Implement error handling or a more sophisticated logging mechanism here
     
    
    Suggestion importance[1-10]: 7

    Why: The suggestion is valid as replacing console.log with a more robust logging or error handling mechanism would improve the production quality of the code.

    7
    Enhancement
    Simplify the schema by using .optional() directly on z.string()

    Use .optional() method directly on the z.string() for assigneeId, state, and label fields
    instead of using .nullable() and then handling it with .catch([]). This simplifies the
    schema and makes it more readable.

    apps/backoffice-v2/src/pages/BusinessesAlerts/get-alerts-search-schema.ts [15-18]

    -assigneeId: z.array(z.string().nullable()).catch([]),
    -state: z.array(z.string().nullable()).catch([]),
    -label: z.array(z.string()).catch([]),
    +assigneeId: z.array(z.string().optional()),
    +state: z.array(z.string().optional()),
    +label: z.array(z.string().optional()),
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion improves code readability and simplifies the schema by using .optional() directly, which is a more appropriate method for optional fields than combining .nullable() with .catch([]).

    8
    Add a check for entityType in the query's enabled condition to prevent unnecessary queries

    Consider checking the existence of entityType in the enabled condition of the useQuery
    hook to ensure that queries are only made when entityType is provided. This can prevent
    unnecessary or erroneous queries when entityType is not available.

    apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx [27]

    -enabled: isAuthenticated && !!sortBy && !!sortDir && !!page && !!pageSize,
    +enabled: isAuthenticated && !!sortBy && !!sortDir && !!page && !!pageSize && !!entityType,
     
    
    Suggestion importance[1-10]: 7

    Why: The suggestion correctly identifies an improvement to ensure that queries are only executed when all necessary parameters, including entityType, are provided. This is a good practice to avoid unnecessary API calls.

    7
    Error handling
    Improve error handling by throwing errors in the fetch function

    It is recommended to handle potential errors in the fetchBusinessAlerts function by
    throwing an appropriate error if the apiClient call fails, instead of returning the error
    directly. This can help in managing error handling more effectively downstream.

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts [122]

     const [alerts, error] = await apiClient({
    +  if (error) throw new Error(`Failed to fetch business alerts: ${error.message}`);
    +});
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion improves error handling by ensuring that errors are thrown and can be caught by error handling mechanisms upstream, rather than just returning the error. This is crucial for robust error management in asynchronous operations.

    8
    Possible bug
    Add null checks before accessing object properties to prevent runtime errors

    Consider adding a conditional rendering check for item before accessing its properties to
    prevent potential runtime errors.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/BusinessAlertsTable.tsx [83-85]

    -to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${
    -  item?.additionalInfo?.businessId ?? ''
    -}`}
    +to={item ? `/${locale}/businesses/alerts/${itemId}${search}&businessId=${item.additionalInfo?.businessId ?? ''}` : '#'}
     
    
    Suggestion importance[1-10]: 8

    Why: This is a valuable suggestion as it addresses a potential runtime error by adding a conditional check before accessing properties of potentially null objects, which enhances the robustness of the code.

    8
    Maintainability
    Define JSX components outside the router configuration to improve modularity

    Avoid using inline JSX in the router configuration as it can make the code harder to
    maintain and test. Instead, define the components outside the router configuration and
    reference them. This will make the router configuration cleaner and more modular.

    apps/backoffice-v2/src/Router/Router.tsx [119-138]

    -element: <TransactionMonitoringAlerts />,
    -element: <Businesses />,
    -element: <BusinessesAlerts />,
    -element: <BusinessesAlertsAnalysisPage />,
    +const transactionMonitoringAlertsElement = <TransactionMonitoringAlerts />;
    +const businessesElement = <Businesses />;
    +const businessesAlertsElement = <BusinessesAlerts />;
    +const businessesAlertsAnalysisPageElement = <BusinessesAlertsAnalysisPage />;
    +// In router configuration
    +element: transactionMonitoringAlertsElement,
    +element: businessesElement,
    +element: businessesAlertsElement,
    +element: businessesAlertsAnalysisPageElement,
     
    
    Suggestion importance[1-10]: 7

    Why: This suggestion correctly points out a best practice in React development to improve code modularity and maintainability by defining components outside of the router configuration.

    7
    Ensure all optional fields are marked as optional for consistency

    Ensure consistent handling of optional fields by applying .optional() to all optional
    fields in the schema for clarity and consistency.

    apps/backoffice-v2/src/pages/BusinessesAlerts/get-alerts-search-schema.ts [27-30]

     selected: BooleanishSchema.optional(),
     businessId: z.string().optional(),
     counterpartyId: z.string().optional(),
    +alertType: z.array(z.string()).optional(),
     
    
    Suggestion importance[1-10]: 7

    Why: The suggestion promotes consistency and clarity by ensuring all optional fields are marked as such. However, the suggested code does not change from the existing code, making the suggestion somewhat redundant.

    7
    Group all imports from 'react' together at the top of the file

    Consider using a consistent approach for importing React components and hooks. Currently,
    some imports like FunctionComponent and useState are directly imported from 'react', while
    others are imported later in the file. It's best practice to group all imports from the
    same module together at the top of the file to improve readability and maintainability.

    apps/backoffice-v2/src/Router/Router.tsx [26-18]

    -import { FunctionComponent } from 'react';
    -import { ReactNode, useCallback, useState } from 'react';
    +import { FunctionComponent, ReactNode, useCallback, useState } from 'react';
     
    
    Suggestion importance[1-10]: 6

    Why: The suggestion correctly identifies an improvement in import organization for better readability and maintainability, though it's a relatively minor enhancement.

    6
    Refactor the toast action function into a separate utility file for better maintainability

    To improve the readability and maintainability of the useAssignAlertsByIdsMutation hook,
    consider refactoring the getToastActionAndContext function into a separate utility file.
    This can help in reusing the function across different components or hooks and reduce the
    complexity of the current file.

    apps/backoffice-v2/src/domains/business-alerts/hooks/mutations/useAssignAlertsMutation/useAssignAlertsMutation.tsx [8-28]

    -const getToastActionAndContext = ({
    +// This function can be moved to a separate utility file.
    +export const getToastActionAndContext = ({
     
    
    Suggestion importance[1-10]: 6

    Why: The suggestion to refactor the getToastActionAndContext function into a separate utility file is valid for improving maintainability and potential reusability. However, it's a moderate improvement as it mainly affects code organization and not functionality.

    6
    Consolidate multiple import statements from the same module into a single line

    Consider using a single import statement for fetching functions from the same module to
    maintain consistency and reduce the lines of code.

    apps/backoffice-v2/src/domains/business-reports/query-keys.ts [3-5]

    -import {
    -  fetchBusinessReports,
    -  fetchLatestBusinessReport,
    -} from '@/domains/business-reports/fetchers';
    +import { fetchBusinessReports, fetchLatestBusinessReport } from '@/domains/business-reports/fetchers';
     
    
    Suggestion importance[1-10]: 5

    Why: The suggestion correctly identifies an opportunity to consolidate import statements for better maintainability, but it's a minor improvement.

    5
    Validation
    Validate reportType against a list of allowed types to prevent errors

    To ensure that the fetchLatestBusinessReport and fetchBusinessReports functions handle
    different types of reports correctly, consider validating reportType against a predefined
    list of allowed types. This can prevent errors related to unsupported report types.

    apps/backoffice-v2/src/domains/business-reports/fetchers.ts [24]

    -reportType: 'MERCHANT_REPORT_T1' | ('ONGOING_MERCHANT_REPORT_T1' & (string & {}));
    +reportType: 'MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1' | 'ANOTHER_SUPPORTED_TYPE';
     
    
    Suggestion importance[1-10]: 7

    Why: Validating reportType against a predefined list of allowed types is a good practice to ensure that the function handles only supported types, which can prevent runtime errors and improve the robustness of the function.

    7
    User experience
    Replace throwing an error with a default component return for unsupported filter types

    The function getFilterInputComponent throws an error for unsupported types, which could be
    handled more gracefully. Consider returning a default component or a null component
    instead of throwing an error, to enhance the user experience by providing a fallback
    behavior.

    apps/backoffice-v2/src/common/components/organisms/Filters/Filters.Input.tsx [12]

    -throw new Error(`Filter input for type ${type} not implemented.`);
    +return DefaultComponent; // Define a DefaultComponent that handles unsupported types gracefully
     
    
    Suggestion importance[1-10]: 5

    Why: The suggestion to handle unsupported types more gracefully is valid and improves user experience, but it's not critical as it depends on the application's requirements for error handling.

    5
    Performance
    Remove unnecessary use of useCallback to simplify the code

    The use of useCallback for onClearSelect might be unnecessary if the function does not
    have complex computations or is not passed down to deeply nested children components.
    Removing useCallback could simplify the code and potentially improve performance if the
    dependency array changes frequently.

    apps/backoffice-v2/src/common/components/organisms/Filters/Filters.List.tsx [13-17]

    -const onClearSelect = useCallback(
    -  (accessor: string) => () => {
    -    onFilter(accessor)([]);
    -  },
    -  [onFilter],
    -);
    +const onClearSelect = (accessor: string) => () => {
    +  onFilter(accessor)([]);
    +};
     
    
    Suggestion importance[1-10]: 4

    Why: While removing unnecessary useCallback could simplify the code, the impact on performance is minimal unless proven by profiling, and the current use might be justified depending on the broader context of the application.

    4

    github-actions[bot] avatar May 16 '24 10:05 github-actions[bot]

    Persistent review updated to latest commit https://github.com/ballerine-io/ballerine/commit/9452a571364764ca6f09d226594576a9103af4d0

    github-actions[bot] avatar May 21 '24 11:05 github-actions[bot]

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Security
    Enable parameter encoding in qs.stringify to prevent URL injection vulnerabilities

    The fetchBusinessAlerts function constructs a query string without encoding the
    parameters, which can lead to security vulnerabilities such as URL injection. It is
    recommended to enable encoding in the qs.stringify method to ensure that the parameters
    are properly encoded.

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts [43]

    -const queryParams = qs.stringify(params, { encode: false });
    +const queryParams = qs.stringify(params, { encode: true });
     
    
    Suggestion importance[1-10]: 10

    Why: Enabling parameter encoding is crucial for preventing URL injection vulnerabilities, making this a high-priority security improvement.

    10
    Improve security by ensuring query parameters are properly encoded

    To avoid potential security risks with query parameter injection, ensure that the
    'queryParams' string is properly sanitized or use a more secure method to construct the
    query string.

    apps/backoffice-v2/src/domains/alerts/fetchers.ts [113-114]

    -const queryParams = qs.stringify(params, { encode: false });
    +const queryParams = qs.stringify(params, { encode: true });
     let url = `${getOriginUrl(env.VITE_API_URL)}/api/v1/external/alerts?${queryParams}`;
     
    
    Suggestion importance[1-10]: 9

    Why: Properly encoding query parameters is crucial for preventing security risks such as query parameter injection. This suggestion significantly enhances the security of the code.

    9
    Performance
    Add dependencies to useCallback to prevent unnecessary re-computations

    Consider adding a dependency array to the useCallback hook for downloadReport to ensure
    that it only re-computes when fileId or reportId changes, which are its dependencies.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts [31]

     const downloadReport = useCallback(async () => {
       ...
    -}, []);
    +}, [fileId, reportId]);
     
    
    Suggestion importance[1-10]: 10

    Why: Adding dependencies to the useCallback hook is crucial for performance optimization. This ensures that the function is only re-created when necessary, preventing unnecessary computations.

    10
    Possible issue
    Remove redundant code to improve clarity and efficiency

    Remove the redundant call to setIsDownloading(true) at line 20, as it is already being set
    at line 17 before entering the try block. This will improve the clarity and efficiency of
    the code.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts [20]

     setIsDownloading(true);
     try {
    -  setIsDownloading(true);
     
    
    Suggestion importance[1-10]: 9

    Why: The suggestion correctly identifies and removes redundant code, improving both clarity and efficiency. This is a significant improvement to the code quality.

    9
    Ensure navigation item keys are unique to avoid potential conflicts

    To ensure that the 'nav-item-business-alerts' key is unique and does not cause conflicts
    in the navigation structure, consider appending a unique identifier or using a more
    specific naming convention.

    apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx [31-33]

     {
       text: 'Ongoing Moniotring',
       href: `/en/businesses/alerts`,
    -  key: 'nav-item-business-alerts',
    +  key: `nav-item-business-alerts-${uniqueId()}`,
     }
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion addresses a potential issue with key conflicts in the navigation structure, which could cause bugs. Ensuring unique keys is important for the stability of the navigation component.

    8
    Replace z.any() with a specific schema to ensure proper validation and avoid runtime errors

    Consider using a more specific type than z.any() for the schema property in the
    updateAlertsDecisionByIds function. Using z.any() can lead to runtime errors due to lack
    of validation. Define a proper schema that matches the expected structure of the response.

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts [87]

    -schema: z.any(),
    +schema: z.object({
    +  decision: z.enum(['ACCEPTED', 'REJECTED', 'PENDING']),
    +  alertIds: z.array(z.string()),
    +}),
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion improves type safety and ensures proper validation, which can prevent runtime errors. However, the exact schema provided in the suggestion might need further refinement based on the actual response structure.

    8
    Possible bug
    Add checks for assigneeId and alertIds to prevent errors during the API call

    The assignAlertsByIds function uses a PATCH method but does not handle the case where
    assigneeId or alertIds might be empty, which could lead to unintended behavior or errors.
    Add checks to ensure these values are provided before making the API call.

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts [60-66]

    +if (!assigneeId || !alertIds.length) {
    +  throw new Error("assigneeId and alertIds must be provided");
    +}
     const [alerts, error] = await apiClient({
       url: `${getOriginUrl(env.VITE_API_URL)}/api/v1/external/alerts/assign`,
       method: Method.PATCH,
       body: {
         assigneeId,
         alertIds,
       },
       schema: z.any(),
     });
     
    
    Suggestion importance[1-10]: 9

    Why: Adding checks for assigneeId and alertIds prevents potential errors and ensures that the API call is made with valid data, improving the robustness of the function.

    9
    Handle potential null or undefined values before calling toUpperCase() on severity

    It is recommended to handle the case where severity might be undefined or null before
    calling toUpperCase() on it. This can prevent potential runtime errors if severity is not
    a string.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx [96-97]

     severityToClassName[
    -  (severity?.toUpperCase() as keyof typeof severityToClassName) ?? 'DEFAULT'
    +  (severity ? severity.toUpperCase() : 'DEFAULT') as keyof typeof severityToClassName
     ]
     
    
    Suggestion importance[1-10]: 9

    Why: This suggestion addresses a potential runtime error by ensuring severity is checked before calling toUpperCase(). This is crucial for preventing unexpected crashes and improving code robustness.

    9
    Define a specific schema for businessReports to enhance type safety and data integrity

    The businessReports property in BusinessAlertItem is defined with z.any(), which could
    lead to potential bugs and unexpected behavior. It's recommended to define a more specific
    schema for businessReports to ensure data integrity and type safety.

    apps/backoffice-v2/src/domains/business-alerts/fetchers.ts [14]

    -businessReports: z.any(),
    +businessReports: z.array(z.object({
    +  reportId: z.string(),
    +  reportDetails: z.string(),
    +  // Add other necessary fields
    +})),
     
    
    Suggestion importance[1-10]: 7

    Why: Defining a specific schema for businessReports enhances type safety and data integrity. However, the suggested schema might need additional fields to fully match the expected data structure.

    7
    Best practice
    Prevent memory leaks by removing the link element after use

    To prevent potential memory leaks and ensure that the created link element is properly
    cleaned up, add removal of the link element after triggering the download.

    apps/backoffice-v2/src/common/utils/save-base64-as-file/save-base64-as-file.ts [1-8]

     const link = document.createElement('a');
     link.download = fileName || 'file';
     link.href = base64;
     link.click();
    +link.remove();
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion follows best practices by ensuring that the created link element is removed after use, preventing potential memory leaks. It is a good practice for resource management.

    8
    Use a centralized utility function for consistent date and time formatting

    To ensure the dayjs formatting is consistent and less error-prone, consider using a
    centralized utility function for date formatting. This approach avoids repetition and
    facilitates easier changes to date formats across the application.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx [37-38]

    -const date = dayjs(dataTimestamp).format('MMM DD, YYYY');
    -const time = dayjs(dataTimestamp).format('hh:mm');
    +const { date, time } = formatDateAndTime(dataTimestamp);
     
    
    Suggestion importance[1-10]: 8

    Why: This suggestion promotes best practices by advocating for the use of a centralized utility function for date formatting, ensuring consistency and reducing the likelihood of errors. It also simplifies future changes to date formats.

    8
    Enhancement
    Add error logging for better debugging and maintenance

    Add error logging within the catch block to help with debugging and maintaining the code.
    This could be done by logging the error object.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts [27]

     catch (error) {
    +  console.error(error);
       toast.error('Failed to download report.');
     }
     
    
    Suggestion importance[1-10]: 8

    Why: Adding error logging is a good practice for debugging and maintenance. This suggestion enhances the code's maintainability and helps in diagnosing issues.

    8
    Maintainability
    Refactor nested routes into a separate function to improve readability and maintainability

    To improve the readability and maintainability of the routing configuration, consider
    refactoring the nested routes into a separate function or component. This will make the
    main router configuration cleaner and easier to manage.

    apps/backoffice-v2/src/Router/Router.tsx [127-145]

     {
       path: '/:locale/businesses',
       element: <Businesses />,
       errorElement: <RouteError />,
    -  children: [
    -    {
    -      path: '/:locale/businesses/alerts',
    -      element: <BusinessesAlerts />,
    -      errorElement: <RouteError />,
    -      children: [
    -        {
    -          path: '/:locale/businesses/alerts/:alertId',
    -          element: <BusinessesAlertsAnalysisPage />,
    -          errorElement: <RouteError />,
    -        },
    -      ],
    -    },
    -  ],
    +  children: getBusinessesChildren(),
     }
     
    
    Suggestion importance[1-10]: 7

    Why: This suggestion improves code readability and maintainability by refactoring nested routes into a separate function. However, it does not address any critical issues or bugs.

    7
    Refactor complex inline expressions to improve code readability

    To improve the readability and maintainability of the JSX code, consider breaking down
    complex inline expressions into well-named variables or helper functions. This change
    would make the code easier to understand and modify.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx [72-79]

    -<TextWithNAFallback
    -  as={Badge}
    -  className={ctw(
    -    severityToClassName[
    -      (severity?.toUpperCase() as keyof typeof severityToClassName) ?? 'DEFAULT'
    -    ],
    -    'w-20 py-0.5 font-bold',
    -  )}
    ->
    +const badgeClass = ctw(
    +  severityToClassName[
    +    (severity ? severity.toUpperCase() : 'DEFAULT') as keyof typeof severityToClassName
    +  ],
    +  'w-20 py-0.5 font-bold'
    +);
    +<TextWithNAFallback as={Badge} className={badgeClass}>
     
    
    Suggestion importance[1-10]: 7

    Why: This suggestion enhances code readability and maintainability by refactoring complex inline expressions into well-named variables. It makes the code easier to understand and modify, which is beneficial for long-term maintenance.

    7
    Use descriptive or thematic class names for styling AvatarFallback

    The className property for the AvatarFallback component is currently set to a color and
    text size. It's recommended to separate these styles into more descriptive class names or
    use existing utility classes that align with design tokens or themes.

    apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx [130]

    -<AvatarFallback className={'bg-[#DCE1E8] text-xs'}>
    +<AvatarFallback className={'bg-secondary-background text-small'}>
     
    
    Suggestion importance[1-10]: 6

    Why: This suggestion improves code maintainability by using more descriptive class names, making the code easier to understand and align with design tokens or themes. However, it is not critical for functionality.

    6
    User experience
    Improve error messages for better user feedback

    Use a more specific error message in the toast to provide better user feedback. For
    instance, include the type of error or a more descriptive message based on the error
    content.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts [27]

    -toast.error('Failed to download report.');
    +toast.error(`Failed to download report: ${error.message}`);
     
    
    Suggestion importance[1-10]: 7

    Why: While improving error messages can enhance user experience, the suggestion is relatively minor compared to others. It does provide better feedback but is not as critical as performance or debugging improvements.

    7

    github-actions[bot] avatar May 21 '24 11:05 github-actions[bot]