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: Improve vendor coupon validation for various discount item types and empty cart scenarios #2351

Merged

Conversation

mralaminahamed
Copy link
Member

@mralaminahamed mralaminahamed commented Aug 27, 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:

This PR fixes an issue with vendor coupon validation when processing discount items. The ensure_vendor_coupon method has been updated to properly handle different scenarios when validating coupons, especially when the cart is empty or when dealing with order items.

Key changes in item validation from discounts:

  1. When cart items are not found:

    • The code now checks if WC()->cart exists and is not empty before processing cart items.
    • If the cart is empty or doesn't exist, it falls back to processing discount items.
  2. Handling different discount item data types:

    • The updated code now handles three scenarios for discount items:
      a. WC_Order_Item_Product objects: Uses get_product_id() method to get the product ID.
      b. Array-based items: Checks for 'product_id' or 'variation_id' keys to determine the item ID.
      c. Other types: Skips items that don't match the above types.

    • This approach ensures that the method can handle various item representations that may occur in different contexts (e.g., cart, order, or custom discount scenarios).

Example Datasets:

To better understand the changes, here are two example datasets that the code now handles correctly:

Dataset 1 (Cart Item):

Array
(
    [3043537094af15ae825df65e187dad16] => stdClass Object
        (
            [object] => Array
                (
                    [product_id] => 17
                    [variation_id] => 0
                    [quantity] => 1
                )
            [product] => WC_Product_Simple Object
                (
                    [id:protected] => 17
                    [data:protected] => Array
                        (
                            [name] => Beanie
                            [price] => 18
                            // ... other product data ...
                        )
                )
            [quantity] => 1
            [price] => 18
        )
)

Dataset 2 (Order Item):

Array
(
    [1] => stdClass Object
        (
            [key] => 1
            [object] => WC_Order_Item_Product Object
                (
                    [id:protected] => 1
                    [data:protected] => Array
                        (
                            [order_id] => 15
                            [name] => Product 0000044
                            [product_id] => 13
                            [variation_id] => 0
                            [quantity] => 2
                            // ... other order item data ...
                        )
                )
            [product] => WC_Product_Simple Object
                (
                    [id:protected] => 13
                    [data:protected] => Array
                        (
                            [name] => Product 0000044
                            [price] => 100
                            // ... other product data ...
                        )
                )
            [quantity] => 2
            [price] => 20000
        )
)

The updated code can now correctly process both these datasets, ensuring proper vendor coupon validation regardless of whether the items come from the cart or an order.

Related Pull Request(s)

  • N/A

Closes

  • Closes # (issue number, if applicable)

How to test the changes in this Pull Request:

  1. Create a vendor coupon
  2. Attempt to apply the coupon to an order with products from the vendor
  3. Verify that the coupon is correctly validated and applied
  4. Test with both cart items and order items to ensure proper functionality
  5. Test scenarios where the cart is empty and coupon is applied directly to an order
  6. Verify that coupons work correctly with different product types (simple, variable, etc.)

Changelog entry

Fix: Vendor coupon validation from discount items

Improved the vendor coupon validation process to correctly handle various scenarios, including empty carts and order items. This ensures that vendor coupons are properly validated and applied in all situations.

Before Changes

Previously, the coupon validation process did not properly handle cases where the cart was empty or when dealing with order items. This could lead to incorrect validation results and potential issues with coupon application.

Specifically, the code did not differentiate between different types of discount items, which could cause errors or incorrect validations when processing orders or applying coupons in certain scenarios.

After Changes

The updated code now properly checks for cart items and handles different types of discount items, including WC_Order_Item_Product and array-based items. This ensures that vendor coupons are correctly validated in all scenarios.

Key improvements:

  • Robust checking for cart existence and contents
  • Proper handling of different discount item types (WC_Order_Item_Product, array-based items)
  • Fallback mechanisms to ensure coupon validation works in various contexts (cart, order, custom discount scenarios)

Feature Video (optional)

N/A

PR Self Review Checklist:

  • Code is following code style guidelines
  • Good naming: variable and function names are clear and self-explanatory
  • KISS: The solution is kept simple and straightforward
  • DRY: There is no unnecessary repetition in the code
  • Code is readable and well-structured
  • No apparent performance issues
  • Complex constructions are refactored or commented for clarity
  • No grammar errors in comments or user-facing strings

FOR PR REVIEWER ONLY:

  • Correct — Does the change do what it's supposed to?
  • Secure — Are there any security concerns with this change?
  • Readable — Is the code easy to understand?
  • Elegant — Does the solution fit well with the overall style and architecture?

Summary by CodeRabbit

  • New Features

    • Enhanced coupon validation process by ensuring the WooCommerce cart is not empty before processing.
    • Improved error handling for discount items, ensuring only valid product IDs are processed.
  • Bug Fixes

    • Resolved issues with processing invalid items from the discount object, leading to more reliable coupon application.

@mralaminahamed mralaminahamed added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval labels Aug 27, 2024
@mralaminahamed mralaminahamed self-assigned this Aug 27, 2024
Copy link
Contributor

coderabbitai bot commented Aug 27, 2024

Walkthrough

The changes enhance the ensure_vendor_coupon method in the includes/Order/Hooks.php file. The updates include a more robust check for the WooCommerce cart's availability and refined handling of discount items, ensuring only valid product IDs are processed during coupon validation.

Changes

File Change Summary
includes/Order/Hooks.php Modified ensure_vendor_coupon method to check if the cart is empty and refined item handling for the discount object, ensuring valid product IDs.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Cart
    participant CouponSystem

    User->>Cart: Check cart status
    Cart->>CouponSystem: Verify cart is not empty
    alt Cart is not empty
        CouponSystem->>Cart: Retrieve discount items
        loop Process items
            Cart->>CouponSystem: Check item validity
            alt Item is valid
                CouponSystem->>CouponSystem: Process valid item
            else Item is invalid
                CouponSystem->>Cart: Skip invalid item
            end
        end
    else Cart is empty
        CouponSystem->>User: No items to process
    end
Loading

Poem

🐰 In the cart where goodies lay,
A rabbit hops to save the day.
With coupons bright, and items right,
No more errors, all in sight!
A joyful dance, a leap, a cheer,
Valid IDs bring us near! 🍀


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • Anthropic Claude for code reviews: The new model is designed to enhance code understanding and generation capabilities. We're excited to hear your feedback as we evaluate its performance.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d029521 and d108888.

Files selected for processing (1)
  • includes/Order/Hooks.php (1 hunks)
Additional comments not posted (5)
includes/Order/Hooks.php (5)

325-325: Ensure cart is not empty before processing items.

The condition if ( WC()->cart && ! WC()->cart->is_empty() ) ensures that the cart is not empty before processing items. This improves robustness by preventing unnecessary processing when there are no items in the cart.

The code changes are approved.


333-334: Check if the item object is set before processing.

The condition if ( ! isset( $item->object ) ) ensures that the object property exists on each item before proceeding. This prevents potential errors from undefined item references.

The code changes are approved.


337-339: Retrieve product ID for WC_Order_Item_Product objects.

The condition if ( is_a( $item->object, 'WC_Order_Item_Product' ) ) retrieves the product ID directly from the object when it is an instance of WC_Order_Item_Product. This ensures that valid product IDs are collected.

The code changes are approved.


341-343: Check for product_id or variation_id in array-based items.

The condition if ( is_array( $item->object ) && ( isset( $item['product_id'] ) || isset( $item['variation_id'] ) ) ) checks for either product_id or variation_id in array-based items and assigns the appropriate value to item_id. This ensures that valid product IDs are collected.

The code changes are approved.


345-346: Skip processing if item_id is not set.

The condition if ( ! $item_id ) ensures that the code skips processing if item_id is not set. This prevents potential errors from undefined item references.

The code changes are approved.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d108888 and 5836972.

Files selected for processing (1)
  • includes/Order/Hooks.php (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • includes/Order/Hooks.php

includes/Order/Hooks.php Outdated Show resolved Hide resolved
@mrabbani mrabbani added 👍 Dev Review Done and removed Needs: Dev Review It requires a developer review and approval labels Aug 28, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5836972 and 3abd9fe.

Files selected for processing (1)
  • includes/Order/Hooks.php (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • includes/Order/Hooks.php

@StalinDurjo StalinDurjo added QA In Progress and removed Needs: Testing This requires further testing labels Sep 11, 2024
@StalinDurjo
Copy link
Contributor

StalinDurjo commented Sep 11, 2024

Issue: Admin is unable to add coupons to new orders
Description: Admin has created a new order and has added a product to the order. Afterwards, admin tries to apply coupon to that order. However, applying coupon displays error on screen.

Please refer to the video attached for reference
https://jam.dev/c/d35ae625-62ec-4664-bb35-445851fc16bb

@mralaminahamed bhai

@shohag121 shohag121 merged commit d1ff7e9 into getdokan:develop Sep 19, 2024
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants