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 Monitoring #2054

Merged
merged 52 commits into from
Mar 19, 2024
Merged

Merchant Monitoring #2054

merged 52 commits into from
Mar 19, 2024

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Feb 7, 2024

User description

Description

  • Added Website monitoring case handling(creation, pdf rendering)
  • UI updates
  • Updated storybook


Type

enhancement, bug_fix


Description

  • Refactored Process Tracker logic for dynamic support based on workflow and processes.
  • Added new components and adapters for handling website monitoring case actions and process tracking.
  • Enhanced Workflow Service with new dependencies and logic for handling base64 file service provider.
  • Extended Blocks Typed with new components like CallToAction and PDFViewerCell.
  • Implemented logic for website monitoring blocks and case actions.
  • Added support for raw HTML descriptions in Dynamic Forms and portal disable option in Popover component.
  • Added new layout component for PDF disclaimers and updated date formatting in PDF Header component.

Changes walkthrough

Relevant files
Enhancement
24 files
useProcessTrackerLogic.tsx
Refactor Process Tracker Logic for Dynamic Support             

apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/useProcessTrackerLogic.tsx

  • Refactored to support dynamic process tracking based on workflow and
    processes.
  • Removed hardcoded process tracking logic.
  • Added support for merchant monitoring process tracking.
  • +31/-111
    WebsiteMonitoringCaseActions.tsx
    Add Website Monitoring Case Actions Component                       

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/WebsiteMonitoringCaseActions.tsx

  • Added new component for handling website monitoring case actions.
  • Implemented logic for handling resolution actions and comments.
  • +90/-0   
    workflow.controller.external.ts
    Reorganize Imports and Add New Dependencies in Workflow Controller

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

  • Reorganized imports for clarity.
  • Added new dependencies for workflow token service and other utilities.

  • +21/-21 
    hook-callback-handler.service.ts
    Add Website Monitoring Process Handling                                   

    services/workflows-service/src/workflow/hook-callback-handler.service.ts

  • Added handling for website monitoring process.
  • Refactored to improve readability and maintainability.
  • +61/-9   
    workflow.service.ts
    Enhance Workflow Service with New Dependencies and Logic 

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

  • Added business service and AJV validator as dependencies.
  • Implemented logic for handling base64 file service provider.
  • +12/-12 
    create-blocks-typed.ts
    Extend Blocks Typed with New Components                                   

    apps/backoffice-v2/src/lib/blocks/create-blocks-typed/create-blocks-typed.ts

  • Added new components for CallToAction and PDFViewerCell.
  • Updated cells mapping to include new components.
  • +15/-13 
    useWebsiteMonitoringCaseActions.ts
    Implement Logic for Website Monitoring Case Actions           

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/hooks/useWebsiteMonitoringCaseActions/useWebsiteMonitoringCaseActions.ts

  • Implemented logic for website monitoring case actions.
  • Added state management for form values and submission handling.
  • +60/-0   
    FieldLayout.tsx
    Support Raw HTML Descriptions in Dynamic Forms                     

    packages/ui/src/components/organisms/DynamicForm/components/layouts/FieldLayout/FieldLayout.tsx

    • Added support for raw HTML descriptions in dynamic forms.
    +18/-9   
    Popover.tsx
    Add Portal Disable Support in Popover Component                   

    packages/ui/src/components/atoms/Popover/Popover.tsx

    • Added support for disabling portal in Popover component.
    +22/-18 
    ProcessTracker.tsx
    Update Process Tracker to Use Dynamic Logic                           

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/ProcessTracker.tsx

    • Updated to use dynamic process tracking logic.
    +10/-26 
    BlocksVariant.tsx
    Support Website Monitoring Blocks Variant                               

    apps/backoffice-v2/src/lib/blocks/variants/BlocksVariant/BlocksVariant.tsx

    • Added support for website monitoring blocks variant.
    +16/-6   
    third-party.proces-tracker.tsx
    Implement Third-Party Process Tracker Adapter                       

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/third-party.proces-tracker.tsx

    • Implemented third-party process tracker adapter.
    +55/-0   
    Entity.page.tsx
    Integrate New Process Tracker Logic and Components             

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

    • Integrated new process tracker logic and components.
    +8/-6     
    useCaseActionsLogic.tsx
    Refactor Case Actions Logic                                                           

    apps/backoffice-v2/src/pages/Entity/components/Case/hooks/useCaseActionsLogic/useCaseActionsLogic.tsx

    • Refactored to improve logic and readability.
    +6/-5     
    Disclaimer.tsx
    Add Disclaimer Layout Component for PDFs                                 

    packages/react-pdf-toolkit/src/components/layouts/Disclaimer/Disclaimer.tsx

    • Added new Disclaimer layout component for PDFs.
    +32/-0   
    merchant-monitoring.process-tracker.ts
    Implement Merchant Monitoring Process Tracker Adapter       

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/merchant-monitoring.process-tracker.ts

    • Implemented merchant monitoring process tracker adapter.
    +44/-0   
    collection-flow.process-tracker.ts
    Implement Collection Flow Process Tracker Adapter               

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/collection-flow.process-tracker.ts

    • Implemented collection flow process tracker adapter.
    +46/-0   
    get-file-metadata.ts
    Add Handling for Base64 File Names                                             

    services/workflows-service/src/common/get-file-metadata/get-file-metadata.ts

    • Added handling for base64 file names.
    +16/-4   
    ubo-flows.process-tracker.ts
    Implement UBO Flows Process Tracker Adapter                           

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/ubo-flows.process-tracker.ts

    • Implemented UBO flows process tracker adapter.
    +42/-0   
    RadioInputAdapter.tsx
    Add RadioInputAdapter for DynamicForm                                       

    packages/ui/src/components/organisms/DynamicForm/components/RSJVInputAdaters/RadioInputAdapter/RadioInputAdapter.tsx

    • Added new RadioInputAdapter for DynamicForm.
    +37/-0   
    usePDFRevisionBlocks.tsx
    Implement Logic for Website Monitoring Blocks                       

    apps/backoffice-v2/src/lib/blocks/variants/WebsiteMonitoringBlocks/hooks/useWebsiteMonitoringBlocks/usePDFRevisionBlocks.tsx

    • Implemented logic for website monitoring blocks.
    +42/-0   
    ActionsVariant.tsx
    Support Website Monitoring Actions Variant                             

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/ActionsVariant/ActionsVariant.tsx

    • Added support for website monitoring actions variant.
    +11/-2   
    base64-file.service.ts
    Add Base64FileService for Handling Base64 Files                   

    services/workflows-service/src/providers/file/file-provider/base64-file.service.ts

    • Added new Base64FileService for handling base64 files.
    +40/-0   
    Header.tsx
    Update Date Formatting in PDF Header Component                     

    packages/react-pdf-toolkit/src/components/layouts/Header/Header.tsx

    • Updated date formatting in PDF Header component.
    +5/-2     

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

    Copy link

    changeset-bot bot commented Feb 7, 2024

    🦋 Changeset detected

    Latest commit: e489f01

    The changes in this PR will be included in the next version bump.

    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

    Not sure what this means? Click here to learn what changesets are.

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

    @github-actions github-actions bot added enhancement New feature or request bug_fix labels Mar 19, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (98ece33)

    Copy link
    Contributor

    github-actions bot commented Mar 19, 2024

    PR Review

    (Review updated until commit 924e0c1)

    ⏱️ Estimated effort to review [1-5]

    4, due to the extensive changes across multiple files, including new features, refactoring, and updates to existing logic. The PR introduces new components, adapters, and utilities, alongside modifications to existing services and UI components. Reviewing these changes requires a thorough understanding of the project's architecture and the implications of the updates on the system's functionality and performance.

    🧪 Relevant tests

    No

    🔍 Possible issues

    Possible Bug: The implementation of new process tracker adapters and the modifications in the useProcessTrackerLogic hook might introduce bugs if not properly integrated with the existing system. Testing these components for various workflows is crucial.

    Performance Concern: The addition of new components and logic, especially in the PDF rendering and process tracking, could impact the application's performance. It's important to assess the performance implications of these changes, particularly in terms of memory usage and response times.

    🔒 Security concerns

    No

    Code feedback:
    relevant fileapps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/useProcessTrackerLogic.tsx
    suggestion      

    Consider adding error handling for unsupported process names in the processTrackers useMemo hook. This will ensure the application gracefully handles configurations with unsupported process names, improving the robustness of the process tracker logic. [important]

    relevant lineconsole.warn(`${processName} is unsupported.`);

    relevant fileservices/workflows-service/src/workflow/hook-callback-handler.service.ts
    suggestion      

    Implement error handling for the prepareWebsiteMonitoringContext method to manage potential failures in document persistence or customer data retrieval. This will enhance the reliability of the website monitoring callback handling. [important]

    relevant lineasync prepareWebsiteMonitoringContext(

    relevant fileservices/workflows-service/src/providers/file/file-provider/base64-file.service.ts
    suggestion      

    Validate the base64 string in the download method to ensure it's well-formed before writing it to a file. This validation can prevent potential errors or security issues related to malformed base64 strings. [medium]

    relevant linewriteFileSync(tmpFile.name, remoteFileConfig as string, { encoding: 'base64' });

    relevant filepackages/react-pdf-toolkit/src/components/layouts/Header/Header.tsx
    suggestion      

    Use a library like date-fns or moment for date formatting to handle different locales and time zones more effectively. This change would improve the flexibility and correctness of date representations in PDF headers. [medium]

    relevant line{`${dayjs(createdAtTimestamp).format(


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
    When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    

    With a configuration file, use the following template:

    [pr_reviewer]
    some_config1=...
    some_config2=...
    
    Utilizing extra instructions

    The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

    Examples for extra instructions:

    [pr_reviewer] # /review #
    extra_instructions="""
    In the 'possible issues' section, emphasize the following:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    How to enable\disable automation
    • When you first install PR-Agent app, the default mode for the review tool is:
    pr_commands = ["/review", ...]
    

    meaning the review tool will run automatically on every PR, with the default configuration.
    Edit this field to enable/disable the tool, or to change the used configurations

    Auto-labels

    The review tool can auto-generate two specific types of labels for a PR:

    • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
    • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
    Extra sub-tools

    The review tool provides a collection of possible feedbacks about a PR.
    It is recommended to review the possible options, and choose the ones relevant for your use case.
    Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
    require_score_review, require_soc2_ticket, require_can_be_split_review, and more.

    Auto-approve PRs

    By invoking:

    /review auto_approve
    

    The tool will automatically approve the PR, and add a comment with the approval.

    To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

    [pr_reviewer]
    enable_auto_approval = true
    

    (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

    You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

    [pr_reviewer]
    maximal_review_effort = 5
    
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

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

    Copy link
    Contributor

    github-actions bot commented Mar 19, 2024

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Maintainability
    Improve variable naming for clarity.

    Consider using a more descriptive variable name than tag for the variable that stores the
    result of finding a tag in workflow?.tags. A name like foundTag or activeTag would make
    the code clearer and more readable.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/useProcessTrackerLogic.tsx [14-18]

    -const tag = useMemo(
    +const foundTag = useMemo(
       () => tags?.find(tag => tagToAccordionCardItem[tag as keyof typeof tagToAccordionCardItem]),
       [tags],
     );
     
    Abstract logic into a separate function for clarity.

    To enhance the maintainability of the code, consider abstracting the logic inside the
    useMemo for processTrackers into a separate function. This will make the code cleaner and
    easier to understand.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/useProcessTrackerLogic.tsx [25-40]

    -const processTrackers = useMemo(
    -  () =>
    -    processes.reduce((list, processName) => {
    -      const ProcessTracker = processTrackersMap[processName as keyof typeof processTrackersMap];
    -      if (!ProcessTracker) {
    -        console.warn(`${processName} is unsupported.`);
    -        return list;
    -      }
    -      list.push(new ProcessTracker(workflow, plugins));
    +const buildProcessTrackers = (processes, workflow, plugins) => 
    +  processes.reduce((list, processName) => {
    +    const ProcessTracker = processTrackersMap[processName as keyof typeof processTrackersMap];
    +    if (!ProcessTracker) {
    +      console.warn(`${processName} is unsupported.`);
           return list;
    -    }, [] as IProcessTracker[]),
    -  [workflow, plugins, processes],
    -);
    +    }
    +    list.push(new ProcessTracker(workflow, plugins));
    +    return list;
    +  }, [] as IProcessTracker[]);
    +const processTrackers = useMemo(() => buildProcessTrackers(processes, workflow, plugins), [workflow, plugins, processes]);
     
    Replace magic strings with constants or enums for action values.

    Consider using a constant object or an enum for the action values like 'resolved',
    'suspend', and 'N/A' to avoid magic strings throughout the code. This will make the code
    more maintainable and less error-prone.

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/WebsiteMonitoringCaseActions.tsx [55-65]

    -<SelectItem value={'resolved'}>Mark as resolved</SelectItem>
    -<SelectItem value={'suspend'}>Suspend Merchant Account</SelectItem>
    -<SelectItem value={'N/A'} disabled>
    +<SelectItem value={ACTION_TYPES.RESOLVED}>Mark as resolved</SelectItem>
    +<SelectItem value={ACTION_TYPES.SUSPEND}>Suspend Merchant Account</SelectItem>
    +<SelectItem value={ACTION_TYPES.NA} disabled>
     
    Enhancement
    Use Array.prototype.find for clearer and more concise code.

    To improve code readability and maintainability, consider using Array.prototype.find
    directly instead of forEach in the getPluginByName method. This will make the intention of
    the code clearer and eliminate the need for a mutable variable.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/third-party.proces-tracker.tsx [42-54]

     private getPluginByName(name: string) {
    -  let plugin: NonNullable<TWorkflowById['context']['pluginsOutput']>[string];
    -  Object.keys(this.workflow?.context?.pluginsOutput ?? {})?.forEach(key => {
    -    if (this.workflow?.context?.pluginsOutput?.[key]?.name !== name) {
    -      return;
    -    }
    -    plugin = this.workflow?.context?.pluginsOutput?.[key];
    -  });
    -  return plugin;
    +  return Object.values(this.workflow?.context?.pluginsOutput ?? {}).find(plugin => plugin?.name === name);
     }
     
    Destructure workflowDefinition directly for simplicity and readability.

    Consider destructuring workflowDefinition from workflow directly in the function parameter
    to simplify the code and improve readability.

    apps/backoffice-v2/src/pages/Entity/Entity.page.tsx [9]

    -const { workflow, selectedEntity, plugins, processTrackerProcesses } = useEntityLogic();
    +const { workflow: { workflowDefinition }, selectedEntity, plugins, processTrackerProcesses } = useEntityLogic();
     
    Use font-semibold for text style consistency.

    Consider using font-semibold instead of font-bold for the text style to maintain
    consistency with the design system.

    packages/react-pdf-toolkit/src/components/atoms/Badge/Badge.tsx [36]

    -<Text style={tw('font-bold text-xs leading-5')}>{text}</Text>
    +<Text style={tw('font-semibold text-xs leading-5')}>{text}</Text>
     
    Adjust title text size to match design specifications.

    Adjust the title text size to align with the design specifications. If text-[18px] is too
    small, consider using a larger size that matches the design.

    packages/react-pdf-toolkit/src/components/atoms/Typography/Typography.tsx [16]

    -title: 'text-[18px]',
    +title: 'text-[24px]',
     
    Best practice
    Ensure a default return value for consistency and error prevention.

    Consider using a default return value for the resolveTitleToTags method to handle cases
    where none of the conditions are met. This will ensure the function always returns a
    consistent type and avoids potential runtime errors.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/merchant-monitoring.process-tracker.ts [27-36]

     private resolveTitleToTags(tags?: string[]) {
       if (tags?.includes(StateTag.PENDING_PROCESS)) return 'Risk Analysis';
       if (tags?.includes(StateTag.FAILURE)) return 'Process failed.';
       if (tags?.includes(StateTag.MANUAL_REVIEW)) return 'Manual Review';
       if (tags?.includes(StateTag.REJECTED)) return 'Rejected';
       if (tags?.includes(StateTag.APPROVED)) return 'Approved';
    +  return 'Unknown Status'; // Default return value
     }
     
    Use generics with FunctionComponent for defining component props.

    The FunctionComponent type should be used with generics to define the props. Instead of
    destructuring props and value directly in the function parameter, define them inside the
    component's prop type for better readability and maintainability.

    apps/backoffice-v2/src/lib/blocks/components/PDFViewerCell/PDFViewer.tsx [4]

    -export const PDFViewerCell: FunctionComponent<TPDFViewerCell> = ({ props, value }) => {
    +export const PDFViewerCell: FunctionComponent<{ props: TPDFViewerCell['props']; value: TPDFViewerCell['value']; }> = ({ props, value }) => {
     
    Use specific types for ColumnDef array for better type safety.

    Use a more specific type than unknown for the ColumnDef array to ensure type safety and
    better IntelliSense support in the editor.

    apps/backoffice-v2/src/lib/blocks/variants/PDFRevisionBlocks/hooks/usePDFRevisionBlocks/usePDFRevisionBlocks.tsx [191]

    -columns: Array<ColumnDef<unknown>>;
    +columns: Array<ColumnDef<YourSpecificType>>;
     
    Replace wildcard exports with explicit exports for better maintainability and readability.

    Consider using explicit exports instead of wildcard exports. Wildcard exports make it
    harder to understand which components are being exported, can lead to name conflicts, and
    make it more difficult for tools like tree-shaking to optimize the bundle size. Explicitly
    exporting each component will improve maintainability and readability of the code.

    packages/react-pdf-toolkit/src/components/icons/index.ts [2-3]

    -export * from './CheckCircleIcon';
    -export * from './CheckSquareIcon';
    +import { CheckCircleIcon } from './CheckCircleIcon';
    +import { CheckSquareIcon } from './CheckSquareIcon';
     
    +export { CheckCircleIcon, CheckSquareIcon };
    +
    Performance
    Use Object.entries for more efficient and readable code.

    To improve the performance and readability of the getSteps method, consider using
    Object.entries instead of Object.keys and then sorting. This approach allows you to access
    both the key and value without additional lookups, making the code cleaner and potentially
    more efficient.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/collection-flow.process-tracker.ts [30-36]

     private getSteps() {
    -  return Object.keys(this.workflow?.context?.flowConfig?.stepsProgress ?? {})?.sort((a, b) => {
    -    return (
    -      (this.workflow?.context?.flowConfig?.stepsProgress?.[a]?.number ?? 0) -
    -      (this.workflow?.context?.flowConfig?.stepsProgress?.[b]?.number ?? 0)
    -    );
    -  });
    +  return Object.entries(this.workflow?.context?.flowConfig?.stepsProgress ?? {})
    +    .sort(([aKey, aValue], [bKey, bValue]) => aValue?.number - bValue?.number)
    +    .map(([key, _]) => key);
     }
     
    Accessibility
    Add a title attribute to the iframe for accessibility.

    For the iframe element, consider adding a title attribute to improve accessibility. Screen
    readers use this to describe the contents of the iframe to users.

    apps/backoffice-v2/src/lib/blocks/components/PDFViewerCell/PDFViewer.tsx [8]

    -<iframe src={`data:application/pdf;base64,${value}#navpanes=0`} width={width} height={height} />
    +<iframe title="PDF Viewer" src={`data:application/pdf;base64,${value}#navpanes=0`} width={width} height={height} />
     
    Possible issue
    Ensure defined values for workflowId and filterId or provide fallbacks.

    Instead of casting types with as string for workflowId and filterId, ensure the values are
    defined or provide a fallback value to avoid potential runtime errors.

    apps/backoffice-v2/src/lib/blocks/variants/PDFRevisionBlocks/hooks/usePDFRevisionBlocks/usePDFRevisionBlocks.tsx [11-12]

    -workflowId: workflowId as string,
    -filterId: filterId as string,
    +workflowId: workflowId ?? '',
    +filterId: filterId ?? '',
     
    Handle potential undefined values for workflowId.

    Consider handling the case where workflow?.id might be undefined in the mutation hooks to
    avoid potential runtime errors.

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/hooks/useWebsiteMonitoringCaseActions/useWebsiteMonitoringCaseActions.ts [16-19]

    -{ workflowId: workflow?.id as string },
    +{ workflowId: workflow?.id ?? 'defaultWorkflowId' },
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

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

    Copy link
    Contributor

    PR Description updated to latest commit (924e0c1)

    Copy link
    Contributor

    Persistent review updated to latest commit 924e0c1

    Copy link
    Contributor

    github-actions bot commented Mar 19, 2024

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Use a more specific type for the uncollapsedItemValue state.

    Consider using a more specific type than string for the uncollapsedItemValue state to
    ensure it matches the expected values. This can help prevent bugs related to incorrect
    value assignments and improve code readability. If uncollapsedItemValue is expected to
    match the names of processes or other specific strings, define a type that includes these
    specific strings as its possible values.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/useProcessTrackerLogic.tsx [20]

    -const [uncollapsedItemValue, setUncollapsedItemValue] = useState<string>();
    +type ProcessName = 'collection-flow' | 'third-party' | 'ubos'; // Add other process names as needed
    +const [uncollapsedItemValue, setUncollapsedItemValue] = useState<ProcessName>();
     
    Add a title attribute to the iframe for accessibility.

    It is recommended to include a title attribute within the iframe for accessibility
    reasons. This title can describe the content or purpose of the iframe to users who rely on
    screen readers.

    apps/backoffice-v2/src/lib/blocks/components/PDFViewerCell/PDFViewer.tsx [8]

    -<iframe src={`data:application/pdf;base64,${value}#navpanes=0`} width={width} height={height} />
    +<iframe src={`data:application/pdf;base64,${value}#navpanes=0`} width={width} height={height} title="PDF Viewer" />
     
    Simplify assignment with optional chaining and nullish coalescing.

    Use optional chaining and nullish coalescing to simplify the assignment of value in the
    addCell method to handle cases where workflow or its nested properties might be undefined.

    apps/backoffice-v2/src/lib/blocks/variants/WebsiteMonitoringBlocks/hooks/useWebsiteMonitoringBlocks/usePDFRevisionBlocks.tsx [31]

    -value: workflow?.context?.entity?.report?.base64Pdf || '',
    +value: workflow?.context?.entity?.report?.base64Pdf ?? '',
     
    Adjust font weight in Badge component.

    Change the font weight from font-bold to font-semibold for the Badge component to match
    the design specifications.

    packages/react-pdf-toolkit/src/components/atoms/Badge/Badge.tsx [36]

    -<Text style={tw('font-bold text-xs leading-5')}>{text}</Text>
    +<Text style={tw('font-semibold text-xs leading-5')}>{text}</Text>
     
    Correct font size for title variant.

    Adjust the font size for the title variant from 18px to 24px to ensure consistency with
    the design guidelines.

    packages/react-pdf-toolkit/src/components/atoms/Typography/Typography.tsx [16]

    -title: 'text-[18px]',
    +title: 'text-[24px]',
     
    Add trailingIcon support to ListItem.

    Add support for a trailingIcon prop to ListItem for cases where an icon is needed at the
    end of the list item.

    packages/react-pdf-toolkit/src/components/atoms/List/List.Item.tsx [27-30]

     <View style={mergeStyles([tw(listItemCva({ iconPosition })), ...styles])}>
    +  {children}
    +  {trailingIcon && <View>{trailingIcon}</View>}
     
    Best practice
    Explicitly define the return type of the getSteps method as string[].

    To improve the type safety and readability of the getSteps method, consider explicitly
    defining the return type of the method as string[]. This change makes it clear what type
    of data is expected to be returned and helps catch potential issues during development.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/collection-flow.process-tracker.ts [30]

    -private getSteps() {
    +private getSteps(): string[] {
     
    Use useEffect for cleanup to prevent memory leaks.

    Consider using React's useEffect hook to clean up the iframe or any other resources when
    the component unmounts to prevent memory leaks.

    apps/backoffice-v2/src/lib/blocks/components/PDFViewerCell/PDFViewer.tsx [4]

    +import { useEffect } from 'react';
     export const PDFViewerCell: FunctionComponent<TPDFViewerCell> = ({ props, value }) => {
    +  useEffect(() => {
    +    return () => {
    +      // Cleanup code here
    +    };
    +  }, []);
    +};
     
    Improve type safety with explicit typing for hooks.

    To enhance type safety and readability, explicitly type the useParams and useFilterId
    hooks return values instead of using type assertions.

    apps/backoffice-v2/src/lib/blocks/variants/WebsiteMonitoringBlocks/hooks/useWebsiteMonitoringBlocks/usePDFRevisionBlocks.tsx [8-9]

    -const { entityId: workflowId } = useParams();
    -const filterId = useFilterId();
    +const { entityId: workflowId } = useParams<{ entityId: string }>();
    +const filterId = useFilterId() as string;
     
    Replace wildcard exports with explicit exports for better readability and maintainability.

    Consider using explicit exports instead of wildcard exports. Wildcard exports can make it
    harder to understand which components are being exported and can lead to unexpected
    behavior if multiple components have the same name. Explicitly listing each export can
    improve readability and maintainability.

    packages/react-pdf-toolkit/src/components/icons/index.ts [2-3]

    -export * from './CheckCircleIcon';
    -export * from './CheckSquareIcon';
    +export { CheckCircleIcon } from './CheckCircleIcon';
    +export { CheckSquareIcon } from './CheckSquareIcon';
     
    Bug
    Ensure resolveTitleToTags always returns a string by adding a default return value.

    The method resolveTitleToTags does not always return a value, which could lead to
    undefined being used where a string is expected. Ensure that this method always returns a
    string by adding a default return value at the end.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/merchant-monitoring.process-tracker.ts [27-36]

    -private resolveTitleToTags(tags?: string[]) {
    +private resolveTitleToTags(tags?: string[]): string {
    +    if (tags?.includes(StateTag.PENDING_PROCESS)) return 'Risk Analysis';
    +    if (tags?.includes(StateTag.FAILURE)) return 'Process failed.';
    +    if (tags?.includes(StateTag.MANUAL_REVIEW)) return 'Manual Review';
    +    if (tags?.includes(StateTag.REJECTED)) return 'Rejected';
    +    if (tags?.includes(StateTag.APPROVED)) return 'Approved';
    +    return 'Unknown'; // Default return value
    +}
     
    Performance
    Use find instead of forEach in getPluginByName for better performance.

    To improve the performance and readability of the getPluginByName method, consider using
    the find method instead of forEach. This change avoids unnecessary iterations after the
    plugin is found.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/third-party.proces-tracker.tsx [42-53]

     private getPluginByName(name: string) {
    +    return Object.values(this.workflow?.context?.pluginsOutput ?? {}).find(plugin => plugin?.name === name);
    +}
     
    Memoize the BlocksComponent children function to improve performance.

    For better performance and to avoid unnecessary re-renders, consider memoizing the
    BlocksComponent children function using React's useCallback hook.

    apps/backoffice-v2/src/lib/blocks/variants/WebsiteMonitoringBlocks/WebsiteMonitoringBlocks.tsx [11]

    -{(Cell, cell) => <Cell {...cell} />}
    +import { useCallback } from 'react';
    +const renderCell = useCallback((Cell, cell) => <Cell {...cell} />, []);
    +...
    +{renderCell}
     
    Maintainability
    Explicitly define the return type of getChildWorkflows.

    To ensure that the getChildWorkflows method is more robust and its intent is clear,
    consider explicitly defining its return type. This helps with code maintainability and
    readability.

    apps/backoffice-v2/src/common/components/molecules/ProcessTracker/hooks/useProcessTrackerLogic/process-tracker-adapters/ubo-flows.process-tracker.ts [39]

    -private getChildWorkflows() {
    +private getChildWorkflows(): TWorkflowById[] {
     
    Replace hardcoded action strings with constants.

    Consider using a constant for action values like 'resolved', 'suspend', and 'N/A' to avoid
    hardcoding strings multiple times. This will make the code more maintainable and less
    error-prone.

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/WebsiteMonitoringCaseActions.tsx [55-64]

    -<SelectItem value={'resolved'}>Mark as resolved</SelectItem>
    -<SelectItem value={'suspend'}>Suspend Merchant Account</SelectItem>
    -<SelectItem value={'N/A'} disabled>
    +<SelectItem value={ACTION_RESOLVED}>Mark as resolved</SelectItem>
    +<SelectItem value={ACTION_SUSPEND}>Suspend Merchant Account</SelectItem>
    +<SelectItem value={ACTION_NA} disabled>
     
    Readability
    Rename mutation functions for clarity.

    Use a more descriptive name for the onMutateApproveEntity and onMutateRejectEntity
    functions to reflect their purpose more clearly, such as approveCase and rejectCase.

    apps/backoffice-v2/src/pages/Entity/components/Case/actions-variants/WebsiteMonitoringCaseActions/hooks/useWebsiteMonitoringCaseActions/useWebsiteMonitoringCaseActions.ts [15-20]

    -const { mutate: onMutateApproveEntity, isLoading: isApproveCaseLoading } = useApproveCaseMutation(
    -const { mutate: onMutateRejectEntity, isLoading: isRejectCaseLoading } = useRejectCaseMutation({
    +const { mutate: approveCase, isLoading: isApproveCaseLoading } = useApproveCaseMutation(
    +const { mutate: rejectCase, isLoading: isRejectCaseLoading } = useRejectCaseMutation({
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

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

    @chesterkmr chesterkmr enabled auto-merge (squash) March 19, 2024 15:44
    @chesterkmr chesterkmr merged commit 9fe7a5c into dev Mar 19, 2024
    9 checks passed
    @chesterkmr chesterkmr deleted the bal-1293 branch March 19, 2024 16:03
    liorzam pushed a commit that referenced this pull request Mar 27, 2024
    * feat: added CountryPicker to UI & ui bump
    
    * feat: added RadioGroup to ui
    
    * feat: added radio group input adapter & updated storybook
    
    * feat: ui bump
    
    * fix: build fix
    
    * feat: added support of htmlRaw descriptions in dynamic form
    
    * feat: added report-creation callback name
    
    * feat: new icons & style changes & bump
    
    * feat: added icon position to list & font changes
    
    * feat: added report templates & added storybook
    
    * feat: type export & bump
    
    * merged with master
    
    * fix: updated exports & bump
    
    * feat: added initial report rendering to backoffice
    
    * feat: added initial case actions variants
    
    * feat: refactored code
    
    * feat: refactored process tracker logic
    
    * feat: implemented process tracking logic for merchant monitoring
    
    * feat: states adjustments & css fixes
    
    * feat: added validation schemas & hoc validator & updated website analysis
    
    * feat: bump
    
    * feat: added empty state to website analysis & upd storybook
    
    * feat: added empty states handling to social media & updated storybook
    
    * feat: render of social media & website analysis report
    
    * fix: fixed import
    
    * feat: added base64 file service provider & added website monitoring callback handler
    
    * feat: common bump
    
    * feat: removed reports from pdf-toolkit & bump
    
    * draft1
    
    * feat: replaced pdf viewer with iframe & added rendering of report out of base64
    
    * feat: added new icons
    
    * fix: fixed pdf blocks types & useMemo rendering bug
    
    * feat: bump
    
    * fix: lock fix
    
    * feat: added date formatting & bump
    
    * fix: fixed website monitoring hook hanlding & backoffice fixes
    
    * feat: bump
    
    * fix: fixed actions variant & base pdf format
    
    * fix: reverted prisma timeouts & removed logging of base64 filenames
    
    * fix: added mime type to pdf block & fixed callback
    
    * feat: added string-ts re-export & fixed hook name
    
    * feat: code refactoring
    
    * fix: renamed PDFRevision to WebsiteMonitoring
    
    * fix: renamed files & added toast to handle unsupported actions
    
    * fix: fixed build
    
    * feat: bump
    
    ---------
    
    Co-authored-by: Alon Peretz <Alonp99@gmail.com>
    @Omri-Levy Omri-Levy mentioned this pull request Nov 4, 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.

    4 participants