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 admin fixed commission setting validation #2437

Merged
merged 2 commits into from
Nov 15, 2024

Conversation

Aunshon
Copy link
Collaborator

@Aunshon Aunshon commented Nov 15, 2024

Restrict admin commission percentage from 0 to 100

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:

Related Pull Request(s)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

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

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

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

PR Self Review Checklist:

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

FOR PR REVIEWER ONLY:

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

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

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced validation for pricing settings, ensuring commission percentages are within the range of 0 to 100.
    • Improved error handling for commission setup, defaulting to 0 if invalid input is detected.
    • Added a new validation method in the CombineInput component to ensure percentage values are valid.
  • Bug Fixes

    • Corrected input handling in the CombineInput component to ensure only valid percentage values are processed.
  • Documentation

    • Updated documentation comments for new validation methods to clarify purpose and parameters.
  • Style

    • Minor formatting adjustments for consistency across the codebase.

Restrict admin commission percentage from 0 to 100
@Aunshon Aunshon self-assigned this Nov 15, 2024
Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes involve significant updates to the Settings and SetupWizard classes, focusing on the validation of pricing and commission settings. The format_price_values method has been replaced by validate_fixed_price_values, which enforces stricter validation rules for price settings. Additionally, the dokan_setup_commission_save method has been enhanced to validate commission percentages before saving. Minor adjustments were made to the CombineInput component to improve input validation and formatting. Overall, the modifications enhance the robustness and reliability of settings handling.

Changes

File Change Summary
includes/Admin/Settings.php - Removed method: format_price_values
- Added method: validate_fixed_price_values
- Updated filter to use new validation method and changed return type from void to array.
includes/Admin/SetupWizard.php - Updated dokan_setup_commission_save method to include validation for commission percentage input, ensuring it is within the range of 0 to 100.
src/admin/components/CombineInput.vue - Updated watch property and onInput method for improved validation and formatting of input values.
- Corrected property name from fixexName to fixedName.

Suggested reviewers

  • mrabbani

🐇 In the land of code, where changes bloom,
New validations rise, dispelling the gloom.
Prices and commissions, all in their place,
With checks in the code, we quicken the pace.
A hop and a skip, through logic we glide,
In the world of settings, let clarity abide! 🌼


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 (5)
src/admin/components/CombineInput.vue (3)

81-88: LGTM! Consider enhancing validation robustness.

The validation logic correctly implements the 0-100 range restriction for percentage values. However, there's room for improvement:

Consider these enhancements:

+const MIN_PERCENTAGE = 0;
+const MAX_PERCENTAGE = 100;

 watch: {
   value: {
     handler(newVal, oldVal) {
       let percentage = newVal.percentage;
-      if ( ! percentage || '' === percentage || Number( percentage ) < 0 || Number( percentage ) > 100 ) {
+      if ( ! percentage || 
+           '' === percentage || 
+           isNaN(Number(percentage)) ||
+           Number( percentage ) < MIN_PERCENTAGE || 
+           Number( percentage ) > MAX_PERCENTAGE ) {
         percentage = oldVal.percentage;
       }

95-98: Consider adding error handling for number formatting.

The use of accounting.unformat is good for consistent number handling, but consider adding error handling:

 onInput: Debounce( function() {
   let self = this;
+  try {
     let data = {
       fixed: self.fixed ? accounting.unformat(self.fixed, dokan.currency.decimal) : '',
       percentage: self.percentage ? accounting.unformat(self.percentage, dokan.currency.decimal): ''
     };
     this.$emit('change', data);
+  } catch (error) {
+    console.error('Error formatting input values:', error);
+    // Emit error event or handle gracefully
+    this.$emit('error', error);
+  }
 }, 500 ),

Line range hint 53-56: Fix typo in prop name 'fixexName'.

There's a typo in the prop name that should be corrected for better code maintainability:

-fixexName: {
+fixedName: {
   type: String,
   default: 'fixed-val-name'
 },

Remember to update any corresponding template bindings:

-:name="fixexName"
+:name="fixedName"
includes/Admin/SetupWizard.php (1)

557-564: LGTM! The commission validation looks good.

The added validation ensures that the admin commission percentage stays within the valid range of 0-100%. This fixes the issue mentioned in the PR objectives.

However, consider adding a notice when an invalid value is provided and defaulted to 0.

 $dokan_commission_percentage = isset( $_POST['dokan_commission_percentage'] ) ? (float) wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['dokan_commission_percentage'] ) ) ) : 0;
 if ( $dokan_commission_percentage < 0 || $dokan_commission_percentage > 100 ) {
+    add_settings_error(
+        'dokan_commission',
+        'dokan_commission_invalid',
+        __( 'Commission percentage must be between 0 and 100. Value has been set to 0.', 'dokan-lite' ),
+        'error'
+    );
     $dokan_commission_percentage = 0;
 }
includes/Admin/Settings.php (1)

73-83: Consider enhancing the validation feedback.

While the validation logic is correct, consider these improvements:

  1. Add an admin notice when reverting to the saved value
  2. Use number_format for consistent decimal handling
 public function validate_fixed_price_values( $option_values, $option_name ) {
     $clickable_types = [ 'flat', 'fixed' ];

     if ( 'dokan_selling' === $option_name && isset( $option_values['commission_type'] ) && in_array( $option_values['commission_type'], $clickable_types, true ) ) {
-        $admin_percentage       = (float) $option_values['admin_percentage'];
+        $admin_percentage = number_format( (float) $option_values['admin_percentage'], 2, '.', '' );
         $saved_admin_percentage = dokan_get_option( 'admin_percentage', 'dokan_selling', '' );

         if ( $admin_percentage < 0 || $admin_percentage > 100 ) {
+            add_settings_error(
+                'admin_percentage',
+                'invalid_percentage',
+                sprintf( __( 'Commission percentage must be between 0-100. Reverting to previous value: %s%%', 'dokan-lite' ), $saved_admin_percentage ),
+                'error'
+            );
             $option_values['admin_percentage'] = $saved_admin_percentage;
         }
     }

     return $option_values;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ac8cfe4 and 2e11ac2.

📒 Files selected for processing (3)
  • includes/Admin/Settings.php (2 hunks)
  • includes/Admin/SetupWizard.php (2 hunks)
  • src/admin/components/CombineInput.vue (1 hunks)
🔇 Additional comments (3)
includes/Admin/Settings.php (3)

33-33: LGTM: Filter hook addition is correct.

The new filter hook for commission validation is properly added with appropriate priority.


64-72: LGTM: Method documentation is complete.

The method documentation properly describes the purpose, parameters, and return type.


73-83: Verify commission validation integration.

Let's verify the integration with other commission-related functionality.

✅ Verification successful

Let me gather more specific information about the commission validation implementation.


Let me check one more aspect to verify the commission validation integration.


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

Commission validation is properly integrated and functioning as expected

The validation implementation is correctly integrated into the settings workflow:

  • The validate_fixed_price_values method is hooked into dokan_save_settings_value filter with proper priority
  • The validation is specifically targeted for fixed/flat commission types
  • The implementation is consistent with the commission settings structure across the codebase
  • Test cases confirm the expected behavior for various commission scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other commission validation implementations and usages

# Check for other commission validation logic
echo "Checking for other commission validation implementations..."
rg -g '!vendor' -l "admin_percentage|commission.*validation"

# Check for filter usage
echo "Checking for filter usage..."
rg -g '!vendor' "dokan_save_settings_value"

Length of output: 1272


Script:

#!/bin/bash
# Check the implementation in Commission Settings classes
echo "Checking Commission Settings implementations..."
rg -A 10 "class.*Setting" includes/Commission/Settings/

# Check for other admin_percentage validations
echo "Checking for other admin_percentage validations..."
rg -A 5 "admin_percentage.*validation|validate.*admin_percentage" --type php

# Check the actual usage of validate_fixed_price_values
echo "Checking validate_fixed_price_values usage..."
ast-grep --pattern 'validate_fixed_price_values($$$)'

Length of output: 3944


Script:

#!/bin/bash
# Check the implementation of commission types and their validation
echo "Checking commission type implementations..."
rg -A 10 "commission_type.*flat|commission_type.*fixed" --type php

# Check for any other validation hooks
echo "Checking related validation hooks..."
rg -A 5 "add_filter.*dokan_save_settings|add_filter.*dokan_settings" --type php

# Check the actual settings saving implementation
echo "Checking settings save implementation..."
rg -A 10 "function.*save_settings" includes/Admin/

Length of output: 15941

Restrict admin commission percentage from 0 to 100
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 (4)
src/admin/components/CombineInput.vue (4)

Line range hint 39-42: Fix typo in prop name fixexName

The prop name contains a typo: fixexName should be fixedName. This typo is inconsistent with the component's naming conventions and could cause confusion.

Apply this fix:

-            fixexName: {
+            fixedName: {
                 type: String,
                 default: 'fixed-val-name'
             },

84-84: Remove debug console.log statement

Debug logging should not be included in production code.

-                    console.log(newPercentage, oldPercentage);

86-88: Simplify validation condition

The validation condition can be simplified by leveraging the validatePercentage method that's already doing part of this validation.

-                    if ( ! newPercentage || '' === newPercentage || Number( newPercentage ) < 0 || Number( newPercentage ) > 100 ) {
+                    if ( ! newPercentage || newPercentage === '' ) {
                         newPercentage = oldPercentage;
                     }

97-103: Enhance percentage validation robustness

While the current validation handles the range check, it could be more robust by handling non-numeric inputs and undefined/null values.

             validatePercentage( percentage ) {
+                if (percentage === undefined || percentage === null) {
+                    return '';
+                }
+                const numValue = Number(percentage);
+                if (isNaN(numValue)) {
+                    return '';
+                }
-                if ( Number( percentage ) < 0 || Number( percentage ) > 100 ) {
+                if ( numValue < 0 || numValue > 100 ) {
                     percentage = '';
                 }
 
                 return percentage;
             },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2e11ac2 and cde4d63.

📒 Files selected for processing (1)
  • src/admin/components/CombineInput.vue (1 hunks)
🔇 Additional comments (2)
src/admin/components/CombineInput.vue (2)

105-109: LGTM! Well-implemented input handling

The input handler correctly implements:

  • Proper debouncing for performance optimization
  • Consistent currency formatting using accounting.unformat
  • Clean data structure emission

97-103: Verify commission validation coverage

While the validation logic here is correct, we should verify that commission percentage validation is consistently applied across all entry points.

Also applies to: 105-109

✅ Verification successful

Let me gather more information with proper file type specifications and additional context.


Based on the comprehensive search results, I can now provide a final response:

Commission validation is properly implemented across the system

The validation of commission percentage between 0-100 is consistently enforced through multiple layers:

  • UI validation in CombineInput.vue
  • Backend validation through dokan()->commission->validate_rate() used across all commission formulas (Fixed, Flat, Percentage, Combine, CategoryBased)
  • Setup wizard validation in includes/Admin/SetupWizard.php enforces the same range
  • Commission settings are properly saved and validated through dedicated Settings classes for Global, Vendor, Product, and OrderItem contexts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other commission percentage validation implementations
echo "Searching for commission percentage validation patterns..."
rg -l "commission|percentage" --type php --type vue

# Search for direct database updates to commission settings
echo "Checking for direct commission updates..."
rg -l "update_option.*commission" --type php

Length of output: 392


Script:

#!/bin/bash
# Search for commission-related code with proper file extensions
echo "Searching for commission validation patterns..."
rg -l "commission|percentage" -g "*.php" -g "*.vue"

# Get context around commission validation
echo "Checking commission validation implementations..."
rg -B 2 -A 2 "validatePercentage|validate.*commission|check.*percentage" -g "*.php" -g "*.vue"

# Check database operations
echo "Checking database operations related to commission..."
rg -B 2 -A 2 "(update|save|set).*commission" -g "*.php" -g "*.vue"

Length of output: 65352

@Aunshon Aunshon merged commit 0235525 into develop Nov 15, 2024
2 checks passed
@mrabbani mrabbani deleted the fix/commission-version-and-decimal branch January 27, 2025 07:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant