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

Merchant ongoing report - Case management page for ongoing reports alerts #2405

Open
wants to merge 4 commits into
base: bal-1644
Choose a base branch
from

Conversation

liorzam
Copy link
Collaborator

@liorzam liorzam commented May 22, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new "Businesses" page and "BusinessesAlerts" page for managing and viewing alerts.
    • Added functionality to download reports as PDF files.
    • Implemented custom hooks for fetching and managing business alerts and reports.
  • Improvements

    • Enhanced alert management with new components like BusinessAlertsTable for better data display.
    • Improved routing structure for better navigation and organization.
  • Bug Fixes

    • Fixed issues related to alert fetching and schema updates to ensure accurate data handling.
  • Refactor

    • Reordered and optimized import statements across multiple files for better code maintainability.
    • Updated and added new schemas for handling business reports and alerts.
  • Style

    • Adjusted styling in various components for improved UI consistency and readability.
  • Documentation

    • Added comprehensive comments and documentation for new hooks and components to aid developer understanding.

Copy link

changeset-bot bot commented May 22, 2024

⚠️ No Changeset found

Latest commit: 52e09cb

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

This PR includes no changesets

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

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

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

Copy link
Contributor

coderabbitai bot commented May 22, 2024

Walkthrough

The recent updates involve significant restructuring and enhancements across multiple components and modules within the backoffice-v2 application. Key changes include the reorganization of routing in Router.tsx, modifications to alert management functionalities, introduction of new hooks and utilities for handling business alerts, and updates to various UI components for improved user experience.

Changes

Files/Paths Change Summary
.../Router/Router.tsx, .../SignIn/SignIn.page.tsx Reordered and added components, affecting routing and structure.
.../common/components/atoms/MultiSelect/MultiSelect.tsx Swapped imports affecting rendering and styling of icons.
.../common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx Reordered imports and adjusted structure of children array in Businesses section.
.../common/hooks/useFilter/useFilter.tsx Added onClear function to clear specific filters.
.../common/utils/save-base64-as-file/save-base64-as-file.ts Introduced saveBase64AsFile function for saving base64-encoded files.
.../domains/alerts/fetchers.ts, .../domains/alerts/helpers/get-alerts-search-schema.ts Updated schemas and fetch functions for handling alerts based on entity type.
.../domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx Added entityType parameter to useAlertsQuery function.
.../domains/business-alerts/fetchers.ts Introduced functions for fetching and managing business alerts.
.../domains/business-alerts/hooks/mutations/... Added custom hooks for handling alert decisions and assignments.
.../domains/business-alerts/hooks/queries/... Introduced hooks for fetching alert definitions, labels, and business alerts.
.../domains/business-alerts/query-keys.ts Added query keys for business alerts and related data.
.../domains/business-reports/fetchers.ts Updated schemas and functions for fetching business reports.
.../domains/business-reports/hooks/queries/useGetBusinessReportsQuery/useGetBusinessReportsQuery.ts Added custom hook for fetching business reports based on businessId.
.../pages/Businesses/Businesses.tsx, .../pages/BusinessesAlerts/BusinessesAlerts.page.tsx Introduced new components for handling business-related pages and alerts.
.../pages/BusinessesAlerts/components/BusinessAlertsTable/... Added components and columns for displaying business alerts in a table format.
.../pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/... Introduced custom hook for downloading reports.

In the code's vast expanse, changes weave,
New routes and alerts, our apps achieve.
Hooks and queries, a rabbit's delight,
Base64 files saved with a click so light.
Business reports, alerts anew,
A cleaner path, a clearer view.
🐇✨ In this update, the future's bright!


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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration File (.coderabbit.yaml)

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@liorzam liorzam changed the title chore: merge Merchant ongoing report - Case management page for ongoing reports alerts May 22, 2024
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: 10

Outside diff range and nitpick comments (4)
apps/backoffice-v2/src/domains/business-reports/hooks/queries/useGetBusinessReportsQuery/useGetBusinessReportsQuery.ts (1)

8-8: Consider removing the console.log statement if it was used for debugging purposes.

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

Line range hint 66-72: Simplify the createProject function.

The function can be simplified by removing the explicit casting to Project since TypeScript's type inference should handle this automatically.

-  return client.project.create({
+  return client.project.create<Project>({

Line range hint 76-85: Optimize image URI generation logic.

The function generateAvatarImageUri could be optimized by using a switch or if-else ladder for clarity and to avoid multiple return statements that make the flow hard to follow.

function generateAvatarImageUri(imageTemplate: string, countOfBusiness: number, pdf = false) {
  let uri;
  if (pdf) {
    uri = `https://blrn-imgs.s3.eu-central-1.amazonaws.com/github/mock-pdf.pdf`;
  } else if (countOfBusiness < 4) {
    uri = faker.image.business(1000, 2000, true);
  } else {
    uri = faker.image.people(1000, 2000, true);
  }
  return uri;
}

[!TIP]
Codebase Verification

The script output indicates that the API_KEY environment variable is not set, which could lead to runtime errors if it is missing. The search results show multiple occurrences of API_KEY, but no validation or default value setting.

To ensure robustness, it is crucial to add validation or default values for API_KEY in the codebase.

  • File: services/workflows-service/scripts/seed.ts
  • Lines: 1-40

Please add validation or default values for API_KEY to prevent potential runtime errors.

Analysis chain

Line range hint 50-64: Ensure environmental variables are validated before use.

The function uses env.API_KEY directly. It's crucial to ensure that this environmental variable is validated or has default values to prevent runtime errors if it's missing.


The script output indicates that the API_KEY environment variable is not set, which could lead to runtime errors if it is missing. To ensure robustness, we need to verify if there are any default values or validation checks for API_KEY in the codebase.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check if API_KEY is set in the environment variables.

# Test: Print the API_KEY environment variable. Expect: Non-empty output.
echo $API_KEY

Length of output: 7



Script:

#!/bin/bash
# Search for occurrences of API_KEY in the codebase to check for validation or default values.

# Find all occurrences of API_KEY in the codebase.
rg 'API_KEY'

# Check if there are any default values or validation checks for API_KEY.
rg 'API_KEY' | xargs -I {} sh -c 'echo {}; grep -E "if|default|validate" {}'

Length of output: 11080

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 060c6e1 and 52e09cb.
Files selected for processing (57)
  • 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/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx (2 hunks)
  • apps/backoffice-v2/src/common/hooks/useFilter/useFilter.tsx (2 hunks)
  • apps/backoffice-v2/src/common/utils/save-base64-as-file/save-base64-as-file.ts (1 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/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx (2 hunks)
  • apps/backoffice-v2/src/domains/business-alerts/fetchers.ts (1 hunks)
  • apps/backoffice-v2/src/domains/business-alerts/hooks/mutations/useAlertsDecisionByIdsMutation/useAlertsDecisionByIdsMutation.tsx (1 hunks)
  • apps/backoffice-v2/src/domains/business-alerts/hooks/mutations/useAssignAlertsMutation/useAssignAlertsMutation.tsx (1 hunks)
  • apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useAlertDefinitionByAlertIdQuery/useAlertDefinitionByAlertIdQuery.tsx (1 hunks)
  • apps/backoffice-v2/src/domains/business-alerts/hooks/queries/useAlertLabelsQuery/useAlertLabelsQuery.tsx (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/useGetBusinessReportsQuery/useGetBusinessReportsQuery.ts (1 hunks)
  • apps/backoffice-v2/src/domains/business-reports/query-keys.ts (2 hunks)
  • apps/backoffice-v2/src/pages/Businesses/Businesses.tsx (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/index.ts (1 hunks)
  • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/interfaces.ts (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/OngoingMonitoringRiskSheet/index.ts (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/components/OngoingMonitoringTable/components/DownloadReportButton/DownloadReportButton.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/useDownloadReportButtonLogic.ts (1 hunks)
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/index.ts (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/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/components/AlertsTable/severity-to-class-name.tsx (2 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/business-reports/seed-business-reports.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/business/business.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)
Files not processed due to max files limit (2)
  • services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
  • services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts
Files not summarized due to errors (5)
  • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx: Error: Server error. Please try again later.
  • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/TransactionMonitoringAlerts.page.tsx: Error: Server error. Please try again later.
  • services/workflows-service/src/data-analytics/types.ts: Error: Server error. Please try again later.
  • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/index.ts: Error: Server error. Please try again later.
  • services/workflows-service/scripts/business-reports/seed-business-reports.ts: Error: Server error. Please try again later.
Files skipped from review due to trivial changes (15)
  • apps/backoffice-v2/src/common/utils/save-base64-as-file/save-base64-as-file.ts
  • apps/backoffice-v2/src/pages/Businesses/Businesses.tsx
  • apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/interfaces.ts
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/BusinessesAlertsAnalysis.page.tsx
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringRiskSheet/index.ts
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/OngoingMonitoringTable.tsx
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/components/DownloadReportButton/DownloadReportButton.tsx
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/index.ts
  • apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/hooks/useBusinessAlertsAnalysisLogic/useBusinessAlertsAnalysisLogic.tsx
  • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/AlertsTable.tsx
  • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsTable/interfaces.ts
  • services/workflows-service/src/business/business.controller.external.ts
  • services/workflows-service/src/data-analytics/data-analytics.service.ts
  • services/workflows-service/src/transaction/transaction.service.ts
  • services/workflows-service/src/workflow/cron/cron.module.ts
Additional comments not posted (54)
apps/backoffice-v2/src/pages/BusinessesAlerts/components/BusinessAlertsTable/index.ts (1)

1-1: Export statement looks good.

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

5-12: The implementation of useAlertLabelsQuery is correct and follows best practices for data fetching with React Query.

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

5-12: The implementation of useAlertDefinitionByAlertIdQuery is correct and efficiently handles conditional fetching based on authentication and alert ID presence.

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

5-14: The implementation of useGetBusinessReportsQuery is correct and follows best practices for data fetching with React Query.

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

Line range hint 3-21: The structure and logic of the query keys for business reports are correctly implemented and ensure type safety and clarity in data fetching operations.

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

Line range hint 2-13: LGTM! Good use of TypeScript features for type safety and immutability.


15-24: LGTM! Consistent use of TypeScript for ensuring type safety.

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

22-31: Good addition of the onClear function to the useFilter hook. It enhances usability by allowing individual filters to be cleared.

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

13-21: The addition of entityType to useAlertsQuery is a positive change, allowing for more granular control over alert queries.

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

5-36: Well-implemented custom hook useBusinessAlertsQuery that follows best practices for data fetching and provides necessary parameters for effective filtering and sorting.

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

7-22: The BusinessAlertsTable component is well-structured and effectively uses custom hooks and the DataTable component for displaying business alerts.

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

29-29: Adding the optional type field to getAlertsSearchSchema is a beneficial enhancement, allowing for more flexible alert querying.

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

5-43: Well-structured query keys for business alerts.

The use of createQueryKeys provides a clean and maintainable way to manage query keys and associated functions.

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

23-49: Well-implemented mutation hook for alert decisions.

The use of getToastAction to determine the appropriate toast message based on the decision is a clean and effective way to handle user feedback.

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

12-38: Well-structured component for displaying ongoing monitoring risks.

The use of the Sheet component provides a clean and effective layout for presenting risk-related information.

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

4-6: LGTM! The generateFakeRiskScore function correctly generates a random risk score between 1 and 100.

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

3-7: The import and usage of DataTable and related components are correctly implemented for displaying transaction details.

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

2-2: Ensure that the setLogger function from @ballerine/workflow-core is correctly integrated and configured.

Verification successful

The setLogger function from @ballerine/workflow-core is correctly integrated and configured in app-logger.service.ts. The logger methods (log, error, warn, debug) are properly bound to the instance methods of AppLoggerService.

  • services/workflows-service/src/common/app-logger/app-logger.service.ts
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration of `setLogger` function.

# Test: Search for the `setLogger` function usage in other parts of the codebase. Expect: Consistent usage and configuration.
rg --type typescript $'setLogger'

Length of output: 67



Script:

#!/bin/bash
# Description: Verify the integration of `setLogger` function.

# Test: Search for the `setLogger` function usage in other parts of the codebase. Expect: Consistent usage and configuration.
rg --type ts 'setLogger'

Length of output: 463



Script:

#!/bin/bash
# Description: Extract the relevant lines from `app-logger.service.ts` to review the configuration of `setLogger`.

# Extract lines around the usage of `setLogger` in `app-logger.service.ts`.
rg --type ts --context 5 'setLogger' services/workflows-service/src/common/app-logger/app-logger.service.ts

Length of output: 739

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

2-7: The structure and logic of the TransactionMonitoringAlerts component are correctly implemented, ensuring proper conditional rendering and pagination.

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

1-8: The structure and logic of the BusinessesAlerts component are correctly implemented, ensuring proper conditional rendering and pagination.

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

1-7: The useTransactionMonitoringAlertsLogic hook is well-structured and makes effective use of custom hooks for managing state and API interactions.


1-7: Verify the integration and correct usage of the useAlertsQuery hook across the application to ensure consistent behavior.

Verification successful

The useAlertsQuery hook is implemented in useAlertsQuery.tsx and is used in useTransactionMonitoringAlertsLogic.tsx. The implementation appears to be correct, and its usage in useTransactionMonitoringAlertsLogic.tsx is consistent with the expected parameters.

  • useAlertsQuery is defined to accept parameters such as sortBy, sortDir, page, pageSize, search, filter, and entityType.
  • It uses these parameters to construct a query key and fetch alerts data using useQuery from @tanstack/react-query.
  • The usage in useTransactionMonitoringAlertsLogic.tsx correctly passes the required parameters to useAlertsQuery.

No issues were found with the integration and usage of the useAlertsQuery hook.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `useAlertsQuery` hook.

# Test: Search for the `useAlertsQuery` hook usage in other parts of the codebase. Expect: Consistent usage and configuration.
rg --type typescript $'useAlertsQuery'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify the usage of `useAlertsQuery` hook.

# Test: Search for the `useAlertsQuery` hook usage in other parts of the codebase. Expect: Consistent usage and configuration.
rg 'useAlertsQuery' --glob '*.ts' --glob '*.tsx'

Length of output: 612



Script:

#!/bin/bash
# Extract the implementation of `useAlertsQuery` from `useAlertsQuery.tsx`
rg --multiline --multiline-dotall --glob 'apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx' 'export const useAlertsQuery = ({[^}]*}) => {[^}]*}'

# Extract the usage of `useAlertsQuery` from `useTransactionMonitoringAlertsLogic.tsx`
rg --multiline --multiline-dotall --glob 'apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx' 'const { data: alerts, isLoading: isLoadingAlerts } = useAlertsQuery\({[^}]*}\)'

Length of output: 770



Script:

#!/bin/bash
# Extract the implementation of `useAlertsQuery` from `useAlertsQuery.tsx`
rg --multiline --multiline-dotall --glob 'apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx' 'export const useAlertsQuery = \(\{[^}]+\}\) => \{[^}]+\}'

# Extract the usage of `useAlertsQuery` from `useTransactionMonitoringAlertsLogic.tsx`
rg --multiline --multiline-dotall --glob 'apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/hooks/useTransactionMonitoringAlertsLogic/useTransactionMonitoringAlertsLogic.tsx' 'const \{ data: alerts, isLoading: isLoadingAlerts \} = useAlertsQuery\(\{[^}]+\}\)'

Length of output: 1900



Script:

#!/bin/bash
# Extract the entire content of `useAlertsQuery.tsx` to review the implementation
cat apps/backoffice-v2/src/domains/alerts/hooks/queries/useAlertsQuery/useAlertsQuery.tsx

Length of output: 937

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

11-57: Ensure proper handling of optional chaining and null checks in the hook.

Verification successful

The script output indicates that optional chaining is used extensively throughout the codebase, but it does not specifically highlight any issues in the useBusinessAlertsLogic.tsx file. Let's manually review the provided code snippet to ensure proper handling of optional chaining and null checks.

export const useBusinessAlertsLogic = () => {
  const { data: session } = useAuthenticatedUserQuery();
  const AlertsSearchSchema = getAlertsSearchSchema();
  const [{ filter, sortBy, sortDir, page, pageSize, search: searchValue }] =
    useZodSearchParams(AlertsSearchSchema);
  const { data: alerts = [], isLoading: isLoadingAlerts } = useBusinessAlertsQuery({
    filter,
    page,
    pageSize,
    search: searchValue,
    sortDir,
    sortBy,
    entityType: 'business',
  });
  const { data: correlationIds } = useAlertCorrelationIdsQuery();
  const { data: assignees } = useUsersQuery();
  const sortedAssignees = useMemo(
    () =>
      // Sort assignees so that the authenticated user is always first
      assignees
        ?.slice()
        ?.sort((a, b) => (a?.id === session?.user?.id ? -1 : b?.id === session?.user?.id ? 1 : 0)),
    [assignees, session?.user?.id],
  );

  const { onPaginate, onPrevPage, onNextPage } = usePagination();
  const isLastPage = (alerts?.length ?? 0) < pageSize || alerts?.length === 0;
  const { search, onSearch } = useSearch({
    initialSearch: searchValue,
  });

  return {
    alerts,
    isLoadingAlerts,
    assignees: sortedAssignees,
    authenticatedUser: session?.user,
    page,
    pageSize,
    correlationIds,
    onPrevPage,
    onNextPage,
    onPaginate,
    isLastPage,
    search,
    onSearch,
  };
};

Analysis:

  • Optional Chaining: The code uses optional chaining (?.) in several places, such as session?.user?.id, assignees?.slice(), and alerts?.length.
  • Nullish Coalescing: The code uses nullish coalescing (??) to provide default values, such as (alerts?.length ?? 0).
  • Null Checks: The code appears to handle potential null or undefined values appropriately using optional chaining and nullish coalescing.

Conclusion:

The useBusinessAlertsLogic.tsx file appears to handle optional chaining and null checks correctly. There are no apparent issues with null pointer exceptions in the provided code snippet.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify proper null checks and optional chaining in useBusinessAlertsLogic.tsx

# Test: Search for potential null pointer exceptions.
rg --type typescript $'?.'

Length of output: 105



Script:

#!/bin/bash
# Description: Verify proper null checks and optional chaining in useBusinessAlertsLogic.tsx

# Test: Search for potential null pointer exceptions.
rg --type typescript '\?\.'

Length of output: 64



Script:

#!/bin/bash
# Description: Verify proper null checks and optional chaining in useBusinessAlertsLogic.tsx

# Test: Search for potential null pointer exceptions.
rg --type ts '\?\.'

Length of output: 254488

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

23-35: Ensure that the navigation items are correctly constructed and dynamically updated based on the filters.

Verification successful

The provided context shows that the navItems are dynamically constructed based on the businessesFilters and individualsFilters in useNavbarLogic.tsx. The navItems are then used in Header.Navbar.tsx to render the navigation items.

  • The navItems array is populated with items derived from businessesFilters and individualsFilters.
  • The useMemo hook ensures that the filters are recalculated only when the filters data changes.
  • The navItems are passed to the Navbar component, which maps over them to render the navigation structure.

This confirms that the navigation items are correctly constructed and dynamically updated based on the filters.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify dynamic updates of navigation items in useNavbarLogic.tsx

# Test: Search for dynamic updates in the navigation items construction.
rg --type typescript $'navItems'

Length of output: 66



Script:

#!/bin/bash
# Description: Verify dynamic updates of navigation items in useNavbarLogic.tsx

# Test: Search for dynamic updates in the navigation items construction.
rg --type ts,tsx 'navItems'

Length of output: 58



Script:

#!/bin/bash
# Description: Verify dynamic updates of navigation items in useNavbarLogic.tsx

# Test: Search for dynamic updates in the navigation items construction.
rg --type-add 'ts:*.{ts,tsx}' 'navItems'

Length of output: 533



Script:

#!/bin/bash
# Description: Extract relevant lines around `navItems` in `useNavbarLogic.tsx` and `Header.Navbar.tsx`

# Extract lines around `navItems` in `useNavbarLogic.tsx`
rg --type-add 'ts:*.{ts,tsx}' -A 10 -B 10 'navItems' apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx

# Extract lines around `navItems` in `Header.Navbar.tsx`
rg --type-add 'ts:*.{ts,tsx}' -A 10 -B 10 'navItems' apps/backoffice-v2/src/common/components/organisms/Header/Header.Navbar.tsx

Length of output: 2312

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

53-56: Ensure that the correlation IDs are correctly mapped to filter options.

Verification successful

The search results indicate that correlationIds are used in multiple files, including AlertsFilters.tsx. The specific line in question correctly maps correlationIds to filter options.

  • apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsFilters/AlertsFilters.tsx: correlationIds?.map(label => ({ label, value: label })) || [],

This confirms that the correlation IDs are correctly mapped to filter options.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify correct mapping of correlation IDs in AlertsFilters.tsx

# Test: Search for the usage of correlation IDs in the component.
rg --type typescript $'correlationIds'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify correct mapping of correlation IDs in AlertsFilters.tsx

# Test: Search for the usage of correlation IDs in the component.
rg --type ts,tsx 'correlationIds'

Length of output: 64



Script:

#!/bin/bash
# Description: Verify correct mapping of correlation IDs in AlertsFilters.tsx

# Test: Search for the usage of correlation IDs in the component.
rg --type ts --type tsx 'correlationIds'

Length of output: 68



Script:

#!/bin/bash
# Description: Verify correct mapping of correlation IDs in AlertsFilters.tsx

# Test: Search for the usage of correlation IDs in the component.
rg --type typescript 'correlationIds'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify correct mapping of correlation IDs in AlertsFilters.tsx

# Test: Search for the usage of correlation IDs in the component.
rg --type ts 'correlationIds'

Length of output: 3422

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

30-84: Review the error handling and success notifications in the mutation to ensure they are correctly implemented.

Verification successful

The search results confirm that the toast notifications for both success and error cases are implemented in the useAssignAlertsMutation.tsx file. The relevant lines are:

  • toast.success(t(toast:${action}.success, context));
  • toast.error(t(toast:${action}.error, context));

These lines ensure that appropriate toast notifications are displayed based on the success or failure of the mutation.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify error handling and success notifications in useAssignAlertsMutation.tsx

# Test: Search for error handling and success notifications.
rg --type typescript $'toast'

Length of output: 63



Script:

#!/bin/bash
# Description: Verify error handling and success notifications in useAssignAlertsMutation.tsx

# Test: Search for error handling and success notifications.
rg --type ts $'toast'

Length of output: 16103

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

17-80: Ensure that the custom rendering logic for columns is correctly implemented and efficiently handles data transformations.

Verification successful

The custom rendering logic for the columns in columns.tsx appears to be correctly implemented. Here are the key points:

  • createdAt Column:

    • Uses dayjs to format the date and time.
    • Displays the date and time in a flex column layout.
  • riskScore Column:

    • Retrieves the risk score and determines its severity.
    • Uses TextWithNAFallback and Badge components to display the risk score and severity with appropriate styling.
  • report Column:

    • Retrieves report details and uses DownloadReportButton to provide a download link.

The custom rendering logic efficiently handles data transformations and displays the information correctly.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify custom rendering logic in columns.tsx

# Test: Search for custom rendering logic in the column definitions.
rg --type typescript $'cell'

Length of output: 62



Script:

#!/bin/bash
# Description: Verify custom rendering logic in columns.tsx

# Test: Search for custom rendering logic in the column definitions.
rg --type tsx 'cell'

Length of output: 48



Script:

#!/bin/bash
# Description: Verify custom rendering logic in columns.tsx

# Test: Search for custom rendering logic in the column definitions.
rg 'cell' apps/backoffice-v2/src/pages/BusinessesAlertsAnalysis/components/OngoingMonitoringTable/columns.tsx

Length of output: 169

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

Line range hint 73-99: Review the lock management methods to ensure they correctly handle database locks and log appropriate messages.

Verification successful

The methods acquireLock and releaseLock in prisma.service.ts are correctly implemented and used in the ongoing-monitoring.cron.ts and its test file. The methods handle locks correctly and log appropriate messages.

  • acquireLock is used to attempt to acquire a lock and logs an error if it fails.
  • releaseLock is used to release a lock and logs whether the release was successful or not.

These methods are also properly tested in the integration test file ongoing-monitoring.cron.intg.test.ts.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify lock management in prisma.service.ts

# Test: Search for lock management methods and their usage.
rg --type typescript $'lock'

Length of output: 62



Script:

#!/bin/bash
# Description: Verify lock management in prisma.service.ts

# Test: Search for lock management methods and their usage.
rg --type ts 'lock'

Length of output: 166315



Script:

#!/bin/bash
# Description: Extract full implementation of acquireLock and releaseLock methods and their usage.

# Extract the full implementation of acquireLock and releaseLock methods
ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async acquireLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async releaseLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

# Extract usage of acquireLock and releaseLock methods
rg 'acquireLock' --type ts
rg 'releaseLock' --type ts

Length of output: 1873



Script:

#!/bin/bash
# Description: Extract full implementation of acquireLock and releaseLock methods and their usage in ongoing-monitoring.cron.ts and its test file.

# Extract the full implementation of acquireLock and releaseLock methods
ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async acquireLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async releaseLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

# Extract usage of acquireLock and releaseLock methods in ongoing-monitoring.cron.ts
rg 'acquireLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts
rg 'releaseLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts

# Extract usage of acquireLock and releaseLock methods in ongoing-monitoring.cron.intg.test.ts
rg 'acquireLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
rg 'releaseLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts

Length of output: 1307



Script:

#!/bin/bash
# Description: Extract full implementation of acquireLock and releaseLock methods and their usage in ongoing-monitoring.cron.ts and its test file.

# Extract the full implementation of acquireLock and releaseLock methods
ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async acquireLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

ast-grep --lang typescript --pattern $'class PrismaService {
  $$$
  async releaseLock(transaction: PrismaTransaction, lockId: number) {
    $$$
  }
  $$$  
}' services/workflows-service/src/prisma/prisma.service.ts

# Extract usage of acquireLock and releaseLock methods in ongoing-monitoring.cron.ts
rg 'acquireLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts
rg 'releaseLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.ts

# Extract usage of acquireLock and releaseLock methods in ongoing-monitoring.cron.intg.test.ts
rg 'acquireLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts
rg 'releaseLock' services/workflows-service/src/workflow/cron/ongoing-monitoring.cron.intg.test.ts

Length of output: 1307

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

11-26: Ensure the BusinessAlertItem schema is comprehensive and aligns with business requirements.


108-118: Validate the implementation of fetchAlertLabels against the API specifications.


53-71: Check the error handling and schema validation in assignAlertsByIds.

Verification successful

The handleZodError function is defined as follows:

export const handleZodError = <TData>(error: unknown, data: TData) => {
  if (!error || isZodError(error)) {
    return data ?? null;
  }
  throw error;
};

This function checks if the error is a Zod error using isZodError. If it is, or if there is no error, it returns the data. Otherwise, it throws the error.

Given this, the error handling in the assignAlertsByIds function appears to be appropriate. The function uses handleZodError to manage potential errors from the API call, ensuring that Zod validation errors are handled gracefully.

  • assignAlertsByIds function:
    • Uses handleZodError to process errors.
    • Ensures that Zod validation errors are managed correctly.

No issues were found with the error handling and schema validation in the assignAlertsByIds function.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify error handling and schema validation for assigning alerts.

# Test: Search for error handling patterns. Expect: Proper error handling.
rg --type python $'handleZodError'

Length of output: 64



Script:

#!/bin/bash
# Correcting the file type to TypeScript and searching for the handleZodError function definition and its usage.

# Search for the definition of handleZodError function
rg 'function handleZodError' --type typescript

# Search for the usage of handleZodError function
rg 'handleZodError' --type typescript

Length of output: 156



Script:

#!/bin/bash
# Correcting the file type to ts and searching for the handleZodError function definition and its usage.

# Search for the definition of handleZodError function
rg 'function handleZodError' --type ts

# Search for the usage of handleZodError function
rg 'handleZodError' --type ts

Length of output: 5742



Script:

#!/bin/bash
# Review the definition of handleZodError function in handle-zod-error.ts

# Display the definition of handleZodError function
rg 'export const handleZodError' --type ts --context 10

Length of output: 931


93-106: Confirm the schema and endpoint correctness in fetchAlertDefinitionByAlertId.

Verification successful

The fetchAlertDefinitionByAlertId function and the AlertDefinitionByAlertIdSchema are defined and used correctly in both apps/backoffice-v2/src/domains/business-alerts/fetchers.ts and apps/backoffice-v2/src/domains/alerts/fetchers.ts. The endpoint URL in the function matches the expected API structure.

  • fetchAlertDefinitionByAlertId function is correctly defined in both files.
  • The endpoint URL is consistent and correctly formatted.
  • The schema AlertDefinitionByAlertIdSchema is correctly used in both instances.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the schema and endpoint for fetching alert definitions.

# Test: Search for the schema usage. Expect: Correct schema usage.
rg --type python $'AlertDefinitionByAlertIdSchema'

Length of output: 80



Script:

#!/bin/bash
# Description: Verify the schema and endpoint for fetching alert definitions.

# Test 1: Search for the schema definition and its usage. Expect: Correct schema usage.
rg 'AlertDefinitionByAlertIdSchema' --type ts

# Test 2: Verify the endpoint URL in the fetch function. Expect: Correct endpoint URL.
rg 'getOriginUrl(env.VITE_API_URL)/api/v1/external/alerts/' --type ts

Length of output: 537



Script:

#!/bin/bash
# Description: Verify the schema and endpoint for fetching alert definitions.

# Test 1: Search for the fetchAlertDefinitionByAlertId function to verify the endpoint URL. Expect: Correct endpoint URL.
rg 'fetchAlertDefinitionByAlertId' --type ts

Length of output: 799



Script:

#!/bin/bash
# Description: Verify the schema and endpoint for fetching alert definitions.

# Test 1: Search for the fetchAlertDefinitionByAlertId function definitions to verify the endpoint URL. Expect: Correct endpoint URL.
rg 'fetchAlertDefinitionByAlertId' --type ts -A 10

Length of output: 5426


34-51: Verify the API endpoint and parameters in fetchBusinessAlerts.


73-91: Ensure the decision update logic in updateAlertsDecisionByIds is robust and secure.

Verification successful

The search results indicate that there are various security-related terms and practices present in the codebase, such as authentication, authorization, validation, and sanitization. However, none of these references directly pertain to the updateAlertsDecisionByIds function in apps/backoffice-v2/src/domains/business-alerts/fetchers.ts.

To ensure the decision update logic in updateAlertsDecisionByIds is robust and secure, we need to specifically verify if there are any security measures or validations applied within this function or its dependencies.


The search results show the implementation of the updateAlertsDecisionByIds function but do not provide any evidence of security checks, validation, or sanitization within this function. To ensure robustness and security, we need to verify if the apiClient function or any other related functions include necessary security measures.

Let's search for the implementation of the apiClient function and check for any security-related practices within it.


The search results indicate that the apiClient function is defined in apps/backoffice-v2/src/common/api-client/api-client.ts. To verify the security measures, we need to inspect the implementation of this function.

Let's extract the implementation of the apiClient function to check for any security-related practices such as validation, authentication, or sanitization.


The apiClient function in apps/backoffice-v2/src/common/api-client/api-client.ts uses a fetcher function to make HTTP requests. It includes setting the Content-Type header to application/json and includes credentials in the request. However, the snippet does not show any explicit security measures such as validation, authentication, or sanitization.

To ensure the robustness and security of the updateAlertsDecisionByIds function, we need to inspect the fetcher function used within apiClient for any security-related practices.


The search for the fetcher function did not yield any results, indicating that it might not be defined as a function or might be named differently. To proceed, we should search for the term fetcher to locate its definition or usage within the codebase.


The search results indicate that the fetcher function is defined in apps/backoffice-v2/src/common/utils/fetcher/fetcher.ts. To verify the security measures, we need to extract the implementation of this function.


The partial implementation of the fetcher function shows that it sets up a fetch request with a timeout and includes headers for Content-Type. However, it does not provide complete information about any security measures such as validation, authentication, or sanitization.

To fully verify the security measures, we need to extract the complete implementation of the fetcher function.


The partial implementation of the fetcher function shows that it handles HTTP requests with a timeout, processes the response, and throws errors for unsuccessful responses. However, it still does not provide complete information about any security measures such as validation, authentication, or sanitization.

To fully verify the security measures, we need to extract the remaining part of the fetcher function.


The complete implementation of the fetcher function includes several security measures:

  1. Timeout Handling: The function sets a timeout for the request, ensuring that it does not hang indefinitely.
  2. Error Handling: It checks for fetch errors and HTTP response errors, logging and throwing appropriate errors.
  3. Response Validation: It uses a schema to validate the response data, ensuring that the data conforms to expected structures.

These measures contribute to the robustness and security of the updateAlertsDecisionByIds function, as it relies on apiClient, which in turn uses fetcher.

Based on the gathered information, the decision update logic in updateAlertsDecisionByIds appears to be robust and secure.

  • The fetcher function includes timeout handling, error handling, and response validation.
  • The apiClient function leverages fetcher to make HTTP requests securely.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the decision update logic for alerts.

# Test: Search for security checks in decision updates. Expect: Security measures in place.
rg --type python $'security'

Length of output: 58



Script:

#!/bin/bash
# Description: Verify the decision update logic for alerts.

# Test: Search for security checks in decision updates. Expect: Security measures in place.
rg --type ts 'security|validation|sanitize|auth'

Length of output: 87431



Script:

#!/bin/bash
# Description: Verify the decision update logic for alerts in the specific file.

# Test: Search for security checks, validation, and sanitization in the `updateAlertsDecisionByIds` function.
rg 'updateAlertsDecisionByIds' -A 10 apps/backoffice-v2/src/domains/business-alerts/fetchers.ts

Length of output: 389



Script:

#!/bin/bash
# Description: Verify the security measures in the `apiClient` function used in `updateAlertsDecisionByIds`.

# Find the implementation of the `apiClient` function.
rg 'function apiClient' -A 20

# If `apiClient` is not a function, search for its definition.
rg 'apiClient' -A 5

Length of output: 27550



Script:

#!/bin/bash
# Description: Extract the implementation of the `apiClient` function to verify security measures.

# Extract the implementation of the `apiClient` function.
rg 'export const apiClient' -A 20 apps/backoffice-v2/src/common/api-client/api-client.ts

Length of output: 503



Script:

#!/bin/bash
# Description: Extract the implementation of the `fetcher` function to verify security measures.

# Extract the implementation of the `fetcher` function.
rg 'function fetcher' -A 20

Length of output: 29



Script:

#!/bin/bash
# Description: Locate the definition or usage of `fetcher` to verify security measures.

# Search for the term `fetcher` to locate its definition or usage.
rg 'fetcher'

Length of output: 20702



Script:

#!/bin/bash
# Description: Extract the implementation of the `fetcher` function to verify security measures.

# Extract the implementation of the `fetcher` function.
rg 'export const fetcher' -A 20 apps/backoffice-v2/src/common/utils/fetcher/fetcher.ts

Length of output: 572



Script:

#!/bin/bash
# Description: Extract the complete implementation of the `fetcher` function to verify security measures.

# Extract the complete implementation of the `fetcher` function.
rg 'export const fetcher' -A 50 apps/backoffice-v2/src/common/utils/fetcher/fetcher.ts

Length of output: 1195



Script:

#!/bin/bash
# Description: Extract the remaining implementation of the `fetcher` function to verify security measures.

# Extract the remaining implementation of the `fetcher` function.
rg 'export const fetcher' -A 100 apps/backoffice-v2/src/common/utils/fetcher/fetcher.ts

Length of output: 2164

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

7-7: Ensure the InlineRule type is flexible enough to accommodate future rule types.

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

Line range hint 18-116: Check the accessibility and responsiveness of the MultiSelect component.

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

Line range hint 3-59: Ensure the form handling in the SignIn page is secure and user-friendly.

Verification successful

The search results indicate that the SignIn.page.tsx file uses zodResolver for form validation and handles errors, including specific error codes like 401. This suggests that the form handling includes validation and user feedback mechanisms.

  • zodResolver(SignInSchema) ensures that the form data is validated against the SignInSchema.
  • The presence of error handling, specifically checking for 401 error codes, indicates that user feedback is provided for authentication errors.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the form handling security and user-friendliness in the SignIn page.

# Test: Search for form validation logic. Expect: Robust validation and user feedback.
rg --type python $'form'

Length of output: 54



Script:

#!/bin/bash
# Description: Verify the form handling security and user-friendliness in the SignIn page.

# Test: Search for form validation logic in TypeScript files. Expect: Robust validation and user feedback.
rg --type tsx 'resolver|validation|error|feedback' apps/backoffice-v2/src/pages/SignIn/SignIn.page.tsx

Length of output: 132



Script:

#!/bin/bash
# Description: Verify the form handling security and user-friendliness in the SignIn page.

# Test: Search for form validation logic in TypeScript files. Expect: Robust validation and user feedback.
rg --type ts 'resolver|validation|error|feedback' apps/backoffice-v2/src/pages/SignIn/SignIn.page.tsx

Length of output: 318

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

2-14: Verify the integration of dropdowns and search functionality in the AlertsHeader.

Verification successful

The integration of AlertsAssignDropdown, AlertsDecisionDropdown, and Search components in the AlertsHeader component has been verified successfully. The components are imported and utilized within the AlertsHeader file.

  • AlertsAssignDropdown is imported and used.
  • AlertsDecisionDropdown is imported and used.
  • Search is imported and used.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration of dropdowns and search functionality in the AlertsHeader.

# Test: Search for dropdown and search component usage. Expect: Proper integration and functionality.
rg --type python $'dropdown'

Length of output: 58



Script:

#!/bin/bash
# Description: Verify the integration of dropdowns and search functionality in the AlertsHeader component.

# Test: Search for the usage of AlertsAssignDropdown, AlertsDecisionDropdown, and Search components in the AlertsHeader file.
rg 'AlertsAssignDropdown|AlertsDecisionDropdown|Search' apps/backoffice-v2/src/pages/TransactionMonitoringAlerts/components/AlertsHeader/AlertsHeader.tsx

Length of output: 888

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

75-96: Ensure the AlertItemSchema is comprehensive and aligns with the alert management requirements.


Line range hint 98-126: Check the API endpoints and parameters in alert management functions.

Verification successful

The API endpoints and parameters in the alert management functions appear to be correctly implemented. The search results show consistent usage of the expected endpoints in the relevant files.

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

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the API endpoints and parameters in alert management functions.

# Test: Search for the API endpoint usage. Expect: Correct endpoint and parameters.
rg --type python $'api/v1/external/alerts'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify the API endpoints and parameters in alert management functions.

# Test: Search for the API endpoint usage. Expect: Correct endpoint and parameters.
rg --type js 'api/v1/external/alerts'

Length of output: 37



Script:

#!/bin/bash
# Description: Verify the API endpoints and parameters in alert management functions.

# Test: Search for the API endpoint usage. Expect: Correct endpoint and parameters.
rg --type js,ts 'api/v1/external/alerts'

Length of output: 70



Script:

#!/bin/bash
# Description: Verify the API endpoints and parameters in alert management functions.

# Test: Search for the API endpoint usage. Expect: Correct endpoint and parameters.
rg --type js 'api/v1/external/alerts'
rg --type ts 'api/v1/external/alerts'

Length of output: 1351

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

128-145: The integration of the Businesses route and its children is correctly implemented.


133-142: The BusinessesAlerts route and its child BusinessesAlertsAnalysisPage are correctly configured.


139-140: The BusinessesAlertsAnalysisPage route is correctly nested and configured.

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

29-48: The 'Created At' column is correctly implemented with appropriate date formatting.


49-58: The 'Business' column correctly handles the display of business names with a fallback.


59-66: The 'Reason' column is well-implemented with a fixed width for consistent display.


67-86: The 'Severity' column effectively uses conditional styling and badges to represent alert severity levels.


87-119: The 'Report Risk Score' column is correctly implemented, effectively displaying risk scores and their severity.


120-140: The 'Assignee' column is well-implemented with visual representation and appropriate fallbacks for missing data.

services/workflows-service/src/alert/alert.controller.external.ts (3)

Line range hint 28-37: The create method is correctly implemented with appropriate use of decorators and service calls.


Line range hint 39-91: The list method is well-implemented, correctly using validation and structured response handling for listing alerts.


Line range hint 93-125: The listBusinessReportAlerts method is correctly implemented for listing business report alerts with appropriate query handling and response structuring.

services/workflows-service/scripts/alerts/generate-alerts.ts (1)

Line range hint 1-669: The script for generating and seeding alerts is well-structured and correctly implements the logic for alert management.

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

Line range hint 234-250: Verify the workflow configuration for consistency.

The workflow configuration uses a mix of hardcoded and dynamic values. It's important to ensure that these configurations are consistent across different environments and use cases.

Comment on lines +717 to +723
id String @id @default(cuid())
crossEnvKey String? @unique
correlationId String
monitoringType MonitoringType
name String
enabled Boolean @default(true)
description String?
Copy link
Contributor

Choose a reason for hiding this comment

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

Added new fields to AlertDefinition. Ensure that the new fields (crossEnvKey, correlationId, monitoringType, name, enabled, description, dedupeStrategy, config, defaultSeverity) are properly documented and validated.

Comment on lines +842 to +852
id String @id @default(cuid())
type BusinessReportType
reportId String @unique
report Json

riskScore Int
businessId String
business Business @relation(fields: [businessId], references: [id])

projectId String
project Project @relation(fields: [projectId], references: [id])
projectId String
project Project @relation(fields: [projectId], references: [id])
Copy link
Contributor

Choose a reason for hiding this comment

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

Updated BusinessReport model with new fields (type, reportId, report, riskScore, businessId). Ensure that the new reportId field's uniqueness is enforced correctly and that the type field correctly uses the BusinessReportType enum.

import { generateKycManualReviewRuntimeAndToken } from './workflows/runtime/geneate-kyc-manual-review-runtime-and-token';
import { Type } from '@sinclair/typebox';
import { seedTransactionsAlerts } from './alerts/generate-alerts';
import { generateWebsiteMonitoringExample } from './workflows/website-monitoring-workflow';
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider handling potential exceptions in asynchronous operations.

The main seeding function does not handle exceptions for asynchronous operations which might lead to unhandled promise rejections. It's recommended to wrap these operations in try-catch blocks or ensure that the promise rejections are handled appropriately.

Comment on lines +12 to +16
if (riskScore <= 84) {
return AlertSeverity.HIGH;
}

return AlertSeverity.HIGH;
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 logic for scores above 84, as both conditions return HIGH.

-  if (riskScore <= 84) {
-    return AlertSeverity.HIGH;
-  }
-  return AlertSeverity.HIGH;
+  return AlertSeverity.HIGH; // All scores above 39 are considered HIGH

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
if (riskScore <= 84) {
return AlertSeverity.HIGH;
}
return AlertSeverity.HIGH;
return AlertSeverity.HIGH; // All scores above 39 are considered HIGH

Comment on lines +16 to +30
const downloadReport = useCallback(async () => {
setIsDownloading(true);

try {
setIsDownloading(true);
const fileContent = await fetchFileContentById(fileId);

const base64 = octetToFileType(fileContent as string, 'application/pdf');

saveBase64AsFile(base64, `report-${reportId}.pdf`);
} catch (error) {
toast.error('Failed to download report.');
} finally {
setIsDownloading(false);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove redundant state setting and add missing dependencies in useCallback.

- setIsDownloading(true);
- }, []);
+ }, [fileId]);

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
const downloadReport = useCallback(async () => {
setIsDownloading(true);
try {
setIsDownloading(true);
const fileContent = await fetchFileContentById(fileId);
const base64 = octetToFileType(fileContent as string, 'application/pdf');
saveBase64AsFile(base64, `report-${reportId}.pdf`);
} catch (error) {
toast.error('Failed to download report.');
} finally {
setIsDownloading(false);
}
const downloadReport = useCallback(async () => {
setIsDownloading(true);
try {
const fileContent = await fetchFileContentById(fileId);
const base64 = octetToFileType(fileContent as string, 'application/pdf');
saveBase64AsFile(base64, `report-${reportId}.pdf`);
} catch (error) {
toast.error('Failed to download report.');
} finally {
setIsDownloading(false);
}
}, [fileId]);

Comment on lines +23 to +33
return (
<Link
to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${
item?.additionalInfo?.businessId ?? ''
}`}
onClick={onClick}
className={`d-full flex p-4`}
>
{children}
</Link>
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve readability of URL construction in the link component.

- to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${
-   item?.additionalInfo?.businessId ?? ''
- }`}
+ const businessId = item?.additionalInfo?.businessId ?? '';
+ to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${businessId}`}

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
return (
<Link
to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${
item?.additionalInfo?.businessId ?? ''
}`}
onClick={onClick}
className={`d-full flex p-4`}
>
{children}
</Link>
);
const businessId = item?.additionalInfo?.businessId ?? '';
return (
<Link
to={`/${locale}/businesses/alerts/${itemId}${search}&businessId=${businessId}`}
onClick={onClick}
className={`d-full flex p-4`}
>
{children}
</Link>
);

Comment on lines +12 to +17
const onClick = useCallback(() => {
sessionStorage.setItem(
'business-transaction-monitoring:transactions-drawer:previous-path',
`${pathname}${search}`,
);
}, [pathname, search]);
Copy link
Contributor

Choose a reason for hiding this comment

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

Use a constant for session storage key to improve maintainability.

+ const PREVIOUS_PATH_KEY = 'business-transaction-monitoring:transactions-drawer:previous-path';
- sessionStorage.setItem(
-   'business-transaction-monitoring:transactions-drawer:previous-path',
+ sessionStorage.setItem(PREVIOUS_PATH_KEY,

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
const onClick = useCallback(() => {
sessionStorage.setItem(
'business-transaction-monitoring:transactions-drawer:previous-path',
`${pathname}${search}`,
);
}, [pathname, search]);
const PREVIOUS_PATH_KEY = 'business-transaction-monitoring:transactions-drawer:previous-path';
const onClick = useCallback(() => {
sessionStorage.setItem(
PREVIOUS_PATH_KEY,
`${pathname}${search}`,
);
}, [pathname, search]);

Comment on lines +25 to +57
export const seedBusinessReports = async (
prisma: PrismaClient,
{ businessRiskIds, project }: { businessRiskIds: string[]; project: Project },
) => {
const fileIds = await seedFiles(prisma, project);

await Promise.all(
businessRiskIds
.map(businessRiskId =>
fileIds.map(fileId =>
prisma.businessReport.create({
data: {
businessId: businessRiskId,
report: {
data: {
summary: {
riskScore: generateFakeRiskScore(),
},
},
reportFileId: fileId,
reportId: faker.datatype.uuid(),
},
projectId: project.id,
type: 'ONGOING_MERCHANT_REPORT_T1',
riskScore: generateFakeRiskScore(),
reportId: faker.datatype.uuid(),
},
}),
),
)
.flat(1),
);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider optimizing the nested mapping to reduce complexity and improve performance, especially for large datasets.

- businessRiskIds.map(businessRiskId => fileIds.map(fileId => prisma.businessReport.create({...})))
+ for (const businessRiskId of businessRiskIds) {
+   for (const fileId of fileIds) {
+     await prisma.businessReport.create({...});
+   }
+ }

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 const seedBusinessReports = async (
prisma: PrismaClient,
{ businessRiskIds, project }: { businessRiskIds: string[]; project: Project },
) => {
const fileIds = await seedFiles(prisma, project);
await Promise.all(
businessRiskIds
.map(businessRiskId =>
fileIds.map(fileId =>
prisma.businessReport.create({
data: {
businessId: businessRiskId,
report: {
data: {
summary: {
riskScore: generateFakeRiskScore(),
},
},
reportFileId: fileId,
reportId: faker.datatype.uuid(),
},
projectId: project.id,
type: 'ONGOING_MERCHANT_REPORT_T1',
riskScore: generateFakeRiskScore(),
reportId: faker.datatype.uuid(),
},
}),
),
)
.flat(1),
);
};
export const seedBusinessReports = async (
prisma: PrismaClient,
{ businessRiskIds, project }: { businessRiskIds: string[]; project: Project },
) => {
const fileIds = await seedFiles(prisma, project);
for (const businessRiskId of businessRiskIds) {
for (const fileId of fileIds) {
await prisma.businessReport.create({
data: {
businessId: businessRiskId,
report: {
data: {
summary: {
riskScore: generateFakeRiskScore(),
},
},
reportFileId: fileId,
reportId: faker.datatype.uuid(),
},
projectId: project.id,
type: 'ONGOING_MERCHANT_REPORT_T1',
riskScore: generateFakeRiskScore(),
reportId: faker.datatype.uuid(),
},
});
}
}
};

@@ -1,7 +1,7 @@
import { IAppLogger, LogPayload } from '@/common/abstract-logger/abstract-logger';
import { setLogger } from '@ballerine/workflow-core';
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider replacing @ts-ignore with a more type-safe approach to handle different entity types.

- // @ts-ignore
- metadata.entity = entity.customer;
+ if ('customer' in entity) {
+   metadata.entity = entity.customer;
+ }

Committable suggestion was skipped due low confidence.

Comment on lines +26 to +47
const [businessReports, error] = await apiClient({
endpoint: `business-reports/latest?businessId=${businessId}&type=${reportType}`,
method: Method.GET,
schema: BusinessReportSchema,
});
console.log({ error });

return handleZodError(error, businessReports);
};

export const fetchBusinessReports = async ({
businessId,
reportType,
}: {
businessId: string;
reportType: 'MERCHANT_REPORT_T1' | ('ONGOING_MERCHANT_REPORT_T1' & (string & {}));
}) => {
const [businessReports, error] = await apiClient({
endpoint: `business-reports/?businessId=${businessId}&type=${reportType}`,
method: Method.GET,
schema: z.array(BusinessReportSchema),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor API endpoint construction to use a function or constant.

+ const getBusinessReportsEndpoint = (businessId, reportType) => `business-reports/?businessId=${businessId}&type=${reportType}`;
- endpoint: `business-reports/?businessId=${businessId}&type=${reportType}`,
+ endpoint: getBusinessReportsEndpoint(businessId, reportType),

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
const [businessReports, error] = await apiClient({
endpoint: `business-reports/latest?businessId=${businessId}&type=${reportType}`,
method: Method.GET,
schema: BusinessReportSchema,
});
console.log({ error });
return handleZodError(error, businessReports);
};
export const fetchBusinessReports = async ({
businessId,
reportType,
}: {
businessId: string;
reportType: 'MERCHANT_REPORT_T1' | ('ONGOING_MERCHANT_REPORT_T1' & (string & {}));
}) => {
const [businessReports, error] = await apiClient({
endpoint: `business-reports/?businessId=${businessId}&type=${reportType}`,
method: Method.GET,
schema: z.array(BusinessReportSchema),
});
const [businessReports, error] = await apiClient({
endpoint: `business-reports/latest?businessId=${businessId}&type=${reportType}`,
method: Method.GET,
schema: BusinessReportSchema,
});
console.log({ error });
return handleZodError(error, businessReports);
};
const getBusinessReportsEndpoint = (businessId, reportType) => `business-reports/?businessId=${businessId}&type=${reportType}`;
export const fetchBusinessReports = async ({
businessId,
reportType,
}: {
businessId: string;
reportType: 'MERCHANT_REPORT_T1' | ('ONGOING_MERCHANT_REPORT_T1' & (string & {}));
}) => {
const [businessReports, error] = await apiClient({
endpoint: getBusinessReportsEndpoint(businessId, reportType),
method: Method.GET,
schema: z.array(BusinessReportSchema),
});

@Blokh Blokh changed the base branch from dev to bal-1644 May 22, 2024 15:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants