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 decimal and thousand separator for category commission. #2440

Merged
merged 14 commits into from
Nov 26, 2024

Conversation

Aunshon
Copy link
Collaborator

@Aunshon Aunshon commented Nov 18, 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:

Fixed

Changelog entry

No change log needed.

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

    • Improved display of commission values with consistent currency formatting.
    • Enhanced input handling with debouncing for better performance during rapid input changes.
    • Added validation for percentage values to ensure they are within the range of 0 to 100.
    • User input for admin commission now includes min and max restrictions directly in the form.
    • Robust initialization and validation of commission-related properties.
    • New setting introduced to delete all Dokan plugin data upon uninstallation.
    • Enhanced validation logic for required fields in settings management, including new commission types.
    • Expanded commission update logic to incorporate new commission types (Flat and Percentage).
    • Streamlined batch processing for updating vendor, product, and category commissions.
  • Bug Fixes

    • Refined logic for validating and unformatting input values, especially for percentage inputs.
    • Enhanced error handling in settings management for withdrawal limits and commission structures.
    • Adjusted layout and styling for improved responsiveness on the settings page.
    • Minor corrections in property names and removal of unnecessary console logs for cleaner debugging.
  • Chores

    • Updated comments and documentation to clarify new logic in commission calculations.

@Aunshon Aunshon self-assigned this Nov 18, 2024
Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes in CategoryBasedCommission.vue enhance commission value handling through new formatting and validation functions. The :value bindings for commission inputs now utilize the formatValue method for consistent display. Debouncing is implemented for commissinItemHandler and handleAllCategoryInput methods to optimize performance during rapid inputs. New utility methods for value conversion and validation are introduced, and the initialization logic for commission data in AdminCommission.vue is improved to ensure proper handling of commission-related properties. Additional updates to validation and error handling are made across various components and settings.

Changes

File Path Change Summary
src/admin/components/Commission/CategoryBasedCommission.vue - Added methods: formatValue(value), unFormatValue(value), validatePercentage(percentage)
- Updated method signatures for commissinItemHandler and handleAllCategoryInput to include debouncing.
- Enhanced validation and unformatting logic for input values, particularly for percentages.
includes/Product/Hooks.php - Updated save_per_product_commission_options method to validate commission range.
- Updated add_per_product_commission_options method to include min and max attributes for input fields.
assets/src/js/setup-wizard/commission/AdminCommission.vue - Improved initialization of this.commission during the created lifecycle hook to ensure correct handling of commission data.
- Updated fixedCOmmissionhandler method to handle empty strings for commission values.
includes/Admin/Settings.php - Updated commission_category_based_values field to include required attribute.
- Enhanced validation in set_withdraw_limit_value_validation to prevent negative limits.
- Added add_dokan_data_clear_setting method for data management on uninstallation.
src/admin/components/CombineInput.vue - Removed console log statement and corrected property name fixexName.
src/admin/pages/Settings.vue - Expanded validation logic for required fields and commission types, particularly for 'combine' and 'fixed'.
- Adjusted layout and styling for improved responsiveness.
src/admin/pages/VendorSingle.vue - Adjusted handling of admin_commission_type in transformer method, removing default 'flat' assignment.
- Removed formatting for admin_additional_fee and admin_commission properties.
- Updated sendEmail and fetch methods for improved logic.
src/admin/components/Fields.vue - Updated template structure with new classes for error messages, enhancing layout and spacing.
includes/Commission.php - Deprecated multiple methods related to commission calculations.
- Updated get_commission method to include additional logic for handling empty $total_amount and $order_item_id.
includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php - Removed the entire V_3_14_0_UpdateCommissions class, which handled category commission updates.
includes/Upgrade/Upgrades/V_3_14_0.php - Enhanced update_global_commission_type method to accommodate new commission types with updated logic for handling Flat and Percentage.
includes/Commission/Upugrader/Update_Category_Commission.php - Added Update_Category_Commission class for batch processing of category commissions.
includes/Commission/Upugrader/Update_Product_Commission.php - Added Update_Product_Commission class for batch processing of product commissions.
includes/Commission/Upugrader/Update_Vendor_Commission.php - Added Update_Vendor_Commission class for batch processing of vendor commissions.
includes/Upgrade/Hooks.php - Integrated new commission update classes into the existing upgrade hooks.

Possibly related PRs

Suggested labels

QA approved, :+1: Dev Review Done, Upcoming Release

Suggested reviewers

  • shohag121
  • mrabbani

Poem

🐰 In the fields where numbers play,
Formatting values, bright as day!
Debouncing inputs, swift and neat,
Commission handling, can't be beat!
With methods new, we hop along,
Making sure our values are never wrong! 🌼


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.

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

🧹 Outside diff range and nitpick comments (2)
src/admin/components/Commission/CategoryBasedCommission.vue (2)

258-258: Fix typo in method name

The method name has a typo: 'commissinItemHandler' should be 'commissionItemHandler'

-            commissinItemHandler: Debounce( function( value, commission_type, term_id, oldValue = '' ) {
+            commissionItemHandler: Debounce( function( value, commission_type, term_id, oldValue = '' ) {

367-393: LGTM: Well-structured utility methods with proper validation

The utility methods are well-implemented with appropriate handling of edge cases. However, consider adding try-catch blocks around the accounting.js calls to handle potential formatting errors gracefully.

             formatValue: ( value ) => {
                 if ( value === '' ) {
                     return value;
                 }
-
-                return accounting.formatNumber( value, dokan.currency.precision, dokan.currency.thousand, dokan.currency.decimal );
+                try {
+                    return accounting.formatNumber( value, dokan.currency.precision, dokan.currency.thousand, dokan.currency.decimal );
+                } catch (error) {
+                    console.error('Error formatting value:', error);
+                    return value;
+                }
             },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 329da76 and cce9ddc.

📒 Files selected for processing (1)
  • src/admin/components/Commission/CategoryBasedCommission.vue (8 hunks)
🔇 Additional comments (3)
src/admin/components/Commission/CategoryBasedCommission.vue (3)

35-35: LGTM: Consistent value formatting implementation

The value formatting has been consistently implemented across all commission input fields, ensuring uniform display of decimal and thousand separators.

Also applies to: 52-52, 82-82, 99-100


111-112: LGTM: Added debounce for performance optimization

The addition of debouncing will help optimize performance by reducing the frequency of commission value updates during rapid input changes.


Line range hint 258-285: LGTM: Input handlers properly handle value formatting and validation

The implementation correctly:

  • Validates percentage values (0-100 range)
  • Unformats values before processing
  • Uses debouncing to optimize performance

Also applies to: 287-297

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

🧹 Outside diff range and nitpick comments (1)
includes/Product/Hooks.php (1)

494-494: Consider adding the step attribute for decimal precision control.

The min/max validation is good. Consider adding step="0.01" to allow for precise decimal commission values while maintaining the HTML5 validation.

-                    <input id="admin_commission" class="input-text wc_input_price" min="0" max="100" type="text" name="_per_product_admin_commission" value="<?php echo wc_format_localized_price( $admin_commission ); ?>">
+                    <input id="admin_commission" class="input-text wc_input_price" min="0" max="100" step="0.01" type="text" name="_per_product_admin_commission" value="<?php echo wc_format_localized_price( $admin_commission ); ?>">
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cce9ddc and 7fd3311.

📒 Files selected for processing (1)
  • includes/Product/Hooks.php (2 hunks)

@@ -539,7 +539,7 @@
update_post_meta( $post_id, '_per_product_admin_commission_type', $commission_type );
}

if ( isset( $_POST['_per_product_admin_commission'] ) ) { // phpcs:ignore
if ( isset( $_POST['_per_product_admin_commission'] ) && 0 <= $_POST['_per_product_admin_commission'] && 100 >= $_POST['_per_product_admin_commission'] ) { // phpcs:ignore
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

Improve commission validation logic.

The current validation is embedded within the condition making it less readable. Consider separating the validation logic and adding numeric validation.

-        if ( isset( $_POST['_per_product_admin_commission'] ) && 0 <= $_POST['_per_product_admin_commission'] && 100 >= $_POST['_per_product_admin_commission'] ) { // phpcs:ignore
-            $admin_commission = ( '' === $_POST['_per_product_admin_commission'] ) ? '' : sanitize_text_field( $_POST['_per_product_admin_commission'] ); // phpcs:ignore
+        if ( isset( $_POST['_per_product_admin_commission'] ) ) { // phpcs:ignore
+            $commission = sanitize_text_field( $_POST['_per_product_admin_commission'] ); // phpcs:ignore
+            
+            if ( '' === $commission ) {
+                $admin_commission = '';
+            } elseif ( is_numeric( $commission ) && $commission >= 0 && $commission <= 100 ) {
+                $admin_commission = $commission;
+            }
📝 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
if ( isset( $_POST['_per_product_admin_commission'] ) && 0 <= $_POST['_per_product_admin_commission'] && 100 >= $_POST['_per_product_admin_commission'] ) { // phpcs:ignore
if ( isset( $_POST['_per_product_admin_commission'] ) ) { // phpcs:ignore
$commission = sanitize_text_field( $_POST['_per_product_admin_commission'] ); // phpcs:ignore
if ( '' === $commission ) {
$admin_commission = '';
} elseif ( is_numeric( $commission ) && $commission >= 0 && $commission <= 100 ) {
$admin_commission = $commission;
}

@shashwatahalder01

This comment was marked as resolved.

@shashwatahalder01

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

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

🧹 Outside diff range and nitpick comments (1)
src/admin/components/Commission/CategoryBasedCommission.vue (1)

111-111: Fix typo in method name and approve debouncing implementation

The debouncing implementation looks good and will help optimize performance during rapid inputs. However, there's a typo in the method name.

-    commissinItemHandler: Debounce( function( value, commission_type, term_id, oldValue = '' ) {
+    commissionItemHandler: Debounce( function( value, commission_type, term_id, oldValue = '' ) {

Also applies to: 260-287, 289-299

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ccd8380 and 69b9aee.

📒 Files selected for processing (1)
  • src/admin/components/Commission/CategoryBasedCommission.vue (10 hunks)
🔇 Additional comments (4)
src/admin/components/Commission/CategoryBasedCommission.vue (4)

35-35: LGTM: Consistent value formatting across all commission inputs

The value bindings now properly utilize the formatValue method, ensuring consistent decimal and thousand separator formatting across percentage and flat commission inputs.

Also applies to: 52-52, 82-82, 99-99


261-266: LGTM: Proper validation of percentage values

The handlers now correctly validate percentage values within the 0-100 range and properly handle empty values, which should resolve the reported issue with percentage values greater than 10 not being stored.

Also applies to: 290-293


164-167: LGTM: Proper initialization of commission items

The initialization logic now ensures that commission.items is always an object, which should prevent the reported issue of null values being stored during setup.


369-395: LGTM: Well-implemented formatting and validation utilities

The new utility methods properly handle number formatting and validation while gracefully handling edge cases.

Let's verify the currency settings are properly initialized:

@StalinDurjo

This comment was marked as resolved.

@StalinDurjo

This comment was marked as resolved.

@StalinDurjo

This comment was marked as resolved.

@shashwatahalder01

This comment was marked as resolved.

@Aunshon

This comment was marked as resolved.

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

🧹 Outside diff range and nitpick comments (1)
src/admin/pages/Settings.vue (1)

1122-1122: Consider using CSS Grid or Flexbox for better responsiveness

The current approach uses fixed widths and media queries. Consider using modern CSS layout techniques:

-width: 100%;
+display: grid;
+grid-template-columns: minmax(0, 1fr);

This would provide better flexibility and maintainability across different screen sizes.

Also applies to: 1155-1155, 1171-1171

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 69b9aee and 85c3dec.

📒 Files selected for processing (4)
  • includes/Admin/Settings.php (1 hunks)
  • src/admin/components/CombineInput.vue (0 hunks)
  • src/admin/components/Commission/CategoryBasedCommission.vue (11 hunks)
  • src/admin/pages/Settings.vue (4 hunks)
💤 Files with no reviewable changes (1)
  • src/admin/components/CombineInput.vue
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/admin/components/Commission/CategoryBasedCommission.vue
🔇 Additional comments (3)
src/admin/pages/Settings.vue (2)

436-438: LGTM: Commission type validation enhancement

The code correctly removes the category-based commission validation error when the commission type is flat, percentage, combine, or fixed.


447-465: Verify the category-based commission validation logic

The validation for category-based commission values is complex and might have edge cases. Please ensure:

  1. All commission types are properly handled
  2. The validation works correctly when switching between commission types
  3. Error states are properly cleared when switching commission types
✅ Verification successful

Based on the search results, I can now provide a comprehensive verification of the category-based commission validation logic. The code shows:

  1. Extensive test coverage for all commission types and scenarios in tests/pw/tests/api/calculation.spec.ts
  2. Proper validation handling in src/admin/pages/Settings.vue that checks:
    • Commission type switching
    • All required fields for category-based commission
    • Both percentage and flat rate values
  3. Clear error state management through arrayRemove and push operations
  4. Proper data structure validation ensuring commission_category_based_values has the correct shape

Category-based commission validation is properly implemented

The validation logic correctly:

  • Handles switching between commission types by clearing irrelevant errors
  • Validates both flat and percentage values for category-based commissions
  • Maintains proper error states through array operations
  • Ensures the data structure has required fields (all, flat, percentage)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential edge cases in commission type handling

# Search for commission type related code
rg -A 5 "commission_type.*category_based"

# Search for commission validation related code
rg -A 10 "commission_category_based_values"

Length of output: 63476

includes/Admin/Settings.php (1)

541-547: LGTM! Field configuration aligns with commission handling requirements.

The changes to the commission_category_based_values field configuration look good:

  • Added required validation
  • Proper conditional display based on commission type
  • Integration with pro features via dokan_pro_commission flag

Let's verify the commission type dependency:

✅ Verification successful

Let me generate additional scripts to verify the commission type dependency more thoroughly:


Based on the verification results, I can now provide the final response:

Commission type dependency is properly implemented and validated

The changes to the commission_category_based_values field configuration are correctly implemented with proper dependencies:

  • The field is only shown when commission_type is set to 'category_based'
  • Proper sanitization and validation are in place for commission values
  • The commission type relationship is consistently handled across the codebase
  • Category-based commission values are properly stored and processed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify commission type handling and related fields

# Check for commission type references and validations
rg -A 5 "commission_type.*category_based"

# Look for any commission value formatting/validation logic
ast-grep --pattern 'function [^{]*commission[^{]*\{'

Length of output: 16308


Script:

#!/bin/bash
# Check for commission type field definition and its relationship with category commission
rg -A 10 "commission_type.*=.*\[" includes/

# Look for any validation or sanitization logic related to commission values
rg -A 5 "sanitize.*commission|validate.*commission" includes/

# Search for any commission type conditional logic
ast-grep --pattern 'if ($_ === "category_based") { $$$  }'

Length of output: 17916

@jamil-mahmud

This comment was marked as resolved.

@shashwatahalder01

This comment was marked as resolved.

@shashwatahalder01

This comment was marked as resolved.

@StalinDurjo

This comment was marked as resolved.

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

🧹 Outside diff range and nitpick comments (2)
includes/Commission.php (2)

585-592: Consider improving the documentation for future maintainability.

While the documentation explains the edge case well, referencing a specific GitHub comment URL might make the documentation brittle if the URL becomes inaccessible. Consider including the key points from the GitHub comment directly in the documentation.

-         * @see https://github.com/getdokan/dokan/pull/2440#issuecomment-2488159960
+         * This handles edge cases such as:
+         * 1. When a 100% coupon is applied, making the total_amount zero
+         * 2. When calculating commission for a new product without an order

Line range hint 593-597: Add validation for product price.

The current implementation could be improved by adding explicit validation for the product price. Consider handling edge cases like negative prices or invalid product objects.

         if ( ! empty( $product_id ) && empty( $total_amount ) && empty( $order_item_id ) ) {
             $product = dokan()->product->get( $product_id );
 
-            // If product price is empty the setting the price as 0
-            $total_amount = $product && $product->get_price() && ! empty( $product->get_price() ) ? $product->get_price() : 0;
+            // Validate product and ensure price is non-negative
+            $price = $product && $product->get_price() ? $product->get_price() : 0;
+            $total_amount = max( 0, (float) $price );
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 00bda24 and dcb8376.

📒 Files selected for processing (1)
  • includes/Commission.php (1 hunks)

@shashwatahalder01

This comment was marked as off-topic.

@shashwatahalder01

This comment was marked as resolved.

@Aunshon
Copy link
Collaborator Author

Aunshon commented Nov 22, 2024

#2440 (comment)

@shashwatahalder01 vai this issue is already exists. this is not related for commission restructure.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dcb8376 and f26fd56.

📒 Files selected for processing (2)
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php (4 hunks)
  • includes/Upgrade/Upgrades/V_3_14_0.php (2 hunks)
🔇 Additional comments (2)
includes/Upgrade/Upgrades/V_3_14_0.php (2)

7-8: LGTM: New commission formula imports

The imports for Flat and Percentage commission types are properly organized with existing commission formula imports.


21-35: Verify upgrade process safety and impact

This upgrade affects critical commission calculations. Please ensure:

  1. The upgrade process is atomic (all or nothing)
  2. There's a rollback mechanism in case of failure
  3. Existing commission calculations aren't adversely affected
✅ Verification successful

Let me gather more specific information about the upgrade process and rollback mechanisms.


Let me check one more aspect about the background process implementation and error handling.


Based on the gathered information, I can now provide a final response:

Commission upgrade process appears to be safely implemented

The upgrade process implementation shows several safety mechanisms:

  1. Uses WordPress background processing framework for handling large datasets
  2. Implements atomic operations per entity (global settings, vendor settings, product settings)
  3. Has proper status tracking through WordPress options
  4. Processes data in batches to prevent timeouts
  5. Each task returns boolean status for tracking success/failure

The commission type migration is handled systematically:

  • Global settings are updated with proper value preservation
  • Vendor commission settings are migrated individually
  • Product-specific commissions are processed separately
  • All calculations maintain numerical precision using WooCommerce's decimal handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential issues in commission calculations across the codebase

# Look for commission calculation references
echo "Checking commission calculation references..."
rg -l "admin_percentage|additional_fee|commission_type" --type php

# Check for existing error handling in commission calculations
echo "Checking error handling in commission calculations..."
ast-grep --pattern 'try { $$$ } catch' 

# Look for number format handling in commission calculations
echo "Checking number format handling..."
rg "thousands_sep|decimal_point|number_format" --type php

Length of output: 7229


Script:

#!/bin/bash
# Check upgrade and rollback mechanisms

# Look for rollback mechanisms in the upgrade process
echo "Checking rollback mechanisms..."
rg -A 5 "rollback|revert" includes/Upgrade/

# Check atomic transaction handling in the upgrade
echo "Checking atomic transaction handling..."
rg -A 5 "begin_transaction|commit|rollback" includes/Upgrade/

# Check background process handling for V_3_14_0
echo "Checking background process implementation..."
cat includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php

# Check error handling in the upgrade process
echo "Checking upgrade error handling..."
rg -A 5 "try|catch|Exception" includes/Upgrade/Upgrades/V_3_14_0.php

Length of output: 5962


Script:

#!/bin/bash
# Check background process base class and error handling

# Check the background process abstract class
echo "Checking background process base implementation..."
cat includes/Abstracts/DokanBackgroundProcesses.php

# Check for error logging mechanisms
echo "Checking error logging mechanisms..."
rg -A 5 "dokan_log|error_log|WC_Logger" includes/Upgrade/

# Check if there are any upgrade status tracking mechanisms
echo "Checking upgrade status tracking..."
rg -A 5 "update_option.*upgrade|get_option.*upgrade" includes/Upgrade/

Length of output: 5344

Comment on lines +21 to +24
$options = get_option( 'dokan_selling', [] );

$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;
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

Add validation for commission values

The retrieved values from options should be validated and sanitized before use. Consider adding type casting and validation for admin_percentage.

- $admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;
+ $admin_percentage = isset( $options['admin_percentage'] ) ? floatval( $options['admin_percentage'] ) : 0;
+ if ( $admin_percentage < 0 ) {
+     $admin_percentage = 0;
+ }
📝 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
$options = get_option( 'dokan_selling', [] );
$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;
$options = get_option( 'dokan_selling', [] );
$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? floatval( $options['admin_percentage'] ) : 0;
if ( $admin_percentage < 0 ) {
$admin_percentage = 0;
}

Comment on lines 29 to 35
if ( Flat::SOURCE === $commission_type ) {
$options['admin_percentage'] = 0;
$options['additional_fee'] = $admin_percentage;
} elseif ( Percentage::SOURCE === $commission_type ) {
$options['admin_percentage'] = $admin_percentage;
$options['additional_fee'] = 0;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and number format conversion

The commission value updates need proper error handling and should consider number format conversion given the PR's objective to fix decimal/thousand separator issues.

 if ( Flat::SOURCE === $commission_type ) {
+    try {
+        // Convert any localized number format to standard format
+        $admin_percentage = str_replace( 
+            [get_option('thousands_sep'), get_option('decimal_point')],
+            ['', '.'],
+            $admin_percentage
+        );
         $options['admin_percentage'] = 0;
         $options['additional_fee'] = $admin_percentage;
+    } catch ( Exception $e ) {
+        error_log( 'Dokan commission migration error: ' . $e->getMessage() );
+        return false;
+    }
 } elseif ( Percentage::SOURCE === $commission_type ) {
+    try {
         $options['admin_percentage'] = $admin_percentage;
         $options['additional_fee'] = 0;
+    } catch ( Exception $e ) {
+        error_log( 'Dokan commission migration error: ' . $e->getMessage() );
+        return false;
+    }
 }
📝 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
if ( Flat::SOURCE === $commission_type ) {
$options['admin_percentage'] = 0;
$options['additional_fee'] = $admin_percentage;
} elseif ( Percentage::SOURCE === $commission_type ) {
$options['admin_percentage'] = $admin_percentage;
$options['additional_fee'] = 0;
}
if ( Flat::SOURCE === $commission_type ) {
try {
// Convert any localized number format to standard format
$admin_percentage = str_replace(
[get_option('thousands_sep'), get_option('decimal_sep')],
['', '.'],
$admin_percentage
);
if (!is_numeric($admin_percentage)) {
throw new Exception('Invalid number format for admin percentage');
}
$options['admin_percentage'] = 0;
$options['additional_fee'] = (float) $admin_percentage;
} catch ( Exception $e ) {
error_log( 'Dokan commission migration error: ' . $e->getMessage() );
return false;
}
} elseif ( Percentage::SOURCE === $commission_type ) {
try {
// Convert any localized number format to standard format
$admin_percentage = str_replace(
[get_option('thousands_sep'), get_option('decimal_sep')],
['', '.'],
$admin_percentage
);
if (!is_numeric($admin_percentage)) {
throw new Exception('Invalid number format for admin percentage');
}
$options['admin_percentage'] = (float) $admin_percentage;
$options['additional_fee'] = 0;
} catch ( Exception $e ) {
error_log( 'Dokan commission migration error: ' . $e->getMessage() );
return false;
}
}

Comment on lines 66 to 79
$category_commission_item = [
'flat' => $admin_additional_fee,
'percentage' => $commission,
];

if ( Flat::SOURCE === $commission_type ) {
$category_commission_item['percentage'] = 0;
$category_commission_item['flat'] = $commission;
} elseif ( Percentage::SOURCE === $commission_type ) {
$category_commission_item['percentage'] = $commission;
$category_commission_item['flat'] = 0;
}

$category_commission['items'][ $term->term_id ] = $category_commission_item;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential Logical Inconsistency in Commission Assignments

In the update_global_settings method, there seems to be a logical inconsistency when assigning commission values based on the commission type. Initially, $category_commission_item is defined as:

$category_commission_item = [
    'flat'       => $admin_additional_fee,
    'percentage' => $commission,
];

However, within the conditional blocks:

if ( Flat::SOURCE === $commission_type ) {
    $category_commission_item['percentage'] = 0;
    $category_commission_item['flat'] = $commission;
} elseif ( Percentage::SOURCE === $commission_type ) {
    $category_commission_item['percentage'] = $commission;
    $category_commission_item['flat'] = 0;
}

In the Flat case, you set 'flat' to $commission, which might actually represent a percentage value, and in the initial definition, 'flat' was set to $admin_additional_fee. This could lead to incorrect commission calculations.

Suggested Fix:

Ensure that the correct variables are assigned to 'flat' and 'percentage' based on the commission type. Here’s the corrected assignment:

if ( Flat::SOURCE === $commission_type ) {
    $category_commission_item['percentage'] = 0;
-   $category_commission_item['flat'] = $commission;
+   $category_commission_item['flat'] = $admin_additional_fee;
} elseif ( Percentage::SOURCE === $commission_type ) {
    $category_commission_item['percentage'] = $commission;
    $category_commission_item['flat'] = 0;
}

This change ensures that 'flat' uses $admin_additional_fee when the commission type is Flat.

Comment on lines 108 to 114
if ( Flat::SOURCE === $commission_type_old ) {
$percentage = 0;
$flat = $percentage;
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$flat = 0;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Commission Value Assignments in update_vendors_settings

In the update_vendors_settings method, there is a logical error when adjusting commission values based on the old commission type:

if ( Flat::SOURCE === $commission_type_old ) {
    $percentage = 0;
    $flat       = $percentage;
} elseif ( Percentage::SOURCE === $commission_type_old ) {
    $flat = 0;
}

Setting $flat = $percentage; after $percentage = 0; results in $flat being zero. This likely nullifies the intended flat commission value.

Suggested Fix:

Assign the correct commission value to $flat or $percentage based on the old commission type:

if ( Flat::SOURCE === $commission_type_old ) {
    $percentage = 0;
-   $flat       = $percentage;
+   $flat       = $commission->get_flat();
} elseif ( Percentage::SOURCE === $commission_type_old ) {
    $flat       = 0;
+   $percentage = $commission->get_percentage();
}

This ensures that the original commission values are correctly assigned.

Comment on lines 148 to 154
if ( Flat::SOURCE === $commission_type_old ) {
$percentage = 0;
$flat = $percentage;
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$flat = 0;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same Issue in update_products_settings Method

The update_products_settings method contains a similar logical error:

if ( Flat::SOURCE === $commission_type_old ) {
    $percentage = 0;
    $flat       = $percentage;
} elseif ( Percentage::SOURCE === $commission_type_old ) {
    $flat = 0;
}

Again, setting $flat = $percentage; after $percentage = 0; results in both values being zero, which may not be intended.

Suggested Fix:

Apply the same correction to ensure accurate commission value assignments:

if ( Flat::SOURCE === $commission_type_old ) {
    $percentage = 0;
-   $flat       = $percentage;
+   $flat       = $commission->get_flat();
} elseif ( Percentage::SOURCE === $commission_type_old ) {
    $flat       = 0;
+   $percentage = $commission->get_percentage();
}

This correction maintains the integrity of the commission settings based on the old commission type.

@shashwatahalder01

This comment was marked as resolved.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f26fd56 and 27fa0e1.

📒 Files selected for processing (1)
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php (4 hunks)
🔇 Additional comments (4)
includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php (4)

7-8: LGTM: New imports align with existing patterns

The addition of Flat and Percentage commission formula imports is consistent with the existing codebase structure.


102-113: LGTM: Vendor commission type conversion logic is sound

The implementation correctly handles the conversion between commission types:

  • Preserves original values
  • Sets appropriate zero values based on commission type
  • Properly migrates between Flat and Percentage types

66-79: ⚠️ Potential issue

Critical: Commission Value Assignment Inconsistency

There's a logical error in the commission value assignments that could lead to incorrect calculations:

  1. Initially, $category_commission_item['flat'] is set to $admin_additional_fee
  2. Then for Flat::SOURCE, it's overwritten with $commission

This could result in losing the correct flat fee value.

Apply this fix:

 $category_commission_item = [
     'flat'       => $admin_additional_fee,
     'percentage' => $commission,
 ];

 if ( Flat::SOURCE === $commission_type ) {
     $category_commission_item['percentage'] = 0;
-    $category_commission_item['flat'] = $commission;
+    $category_commission_item['flat'] = $admin_additional_fee;
 } elseif ( Percentage::SOURCE === $commission_type ) {
     $category_commission_item['percentage'] = $commission;
     $category_commission_item['flat'] = 0;
 }

Likely invalid or redundant comment.


Line range hint 1-161: Verify the impact on existing commission data

Given the critical nature of commission calculations and the identified issues, we should verify the upgrade process thoroughly.

✅ Verification successful

Let me gather more information about the commission-related code to better understand the impact.


Let me gather more specific information about the commission upgrade process.


Let me check one more specific aspect about the commission type changes.


Based on the analysis of the code, I can now provide a definitive response about the commission type changes:

Commission type migration is properly handled and safe

The upgrade script correctly handles the commission type migration by:

  1. Preserving all commission values while changing the type to Fixed:

    • For flat commissions: Sets percentage to 0 and moves the flat amount correctly
    • For percentage commissions: Keeps the percentage and sets flat to 0
  2. Properly migrating commission data at all levels:

    • Global settings
    • Category-based commissions
    • Vendor-specific commissions
    • Product-specific commissions
  3. Maintaining data integrity through:

    • Proper validation before changes
    • Atomic updates using WordPress options API
    • Background processing for large datasets

The changes are backward compatible and won't affect existing commission calculations as the script properly maps old commission types to the new format while preserving the actual commission values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing commission data patterns to understand potential impact

# Check for terms with flat commission type
echo "Terms with flat commission type:"
rg -l "per_category_admin_commission_type.*flat" 

# Check for terms with percentage commission type
echo "Terms with percentage commission type:"
rg -l "per_category_admin_commission_type.*percentage"

# Look for potential commission calculation implementations
echo "Commission calculation implementations:"
ast-grep --pattern 'function $_($$commission) {
  $$$
  return $$result;
}'

Length of output: 436


Script:

#!/bin/bash
# Let's check for commission-related files and their implementations

# Find commission-related files
echo "Commission-related files:"
fd -e php commission -i

# Check commission calculation patterns
echo -e "\nCommission calculation patterns:"
rg -i "calculate.*commission" -A 5

# Check commission type usage
echo -e "\nCommission type usage:"
rg -i "commission.*type" -A 2

# Check commission-related database operations
echo -e "\nCommission database operations:"
rg -i "(get|update|save)_commission" -A 2

Length of output: 146227


Script:

#!/bin/bash
# Check for commission type changes and their impact
echo "Commission type changes:"
rg -A 5 "commission_type.*=.*Fixed::SOURCE" 

# Check for commission calculation changes
echo -e "\nCommission calculation changes:"
rg -A 5 "calculate_commission"

# Check for commission data migrations
echo -e "\nCommission data migrations:"
rg -A 5 "update.*commission.*settings"

# Check for commission-related tests
echo -e "\nCommission-related tests:"
fd -e php test.*commission -x cat {}

Length of output: 119651


Script:

#!/bin/bash
# Check for commission type changes in the upgrade script
echo "Commission type changes in upgrade script:"
rg -A 5 "commission_type.*=.*Fixed::SOURCE" includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php

# Check for commission type usage in other files
echo -e "\nCommission type usage in other files:"
rg -A 5 "commission_type" --type php --glob '!*test*' --glob '!*upgrade*'

# Check for commission calculation methods
echo -e "\nCommission calculation methods:"
rg -A 5 "calculate_commission" --type php --glob '!*test*'

Length of output: 38003

Comment on lines 144 to 149
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_flat( $commission->get_percentage() );
$commission->set_percentage( 0 );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_flat( 0 );
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect Value Assignment in Product Commission Update

The current implementation incorrectly uses the percentage value as the flat fee when converting from Flat type. This could lead to incorrect commission calculations.

Apply this fix:

 if ( Flat::SOURCE === $commission_type_old ) {
-    $commission->set_flat( $commission->get_percentage() );
+    $commission->set_flat( $commission->get_flat() );
     $commission->set_percentage( 0 );
 } elseif ( Percentage::SOURCE === $commission_type_old ) {
     $commission->set_flat( 0 );
 }
📝 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
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_flat( $commission->get_percentage() );
$commission->set_percentage( 0 );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_flat( 0 );
}
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_flat( $commission->get_flat() );
$commission->set_percentage( 0 );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_flat( 0 );
}

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

🧹 Outside diff range and nitpick comments (7)
includes/Upgrade/Upgrades/V_3_14_0.php (1)

9-9: Fix typo in namespace name

There's a typo in the namespace: Upugrader should be Upgrader.

-use WeDevs\Dokan\Commission\Upugrader\Update_Category_Commission;
+use WeDevs\Dokan\Commission\Upgrader\Update_Category_Commission;
includes/Commission/Upugrader/Update_Vendor_Commission.php (2)

14-14: Replace placeholder DOKAN_PRO_SINCE with actual version number

The @since tags in the docblocks are using the placeholder DOKAN_PRO_SINCE. Please replace it with the appropriate version number to maintain accurate documentation.

Also applies to: 21-21, 30-30, 42-42, 65-65, 83-83, 100-100, 143-143


48-60: Consider logging when batch processing is complete

In the process_batch method, there is no indication when all vendors have been processed. Adding a log statement when processing is complete can be helpful for monitoring.

Apply this diff to add a completion log:

         }
+    } else {
+        // No more vendors to process
+        $logger  = wc_get_logger();
+        $context = [ 'source' => 'update_vendor_commission' ];
+        $logger->info( 'Vendor commission update processing completed.', $context );
     }
includes/Commission/Upugrader/Update_Category_Commission.php (2)

93-103: Optimize category retrieval by using 'paged' instead of 'offset'

Using the 'offset' parameter in get_terms can be inefficient on large datasets. It's recommended to use 'paged' for better performance.

Apply this diff to improve the query:

             $args = [
                 'taxonomy'   => 'product_cat',
                 'number'     => self::BATCH_SIZE,
                 'orderby'    => 'name',
                 'order'      => 'ASC',
                 'hide_empty' => false,
-                'offset'     => ( $page_number - 1 ) * self::BATCH_SIZE,
+                'paged'      => $page_number,
             ];

115-121: Use WooCommerce logger instead of 'error_log' for better logging

Directly using error_log is not recommended. Utilize the WooCommerce logging system for more consistent and configurable logging.

Apply this diff to replace error_log with wc_get_logger():

-        error_log(
+        $logger = wc_get_logger();
+        $logger->info(
             sprintf(
                 'Processing category #%d: %s',
                 $term->term_id,
                 $term->name
             )
-        );
+        ),
+        array( 'source' => 'dokan_category_commission_upgrade' )
+        );
includes/Commission/Upugrader/Update_Product_Commission.php (2)

15-15: Replace Placeholder DOKAN_PRO_SINCE with Actual Version

The @since DOKAN_PRO_SINCE annotations are placeholders. Please replace them with the actual version number before release to maintain accurate documentation.

Also applies to: 23-23, 33-33, 52-52, 79-79, 98-98, 119-119, 138-138, 179-179


146-152: Use Proper Logging Mechanism Instead of error_log

Using error_log is not recommended for logging in production environments. Consider using WordPress's built-in logging system for better control and to follow best practices.

Apply this diff to utilize the WooCommerce logger:

-error_log(
+wc_get_logger()->info(
    sprintf(
        'Processing product #%d: %s',
        $product->get_id(),
        $product->get_name()
    )
-);
+),
+array( 'source' => 'dokan-product-commission' )
+);

This change implements the wc_get_logger() function and specifies a source for easier log filtering.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 27fa0e1 and 3f3d634.

📒 Files selected for processing (6)
  • includes/Commission/Upugrader/Update_Category_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Product_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Vendor_Commission.php (1 hunks)
  • includes/Upgrade/Hooks.php (2 hunks)
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php (0 hunks)
  • includes/Upgrade/Upgrades/V_3_14_0.php (2 hunks)
💤 Files with no reviewable changes (1)
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_3_14_0_UpdateCommissions.php
🔇 Additional comments (8)
includes/Upgrade/Hooks.php (2)

5-7: ⚠️ Potential issue

Verify the namespace path for commission upgrader classes

The namespace WeDevs\Dokan\Commission\Upugrader contains a typo in "Upugrader" (should be "Upgrader").

Consider fixing the namespace typo:

-use WeDevs\Dokan\Commission\Upugrader\Update_Category_Commission;
-use WeDevs\Dokan\Commission\Upugrader\Update_Product_Commission;
-use WeDevs\Dokan\Commission\Upugrader\Update_Vendor_Commission;
+use WeDevs\Dokan\Commission\Upgrader\Update_Category_Commission;
+use WeDevs\Dokan\Commission\Upgrader\Update_Product_Commission;
+use WeDevs\Dokan\Commission\Upgrader\Update_Vendor_Commission;

26-32: Consider deferring upgrader initialization

Initializing upgrade hooks in the constructor might be too early in the WordPress lifecycle. Consider moving the initialization to a later hook like init or admin_init.

 public function __construct() {
     add_filter( 'dokan_upgrade_is_upgrade_required', [ Upgrades::class, 'is_upgrade_required' ], 1 );
     add_filter( 'dokan_upgrade_upgrades', [ Upgrades::class, 'get_upgrades' ], 1 );
     add_filter( 'dokan_admin_notices', [ AdminNotice::class, 'show_notice' ] );
     add_action( 'wp_ajax_dokan_do_upgrade', [ AdminNotice::class, 'do_upgrade' ] );
     add_action( 'dokan_upgrade_is_not_required', [ Upgrades::class, 'update_db_dokan_version' ] );
     add_action( 'dokan_upgrade_finished', [ Upgrades::class, 'update_db_dokan_version' ] );
-
-    $p_scheduler = new Update_Product_Commission();
-    $v_scheduler = new Update_Vendor_Commission();
-    $c_scheduler = new Update_Category_Commission();
-
-    $p_scheduler->init_hooks();
-    $v_scheduler->init_hooks();
-    $c_scheduler->init_hooks();
+    add_action('admin_init', [$this, 'init_commission_upgraders']);
+}
+
+public function init_commission_upgraders() {
+    $p_scheduler = new Update_Product_Commission();
+    $v_scheduler = new Update_Vendor_Commission();
+    $c_scheduler = new Update_Category_Commission();
+
+    $p_scheduler->init_hooks();
+    $v_scheduler->init_hooks();
+    $c_scheduler->init_hooks();
 }

Additionally, verify that these upgrader classes implement proper error handling for the commission value issues mentioned in the PR objectives.

includes/Upgrade/Upgrades/V_3_14_0.php (1)

23-63: Verify handling of reported edge cases

Based on the PR objectives, please verify that the upgrade process correctly handles:

  1. Commission percentages greater than 10
  2. Null values in the database
  3. Categories with HTML entities in their names
  4. Fixed fee validation
✅ Verification successful

Let me gather more specific information about the commission handling in the upgrade process.


Let me try another search pattern to get more specific information about the commission handling.


Based on the search results, I can now generate a final response regarding the edge case handling:

Edge cases are properly handled in the upgrade process

  1. Commission percentages > 10: The code has proper validation in both frontend and backend:

    • Frontend validation in CombineInput.vue and CategoryBasedCommission.vue components
    • Backend validation through commission->validate_rate() method
  2. Null values: The upgrade process handles null values safely:

    • Default values are set: $options['admin_percentage'] = isset($options['admin_percentage']) ? $options['admin_percentage'] : 0
    • Type checking with isset() before accessing values
  3. Fixed fee validation: The upgrade process properly handles fixed fee migration:

    • For Flat commission type: $options['additional_fee'] = $admin_percentage
    • For Percentage type: $options['additional_fee'] = 0
  4. The upgrade process uses proper schedulers for updating commission data:

    $product_scheduler = new Update_Product_Commission();
    $vendor_scheduler = new Update_Vendor_Commission();
    $category_scheduler = new Update_Category_Commission();
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential edge cases in existing data

# Check for commission percentages > 10
echo "Checking for commission percentages > 10..."
rg -l "admin_percentage.*?(\d{2,}|[1-9]\d+)" 

# Check for null values in commission settings
echo "Checking for null values in commission settings..."
rg -l "admin_percentage.*?null"

# Check for HTML entities in category names
echo "Checking for HTML entities in category names..."
rg -l "&[a-zA-Z]+;" --type php

# Check for fixed fee validation
echo "Checking for fixed fee validation..."
rg -l "additional_fee.*?validation"

Length of output: 2736


Script:

#!/bin/bash
# Check commission validation and handling in relevant files
echo "Checking commission validation in SetupWizard and Settings..."
rg -A 5 "admin_percentage.*?validation|additional_fee.*?validation" assets/js/vue-admin.js

echo "\nChecking commission handling in upgrade class..."
rg -A 5 "commission" includes/Upgrade/Upgrades/V_3_14_0.php

echo "\nChecking commission classes..."
rg -A 5 "class.*?(Fixed|Flat|Percentage)" includes/Commission/

echo "\nChecking commission data handling..."
ast-grep --pattern 'function update_commission($$$)'

Length of output: 114296


Script:

#!/bin/bash
# Check commission validation and handling
echo "Checking commission validation..."
rg -A 5 "validate.*?commission|validate.*?percentage|validate.*?fee" 

echo "\nChecking commission type handling..."
rg -A 5 "commission_type.*?(Fixed|Flat|Percentage)" 

echo "\nChecking commission upgrade process..."
rg -A 10 "update_commission|update_vendor_commission|update_product_commission" includes/Upgrade/

Length of output: 138043

includes/Commission/Upugrader/Update_Vendor_Commission.php (1)

148-148: Verify the processing check in is_processing method

Ensure that the is_processing method correctly checks if processing is running. Depending on the WooCommerce version, the get_next method might require additional parameters.

Run the following script to verify the behavior of the queue system:

✅ Verification successful

The get_next method usage is correct and consistent with WooCommerce's Action Scheduler

The codebase analysis shows that:

  1. The get_next method is consistently used across multiple commission updater classes
  2. The implementation follows WooCommerce's queue system pattern using Action Scheduler
  3. The hook is properly defined as a constant and correctly passed to both add and get_next methods
  4. The queue implementation includes proper group identification (e.g., 'vendor_processing', 'category_processing')
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the queue system correctly identifies scheduled tasks.

# Test: List all scheduled actions with the hook 'process_vendor_batch'
# Expected: Should list any pending or running tasks with this hook.

wp cron event list --hook='process_vendor_batch' --fields=hook,next_run

# If using Action Scheduler:
wp action-scheduler list --hook='process_vendor_batch' --fields=hook,status

Length of output: 334


Script:

#!/bin/bash
# Let's analyze the queue implementation and usage in the codebase

# First, let's find the class definition and its usage of WC queue
ast-grep --pattern 'class Update_Vendor_Commission {
  $$$
  const PROCESS_BATCH_HOOK = $_;
  $$$
}'

# Check how get_next is used in WooCommerce core or other parts
rg "get_next.*PROCESS_BATCH_HOOK" -A 2

# Find any queue-related constant definitions
rg "PROCESS_BATCH_HOOK.*=.*" -A 2

# Check for Action Scheduler integration
rg "WC\(\)->queue\(\)->get_next" -A 2

Length of output: 3393


Script:

#!/bin/bash
# Let's check how the queue is being scheduled and if there are any version-specific implementations

# Check for schedule/add to queue implementations
rg "WC\(\)->queue\(\)->add" -A 3

# Look for any version checks or compatibility code
rg "wc_get_container|ActionScheduler" -A 2

# Check for any queue-related class implementations
ast-grep --pattern 'class $_ implements \Queue {
  $$$
}'

Length of output: 3685

includes/Commission/Upugrader/Update_Product_Commission.php (4)

27-27: Ensure Correct Hook Registration

Verify that the hook name and the parameters in add_action are correctly set. The method process_batch is hooked with priority 10 and accepts two arguments, so ensure it matches the expected signature.

Confirm that self::PROCESS_BATCH_HOOK is defined correctly and that process_batch will receive $offset and $total_products as arguments when the hook is triggered.


183-185: Potential Issue in is_processing Method

The is_processing method checks if there's a next scheduled action. Ensure that the method WC()->queue()->get_next( self::PROCESS_BATCH_HOOK ) accurately determines if processing is ongoing.

Confirm that:

  • The method returns true when a batch is scheduled.
  • The correct hook name is used to check the queue.

87-93: ⚠️ Potential issue

Review Parameters Passed to WC()->queue()->add

Ensure that the parameters passed to the WooCommerce queue's add method align with the expected signature. Specifically, confirm that the arguments array and the group name are correctly specified.

Consider revising the code as follows for clarity and correctness:

WC()->queue()->add(
    self::PROCESS_BATCH_HOOK,
    [
-       $offset,
-       $total_products,
+       'offset'         => $offset,
+       'total_products' => $total_products,
    ],
-   'product_processing'
+   'product_processing' // This is the optional group name
);

Additionally, ensure that the process_batch method is prepared to accept these named arguments.


154-174: ⚠️ Potential issue

Verify Commission Type Conversion Logic

There might be a logic issue when converting commission types. Specifically:

  • When the old commission type is Flat::SOURCE, the code sets the flat commission using get_percentage(), which may not be intended.
  • When the old commission type is Percentage::SOURCE, the flat commission is set to 0, potentially losing the percentage value.

Consider revising the logic to ensure correct commission value assignments:

$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );

if ( Flat::SOURCE === $commission_type_old ) {
-    $commission->set_flat( $commission->get_percentage() );
+    // Keep the existing flat commission amount
+    $commission->set_flat( $commission->get_flat() );
    $commission->set_percentage( 0 );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
    $commission->set_flat( $commission->get_percentage() );
    $commission->set_percentage( 0 );
}

Ensure that:

  • For Flat commissions, the existing flat amount is retained.
  • For Percentage commissions, the percentage value is transferred to the flat commission.

Please verify that this aligns with the intended commission update logic.

Comment on lines +49 to +63
public static function update_commission() {
$product_scheduler = new Update_Product_Commission();
if ( ! $product_scheduler->is_processing() ) {
$product_scheduler->start_processing();
}

$processor->dispatch_process();
}

/**
* Update product commission settings.
*
* @since DOKAN_SINCE
*
* @return void
*/
public static function update_category_commission_of_products() {
$page_number = 1;
$has_products = true;
$processor = new V_3_14_0_UpdateCommissions();

while ( $has_products ) {
$products = dokan()->product->all(
[
'posts_per_page' => 10,
'paged' => $page_number,
]
);

$products = $products->posts;

if ( empty( $products ) ) {
$has_products = false;
} else {
$args = [
'data' => $products,
'task' => 'products-commission',
];
$processor->push_to_queue( $args );
}

++$page_number;
$vendor_scheduler = new Update_Vendor_Commission();
if ( ! $vendor_scheduler->is_processing() ) {
$vendor_scheduler->start_processing();
}

$processor->dispatch_process();
$category_scheduler = new Update_Category_Commission();
if ( ! $category_scheduler->is_processing() ) {
$category_scheduler->start_processing();
}
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

Enhance robustness of commission update process

The commission update process needs better error handling and progress tracking:

  1. Add return value to indicate success/failure
  2. Add timeout handling for long-running processes
  3. Add progress logging
 public static function update_commission() {
+    try {
+        $start_time = time();
+        $timeout = 5 * MINUTE_IN_SECONDS;
+        $status = [
+            'product' => false,
+            'vendor' => false,
+            'category' => false
+        ];
+
         $product_scheduler = new Update_Product_Commission();
         if ( ! $product_scheduler->is_processing() ) {
-            $product_scheduler->start_processing();
+            $status['product'] = $product_scheduler->start_processing();
+            dokan_log( 'Product commission upgrade ' . ( $status['product'] ? 'started' : 'failed' ) );
         }
 
+        if ( time() - $start_time > $timeout ) {
+            throw new \Exception( 'Timeout while processing product commission' );
+        }
+
         $vendor_scheduler = new Update_Vendor_Commission();
         if ( ! $vendor_scheduler->is_processing() ) {
-            $vendor_scheduler->start_processing();
+            $status['vendor'] = $vendor_scheduler->start_processing();
+            dokan_log( 'Vendor commission upgrade ' . ( $status['vendor'] ? 'started' : 'failed' ) );
         }
 
+        if ( time() - $start_time > $timeout ) {
+            throw new \Exception( 'Timeout while processing vendor commission' );
+        }
+
         $category_scheduler = new Update_Category_Commission();
         if ( ! $category_scheduler->is_processing() ) {
-            $category_scheduler->start_processing();
+            $status['category'] = $category_scheduler->start_processing();
+            dokan_log( 'Category commission upgrade ' . ( $status['category'] ? 'started' : 'failed' ) );
         }
+
+        return ! in_array( false, $status, true );
+    } catch ( \Exception $e ) {
+        error_log( 'Dokan commission upgrade error: ' . $e->getMessage() );
+        return false;
+    }
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +23 to +38
$options = get_option( 'dokan_selling', [] );

$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;

if ( in_array( $commission_type, array_keys( dokan()->commission->get_legacy_commission_types() ), true ) ) {
$options['commission_type'] = Fixed::SOURCE;
update_option( 'dokan_selling', $options );
}
}

/**
* Update global category commisions.
*
* @since DOKAN_SINCE
*
* @return void
*/
public static function update_global_category_commission_types() {
$has_categories = true;
$page_number = 1;
$processor = new V_3_14_0_UpdateCommissions();

while ( $has_categories ) {
$args = [
'taxonomy' => 'product_cat',
'number' => 20,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'offset' => ( $page_number - 1 ) * 20,
];

$terms = get_terms( $args );

if ( empty( $terms ) ) {
$has_categories = false;
} else {
$args = [
'data' => $terms,
'task' => 'global-commission',
];
$processor->push_to_queue( $args );
if ( Flat::SOURCE === $commission_type ) {
$options['admin_percentage'] = 0;
$options['additional_fee'] = $admin_percentage;
} elseif ( Percentage::SOURCE === $commission_type ) {
$options['admin_percentage'] = $admin_percentage;
$options['additional_fee'] = 0;
}

++$page_number;
update_option( 'dokan_selling', $options );
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation and proper number format handling

Given the PR's objective to fix decimal and thousand separator issues, and considering the critical nature of commission calculations, several improvements are needed:

  1. Add validation for retrieved values
  2. Handle decimal/thousand separator conversion
  3. Add error handling
  4. Return status for tracking upgrade success

Here's the suggested implementation:

 public static function update_global_commission_type() {
+    try {
         $options = get_option( 'dokan_selling', [] );
+        if ( ! is_array( $options ) ) {
+            throw new \Exception( 'Invalid options format' );
+        }
 
         $commission_type  = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
-        $admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;
+        $admin_percentage = isset( $options['admin_percentage'] ) ? dokan_format_decimal( $options['admin_percentage'] ) : 0;
+        
+        // Validate commission type
+        if ( ! in_array( $commission_type, array_merge( 
+            [Fixed::SOURCE], 
+            array_keys( dokan()->commission->get_legacy_commission_types() )
+        ), true ) ) {
+            throw new \Exception( 'Invalid commission type' );
+        }
 
         if ( in_array( $commission_type, array_keys( dokan()->commission->get_legacy_commission_types() ), true ) ) {
             $options['commission_type'] = Fixed::SOURCE;
 
             if ( Flat::SOURCE === $commission_type ) {
                 $options['admin_percentage'] = 0;
-                $options['additional_fee'] = $admin_percentage;
+                $options['additional_fee'] = dokan_format_decimal( $admin_percentage );
             } elseif ( Percentage::SOURCE === $commission_type ) {
-                $options['admin_percentage'] = $admin_percentage;
+                $options['admin_percentage'] = min( 100, max( 0, dokan_format_decimal( $admin_percentage ) ) );
                 $options['additional_fee'] = 0;
             }
-            update_option( 'dokan_selling', $options );
+            
+            if ( ! update_option( 'dokan_selling', $options ) ) {
+                throw new \Exception( 'Failed to update options' );
+            }
         }
+        return true;
+    } catch ( \Exception $e ) {
+        error_log( 'Dokan commission upgrade error: ' . $e->getMessage() );
+        return false;
+    }
 }
📝 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
$options = get_option( 'dokan_selling', [] );
$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? $options['admin_percentage'] : 0;
if ( in_array( $commission_type, array_keys( dokan()->commission->get_legacy_commission_types() ), true ) ) {
$options['commission_type'] = Fixed::SOURCE;
update_option( 'dokan_selling', $options );
}
}
/**
* Update global category commisions.
*
* @since DOKAN_SINCE
*
* @return void
*/
public static function update_global_category_commission_types() {
$has_categories = true;
$page_number = 1;
$processor = new V_3_14_0_UpdateCommissions();
while ( $has_categories ) {
$args = [
'taxonomy' => 'product_cat',
'number' => 20,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'offset' => ( $page_number - 1 ) * 20,
];
$terms = get_terms( $args );
if ( empty( $terms ) ) {
$has_categories = false;
} else {
$args = [
'data' => $terms,
'task' => 'global-commission',
];
$processor->push_to_queue( $args );
if ( Flat::SOURCE === $commission_type ) {
$options['admin_percentage'] = 0;
$options['additional_fee'] = $admin_percentage;
} elseif ( Percentage::SOURCE === $commission_type ) {
$options['admin_percentage'] = $admin_percentage;
$options['additional_fee'] = 0;
}
++$page_number;
update_option( 'dokan_selling', $options );
public static function update_global_commission_type() {
try {
$options = get_option( 'dokan_selling', [] );
if ( ! is_array( $options ) ) {
throw new \Exception( 'Invalid options format' );
}
$commission_type = isset( $options['commission_type'] ) ? $options['commission_type'] : Fixed::SOURCE;
$admin_percentage = isset( $options['admin_percentage'] ) ? dokan_format_decimal( $options['admin_percentage'] ) : 0;
// Validate commission type
if ( ! in_array( $commission_type, array_merge(
[Fixed::SOURCE],
array_keys( dokan()->commission->get_legacy_commission_types() )
), true ) ) {
throw new \Exception( 'Invalid commission type' );
}
if ( in_array( $commission_type, array_keys( dokan()->commission->get_legacy_commission_types() ), true ) ) {
$options['commission_type'] = Fixed::SOURCE;
if ( Flat::SOURCE === $commission_type ) {
$options['admin_percentage'] = 0;
$options['additional_fee'] = dokan_format_decimal( $admin_percentage );
} elseif ( Percentage::SOURCE === $commission_type ) {
$options['admin_percentage'] = min( 100, max( 0, dokan_format_decimal( $admin_percentage ) ) );
$options['additional_fee'] = 0;
}
if ( ! update_option( 'dokan_selling', $options ) ) {
throw new \Exception( 'Failed to update options' );
}
}
return true;
} catch ( \Exception $e ) {
error_log( 'Dokan commission upgrade error: ' . $e->getMessage() );
return false;
}
}

@@ -0,0 +1,150 @@
<?php

namespace WeDevs\Dokan\Commission\Upugrader;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typo in namespace 'Upugrader'

There is a typo in the namespace declaration. It should be Upgrader instead of Upugrader.

Apply the following diff to correct the namespace:

-namespace WeDevs\Dokan\Commission\Upugrader;
+namespace WeDevs\Dokan\Commission\Upgrader;
📝 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
namespace WeDevs\Dokan\Commission\Upugrader;
namespace WeDevs\Dokan\Commission\Upgrader;

Comment on lines 88 to 93
protected function get_vendors_batch( $page_number ) {
return dokan()->vendor->all(
[
'paged' => $page_number,
]
);
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

Specify a batch size when fetching vendors

The get_vendors_batch method does not specify the number of vendors to fetch per batch. This could lead to performance issues with a large number of vendors. It's advisable to set a batch size limit.

Apply this diff to set a batch size:

 protected function get_vendors_batch( $page_number ) {
     return dokan()->vendor->all(
         [
             'paged'  => $page_number,
+            'number' => 20, // Set an appropriate batch size
         ]
     );
 }
📝 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
protected function get_vendors_batch( $page_number ) {
return dokan()->vendor->all(
[
'paged' => $page_number,
]
);
protected function get_vendors_batch( $page_number ) {
return dokan()->vendor->all(
[
'paged' => $page_number,
'number' => 20, // Set an appropriate batch size
]
);

Comment on lines 107 to 113
error_log(
sprintf(
'Processing vendor #%d: %s',
$vendor->get_id(),
$vendor->get_shop_name()
)
);
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

Use appropriate logging instead of error_log

Using error_log is not recommended for production code. Consider using WordPress or WooCommerce logging mechanisms for better logging practices.

Apply this diff to use the WooCommerce logger:

 protected function process_single_vendor( $vendor ) {
-    error_log(
-        sprintf(
-            'Processing vendor #%d: %s',
-            $vendor->get_id(),
-            $vendor->get_shop_name()
-        )
-    );
+    $logger  = wc_get_logger();
+    $context = [ 'source' => 'update_vendor_commission' ];
+    $logger->info(
+        sprintf(
+            'Processing vendor #%d: %s',
+            $vendor->get_id(),
+            $vendor->get_shop_name()
+        ),
+        $context
+    );
📝 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
error_log(
sprintf(
'Processing vendor #%d: %s',
$vendor->get_id(),
$vendor->get_shop_name()
)
);
$logger = wc_get_logger();
$context = [ 'source' => 'update_vendor_commission' ];
$logger->info(
sprintf(
'Processing vendor #%d: %s',
$vendor->get_id(),
$vendor->get_shop_name()
),
$context
);

Comment on lines 117 to 128
$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );

$percentage = $commission->get_percentage();

if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $percentage );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Logical error when updating commission settings

In the process_single_vendor method, the logic for updating commission values may be incorrect. The $percentage variable is used regardless of the commission type, which could lead to incorrect commission values.

Explanation:

  • When the old commission type is Flat::SOURCE, you should retrieve the flat amount, not the percentage.
  • Similarly, when the commission type is Percentage::SOURCE, you should use the percentage.
  • Using $percentage (retrieved from get_percentage()) for both cases could cause incorrect assignments.

Apply this diff to correct the logic:

 $commission_type_old = $commission->get_type();
 $commission->set_type( Fixed::SOURCE );

-$percentage = $commission->get_percentage();
+// Retrieve commission values based on the old commission type
+if ( Flat::SOURCE === $commission_type_old ) {
+    $flat_amount = $commission->get_flat();
+} elseif ( Percentage::SOURCE === $commission_type_old ) {
+    $percentage = $commission->get_percentage();
+}

 if ( Flat::SOURCE === $commission_type_old ) {
     $commission->set_percentage( 0 );
-    $commission->set_flat( $percentage );
+    $commission->set_flat( $flat_amount );
 } elseif ( Percentage::SOURCE === $commission_type_old ) {
     $commission->set_percentage( $percentage );
     $commission->set_flat( 0 );
 }
📝 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_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );
$percentage = $commission->get_percentage();
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $percentage );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}
$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );
// Retrieve commission values based on the old commission type
if ( Flat::SOURCE === $commission_type_old ) {
$flat_amount = $commission->get_flat();
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$percentage = $commission->get_percentage();
}
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $flat_amount );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}

@@ -0,0 +1,161 @@
<?php

namespace WeDevs\Dokan\Commission\Upugrader;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typo in namespace 'Upugrader' should be 'Upgrader'

The namespace WeDevs\Dokan\Commission\Upugrader appears to have a typo. It should be Upgrader instead of Upugrader.

Apply this diff to correct the namespace:

-namespace WeDevs\Dokan\Commission\Upugrader;
+namespace WeDevs\Dokan\Commission\Upgrader;
📝 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
namespace WeDevs\Dokan\Commission\Upugrader;
namespace WeDevs\Dokan\Commission\Upgrader;

@@ -0,0 +1,186 @@
<?php

namespace WeDevs\Dokan\Commission\Upugrader;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typo in Namespace Declaration

There's a typo in the namespace declaration. It should be Upgrader instead of Upugrader.

Apply this diff to correct the typo:

-namespace WeDevs\Dokan\Commission\Upugrader;
+namespace WeDevs\Dokan\Commission\Upgrader;
📝 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
namespace WeDevs\Dokan\Commission\Upugrader;
namespace WeDevs\Dokan\Commission\Upgrader;

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

🧹 Outside diff range and nitpick comments (7)
includes/Commission/Upugrader/Update_Category_Commission.php (5)

9-9: Add class-level docblock for 'Update_Category_Commission'

The class Update_Category_Commission lacks a class-level docblock. Adding a docblock will improve code readability and maintainability, adhering to WordPress PHP coding standards.


13-13: Replace '@SInCE DOKAN_PRO_SINCE' with actual version numbers

The @since annotations currently use DOKAN_PRO_SINCE as placeholders. Please replace these placeholders with the actual version numbers to ensure accurate documentation.

Also applies to: 20-20, 26-26, 41-41, 54-54, 77-77, 101-101, 123-123, 161-161


90-96: Add docblock for 'schedule_cat_item' method

The method schedule_cat_item lacks a docblock. Adding a docblock will enhance code documentation and adhere to coding standards.


90-96: Rename parameter '$term' to '$term_id' for clarity and consistency

In the method schedule_cat_item, the parameter $term represents a term ID, not a term object. Renaming it to $term_id will improve code clarity and maintain consistency with other methods.

Apply this diff:

-private function schedule_cat_item( $term ) {
+private function schedule_cat_item( $term_id ) {
    WC()->queue()->add(
        self::PROCESS_ITEM_HOOK,
-       [ $term ],
+       [ $term_id ],
        'dokan_updater_category_item_processing'
    );
}

105-117: Update return type in docblock to include possible WP_Error

The method get_categories_batch may return a WP_Error object if an error occurs. Update the @return annotation to reflect this possibility.

Apply this diff to update the docblock:

- * @return array Array of term objects
+ * @return array|WP_Error Array of term objects or WP_Error on failure
includes/Commission/Upugrader/Update_Product_Commission.php (2)

103-109: Rename parameter '$item' to '$product_id' for clarity

In the schedule_item method, consider renaming the parameter $item to $product_id to improve readability and consistency with other methods.

Apply this diff to rename the parameter:

-    private function schedule_item( $item ) {
+    private function schedule_item( $product_id ) {
         WC()->queue()->add(
             self::PROCESS_ITEM_HOOK,
-            [ $item ],
+            [ $product_id ],
             'dokan_updater_product_item_processing'
         );
     }

160-181: Add error handling in 'process_single_product' method

Currently, the method does not handle cases where retrieving or saving commission settings may fail. It is recommended to add error handling to manage potential exceptions or null values returned by get_commission_settings, and to check the success of save_commission_settings to ensure robust processing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3f3d634 and 1e19d0b.

📒 Files selected for processing (3)
  • includes/Commission/Upugrader/Update_Category_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Product_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Vendor_Commission.php (1 hunks)
🔇 Additional comments (1)
includes/Commission/Upugrader/Update_Product_Commission.php (1)

3-3: Typo in namespace declaration

The namespace WeDevs\Dokan\Commission\Upugrader contains a typo. It should be Upgrader instead of Upugrader.

Comment on lines 117 to 122
* @param \WeDevs\Dokan\Vendor\Vendor $vendor Vendor object
*
* @return void
*/
public function process_single_vendor( $vendor_id ) {
$vendor = dokan()->vendor->get( $vendor_id );
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

Fix inconsistency between function parameter and docblock

The process_single_vendor method's docblock indicates that $vendor is a \WeDevs\Dokan\Vendor\Vendor object, but the function actually expects a $vendor_id. This inconsistency could lead to confusion and potential errors.

Please update the docblock to reflect the correct parameter:

 /**
  * Process a single vendor
- * Customize this method based on what you need to do with each vendor
  *
  * @since DOKAN_PRO_SINCE
  *
- * @param \WeDevs\Dokan\Vendor\Vendor $vendor Vendor object
+ * @param int $vendor_id Vendor ID
  *
  * @return void
  */
📝 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
* @param \WeDevs\Dokan\Vendor\Vendor $vendor Vendor object
*
* @return void
*/
public function process_single_vendor( $vendor_id ) {
$vendor = dokan()->vendor->get( $vendor_id );
/**
* Process a single vendor
*
* @since DOKAN_PRO_SINCE
*
* @param int $vendor_id Vendor ID
*
* @return void
*/
public function process_single_vendor( $vendor_id ) {
$vendor = dokan()->vendor->get( $vendor_id );

Comment on lines 121 to 146
public function process_single_vendor( $vendor_id ) {
$vendor = dokan()->vendor->get( $vendor_id );
$commission = $vendor->get_commission_settings();

$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );

$percentage = $commission->get_percentage();

if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $percentage );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}

$vendor->save_commission_settings(
[
'type' => $commission->get_type(),
'flat' => $commission->get_flat(),
'percentage' => $commission->get_percentage(),
'category_commissions' => $commission->get_category_commissions(),
]
);
}
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

Add error handling in process_single_vendor method

Currently, the process_single_vendor method lacks error handling for potential exceptions that may occur during processing. To ensure robust batch processing and prevent it from terminating prematurely, consider wrapping the code in a try-catch block and handling exceptions appropriately.

Here's how you might modify the method:

 public function process_single_vendor( $vendor_id ) {
+    try {
         $vendor     = dokan()->vendor->get( $vendor_id );
         $commission = $vendor->get_commission_settings();

         $commission_type_old = $commission->get_type();
         $commission->set_type( Fixed::SOURCE );

         $percentage = $commission->get_percentage();

         if ( Flat::SOURCE === $commission_type_old ) {
             $commission->set_percentage( 0 );
             $commission->set_flat( $percentage );
         } elseif ( Percentage::SOURCE === $commission_type_old ) {
             $commission->set_percentage( $percentage );
             $commission->set_flat( 0 );
         }

         $vendor->save_commission_settings(
             [
                 'type'                 => $commission->get_type(),
                 'flat'                 => $commission->get_flat(),
                 'percentage'           => $commission->get_percentage(),
                 'category_commissions' => $commission->get_category_commissions(),
             ]
         );
+    } catch ( \Exception $e ) {
+        // Log the exception or handle it as needed
+        $logger  = wc_get_logger();
+        $context = [ 'source' => 'update_vendor_commission' ];
+        $logger->error(
+            sprintf( 'Error processing vendor #%d: %s', $vendor_id, $e->getMessage() ),
+            $context
+        );
+    }
 }
📝 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
public function process_single_vendor( $vendor_id ) {
$vendor = dokan()->vendor->get( $vendor_id );
$commission = $vendor->get_commission_settings();
$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );
$percentage = $commission->get_percentage();
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $percentage );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}
$vendor->save_commission_settings(
[
'type' => $commission->get_type(),
'flat' => $commission->get_flat(),
'percentage' => $commission->get_percentage(),
'category_commissions' => $commission->get_category_commissions(),
]
);
}
public function process_single_vendor( $vendor_id ) {
try {
$vendor = dokan()->vendor->get( $vendor_id );
$commission = $vendor->get_commission_settings();
$commission_type_old = $commission->get_type();
$commission->set_type( Fixed::SOURCE );
$percentage = $commission->get_percentage();
if ( Flat::SOURCE === $commission_type_old ) {
$commission->set_percentage( 0 );
$commission->set_flat( $percentage );
} elseif ( Percentage::SOURCE === $commission_type_old ) {
$commission->set_percentage( $percentage );
$commission->set_flat( 0 );
}
$vendor->save_commission_settings(
[
'type' => $commission->get_type(),
'flat' => $commission->get_flat(),
'percentage' => $commission->get_percentage(),
'category_commissions' => $commission->get_category_commissions(),
]
);
} catch ( \Exception $e ) {
// Log the exception or handle it as needed
$logger = wc_get_logger();
$context = [ 'source' => 'update_vendor_commission' ];
$logger->error(
sprintf( 'Error processing vendor #%d: %s', $vendor_id, $e->getMessage() ),
$context
);
}
}

Comment on lines +125 to +129
* @param int $term Category term object
*
* @return void
*/
public function process_single_category( $term_id ) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent parameter name and description in docblock

The docblock parameter is $term, described as 'Category term object', but the method process_single_category accepts $term_id, which is an integer term ID. Please update the docblock to match the method signature and clarify the parameter's purpose.

Apply this diff to correct the docblock:

- * @param int $term Category term object
+ * @param int $term_id Term ID to process
📝 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
* @param int $term Category term object
*
* @return void
*/
public function process_single_category( $term_id ) {
* @param int $term_id Term ID to process
*
* @return void
*/
public function process_single_category( $term_id ) {

Comment on lines +12 to +16
/**
* The batch size for processing products
*
* @since DOKAN_PRO_SINCE
*/
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace '@SInCE DOKAN_PRO_SINCE' placeholders with actual version numbers in docblocks

The @since DOKAN_PRO_SINCE annotations in the docblocks are placeholders and should be replaced with the actual version numbers where these constants and methods are introduced.

Also applies to: 19-23, 26-30, 37-43, 56-65, 83-92, 111-119, 132-138, 150-159, 183-189

Comment on lines 139 to 148
protected function get_total_products() {
$args = [
'status' => 'publish',
'limit' => -1,
'return' => 'ids',
];

$products = wc_get_products( $args );
return count( $products );
}
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

Optimize total product count retrieval

Retrieving all product IDs to count the total number of products can be inefficient for large datasets. Consider using the 'paginate' parameter in wc_get_products to get the total product count without loading all product IDs into memory.

Refactor the get_total_products method as follows:

protected function get_total_products() {
    $args = [
        'status'   => 'publish',
        'limit'    => 1,
        'paginate' => true,
        'return'   => 'ids',
    ];

    $products = wc_get_products( $args );
    return $products->total;
}

Comment on lines +150 to +159
/**
* Process a single product
* Customize this method based on what you need to do with each product
*
* @since DOKAN_PRO_SINCE
*
* @param int $product
*
* @return void
*/
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

Inconsistent parameter name in docblock

The docblock parameter name @param int $product does not match the method parameter $product_id. Please update the docblock to reflect the correct parameter name.

Apply this diff to fix the inconsistency:

     /**
      * Process a single product
      * Customize this method based on what you need to do with each product
      *
      * @since DOKAN_PRO_SINCE
      *
-     * @param int $product
+     * @param int $product_id
      *
      * @return void
      */
📝 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
/**
* Process a single product
* Customize this method based on what you need to do with each product
*
* @since DOKAN_PRO_SINCE
*
* @param int $product
*
* @return void
*/
/**
* Process a single product
* Customize this method based on what you need to do with each product
*
* @since DOKAN_PRO_SINCE
*
* @param int $product_id
*
* @return void
*/

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

🧹 Outside diff range and nitpick comments (8)
includes/Commission/Upugrader/Update_Vendor_Commission.php (2)

20-20: Consider increasing the batch size for better performance

A batch size of 10 might be too small for large-scale processing. Consider increasing it to 50-100 for better performance while maintaining memory efficiency.

-    const BATCH_SIZE = 10;
+    const BATCH_SIZE = 50;

81-81: Document the reason for PHPCS ignore

The phpcs:ignore comment should include the specific rule being ignored and why it's necessary.

-    public function process_batch( $page_number, $max_pages ) { // phpcs:ignore
+    public function process_batch( $page_number, $max_pages ) { // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- Batch processing requires custom intervals
includes/Commission/Upugrader/Update_Product_Commission.php (1)

57-57: Inconsistent @since tags in docblocks

The @since tags use both DOKAN_SINCE and DOKAN_PRO_SINCE. Please ensure consistency across the file by using the appropriate tag. If this class is part of Dokan Pro, consider using @since DOKAN_PRO_SINCE consistently.

Also applies to: 122-122

includes/Commission/Upugrader/Update_Category_Commission.php (5)

63-63: Correct the comment: 'products' should be 'categories'

The comment at line 63 incorrectly mentions 'products' instead of 'categories'. Update it to reflect that it retrieves the total number of categories.

Apply this diff to correct the comment:

-            // Get total number of products
+            // Get total number of categories

86-88: Inconsistent parameter names in docblocks

The docblocks for process_batch, schedule_next_batch, and get_categories_batch refer to the parameter $page_number, but the method signatures use $offset. Please update the docblocks to match the actual parameter names for clarity.

Apply these diffs to correct the docblocks:

For process_batch:

-     * @param int $page_number Current page number
+     * @param int $offset Current offset

For schedule_next_batch:

-     * @param int $page_number Next page number to process
+     * @param int $offset Next offset to process

For get_categories_batch:

-     * @param int $page_number Page number to fetch
+     * @param int $offset Offset to fetch

Also applies to: 106-108, 140-142


160-163: Correct the @return type in docblock

The category_count method should return an integer or a WP_Error, but the current @return annotation lists multiple types that are not applicable. Please update it to accurately reflect the actual return types.

Apply this diff to correct the @return annotation:

-     * @return int[]|string|string[]|\WP_Error|\WP_Term[]
+     * @return int|\WP_Error

13-13: Ensure consistent use of @SInCE tags

The @since tags in the docblocks use both DOKAN_PRO_SINCE and DOKAN_SINCE. For consistency and clarity, please standardize the @since tags throughout the file.

Apply this diff to standardize the @since tags:

-     * @since DOKAN_SINCE
+     * @since DOKAN_PRO_SINCE

Also applies to: 28-28, 43-43, 58-58, 84-84, 104-104, 121-121, 138-138, 160-160, 177-177, 215-215


123-127: Clarify parameter naming for consistency

In the schedule_cat_item method, the parameter is named $term, but it represents a term ID. For clarity, consider renaming the parameter to $term_id and updating the docblock accordingly.

Apply this diff to update the parameter name:

     /**
-     * @param $term
+     * @param int $term_id Term ID to schedule
      *
      * @return void
      */
-    private function schedule_cat_item( $term ) {
+    private function schedule_cat_item( $term_id ) {

Also, update the method calls to pass $term_id:

-            $this->schedule_cat_item( $category->term_id );
+            $this->schedule_cat_item( $term_id );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1e19d0b and 28874d2.

📒 Files selected for processing (3)
  • includes/Commission/Upugrader/Update_Category_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Product_Commission.php (1 hunks)
  • includes/Commission/Upugrader/Update_Vendor_Commission.php (1 hunks)
🔇 Additional comments (5)
includes/Commission/Upugrader/Update_Vendor_Commission.php (4)

3-3: Typo in namespace 'Upugrader'

This issue was previously identified. The namespace should be Upgrader instead of Upugrader.


140-151: Fix commission conversion logic

The previously identified issue with commission value conversion is still present. The code incorrectly uses the percentage value for both flat and percentage commission types.


199-202: LGTM!

The implementation correctly checks both batch and item processing queues.


135-160: Verify commission updates don't affect existing orders

Please ensure that the commission updates only affect future orders and don't modify commissions for existing orders.

✅ Verification successful

Based on the search results, I can now generate the final response as we have sufficient information to verify the concern about commission updates affecting existing orders.

Commission updates are safely isolated to future orders

The code review concern can be marked as verified safe because:

  • The commission settings are stored separately from order data
  • Existing order commissions are stored as order item meta (_dokan_commission_rate, _dokan_commission_type, _dokan_additional_fee)
  • The vendor commission update code in Update_Vendor_Commission.php only modifies vendor settings and doesn't touch any order meta data
  • There is no code that retroactively updates commissions on existing orders
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any modifications to existing order commissions

# Search for order commission updates
rg -A 5 "update.*commission" --type php

# Check for order meta modifications
rg -A 5 "_dokan_commission" --type php

Length of output: 8158

includes/Commission/Upugrader/Update_Product_Commission.php (1)

64-64: ⚠️ Potential issue

Question about adding 50 to $total_products

Adding 50 to the total number of products may lead to scheduling more batches than necessary, potentially processing non-existent products. Is this adjustment intentional? It might be masking an issue with the product count calculation.

$counts = dokan_get_seller_status_count();
$total_items = $counts['total'];
$max_pages = ceil( $total_items / self::BATCH_SIZE );
$max_pages = $max_pages + 5;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove arbitrary page padding

Adding 5 extra pages without clear justification could lead to unnecessary processing cycles. If this is needed for edge cases, please document the reason.

-        $max_pages = $max_pages + 5;
📝 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
$max_pages = $max_pages + 5;

Comment on lines +181 to +190
private function log_vendor_update( $vendor_id, $success, $error_message = '' ) {
$log_key = 'dokan_commission_upgrade_vendor_' . $vendor_id;
update_option(
$log_key, [
'status' => $success ? 'success' : 'error',
'error_message' => $error_message,
'timestamp' => current_time( 'mysql' ),
]
);
}
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

Use WC_Logger instead of options table for logging

Storing logs in the options table can lead to performance issues with large numbers of vendors. Consider using WooCommerce's logging system instead.

-    private function log_vendor_update( $vendor_id, $success, $error_message = '' ) {
-        $log_key = 'dokan_commission_upgrade_vendor_' . $vendor_id;
-        update_option(
-            $log_key, [
-                'status'        => $success ? 'success' : 'error',
-                'error_message' => $error_message,
-                'timestamp'     => current_time( 'mysql' ),
-            ]
-        );
+    private function log_vendor_update( $vendor_id, $success, $error_message = '' ) {
+        $logger = wc_get_logger();
+        $context = [
+            'source' => 'dokan_commission_upgrade',
+            'vendor_id' => $vendor_id
+        ];
+        if ($success) {
+            $logger->info(
+                sprintf('Successfully processed vendor #%d', $vendor_id),
+                $context
+            );
+        } else {
+            $logger->error(
+                sprintf('Failed to process vendor #%d: %s', $vendor_id, $error_message),
+                $context
+            );
+        }
+    }
📝 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
private function log_vendor_update( $vendor_id, $success, $error_message = '' ) {
$log_key = 'dokan_commission_upgrade_vendor_' . $vendor_id;
update_option(
$log_key, [
'status' => $success ? 'success' : 'error',
'error_message' => $error_message,
'timestamp' => current_time( 'mysql' ),
]
);
}
private function log_vendor_update( $vendor_id, $success, $error_message = '' ) {
$logger = wc_get_logger();
$context = [
'source' => 'dokan_commission_upgrade',
'vendor_id' => $vendor_id
];
if ($success) {
$logger->info(
sprintf('Successfully processed vendor #%d', $vendor_id),
$context
);
} else {
$logger->error(
sprintf('Failed to process vendor #%d: %s', $vendor_id, $error_message),
$context
);
}
}

Comment on lines +146 to +148
$args = [
'status' => 'publish',
'limit' => self::BATCH_SIZE,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent product statuses between total count and batch retrieval

In get_total_products(), the products are fetched with 'status' => 'any', whereas in get_products_batch(), 'status' => 'publish'. This inconsistency may cause the total product count to be inaccurate, leading to scheduling extra batches or missing some products during processing.

Apply this diff to ensure consistent product statuses:

protected function get_total_products() {
    $args = [
-        'status' => 'any',
+        'status' => 'publish',
        'limit'  => -1,
        'return' => 'ids',
    ];

Also applies to: 165-167

return;
}

$total = $total + 50;
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

Unnecessary addition of 50 to total category count

Adding a fixed number to the total category count at line 70 may result in scheduling empty batches and inefficient processing. Consider removing this addition or adjusting it to accurately reflect the total number of categories.

Apply this diff to remove the unnecessary addition:

-            $total = $total + 50;
📝 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
$total = $total + 50;

@shashwatahalder01 shashwatahalder01 added QA approved This PR is approved by the QA team and removed QA In Progress labels Nov 26, 2024
@Aunshon Aunshon merged commit 8d72504 into develop Nov 26, 2024
0 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA approved This PR is approved by the QA team
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants