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

fix: corrected home page merchants metrics source of truth (BAL-3396, BAL-3397) #2968

Merged
merged 4 commits into from
Jan 16, 2025

Conversation

r4zendev
Copy link
Collaborator

@r4zendev r4zendev commented Jan 16, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced business report metrics to include count of unmonitored merchants.
    • Introduced a method to count business records based on specific criteria.
    • Added a new method for calculating merchant monitoring metrics with detailed insights.
  • Improvements

    • Improved ongoing monitoring feature state management with clearer logic and timestamp tracking.
    • Streamlined code readability in business controller.

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

changeset-bot bot commented Jan 16, 2025

⚠️ No Changeset found

Latest commit: 47fd317

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 16, 2025

Warning

Rate limit exceeded

@r4zendev has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 3d00e17 and 47fd317.

📒 Files selected for processing (1)
  • services/workflows-service/src/business/business.service.ts (2 hunks)

Walkthrough

The pull request introduces modifications to the BusinessReportControllerExternal, BusinessController, BusinessRepository, and BusinessService classes. The getMetrics method in the business report service is enhanced to include additional metrics, while the business controller simplifies the logic for determining feature enablement. A new method for counting business records is added to the repository, and the service is updated to handle metrics related to merchants, including date manipulations and default value settings.

Changes

File Change Summary
services/workflows-service/src/business-report/business-report.controller.external.ts - Modified getMetrics method to retrieve additional metrics, including unmonitored merchants count.
services/workflows-service/src/business/business.controller.external.ts - Introduced isEnabled variable for clearer feature state logic.
- Added disabledAt timestamp tracking in featureConfig.
services/workflows-service/src/business/business.repository.ts - Added count method to count business records based on specific criteria.
services/workflows-service/src/business/business.service.ts - Added getMerchantMonitoringMetrics method to calculate and return merchant-related metrics.
- Updated import for Business to include Prisma.

Suggested labels

enhancement, Review effort [1-5]: 3

Suggested reviewers

  • MatanYadaev
  • Omri-Levy

Poem

🐰 In the code where metrics play,
New features hop and dance today!
With counts and states all crystal clear,
Our rabbit heart sings with cheer!
Hooray for changes, bright and bold,
A tale of metrics, happily told! 🌟


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: 0

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

172-182: Consider adjusting date range comparison operators.

The current implementation might miss edge cases. Consider using:

  • gte (greater than or equal) for the from date
  • lt (less than) for the to date

This ensures consistent date range boundaries and follows the common practice of inclusive start and exclusive end dates.

  metadata: {
    path: ['featureConfig', FEATURE_LIST.ONGOING_MERCHANT_REPORT, 'disabledAt'],
    not: 'null',
-   ...(from && { gt: dayjs(from).toDate().getTime() }),
-   ...(to && { lte: dayjs(to).toDate().getTime() }),
+   ...(from && { gte: dayjs(from).toDate().getTime() }),
+   ...(to && { lt: dayjs(to).toDate().getTime() }),
  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 37ccb73 and 5e63620.

📒 Files selected for processing (2)
  • services/workflows-service/src/business-report/business-report.controller.external.ts (2 hunks)
  • services/workflows-service/src/business/business.controller.external.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: lint
🔇 Additional comments (4)
services/workflows-service/src/business/business.controller.external.ts (1)

158-165: LGTM! Improved state management for merchant monitoring.

The changes enhance tracking of merchant monitoring state by:

  1. Introducing a clear isEnabled flag
  2. Adding a disabledAt timestamp when monitoring is disabled
services/workflows-service/src/business-report/business-report.controller.external.ts (3)

47-47: LGTM! Added dayjs for consistent date handling.

The import of dayjs ensures consistent date handling across the application.


184-193: LGTM! Correctly combines metrics with removed merchants count.

The implementation properly:

  1. Fetches metrics from the merchant monitoring client
  2. Adds the count of removed merchants
  3. Returns a combined response

172-193: Verify single source of truth for removed merchants metric.

Let's ensure there are no conflicting implementations of the "removed merchants" metric.

✅ Verification successful

Implementation verified as single source of truth

The "removed merchants" metric is consistently implemented and has a clear data flow from the backend calculation through to the UI display, with no conflicting implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other uses of the disabledAt field or removed merchants metric

echo "Checking for other uses of disabledAt field..."
rg -A 5 "disabledAt.*ONGOING_MERCHANT_REPORT"

echo "Checking for other implementations of removed merchants metric..."
rg -A 5 "removedMerchants"

Length of output: 5076

@r4zendev r4zendev changed the title fix: corrected "removed merchants" metric source of truth fix: corrected "removed merchants" metric source of truth (BAL-3396) Jan 16, 2025
@r4zendev r4zendev changed the title fix: corrected "removed merchants" metric source of truth (BAL-3396) fix: corrected "removed merchants" metric source of truth (BAL-3396, BAL-3397) Jan 16, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
services/workflows-service/src/business/business.service.ts (1)

97-117: Simplify complex metadata parsing with a helper function.

The metadata parsing logic is complex and could be moved to a separate helper function for better readability and reusability.

+  private parseFeatureDisabledAt(metadata: unknown): number | null {
+    return z
+      .number()
+      .nullable()
+      .catch(() => null)
+      .parse(
+        (
+          metadata as {
+            featureConfig: Record<
+              (typeof FEATURE_LIST)[keyof typeof FEATURE_LIST],
+              TCustomerFeaturesConfig & { disabledAt: number | null | undefined }
+            >;
+          }
+        )?.featureConfig?.[FEATURE_LIST.ONGOING_MERCHANT_REPORT]?.disabledAt,
+      );
+  }

   async getMerchantMonitoringMetrics({
     // ... existing parameters
   }) {
     // ... existing date handling

     const totalActiveMerchants = allProjectMerchants.filter(b => {
-      const disabledAt = z
-        .number()
-        .nullable()
-        .catch(() => null)
-        .parse(
-          (
-            b.metadata as {
-              featureConfig: Record<
-                (typeof FEATURE_LIST)[keyof typeof FEATURE_LIST],
-                TCustomerFeaturesConfig & { disabledAt: number | null | undefined }
-              >;
-            }
-          )?.featureConfig?.[FEATURE_LIST.ONGOING_MERCHANT_REPORT]?.disabledAt,
-        );
+      const disabledAt = this.parseFeatureDisabledAt(b.metadata);

       return (
         disabledAt === null ||
         (b.metadata === null && features?.ONGOING_MERCHANT_REPORT?.options?.runByDefault)
       );
     }).length;
services/workflows-service/src/business-report/business-report.controller.external.ts (1)

169-192: Consider handling potential errors when combining metrics.

The implementation looks good but could benefit from error handling when combining metrics from different sources. If either call fails, the entire metrics endpoint will fail.

   async getMetrics(
     @CurrentProject() currentProjectId: TProjectId,
     @Query() { from, to }: BusinessReportMetricsRequestQueryDto,
   ) {
     const { id: customerId, features } = await this.customerService.getByProjectId(
       currentProjectId,
     );

+    try {
       const { totalActiveMerchants, addedMerchantsCount, unmonitoredMerchants } =
         await this.businessService.getMerchantMonitoringMetrics({
           projectIds: [currentProjectId],
           features,
           from,
           to,
         });

       const merchantMonitoringMetrics = await this.merchantMonitoringClient.getMetrics({
         customerId,
         from,
         to,
       });

       return {
         ...merchantMonitoringMetrics,
         totalActiveMerchants,
         addedMerchantsCount,
         removedMerchantsCount: unmonitoredMerchants,
       };
+    } catch (error) {
+      this.logger.error('Failed to retrieve metrics', { error });
+      throw new common.InternalServerErrorException('Failed to retrieve metrics');
+    }
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e63620 and 3d00e17.

📒 Files selected for processing (4)
  • services/workflows-service/src/business-report/business-report.controller.external.ts (1 hunks)
  • services/workflows-service/src/business/business.controller.external.ts (1 hunks)
  • services/workflows-service/src/business/business.repository.ts (1 hunks)
  • services/workflows-service/src/business/business.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • services/workflows-service/src/business/business.controller.external.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test_windows
  • GitHub Check: build (windows-latest)
  • GitHub Check: test_linux
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: lint
🔇 Additional comments (3)
services/workflows-service/src/business/business.repository.ts (1)

110-117: LGTM! Well-implemented count method.

The implementation correctly uses project scoping and follows the repository pattern. The method signature aligns with Prisma's patterns, making it type-safe and consistent with the codebase.

services/workflows-service/src/business/business.service.ts (2)

163-168: LGTM! Clear and consistent return structure.

The return object provides a clean interface with well-named metrics.


142-161: Verify the date comparison logic for unmonitored merchants.

The date comparison in the unmonitored merchants query uses getTime() which might not match the format of stored timestamps. Also, consider extracting the common query conditions into a shared variable.

✅ Verification successful

The timestamp comparison logic is correct and safe to use.

The metadata field is a JSON type in PostgreSQL that can handle numeric timestamp comparisons. The current implementation using getTime() correctly converts dates to Unix timestamps in milliseconds, which is a valid format for JSON field comparisons in PostgreSQL.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check how timestamps are stored in the database
ast-grep --pattern 'metadata: {
  path: ["featureConfig", $_, "disabledAt"],
  $$$
}'

Length of output: 87


Script:

#!/bin/bash
# Check Prisma schema for metadata field definition
fd -e prisma | xargs cat

# Find similar metadata timestamp comparisons
rg -A 2 -B 2 '"featureConfig".+"disabledAt"' --type ts

# Look for other timestamp comparisons with metadata
rg "metadata.*getTime\(\)" --type ts

Length of output: 27551

@r4zendev r4zendev changed the title fix: corrected "removed merchants" metric source of truth (BAL-3396, BAL-3397) fix: corrected home page merchants metrics source of truth (BAL-3396, BAL-3397) Jan 16, 2025
@r4zendev r4zendev enabled auto-merge (squash) January 16, 2025 15:32
@r4zendev r4zendev merged commit 28bf7b9 into dev Jan 16, 2025
18 checks passed
@r4zendev r4zendev deleted the bal3396 branch January 16, 2025 15:39
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.

4 participants