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 1644 - report in case management #2343

Closed
wants to merge 109 commits into from
Closed

Bal 1644 - report in case management #2343

wants to merge 109 commits into from

Conversation

alonp99
Copy link
Collaborator

@alonp99 alonp99 commented May 5, 2024

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.

    liorzblrn and others added 30 commits April 15, 2024 21:40
    …:ballerine-io/ballerine into blokh/feat/add-business-report-report-id
    # Conflicts:
    #	services/workflows-service/prisma/data-migrations
    #	services/workflows-service/src/business-report/business-report.repository.ts
    # Conflicts:
    #	services/workflows-service/prisma/data-migrations
    # Conflicts:
    #	services/workflows-service/prisma/data-migrations
    Copy link
    Contributor

    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

    Blokh added 7 commits May 21, 2024 15:48
    # Conflicts:
    #	services/workflows-service/prisma/data-migrations
    #	services/workflows-service/scripts/alerts/generate-alerts.ts
    #	services/workflows-service/src/alert/alert.service.intg.test.ts
    #	services/workflows-service/src/data-analytics/data-analytics.service.ts
    #	services/workflows-service/src/data-analytics/types.ts
    # Conflicts:
    #	pnpm-lock.yaml
    #	services/workflows-service/scripts/alerts/generate-alerts.ts
    #	services/workflows-service/src/alert/alert.service.intg.test.ts
    #	services/workflows-service/src/data-analytics/data-analytics.service.ts
    #	services/workflows-service/src/data-analytics/types.ts
    Base automatically changed from blokh/feat/add-business-report-report-id to dev May 22, 2024 08:44
    Blokh added 2 commits May 22, 2024 13:13
    # Conflicts:
    #	services/workflows-service/prisma/schema.prisma
    #	services/workflows-service/scripts/alerts/generate-alerts.ts
    #	services/workflows-service/scripts/seed.ts
    #	services/workflows-service/src/alert/alert.controller.external.ts
    #	services/workflows-service/src/alert/alert.service.intg.test.ts
    #	services/workflows-service/src/alert/alert.service.ts
    #	services/workflows-service/src/alert/consts.ts
    #	services/workflows-service/src/business-report/business-report.controller.internal.ts
    #	services/workflows-service/src/business-report/business-report.repository.ts
    #	services/workflows-service/src/business-report/business-report.service.ts
    #	services/workflows-service/src/data-analytics/data-analytics.service.ts
    #	services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts
    #	services/workflows-service/src/workflow/hook-callback-handler.service.ts
    Copy link
    Contributor

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

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

    Actionable comments posted: 13

    Outside diff range and nitpick comments (8)
    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringRiskSheet/OngoingMonitoringRiskSheet.tsx (1)

    24-28: Ensure accessibility for dynamic content.

    The component dynamically inserts content which may affect users with disabilities. Consider adding appropriate ARIA roles and properties to enhance accessibility, especially for dynamic content like the ongoing monitoring risk changes.

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

    3-3: Validate prop types for enhanced reliability.

    The component uses several props like transactions, heading, and summary. Consider using TypeScript's PropTypes or similar mechanisms to validate these props to ensure they meet expected types and structures, enhancing component reliability.

    Also applies to: 7-7

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

    2-2: Ensure proper dependency management in NestJS.

    The AppLoggerService class uses @Inject('LOGGER') for dependency injection. Ensure that the 'LOGGER' token is correctly configured in the NestJS module to avoid runtime errors. Additionally, consider defining an interface or using a class for the logger to enhance type safety and maintainability.

    Also applies to: 4-4

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/TransactionMonitoringAlerts.page.tsx (1)

    2-2: Optimize component imports for better maintainability.

    Consider using a barrel file for importing components from the same directory or module. This can simplify the import statements and make the code cleaner and easier to maintain.

    Also applies to: 3-3, 6-6

    apps/backoffice-v2/src/pages/BusinessesAlerts/BusinessesAlerts.page.tsx (1)

    2-2: Optimize component imports for better maintainability.

    Consider using a barrel file for importing components from the same directory or module. This can simplify the import statements and make the code cleaner and easier to maintain.

    Also applies to: 3-3, 6-6

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

    Line range hint 18-116: Review the MultiSelect component for proper state management and re-render optimizations. Consider using React.memo or useMemo for performance improvements.

    - export const MultiSelect = <
    + export const MultiSelect = React.memo(<
    services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts (1)

    [!TIP]
    Codebase Verification

    The current test cases for OngoingMonitoringCron do not include scenarios for error handling or verifying that Sentry captures exceptions. To ensure comprehensive test coverage for the new Sentry integration, consider adding test cases that simulate error scenarios and verify that Sentry captures these exceptions.

    • Add a test case to simulate an error occurring within the handleCron method and verify that mockSentryService().captureException is called.
    Analysis chain

    Line range hint 17-38: Ensure comprehensive test coverage for new Sentry integration.

    The integration of SentryService in the cron job should be accompanied by tests to verify that it captures exceptions as expected. Consider adding a test case to simulate a scenario where an error occurs, and verify that Sentry captures it.

    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Verify Sentry captures exceptions in cron job tests.
    
    # Test: Search for Sentry test cases. Expect: At least one test case for Sentry capturing exceptions.
    rg --type typescript $'mockSentryService().captureException'
    

    Length of output: 96



    Script:

    #!/bin/bash
    # Description: Verify Sentry captures exceptions in cron job tests.
    
    # Test: Search for Sentry test cases. Expect: At least one test case for Sentry capturing exceptions.
    rg --type ts $'mockSentryService().captureException'
    

    Length of output: 53



    Script:

    #!/bin/bash
    # Description: Verify error handling test cases in cron job tests.
    
    # Test: Search for error handling test cases. Expect: At least one test case for error handling.
    rg --type ts 'catch' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
    

    Length of output: 102



    Script:

    #!/bin/bash
    # Description: Verify test cases related to OngoingMonitoringCron class.
    
    # Test: Search for test cases related to OngoingMonitoringCron class. Expect: At least one test case for OngoingMonitoringCron.
    rg --type ts 'OngoingMonitoringCron' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
    

    Length of output: 368



    Script:

    #!/bin/bash
    # Description: Extract test cases from ongoing-monitoring.cron.intg.test.ts for manual inspection.
    
    # Extract test cases for manual inspection.
    sed -n '/describe/,/});/p' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
    

    Length of output: 1944

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

    717-723: Add documentation for the AlertDefinition model.

    It would be beneficial to add comments describing the purpose and use of each field in the AlertDefinition model, especially for new fields like monitoringType and defaultSeverity. This will enhance maintainability and clarity for other developers.

    Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between ce8bf38 and 48bf1d3.
    Files selected for processing (36)
    • apps/backoffice-v2/src/Router/Router.tsx (2 hunks)
    • apps/backoffice-v2/src/common/components/atoms/MultiSelect/MultiSelect.tsx (4 hunks)
    • apps/backoffice-v2/src/common/hooks/useFilter/useFilter.tsx (2 hunks)
    • apps/backoffice-v2/src/domains/alerts/fetchers.ts (3 hunks)
    • apps/backoffice-v2/src/domains/alerts/helpers/get-alerts-search-schema.ts (2 hunks)
    • apps/backoffice-v2/src/domains/business-alerts/fetchers.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-alerts/query-keys.ts (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/BusinessesAlerts.page.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/BusinessAlertsTable.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/hooks/useBusinessAlertsTableLogic/useBusinessAlertsTableLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/utils/get-severity-from-risk-score.ts (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/hooks/useBusinessAlertsLogic/useBusinessAlertsLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/BusinessesAlertsAnalysis.page.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringRiskSheet/OngoingMonitoringRiskSheet.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/columns.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/TransactionMonitoringAlerts.page.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsFilters/AlertsFilters.tsx (2 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsHeader/AlertsHeader.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/AlertsTable.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx (2 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlertsAnalysis/components/AlertAnalysisSheet/AlertAnalysisSheet.tsx (1 hunks)
    • services/workflows-service/prisma/schema.prisma (2 hunks)
    • services/workflows-service/scripts/alerts/generate-alerts.ts (1 hunks)
    • services/workflows-service/scripts/seed.ts (1 hunks)
    • services/workflows-service/src/alert/alert.controller.external.ts (2 hunks)
    • services/workflows-service/src/common/app-logger/app-logger.service.ts (1 hunks)
    • services/workflows-service/src/data-analytics/data-analytics.service.ts (1 hunks)
    • services/workflows-service/src/data-analytics/types.ts (1 hunks)
    • services/workflows-service/src/prisma/prisma.service.ts (3 hunks)
    • services/workflows-service/src/transaction/transaction.service.ts (2 hunks)
    • services/workflows-service/src/workflow/cron/cron.module.ts (1 hunks)
    • services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts (5 hunks)
    • services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts (2 hunks)
    Files skipped from review due to trivial changes (5)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/utils/get-severity-from-risk-score.ts
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/AlertsTable.tsx
    • services/workflows-service/scripts/alerts/generate-alerts.ts
    • services/workflows-service/src/workflow/cron/cron.module.ts
    Additional comments not posted (27)
    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts (1)

    1-4: LGTM! The update to IAlertsTableProps aligns with the enhanced alert management features.

    apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/BusinessesAlertsAnalysis.page.tsx (1)

    1-13: Well implemented! The use of useBusinessAlertsAnalysisLogic and the handling of potential undefined values with a fallback are both prudent choices.

    apps/backoffice-v2/src/common/hooks/useFilter/useFilter.tsx (1)

    22-31: The addition of the onClear function is a valuable enhancement to the filter functionality, allowing users to reset specific filters easily.

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

    1-22: Well implemented! The BusinessAlertsTable component is correctly set up with dynamic sorting and initial state configuration, enhancing user interaction.

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

    Line range hint 6-29: The addition of the type parameter to the alert search schema is a thoughtful enhancement, allowing for more granular alert management.

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

    1-43: The structured approach to defining query keys for business alerts enhances maintainability and ensures efficient data fetching.

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

    23-23: LGTM! The entityType 'business' aligns with the PR objectives for business-specific alerts.

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

    53-56: Ensure memoization dependencies are correctly specified to avoid unnecessary re-renders.

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

    53-53: Good use of custom error handling for Prisma errors and integration with Sentry for error tracking.

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

    34-66: The columns for 'Date & Time' and 'Risk Score' are well-implemented with appropriate formatting and data representation.

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

    Line range hint 73-99: Effective use of PostgreSQL advisory locks for managing database transactions and robust error handling.

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

    11-26: Ensure the BusinessAlertItem schema is correctly defined and matches the expected data structure.


    53-71: Check the use of apiClient in assignAlertsByIds. Ensure that the API endpoint and method are correctly configured.


    73-91: Validate the logic in updateAlertsDecisionByIds to ensure it correctly handles different alert decisions.


    98-106: Confirm that fetchAlertDefinitionByAlertId fetches the correct alert definition based on the alert ID.


    110-118: Ensure that fetchAlertLabels correctly retrieves alert labels and handles errors appropriately.

    services/workflows-service/src/data-analytics/types.ts (2)

    7-7: Ensure the InlineRule type is correctly used throughout the codebase, especially in functions that accept this type.

    Verification successful

    The InlineRule type is used consistently across the codebase, particularly in the data-analytics.service.ts and alert.service.ts files. This confirms that the type is correctly utilized in various functions and imports.

    • services/workflows-service/src/data-analytics/data-analytics.service.ts
    • services/workflows-service/src/alert/alert.service.ts
    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Verify usage of `InlineRule` type.
    
    # Test: Search for `InlineRule` usage. Expect: Consistent usage across the codebase.
    rg --type typescript 'InlineRule' 'services/workflows-service/src'
    

    Length of output: 99



    Script:

    #!/bin/bash
    # Description: Verify usage of `InlineRule` type.
    
    # Test: Search for `InlineRule` usage. Expect: Consistent usage across the codebase.
    rg --type ts 'InlineRule' 'services/workflows-service/src'
    

    Length of output: 1048


    7-7: Check if the id field in InlineRule should be strictly typed as string or if it can be more specific.

    Verification successful

    The search results indicate that the id field is predominantly used as a string across various files in the codebase. There are no indications that the id field in InlineRule should be more specific than string.

    • The id field is used in multiple contexts, including tests, services, controllers, and repositories, and it is consistently typed as string.
    • There are no specific types or enums being used for the id field that would suggest a more specific type is necessary.

    Based on this evidence, it is appropriate to conclude that the id field in InlineRule should remain typed as string.

    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Verify the type of `id` in `InlineRule`.
    
    # Test: Search for `id` field usage. Expect: Specific type usage where possible.
    rg --type typescript 'id:' 'services/workflows-service/src'
    

    Length of output: 92



    Script:

    #!/bin/bash
    # Description: Verify the type of `id` in `InlineRule`.
    
    # Test: Search for `id` field usage. Expect: Specific type usage where possible.
    rg --type ts 'id:' 'services/workflows-service/src'
    

    Length of output: 42391

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

    2-2: Ensure that useSelect is used correctly and efficiently in AlertsHeader.


    10-10: Check the AlertsHeader component for accessibility features, especially in dropdowns and interactive elements.

    apps/backoffice-v2/src/domains/alerts/fetchers.ts (2)

    75-96: Review the AlertItemSchema for correctness and ensure it matches the expected data structure.


    Line range hint 100-118: Check the fetchAlerts function for proper error handling and performance optimizations.

    apps/backoffice-v2/src/Router/Router.tsx (1)

    128-145: Ensure that the routing configuration for /locale/businesses is correctly set up and matches the application's requirements.

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

    72-82: Ensure proper handling of unknown severity values.

    As previously suggested, adding error handling for unexpected severity values is crucial to prevent runtime errors. The existing solution should be implemented if not already done.

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

    Line range hint 23-37: Ensure proper initialization and usage of SentryService.

    The addition of SentryService for error tracking is a good practice, especially for background tasks like cron jobs where errors might not be immediately visible.

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

    842-852: Ensure consistency in the use of unique constraints.

    The reportId field in the BusinessReport model is marked as unique, which is excellent for ensuring data integrity. However, consider adding a unique constraint that includes both reportId and projectId to prevent duplicate reports across different projects.

    -  reportId String             @unique
    +  reportId String             @unique([reportId, projectId])

    Likely invalid or redundant comment.

    services/workflows-service/scripts/seed.ts (1)

    37-37: Validate the appropriateness of generated mock data.

    Ensure that the data generated by the faker library aligns with the business requirements and testing scenarios. This includes checking the realism and variability of the data, especially for fields that may affect the application's behavior during testing.

    Copy link
    Contributor

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

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

    Actionable comments posted: 1

    Outside diff range and nitpick comments (1)
    services/workflows-service/src/workflow/hook-callback-handler.service.ts (1)

    Line range hint 132-169: Ensure robust error handling and data integrity in prepareWebsiteMonitoringContext. Consider adding more specific error messages and validations for data operations, especially when dealing with external inputs and database interactions.

    Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between 48bf1d3 and 410de81.
    Files selected for processing (4)
    • services/workflows-service/prisma/data-migrations (1 hunks)
    • services/workflows-service/src/business-report/business-report.repository.ts (1 hunks)
    • services/workflows-service/src/business-report/business-report.service.ts (1 hunks)
    • services/workflows-service/src/workflow/hook-callback-handler.service.ts (5 hunks)
    Files skipped from review due to trivial changes (1)
    • services/workflows-service/prisma/data-migrations
    Additional comments not posted (2)
    services/workflows-service/src/business-report/business-report.repository.ts (1)

    39-46: The addition of the findFirst method enhances the repository's capabilities by allowing specific queries for the first matching business report. Good use of scoped queries for multi-tenancy.

    services/workflows-service/src/business-report/business-report.service.ts (1)

    51-56: The addition of the findFirst method in the service layer correctly delegates to the repository, maintaining a clean separation of concerns. Good use of async/await for asynchronous operations.

    Copy link
    Contributor

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

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

    Actionable comments posted: 0

    Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between 410de81 and 45f1ebb.
    Files selected for processing (2)
    • services/workflows-service/prisma/data-migrations (1 hunks)
    • services/workflows-service/scripts/alerts/generate-alerts.ts (5 hunks)
    Files skipped from review as they are similar to previous changes (2)
    • services/workflows-service/prisma/data-migrations
    • services/workflows-service/scripts/alerts/generate-alerts.ts

    Copy link
    Contributor

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

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

    Actionable comments posted: 4

    Outside diff range and nitpick comments (2)
    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/columns.tsx (1)

    21-21: Consider updating the TODO comment to reflect the current status of the decisions PR.

    If the decisions PR has been merged, update the type here accordingly. If not, consider adding a reference to the PR for easier tracking.

    apps/backoffice-v2/src/common/components/organisms/DataTable/DataTable.tsx (1)

    56-58: Ensure the TypeScript types are correctly defined for the props object.

    The use of TypeScript for prop types adds robustness to the component. Consider adding more detailed comments or documentation on how these props affect the component's behavior, especially for complex objects like scroll.

    Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between 45f1ebb and c6a0f23.
    Files selected for processing (31)
    • apps/backoffice-v2/src/common/components/atoms/MultiSelect/MultiSelect.tsx (4 hunks)
    • apps/backoffice-v2/src/common/components/atoms/OpenUrlInNewTabButton/OpenUrlInNewTabButton.tsx (1 hunks)
    • apps/backoffice-v2/src/common/components/organisms/DataTable/DataTable.tsx (2 hunks)
    • apps/backoffice-v2/src/domains/alerts/fetchers.ts (2 hunks)
    • apps/backoffice-v2/src/domains/alerts/helpers/get-alerts-search-schema.ts (2 hunks)
    • apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx (1 hunks)
    • apps/backoffice-v2/src/domains/alerts/query-keys.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-alerts/fetchers.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useBusinessAlertsQuery/useBusinessAlertsQuery.tsx (1 hunks)
    • apps/backoffice-v2/src/domains/business-alerts/query-keys.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-reports/fetchers.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportsQuery/useBusinessReportsQuery.ts (1 hunks)
    • apps/backoffice-v2/src/domains/business-reports/hooks/queries/useLatestBusinessReportQuery/useLatestBusinessReportQuery.tsx (1 hunks)
    • apps/backoffice-v2/src/domains/business-reports/query-keys.ts (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/hooks/useBusinessAlertsTableLogic/useBusinessAlertsTableLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/interfaces.ts (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlerts/hooks/useBusinessAlertsLogic/useBusinessAlertsLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/OngoingMonitoringTable.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/columns.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/SignIn/SignIn.page.tsx (2 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsFilters/AlertsFilters.tsx (2 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/columns.tsx (2 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/hooks/useAlertsTableLogic.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/severity-to-class-name.tsx (1 hunks)
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx (1 hunks)
    • services/workflows-service/scripts/alerts/generate-alerts.ts (6 hunks)
    • services/workflows-service/scripts/seed.ts (2 hunks)
    • services/workflows-service/src/alert/alert.controller.external.ts (2 hunks)
    Files skipped from review due to trivial changes (2)
    • apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/interfaces.ts
    Files skipped from review as they are similar to previous changes (14)
    • apps/backoffice-v2/src/common/components/atoms/MultiSelect/MultiSelect.tsx
    • apps/backoffice-v2/src/domains/alerts/helpers/get-alerts-search-schema.ts
    • apps/backoffice-v2/src/domains/business-alerts/fetchers.ts
    • apps/backoffice-v2/src/domains/business-alerts/query-keys.ts
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/columns.tsx
    • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/hooks/useBusinessAlertsTableLogic/useBusinessAlertsTableLogic.tsx
    • apps/backoffice-v2/src/pages/BusinessesAlerts/hooks/useBusinessAlertsLogic/useBusinessAlertsLogic.tsx
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/columns.tsx
    • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsFilters/AlertsFilters.tsx
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts
    • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx
    • services/workflows-service/scripts/alerts/generate-alerts.ts
    • services/workflows-service/src/alert/alert.controller.external.ts
    Additional comments not posted (29)
    apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportsQuery/useBusinessReportsQuery.ts (1)

    6-19: The implementation of useBusinessReportsQuery looks solid and adheres to best practices for data fetching in React.

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

    3-20: The query key generation using createQueryKeys is implemented correctly and efficiently. This approach enhances the maintainability and scalability of the code.

    apps/backoffice-v2/src/domains/business-reports/hooks/queries/useLatestBusinessReportQuery/useLatestBusinessReportQuery.tsx (1)

    5-12: The implementation of useLatestBusinessReportQuery is robust, correctly handling authentication and parameter validation. This ensures that the query is only executed when appropriate, optimizing performance and resource usage.

    apps/backoffice-v2/src/common/components/atoms/OpenUrlInNewTabButton/OpenUrlInNewTabButton.tsx (1)

    6-31: The OpenUrlInNewTabButton component is well-implemented, with attention to security, accessibility, and styling. The use of conditional styling and aria-disabled attributes enhances the user experience and accessibility.

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

    5-33: The implementation of useBusinessAlertsQuery is robust, efficiently handling authentication and parameter validation. This ensures that the query is only executed when all necessary conditions are met, optimizing performance and resource usage.

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

    10-24: The severity to class name mappings are correctly implemented and use TypeScript's type safety features effectively.

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

    9-22: The query keys for alerts are well-defined, incorporating necessary parameters for effective data fetching and sorting.

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/hooks/useAlertsTableLogic.tsx (1)

    8-8: The hook useAlertsTableLogic is well-implemented, correctly using React hooks for performance optimizations and session management.

    Also applies to: 10-10

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

    22-51: The fetch functions for business reports are correctly implemented using async/await and handle errors effectively with handleZodError.

    apps/backoffice-v2/src/pages/SignIn/SignIn.page.tsx (1)

    Line range hint 21-58: The sign-in form is well-implemented, using modern React practices and libraries for form handling and validation.

    apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/columns.tsx (11)

    21-21: The 'dataTimestamp' column implementation looks good and handles null values correctly.


    21-21: The 'updatedAt' column implementation is consistent and correct.


    21-21: The 'correlationId' column effectively uses the Badge component to display the ID, ensuring it fits within the UI constraints.


    21-21: The 'subject' column correctly handles potential null values and displays the subject's name.


    21-21: The 'subject.type' column correctly formats the subject type using the titleCase function.


    21-21: The 'subject.correlationId' column effectively uses a custom hook to manage text overflow, enhancing UI responsiveness and accessibility.


    21-21: The 'severity' column dynamically applies classes based on the alert's severity, which is a robust method for providing visual cues in the UI.


    21-21: The 'alertDetails' column implementation handles long text appropriately by setting a maximum width, ensuring the UI remains clean.


    21-21: The 'assignee' column effectively uses the Avatar component with a fallback mechanism, which is a good practice for handling missing images.


    21-21: The 'status' column correctly formats the status using the titleCase function.


    21-21: The 'decision' column implementation is complex but correctly handles the conversion to screaming snake case and applies dynamic styling based on the decision.

    apps/backoffice-v2/src/common/components/organisms/DataTable/DataTable.tsx (1)

    191-197: The DataTable component is well-implemented with a clear structure and efficient use of React hooks.

    services/workflows-service/scripts/seed.ts (7)

    38-38: Ensure secure handling of user passwords.


    38-38: Standardize workflow definition creation.


    38-38: Optimize file handling operations.


    38-38: Consider adding error handling for database operations.


    991-998: Ensure proper error handling for the seedOngoingMonitoringAlerts function.

    #!/bin/bash
    # Description: Verify error handling in the `seedOngoingMonitoringAlerts` function.
    
    # Test: Search for error handling logic. Expect: Try-catch blocks or equivalent.
    rg --type typescript 'try {.*seedOngoingMonitoringAlerts.*} catch'

    1000-1000: Consider implementing error handling for seedBusinessReports.

    #!/bin/bash
    # Description: Verify error handling in the `seedBusinessReports` function.
    
    # Test: Search for error handling logic. Expect: Try-catch blocks or equivalent.
    rg --type typescript 'try {.*seedBusinessReports.*} catch'

    991-998: Verify the filtering logic in seedOngoingMonitoringAlerts to ensure it aligns with business requirements.

    #!/bin/bash
    # Description: Verify the filtering logic in `seedOngoingMonitoringAlerts`.
    
    # Test: Search for the function implementation and check the filtering conditions.
    ast-grep --lang typescript --pattern $'function seedOngoingMonitoringAlerts($_, $_) {
      $$$
    }'

    agentUserIds: agentUsers.map(({ id }) => id),
    });

    await seedBusinessReports(client, { businessRiskIds, project: project1 });
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Address the TODO comment regarding creating businesses with end users attached.

    Would you like me to help implement this feature or should I open a GitHub issue to track this task?

    Comment on lines +19 to +20
    export type TBusinessReportType = ('MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1') &
    (string & {});
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Consider simplifying the type definition for TBusinessReportType to enhance readability and maintainability.

    - export type TBusinessReportType = ('MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1') &
    -   (string & {});
    + export type TBusinessReportType = 'MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1';

    Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

    Suggested change
    export type TBusinessReportType = ('MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1') &
    (string & {});
    export type TBusinessReportType = 'MERCHANT_REPORT_T1' | 'ONGOING_MERCHANT_REPORT_T1';

    Comment on lines +75 to +96
    export const AlertSchema = ObjectWithIdSchema.extend({
    dataTimestamp: z.string().datetime(),
    updatedAt: z.string().datetime(),
    subject: ObjectWithIdSchema.extend({
    name: z.string(),
    correlationId: z.string(),
    alertDetails: z.string(),
    // amountOfTxs: z.number(),
    assignee: ObjectWithIdSchema.extend({
    fullName: z.string(),
    avatarUrl: z.string().nullable().optional(),
    })
    .nullable()
    .default(null),
    status: z.enum(AlertStatuses),
    decision: z.enum(AlertStates).nullable().default(null),
    counterpartyId: z.string().nullable().default(null),
    type: z.enum(['business', 'counterparty']),
    }),
    );
    severity: z.enum(AlertSeverities),
    correlationId: z.string(),
    alertDetails: z.string(),
    // amountOfTxs: z.number(),
    assignee: ObjectWithIdSchema.extend({
    fullName: z.string(),
    avatarUrl: z.string().nullable().optional(),
    })
    .nullable()
    .default(null),
    status: z.enum(AlertStatuses),
    decision: z.enum(AlertStates).nullable().default(null),
    counterpartyId: z.string().nullable().default(null),
    });
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    The alert fetching functions are well-implemented, correctly using async/await and error handling. Consider breaking down fetchAlerts into smaller functions for better maintainability.

    Comment on lines +7 to +27
    export const OngoingMonitoringTable: FunctionComponent<{
    businessReports: TBusinessReport[];
    }> = ({ businessReports }) => {
    return (
    <DataTable
    data={businessReports}
    columns={columns}
    props={{
    container: {
    className: 'max-w-[411px]',
    },
    scroll: {
    className: 'h-[47vh]',
    },
    }}
    options={{
    enableSorting: false,
    }}
    />
    );
    };
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Consider memoizing the DataTable component or its props to prevent unnecessary re-renders, especially if the businessReports data can be large or complex. Additionally, ensure that accessibility features such as ARIA labels are correctly implemented in the DataTable component.

    @alonp99 alonp99 closed this Sep 12, 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.

    6 participants