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 Analytics report test cases #2436

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

mrabbani
Copy link
Member

@mrabbani mrabbani commented Nov 15, 2024

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Update the SQL condition to sum of the Dokan Total e.i. total_admin_commission, total_vendor_earning, and etc.

Related Pull Request(s)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • New Features
    • Enhanced WooCommerce Analytics reports for Dokan orders with improved vendor filtering and additional data points like average items per order and average order value.
  • Bug Fixes
    • Refined calculations for vendor earnings and admin commissions to ensure accuracy.
  • Tests
    • Updated tests to incorporate a mock for the Commission class, improving validation of order statistics.
    • Restructured tests for clarity and focus on commission-related logic.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes involve significant updates to the QueryFilter class in the WooCommerce Analytics reports for Dokan orders. Key modifications include enhancements to SQL query filtering, improved total calculations with conditional logic, and the addition of new data points in report columns. Corresponding tests have been adjusted to incorporate a mock Commission class, refining the validation of order statistics. Overall, these updates aim to improve the accuracy and clarity of analytics related to Dokan's order processing.

Changes

File Change Summary
includes/Analytics/Reports/Orders/Stats/QueryFilter.php Updated register_hooks, modify_admin_report_columns, add_select_subquery_for_total, and add_where_subquery_for_vendor_filter methods for enhanced SQL filtering and accurate calculations for vendor earnings and report columns.
tests/php/src/Analytics/Reports/OrderQueryFilterTest.php Introduced Commission mock, updated test_dokan_order_stats_fields_are_selected_for_seller for better data retrieval, and adjusted test_filter_hooks_are_applied_for_orders_query.
tests/php/src/Analytics/Reports/OrderStatsQueryFilterTest.php Added Commission import, commented out assertions in test_order_stats_hook_registered, removed test_dokan_order_stats_added_to_wc_select_query_for_seller, and renamed test_dokan_order_stats_added_to_wc_select_query_for_admin.
tests/php/src/Analytics/Reports/ReportTestCase.php Added Commission import, commented out financial metrics in get_dokan_stats_data, and introduced tear_down method for cleanup.

Possibly related PRs

Suggested labels

QA approved, :+1: Dev Review Done

Suggested reviewers

  • shohag121

Poem

🐰 In the fields where orders flow,
The stats now shine, a brighter glow.
With filters set and totals right,
Dokan's reports take flight tonight!
So hop along, let data play,
In WooCommerce, we find our way! 🌟


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

@mrabbani mrabbani self-assigned this Nov 15, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
tests/php/src/Analytics/Reports/ReportTestCase.php (1)

115-118: Consider improving test isolation

While the tear_down method correctly sets up the Commission instance and calls the parent method, consider the following improvements:

  1. Reset any Commission-specific state before setting the new instance
  2. Document why this setup is needed in tear_down rather than setUp

Consider this enhanced implementation:

 public function tear_down() {
+    // Reset Commission state after each test
+    dokan()->get_container()->remove('commission');
     dokan()->get_container()->extend( 'commission' )->setConcrete( new Commission() );
     parent::tear_down();
 }
tests/php/src/Analytics/Reports/OrderStatsQueryFilterTest.php (2)

47-48: Document the reason for commented assertions

These assertions are testing important hook registrations. If they're temporarily disabled due to the coupon amount distribution issue, please add a TODO comment explaining:

  1. Why these assertions are commented out
  2. The ticket/issue number for tracking
  3. When they will be re-enabled
-        // self::assertNotFalse( has_filter( 'woocommerce_analytics_clauses_where_orders_stats_total', [ $order_stats_query_filter, 'add_where_subquery' ] ) );
-        // self::assertNotFalse( has_filter( 'woocommerce_analytics_clauses_where_orders_stats_interval', [ $order_stats_query_filter, 'add_where_subquery' ] ) );
+        // TODO: Temporarily disabled due to coupon amount distribution issue (#ISSUE-NUMBER)
+        // Re-enable once the where clause filtering is updated
+        // self::assertNotFalse( has_filter( 'woocommerce_analytics_clauses_where_orders_stats_total', [ $order_stats_query_filter, 'add_where_subquery' ] ) );
+        // self::assertNotFalse( has_filter( 'woocommerce_analytics_clauses_where_orders_stats_interval', [ $order_stats_query_filter, 'add_where_subquery' ] ) );

128-135: Consider enhancing assertion messages

While the error messages are improved, they could be even more helpful during failures.

-            $this->assertEquals( $expected, $report_data->totals->{"total_$key"}, $key . ' Mismatch: Expected: ' . $expected . ' Got: ' . $val );
+            $this->assertEquals(
+                $expected,
+                $report_data->totals->{"total_$key"},
+                sprintf(
+                    '%s Mismatch: Expected %.2f (%.2f × %d sub-orders), Got %.2f',
+                    $key,
+                    $expected,
+                    $val,
+                    $sub_ord_count,
+                    $report_data->totals->{"total_$key"}
+                )
+            );
tests/php/src/Analytics/Reports/OrderQueryFilterTest.php (2)

96-110: Consider extracting the mock earnings logic to a helper method

The Commission mock setup is well-structured with proper conditional logic for different scenarios. However, the callback logic in get_earning_by_order could be moved to a separate helper method to improve readability.

Consider refactoring like this:

 $mock_commission = Mockery::mock( Commission::class );
 dokan()->get_container()->extend( 'commission' )->setConcrete( $mock_commission );
-$mock_commission->shouldReceive( 'get_earning_by_order' )->andReturnUsing(
-    function ( $order, $context = 'seller' ) use ( $expected_data ) {
-        if ( $order->get_meta( 'has_sub_order' ) ) {
-            return 0;
-        }
-        if ( $context === 'admin' ) {
-            return $expected_data['admin_commission'];
-        }
-        return $expected_data['vendor_earning'];
-    }
-);
+$mock_commission->shouldReceive( 'get_earning_by_order' )->andReturnUsing(
+    [ $this, 'get_mock_earning_by_order' ]
+);
+
+private function get_mock_earning_by_order( $order, $context = 'seller' ) {
+    if ( $order->get_meta( 'has_sub_order' ) ) {
+        return 0;
+    }
+    if ( $context === 'admin' ) {
+        return $this->expected_data['admin_commission'];
+    }
+    return $this->expected_data['vendor_earning'];
+}

139-147: Consider optimizing the array_reduce callback

The array_reduce implementation is clean but could be optimized with an early return to avoid unnecessary iterations once the matching order is found.

Consider this optimization:

 $order_data = array_reduce(
     $report_data,
     function ( $carry, $item ) use ( $s_id ) {
-        if ( $item['order_id'] === $s_id ) {
-            $carry = $item;
-        }
-
-        return $carry;
+        return $item['order_id'] === $s_id ? $item : $carry;
     },
     null
 );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ac8cfe4 and 849400c.

📒 Files selected for processing (4)
  • includes/Analytics/Reports/Orders/Stats/QueryFilter.php (1 hunks)
  • tests/php/src/Analytics/Reports/OrderQueryFilterTest.php (3 hunks)
  • tests/php/src/Analytics/Reports/OrderStatsQueryFilterTest.php (4 hunks)
  • tests/php/src/Analytics/Reports/ReportTestCase.php (2 hunks)
🔇 Additional comments (5)
tests/php/src/Analytics/Reports/ReportTestCase.php (1)

5-5: LGTM: Commission class import added correctly

The import statement is properly placed and necessary for the Commission class usage in the tear_down method.

tests/php/src/Analytics/Reports/OrderStatsQueryFilterTest.php (3)

7-7: LGTM!

The Commission class import is correctly added and aligns with the test modifications.


101-115: LGTM! Well-structured Commission mock setup

The Commission mock is well implemented with:

  • Clear context handling (seller/admin)
  • Proper sub-order logic
  • Explicit return values

69-69: Verify test coverage for where clause filtering

The where clause filtering is commented out, which could leave a gap in test coverage.

Let's check the test coverage for the where clause filtering:

✅ Verification successful

Where clause filtering is adequately covered in other test files

The commented out add_where_subquery in OrderStatsQueryFilterTest.php is specifically related to coupon amount distribution, while the where clause filtering functionality is still being tested in:

  • ProductStatsQueryFilterTest.php
  • ProductQueryFilterTest.php
  • OrderQueryFilterTest.php

These files contain active assertions and mocking for the where clause filtering, ensuring the functionality remains tested across different contexts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other tests that might be covering the where clause filtering
rg -l "add_where_subquery" "tests/"

# Check if there are any existing tests for coupon amount distribution
rg -l "coupon.*amount.*distribution" "tests/"

Length of output: 321


Script:

#!/bin/bash
# Check the context of add_where_subquery usage in the test files
rg "add_where_subquery" tests/php/src/Analytics/Reports/ -B 2 -A 2

# Check if there are any active tests for where clause filtering
ast-grep --pattern 'function test_$_($$$) {
  $$$
  add_where_subquery
  $$$
}'

Length of output: 10488

tests/php/src/Analytics/Reports/OrderQueryFilterTest.php (1)

6-6: LGTM: Clean import addition

The Commission class import is properly placed and necessary for the new commission-related test functionality.

Comment on lines +104 to +109
// 'vendor_gateway_fee' => random_int( 5, 10 ),
// 'vendor_discount' => random_int( 5, 10 ),
'admin_commission' => random_int( 5, 10 ),
'admin_gateway_fee' => random_int( 5, 10 ),
'admin_discount' => random_int( 5, 10 ),
'admin_subsidy' => random_int( 5, 10 ),
// 'admin_gateway_fee' => random_int( 5, 10 ),
// 'admin_discount' => random_int( 5, 10 ),
// 'admin_subsidy' => random_int( 5, 10 ),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Keep the commented metrics in test data

The commented-out metrics (vendor_gateway_fee, vendor_discount, admin_gateway_fee, admin_discount, admin_subsidy) are actively used throughout the codebase:

  • They are part of the database schema in includes/Install/Installer.php
  • Used in order analytics and reporting in includes/Analytics/Reports/Orders/Stats/DataStore.php
  • Included in query filters for order statistics
  • Stored as order meta data

These metrics should remain in the test data to ensure proper test coverage of the analytics and reporting features.

🔗 Analysis chain

Verify the intentional removal of financial metrics

Several financial metrics have been commented out without replacement:

  • vendor_gateway_fee
  • vendor_discount
  • admin_gateway_fee
  • admin_discount
  • admin_subsidy

Please confirm if this is intentional and whether these metrics are no longer needed in the test data.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these metrics are still used in other test files or main code
rg -l "(vendor|admin)_(gateway_fee|discount|subsidy)" --type php

Length of output: 335


Script:

#!/bin/bash
# Check the actual usage of these metrics in the related files
rg "(vendor|admin)_(gateway_fee|discount|subsidy)" --type php -C 2

Length of output: 6386

Comment on lines +127 to +138
$commission = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_commission ELSE 0 END)";
$vendor_earning = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_earning ELSE 0 END)";

$clauses[] = "$vendor_earning as total_vendor_earning";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_gateway_fee ELSE 0 END) as total_vendor_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_discount ELSE 0 END) as total_vendor_discount";
$clauses[] = "$commission as total_admin_commission";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_gateway_fee ELSE 0 END) as total_admin_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_discount ELSE 0 END) as total_admin_discount";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_subsidy ELSE 0 END) as total_admin_subsidy";
$clauses[] = " $commission / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_admin_commission";
$clauses[] = "$vendor_earning / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_vendor_earning";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Fix leading commas to prevent SQL syntax errors

The variables $commission and $vendor_earning start with leading commas. When these are concatenated into the $clauses[] array, it results in extra commas in the SQL query, which can cause syntax errors.

Apply the following diff to remove the leading commas from the variable definitions:

-        $commission = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_commission ELSE 0 END)";
-        $vendor_earning = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_earning ELSE 0 END)";
+        $commission = "SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_commission ELSE 0 END)";
+        $vendor_earning = "SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_earning ELSE 0 END)";

Additionally, ensure that commas are correctly placed when adding these variables to the clauses:

-        $clauses[] = "$vendor_earning  as total_vendor_earning";
-        $clauses[] = "$commission as total_admin_commission";
+        $clauses[] = ", $vendor_earning as total_vendor_earning";
+        $clauses[] = ", $commission as total_admin_commission";

This adjustment will prevent extra commas in the SQL query and ensure proper syntax.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$commission = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_commission ELSE 0 END)";
$vendor_earning = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_earning ELSE 0 END)";
$clauses[] = "$vendor_earning as total_vendor_earning";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_gateway_fee ELSE 0 END) as total_vendor_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_discount ELSE 0 END) as total_vendor_discount";
$clauses[] = "$commission as total_admin_commission";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_gateway_fee ELSE 0 END) as total_admin_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_discount ELSE 0 END) as total_admin_discount";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_subsidy ELSE 0 END) as total_admin_subsidy";
$clauses[] = " $commission / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_admin_commission";
$clauses[] = "$vendor_earning / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_vendor_earning";
$commission = "SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_commission ELSE 0 END)";
$vendor_earning = "SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_earning ELSE 0 END)";
$clauses[] = ", $vendor_earning as total_vendor_earning";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_gateway_fee ELSE 0 END) as total_vendor_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN vendor_discount ELSE 0 END) as total_vendor_discount";
$clauses[] = ", $commission as total_admin_commission";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_gateway_fee ELSE 0 END) as total_admin_gateway_fee";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_discount ELSE 0 END) as total_admin_discount";
$clauses[] = ", SUM( CASE WHEN {$table_name}.order_type IN($types) THEN admin_subsidy ELSE 0 END) as total_admin_subsidy";
$clauses[] = " $commission / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_admin_commission";
$clauses[] = "$vendor_earning / SUM( CASE WHEN {$table_name}.order_type IN($types) THEN 1 ELSE 0 END ) AS avg_vendor_earning";

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.

1 participant