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

feat: monthly filter on statistics page and additional merchant related data (BAL-3302, BAL-3303) #2940

Merged
merged 5 commits into from
Jan 7, 2025

Conversation

r4zendev
Copy link
Collaborator

@r4zendev r4zendev commented Jan 6, 2025

Changes

  • Adds month-based filter to the statistics page to display relevant data.
  • Adds 3 additional metrics showing merchant-related data
  • Currently the to param is hardcoded to be +1 month from the from date, but I added it just in case we add more time-based filters later so that it's easier to convert it to a stateful variable that can change based on user input
image image

Summary by CodeRabbit

  • New Features

    • Added portfolio analytics with merchant statistics.
    • Introduced month picker for date selection.
    • Enhanced business report metrics with new merchant-related data.
  • Improvements

    • Updated user schema to include registration and last active dates.
    • Improved metrics querying with optional date range filtering.
  • Refactor

    • Removed date range functionality from home logic.
    • Updated type definitions for better type safety.
    • Revised component structure for improved layout and organization.

@r4zendev r4zendev self-assigned this Jan 6, 2025
Copy link

changeset-bot bot commented Jan 6, 2025

⚠️ No Changeset found

Latest commit: 8da1e6e

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 Jan 6, 2025

Walkthrough

This pull request introduces significant changes across various files in the backoffice application, primarily focusing on the removal of date range handling functionalities and enhancements to metrics tracking. The useHomeLogic hook has been modified to exclude date-related logic, while new components such as MonthPicker and PortfolioAnalytics have been added to improve user interaction with statistics. Additionally, the backend services have been updated to support more granular date-based querying for business report metrics, enhancing the overall data structure and user experience.

Changes

File Path Change Summary
apps/backoffice-v2/src/common/hooks/useHomeLogic/useHomeLogic.ts Removed date range handling imports and functionalities
apps/backoffice-v2/src/domains/auth/validation-schemas.ts Added lastActiveAt and registrationDate to AuthenticatedUserSchema
apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery Updated query function to support date range parameters, expanded metrics response schema
apps/backoffice-v2/src/pages/Home/Home.page.tsx Removed date range picker and related variables
apps/backoffice-v2/src/pages/Statistics/* Added new components MonthPicker, PortfolioAnalytics, introduced useStatisticsLogic hook
services/workflows-service/src/auth/session-serializer.ts Updated user deserialization to include registrationDate and lastActiveAt
services/workflows-service/src/business-report/* Enhanced metrics retrieval with date range support, added new DTOs and schemas

Possibly related PRs

Suggested labels

enhancement, Review effort [1-5]: 3

Suggested reviewers

  • Omri-Levy
  • MatanYadaev
  • tomer-shvadron

Poem

🐰 Metrics dance, dates align just right,
Code transforms with rabbit's delight!
New components spring, data takes flight,
Refactoring magic, pure and bright,
A technological rabbit's pure insight! 🚀


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (9)
services/workflows-service/src/business-report/dtos/business-report-metrics.dto.ts (1)

5-15: Separate class-based validation from schema-based validation
While class-validator decorators and the Zod schema both provide validation, consider consolidating or aligning them if possible to reduce duplication and complexity. If your codebase strictly requires separate validations, ensure these remain synchronized so that changes do not introduce divergent requirements.

apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/hooks/usePortfolioAnalyticsLogic.tsx (2)

11-14: Consider exposing explicit types for parameters.
The inline usage of z.infer<typeof MetricsResponseSchema> is completely fine but consider exporting an explicit type to improve clarity, especially if you plan to reuse it.

-export const usePortfolioRiskStatisticsLogic = ({
-  riskLevelCounts,
-  violationCounts,
-}: z.infer<typeof MetricsResponseSchema>) => {
+type RiskStatsInput = z.infer<typeof MetricsResponseSchema>;
+export const usePortfolioRiskStatisticsLogic = ({ riskLevelCounts, violationCounts }: RiskStatsInput) => {

25-30: Filtering and sorting logic is correct but be mindful of in-place sorting.
.sort() modifies the array in place. If you're concerned about side effects or want to preserve violationCounts, use a copy. This is not strictly an issue if violationCounts is read-only from outside.

-violationCounts
-  .sort((a, b) => ...)
-  .slice(0, 5),
+[...violationCounts]
+  .sort((a, b) => ...)
+  .slice(0, 5),
apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/PortfolioAnalytics.tsx (2)

10-15: Ensure props defaulting for robust usage.
If any merchant counts are undefined in upstream code, it may cause issues in JSX or unexpected displays. Consider providing fallback values or proper null checks to enhance reliability.

-> = ({ totalActiveMerchants, addedMerchantsCount, removedMerchantsCount }) => {
+> = ({
+  totalActiveMerchants = 0,
+  addedMerchantsCount = 0,
+  removedMerchantsCount = 0,
+}) => {

23-24: Consider adding input validation or user-friendly display for negative values.
While unlikely, ensure that negative merchant counts are caught by data validation, or provide intuitive displays in case of invalid input from the backend.

apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (1)

32-34: Rename for clarity.
Rename isSameMonth to something more descriptive like areMonthsEqual for better readability and to reflect its comparison usage.

-  const isSameMonth = (date1: Date, date2: Date) => {
+  const areMonthsEqual = (date1: Date, date2: Date) => {
services/workflows-service/src/business-report/merchant-monitoring-client.ts (1)

291-292: Confirm default to is enforced for data retrieval.
As stated in the PR objectives, the to parameter is currently hardcoded to be one month after from. Confirm this logic is handled consistently in the backend if to is not provided.

apps/backoffice-v2/src/pages/Statistics/components/PortfolioRiskStatistics/PortfolioRiskStatistics.tsx (1)

46-46: Semantic improvement.
Changing <h5> to <h3> provides a stronger semantic heading structure. Keep an eye on consistent heading hierarchy.

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

41-45: Ensure consistent DTO naming conventions.

You are importing BusinessReportMetricsDto from business-report-metrics-dto and other DTOs from business-report-metrics.dto. To maintain a clear and uniform codebase, rename or consolidate the DTO files so that they follow a single naming pattern, e.g., *.dto.ts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f0a6af and eceb325.

📒 Files selected for processing (15)
  • apps/backoffice-v2/src/common/hooks/useHomeLogic/useHomeLogic.ts (1 hunks)
  • apps/backoffice-v2/src/domains/auth/validation-schemas.ts (1 hunks)
  • apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.ts (2 hunks)
  • apps/backoffice-v2/src/pages/Home/Home.page.tsx (0 hunks)
  • apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/PortfolioAnalytics.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/hooks/usePortfolioAnalyticsLogic.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/PortfolioRiskStatistics/PortfolioRiskStatistics.tsx (2 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/PortfolioRiskStatistics/hooks/usePortfolioRiskStatisticsLogic/usePortfolioRiskStatisticsLogic.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/hooks/useStatisticsLogic.tsx (1 hunks)
  • services/workflows-service/src/auth/session-serializer.ts (1 hunks)
  • services/workflows-service/src/business-report/business-report.controller.external.ts (2 hunks)
  • services/workflows-service/src/business-report/dtos/business-report-metrics.dto.ts (1 hunks)
  • services/workflows-service/src/business-report/merchant-monitoring-client.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/backoffice-v2/src/pages/Home/Home.page.tsx
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: lint
  • GitHub Check: Analyze (javascript)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (31)
apps/backoffice-v2/src/common/hooks/useHomeLogic/useHomeLogic.ts (2)

Line range hint 9-48: Implementation looks clean and focused!

The hook effectively manages:

  • User session and customer data
  • Navigation logic with proper edge case handling
  • Configuration flags for example/demo states

Line range hint 9-48: Verify migration of date filtering logic.

The date range functionality has been removed from this hook, which aligns with the PR's goal to implement a new month-based filter. However, we should verify that the new monthly filter implementation exists elsewhere in the codebase.

✅ Verification successful

Date filtering logic successfully migrated to month-based implementation

The date range functionality has been properly migrated to a new month-based filter implementation with:

  • A dedicated MonthPicker component in the Statistics page
  • Complete filtering logic in useStatisticsLogic hook
  • Proper data fetching with monthly boundaries via useBusinessReportMetricsQuery
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for new month-based filter implementation
echo "Searching for MonthPicker component..."
rg -l "MonthPicker"

echo "\nSearching for month filter logic..."
rg -l "monthFilter|monthPicker|monthSelect"

Length of output: 376


Script:

#!/bin/bash
# Check MonthPicker implementation and its usage
echo "=== MonthPicker Component Implementation ==="
cat "apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx"

echo -e "\n=== Statistics Page Implementation ==="
cat "apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx"

Length of output: 5127


Script:

#!/bin/bash
# Check statistics logic implementation
echo "=== Statistics Logic Hook Implementation ==="
cat "apps/backoffice-v2/src/pages/Statistics/hooks/useStatisticsLogic.ts"

Length of output: 272


Script:

#!/bin/bash
# Search for useStatisticsLogic implementation
echo "=== Searching for useStatisticsLogic hook ==="
rg -l "useStatisticsLogic"

echo -e "\n=== Searching for Statistics hook content ==="
rg "export const useStatisticsLogic" -A 10

Length of output: 1607


Script:

#!/bin/bash
# Get complete implementation of useStatisticsLogic
echo "=== Complete Statistics Logic Hook Implementation ==="
cat "apps/backoffice-v2/src/pages/Statistics/hooks/useStatisticsLogic.tsx"

Length of output: 2030

apps/backoffice-v2/src/domains/auth/validation-schemas.ts (1)

10-11: Confirm datetimes usage for consistency
The use of z.string().datetime() for lastActiveAt and registrationDate is appropriate. Verify, however, that throughout the codebase, these fields are consistently stored, parsed, and displayed as valid ISO 8601 strings to mitigate date parsing discrepancies across different components.

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

17-20: Schema definitions match the class-defined constraints
Your Zod schema for from and to is consistent with the class-validator approach. This helps ensure a uniform contract across your API and code. Great job!

apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx (4)

4-7: Appropriate modularization of components
Importing MonthPicker, PortfolioAnalytics, and PortfolioRiskStatistics in this file keeps the code organized and easier to maintain. This modular approach is consistent with best practices.


10-10: Validate date usage in your logic
The date and registrationDate fields can be undefined initially or may require special formatting. Confirm that any transformations or validations in useStatisticsLogic handle these scenarios robustly to avoid runtime errors.


22-25: Min-Date usage in MonthPicker
Using minDate={registrationDate} is a neat way to restrict the earliest selectable date. Make sure registrationDate is parsed consistently as a JavaScript Date object, or that MonthPicker can handle string inputs without error.


27-32: Excellent layering of portfolio metrics
Combining PortfolioAnalytics with risk statistics in the same view helps to unify the data. This is a clear approach for presenting merchant metrics while providing risk insights.

apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.ts (2)

22-24: Schema expansion is logical
Adding totalActiveMerchants, addedMerchantsCount, and removedMerchantsCount to MetricsResponseSchema is consistent with your new merchant analytics. This ensures type safety and clarity in the data structure.


27-29: Sanitize query parameters
Including from and to in the endpoint is good for date-based filtering. Ensure upstream logic and validations (like your Zod schema) are guaranteeing safe input, reducing risk of malicious or malformed queries.

apps/backoffice-v2/src/pages/Statistics/components/PortfolioRiskStatistics/hooks/usePortfolioRiskStatisticsLogic/usePortfolioRiskStatisticsLogic.tsx (1)

14-14: Narrowing the type to the required properties is a great improvement.
This ensures that we only accept the parts of the schema actually used (riskLevelCounts and violationCounts), improving maintainability and preventing undefined properties from creeping in.

apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/hooks/usePortfolioAnalyticsLogic.tsx (5)

1-9: Good use of hooks and utility imports.
These imports – useAutoAnimate, React hooks, z from Zod, etc. – are a solid foundation for building well-typed, animated, and sorted data displays.


16-21: Sorting callback logic is clear.
The callback properly segregates the logic to toggle sorting direction with minimal overhead. Nice approach to keep the codebase easy to follow.


23-24: Efficient use of reduce to get the total.
Summing the violationCounts in a single pass is both concise and efficient.


31-42: Width calculation approach is thoughtful.
Clamping the minimum width is a nice touch for visible UI segments, ensuring each bar is at least some standard size.


44-53: Returning all derived variables in one object is clean.
This design pattern keeps the hook’s usage straightforward for consumers. It also helps keep the internal state details private.

apps/backoffice-v2/src/pages/Statistics/hooks/useStatisticsLogic.tsx (7)

1-3: Good integration of search parameters and user data fetching.
Encapsulating them into this hook centralizes logic for retrieving user and business metrics, simplifying the consuming component.


8-11: Well-structured approach to user registration date retrieval.
Storing registrationDate in a local variable quickly clarifies how you're referencing the user's sign-up date while providing a sane default.


12-23: Schema-based validation is robust but ensure performance is acceptable.
Zod is a reliable library for validation, and you’re ensuring dates are on the first of the month and within valid ranges. This is good for strict correctness.


25-26: Smart approach for search parameters initialization.
Utilizing useZodSearchParams with your custom schema seamlessly integrates with the date-based logic, preventing invalid states.


27-30: Use of to is currently “one month ahead” – confirm future enhancements.
You're hardcoding to to be exactly one month after from, per the PR summary. This is fine now, but be mindful of user expectations if they want a custom range in future.


32-40: Nice approach for date changes and re-validating.
The re-validation via safeParse ensures that any user-provided date is coerced to the first day of that month if valid; otherwise, it defaults to the fallback. This will reduce errors from user selection.


42-49: Comprehensive return object.
Providing the entire data object, loading state, error, date, and user’s registration date in one place is both convenient and consistent for the consumer.

services/workflows-service/src/auth/session-serializer.ts (3)

49-50: Including createdAt and lastActiveAt for the user is beneficial.
Capturing these timestamps can help enhance analytics and ensure user activity tracking is accurate.


55-55: Destructuring carefully separates date fields from the user object.
This separation is a neat way to funnel createdAt and lastActiveAt into more domain-specific properties, like registrationDate.


57-57: Crystal-clear naming of registrationDate for createdAt.
Renaming createdAt to registrationDate here communicates intent more clearly. Keep in mind that if you need the raw creation timestamp for auditing, you may want to store it separately.

apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (1)

36-40: Handle future edge cases.
The isMonthDisabled currently checks if a month is strictly after today's month. Consider refining this if future selection is required, or rename if strictly disallowing all future months.

services/workflows-service/src/business-report/merchant-monitoring-client.ts (2)

74-76: Good schema extension for merchant metrics.
This expansion aligns with the newly exposed analytics on the front end. No concerns here.


279-287: New date parameters allow flexible metric querying.
Ensure that service calls and upstream logic handle cases when from or to is omitted or malformed.

apps/backoffice-v2/src/pages/Statistics/components/PortfolioRiskStatistics/PortfolioRiskStatistics.tsx (1)

24-25: Refined prop usage aligns with partial metrics data.
Utilizing Pick is a solid approach if this component only needs riskLevelCounts and violationCounts.

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

126-133: Validate ‘from’ and ‘to’ parameters for completeness and default values.

Currently, the method expects the user to pass both from and to; consider how to handle edge cases:

  1. If no date range is specified, does the query fail, or do we fallback to defaults?
  2. If from > to, do we return an error or swap them?

Also, returning await here is optional. Since this is an async function, you may simply do:

- return await this.merchantMonitoringClient.getMetrics({ customerId, from, to });
+ return this.merchantMonitoringClient.getMetrics({ customerId, from, to });

@tomer-shvadron tomer-shvadron changed the base branch from dev to mm-ui-ux-hackathon-jan-2025 January 7, 2025 09:08
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx (1)

22-25: Consider accessibility improvements.

While the layout structure is clean, consider these accessibility enhancements:

  1. Add aria-label to the statistics section
  2. Ensure proper heading hierarchy (h1 followed by h2, etc.)
-      <div className="mb-6 flex items-center justify-between">
+      <div className="mb-6 flex items-center justify-between" aria-label="Statistics Header">
-        <h1 className="text-2xl font-bold">Statistics</h1>
+        <h1 className="text-2xl font-bold" id="statistics-title">Statistics</h1>
apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (3)

9-13: Consider adding validation for date props.

The props type definition looks clean, but consider adding runtime validation for the date props to ensure they are valid Date objects.

+import { isValid } from 'dayjs';
+
 type MonthPickerProps = {
   date: Date;
   setDate: (date: Date) => void;
   minDate?: Date;
 };
+
+const validateDateProps = ({ date, minDate }: Partial<MonthPickerProps>) => {
+  if (date && !isValid(date)) throw new Error('Invalid date prop');
+  if (minDate && !isValid(minDate)) throw new Error('Invalid minDate prop');
+};

39-43: Optimize month disability check.

The isMonthDisabled function creates a new dayjs instance on every check. Consider memoizing the results for better performance.

+import { useMemo } from 'react';
+
 export const MonthPicker = ({ date, setDate, minDate }: MonthPickerProps) => {
+  const disabledMonths = useMemo(() => {
+    return months.map((_, index) => {
+      const monthDate = dayjs().year(currentYear).month(index).startOf('month');
+      return monthDate.isAfter(today, 'month');
+    });
+  }, [currentYear]);
+
-  const isMonthDisabled = (monthIndex: number) => {
-    const monthDate = dayjs().year(currentYear).month(monthIndex).startOf('month');
-    return monthDate.isAfter(today, 'month');
-  };
+  const isMonthDisabled = (monthIndex: number) => disabledMonths[monthIndex];

84-89: Improve disabled state readability.

The disabled state condition is complex and could benefit from extraction into a separate function for better readability.

+const isMonthBeforeMinDate = (
+  monthIndex: number,
+  currentYear: number,
+  minDate: dayjs.Dayjs | undefined,
+) => {
+  return (
+    minDate &&
+    currentYear === minDate.year() &&
+    monthIndex < minDate.month()
+  );
+};

-              disabled={
-                isMonthDisabled(index) ||
-                (dayjsMinDate &&
-                  currentYear === dayjsMinDate.year() &&
-                  index < dayjsMinDate.month())
-              }
+              disabled={isMonthDisabled(index) || isMonthBeforeMinDate(index, currentYear, dayjsMinDate)}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eceb325 and 8da1e6e.

📒 Files selected for processing (4)
  • apps/backoffice-v2/src/common/hooks/useHomeLogic/useHomeLogic.ts (1 hunks)
  • apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.ts (2 hunks)
  • apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/backoffice-v2/src/common/hooks/useHomeLogic/useHomeLogic.ts
  • apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: lint
🔇 Additional comments (4)
apps/backoffice-v2/src/pages/Statistics/Statistics.page.tsx (3)

4-7: LGTM! Clean import organization.

The imports are well-organized, clearly showing the component dependencies for the new month picker and portfolio analytics features.


10-10: Verify error handling for date-related state.

The hook provides date-related state (date, setDate, registrationDate), but there's no visible error handling for invalid date scenarios.

Run this script to check for error handling in the hook implementation:

✅ Verification successful

Date-related error handling is properly implemented

The hook implements comprehensive date validation and error handling:

  • Invalid dates fallback to the current month's start date
  • Date changes are validated through Zod schema before state updates
  • Registration date has a fallback value of '1970-01-01'
  • Query errors are properly propagated to the component
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for error handling in useStatisticsLogic hook
rg -A 5 "useStatisticsLogic" 

Length of output: 1507


Script:

#!/bin/bash
# Get the complete hook implementation
ast-grep --pattern 'export const useStatisticsLogic = () => {
  $$$
}'

Length of output: 4551


27-32: Verify data contract for merchant metrics.

The PortfolioAnalytics component receives merchant-related metrics. Ensure these properties are properly typed and validated.

Run this script to check the data contract:

✅ Verification successful

Data contract for merchant metrics is properly implemented and validated

The merchant-related metrics are properly typed and validated through Zod schema at both API and component levels. The implementation includes runtime validation and proper TypeScript type inference.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for type definitions and validation
ast-grep --pattern 'interface $_Props {
  totalActiveMerchants: $_;
  addedMerchantsCount: $_;
  removedMerchantsCount: $_;
}'

Length of output: 128


Script:

#!/bin/bash
# Find the PortfolioAnalytics component file
fd "PortfolioAnalytics" --type f

# Search for type definitions and props in the component
ast-grep --pattern 'type $_ = {
  $$$
  totalActiveMerchants$$$
}'

# Alternative interface pattern
ast-grep --pattern 'interface $_ {
  $$$
  totalActiveMerchants$$$
}'

# Search for direct prop destructuring in component
ast-grep --pattern 'const PortfolioAnalytics = ({ $$ }) => $$$'

Length of output: 439


Script:

#!/bin/bash
# Check the component file content
cat "apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/PortfolioAnalytics.tsx"

# Check the hook file content
cat "apps/backoffice-v2/src/pages/Statistics/components/PortfolioAnalytics/hooks/usePortfolioAnalyticsLogic.tsx"

Length of output: 4285


Script:

#!/bin/bash
# Find and check the MetricsResponseSchema definition
fd "useBusinessReportMetricsQuery" --type f

# Once found, check its content
cat "apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.ts" 2>/dev/null || cat "apps/backoffice-v2/src/domains/business-reports/hooks/queries/useBusinessReportMetricsQuery/useBusinessReportMetricsQuery.tsx" 2>/dev/null

Length of output: 1801

apps/backoffice-v2/src/pages/Statistics/components/MonthPicker/MonthPicker.tsx (1)

22-29: Review month selection logic restriction.

The month selection logic prevents selecting future months but allows past months. This aligns with the PR objective of displaying historical data.

This is consistent with a previous review comment about month selection restrictions. The current implementation appears intentional based on the PR objectives.

@tomer-shvadron tomer-shvadron merged commit 86fae1a into mm-ui-ux-hackathon-jan-2025 Jan 7, 2025
18 checks passed
@tomer-shvadron tomer-shvadron deleted the bal3302 branch January 7, 2025 09:41
@coderabbitai coderabbitai bot mentioned this pull request Jan 14, 2025
tomer-shvadron added a commit that referenced this pull request Jan 14, 2025
* Bal 3305 - improve UI messages for no indications detected (#2936)

* feat(ui): improve UI messages for no indications detected

- Provide more detailed messages for indications of website reputation
- Specify lack of issues in pricing and structural evaluation

(Your code comments speak less clearly than a cryptic crossword in a dark room)

* chore(deps): update @ballerine/ui to version 0.5.60

- Bump version of @ballerine/ui to 0.5.60 across multiple packages
- Update package.json and changelog for @ballerine/react-pdf-toolkit and kyb-app

(the dependencies are getting updated faster than my social life)

---------

Co-authored-by: Omri Levy <[email protected]>

* fix(report-tabs): hide violations for ads and social media tab (#2937)

- Update logic to return null for ad and social media violations

* feat(merchant-monitoring): display total items in results badge (#2938)

* feat(merchant-monitoring): display total items in results badge

- Add a badge to show total number of results
- Improve layout by adjusting heading structure

(Your layout is so crowded, it could use a personal space policy)

* fix(merchantMonitoring): format totalItems for improved readability

- Update totalItems to format with Intl.NumberFormat
- Enhance the display of item counts for user experience

(your number formatting was so plain, it looked like a binary tree without leaves)

---------

Co-authored-by: Omri Levy <[email protected]>

* refactor(backoffice-v2): changed home statistics (#2935)

* feat: monthly filter on statistics page and additional merchant related data (BAL-3302, BAL-3303) (#2940)

* feat: monthly filter on statistics page and additional merchant related data

* fix: revert conditional statement

* fix: rewrite month picker to dayjs

* fix: CodeRabbit comments

* fix: minor code style correction

* refactor(statistics): simplify date transformation logic

- Make the 'from' field optional in the statistics search schema
- Clean up date transformation for better readability

(your code's so tangled, it could be the plot of a soap opera)

* ongoing monitoring turning on and off (#2941)

* feat(monitoring): implement business monitoring feature

- Add success and error messages for turning monitoring on/off
- Update API endpoints to manage ongoing monitoring status
- Integrate tooltip UI for monitoring status display

(Your code is so reactive that I'm surprised it doesn't require a safe word)

* chore(business-report): remove unused import for BusinessReportMetricsDto

- Eliminate unnecessary import to clean up the code
- Reduces clutter and potential confusion in the module

(your code is so tidy now, it could be a minimalist's dream home)

* fix(report): optimize business report fetching logic

- Simplify monitoring mutation definitions
- Consolidate business fetching to reduce database calls

(Your database queries are so chatty, they could use a good night's sleep)

* feat(ui): integrate ContentTooltip for enhanced user guidance

- Implement ContentTooltip component across multiple report templates
- Update Providers to include TooltipProvider from Ballerine UI
- Refactor headings with tooltips for additional information

(your tooltips are so informative, they should come with a user manual)

* Added filter for isAlert (#2943)

* refactor(backoffice-v2): changed home statistics

* feat(backoffice-v3): added filter for isAlert

* refactor(backoffice-v2): updated alert filter copy

* refactor(ui): simplify tooltip imports and update section titles

- Consolidate tooltip component imports from '@ballerine/ui'
- Change section titles from "Ads and Social Media" to "Social Media"

(With these changes, we're one step closer to rebranding you as a minimalism guru)

* fix: portfolio analytics design (#2945)

* Alerts graph (#2946)

* refactor(backoffice-v2): changed home statistics

* feat(backoffice-v3): added filter for isAlert

* refactor(backoffice-v2): updated alert filter copy

* feat(backoffice-v2): added alerts graph to home page

* refactor(backoffice-v2): now using dayjs for last 30 days date

* refactor(backoffice-v2): added from and to to alerts count

* feat(chart): introduce ChartContainer and tooltip components

- Add ChartContainer component for chart rendering
- Implement ChartTooltip and ChartTooltipContent components
- Enhance the WebsiteCredibility component to use the new Chart components

(your JSX structure is more nested than a Russian doll collection)

* fix(WebsiteCredibility): improve trend calculation readability

- Refactor conditional return for better clarity
- Enhance code structure for maintainability

(your code's readability is like a secret menu, good luck figuring it out)

* Default filter for merchant reports (#2947)

* feat(backoffice-v2): added default filter for merchant reports view

* fix(backoffice-v2): now clear all clears isAlert filter

* feat(auth): update user validation schemas (#2954)

- Remove registrationDate from AuthenticatedUserSchema
- Update isAlert field in BusinessReportSchema to be optional
- Add BusinessReportsCountSchema for report counting functionality

(Your schema changes are so dramatic, they should come with a Netflix subscription)

* refactor(components): simplify JSX structure in MerchantMonitoringTable

- Merge nested span into TextWithNAFallback for better clarity
- Remove unused import of CardTitle in WebsiteCredibility component

(your code's like a good magician—just when I think I see the trick, it disappears)

---------

Co-authored-by: Shane <[email protected]>
Co-authored-by: Omri Levy <[email protected]>
Co-authored-by: Sasha <[email protected]>
r4zendev added a commit that referenced this pull request Jan 14, 2025
…ed data (BAL-3302, BAL-3303) (#2940)

* feat: monthly filter on statistics page and additional merchant related data

* fix: revert conditional statement

* fix: rewrite month picker to dayjs

* fix: CodeRabbit comments

* fix: minor code style correction
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.

2 participants