Skip to content

Fix: Upsell Order Bump product visibility issues (Issue #364) #416

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

imti2create
Copy link

@imti2create imti2create commented Mar 18, 2025

Fix for Issue #364: Offer Product Doesn't Appear

This PR addresses the issue where offer products don't appear during checkout when using the Upsell Order Bump module.

Root Causes Identified

  1. Logic Error in Display Condition: The original code used an overly restrictive condition to determine if an offer should be displayed, requiring all cart products to match the target products.

  2. Array Initialization Issues: The $all_cart_category_ids array wasn't properly initialized before use, causing PHP notices that could prevent checkout bump from displaying.

  3. Input Validation Issues: Incomplete validation of incoming product data was causing issues with variable products and special product types.

  4. Error Handling Deficiencies: Inadequate error handling in both PHP and JavaScript made it difficult to diagnose issues.

Changes Made

  1. OrderBump.php:

    • Properly initialized arrays to prevent PHP notices
    • Modified conditional logic to show offers if ANY cart product matches ANY target product/category
    • Added validation for bump_info object to prevent PHP errors
  2. bump-product-front-view.php:

    • Added initialization for product variables
    • Improved handling of different product types
    • Set default values for missing properties in bump_info
    • Enhanced image URL handling with fallbacks
  3. order-bump-custom.js:

    • Added input validation for the extraProducts function
    • Created loading state while processing
    • Enhanced error handling for AJAX requests
    • Improved user feedback during selection
  4. Ajax.php:

    • Added proper validation for offer products
    • Enhanced error handling with JSON responses
    • Improved cart management logic

Testing

The changes have been tested with various product configurations and checkout scenarios to verify they address the issue without introducing new problems.

Closes #364

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced validation and error messaging to ensure that upsell items and variations are processed correctly during checkout.
  • New Features
    • Introduced dynamic feedback that updates the cart immediately upon successful upsell interactions.
  • Refactor
    • Streamlined the upsell offer display logic for clearer, more reliable presentations of offers during the shopping experience.

Copy link

coderabbitai bot commented Mar 18, 2025

Walkthrough

This PR enhances the Upsell Order Bump module by introducing rigorous validations and improved error handling across its PHP and JavaScript components. It includes checks for product and variation existence, default values for missing inputs, early exits when necessary, and enhanced AJAX interactions. The changes also refine the rendering logic for the bump offer template to ensure the offer product is displayed correctly during checkout.

Changes

File(s) Change Summary
Includes/Modules/UpsellOrderBump/Includes/Ajax.php
.../OrderBump.php
Enhanced validations and error handling: default value assignments, product and variation existence checks with wc_get_product, early return conditions, and try-catch exception handling to manage errors during cart operations.
Includes/Modules/UpsellOrderBump/assets/js/order-bump-custom.js Added input validation for product_id, ensured proper defaults for offer_variation_id and bump_price, restructured AJAX calls with updated success and failure callbacks, and maintained UI consistency through proper error logging and state reversion.
Includes/Modules/UpsellOrderBump/templates/bump-product-front-view.php Improved product type handling by initializing default variables, validating product existence, using conditional logic for rendering bump offers, and ensuring fallback values for images and titles when offer data is missing.

Sequence Diagram(s)

sequenceDiagram
    participant UI as User Interface
    participant JS as order-bump-custom.js
    participant AJAX as Ajax.php
    participant Backend as Cart Handler

    UI->>JS: Trigger upsell bump action
    JS->>AJAX: Send AJAX request with offer details
    AJAX->>Backend: Validate product & variation data
    Backend-->>AJAX: Return success/error response
    AJAX->>JS: Process response, update cart totals
    JS->>UI: Refresh UI or revert changes on error
Loading

Assessment against linked issues

Objective Addressed Explanation
Offer product doesn't appear [#364]

Poem

I'm your coding rabbit, hopping with delight,
Validations all in place, making offers shine bright.
The bumps now leap into view with every checkout run,
No hidden carrots—each offer is there with fun!
Cheers to clean code and a smooth UI ride!
🥕🐇 Happy hopping in our code garden!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
Includes/Modules/UpsellOrderBump/assets/js/order-bump-custom.js (2)

1-1: Ensure naming clarity for extraProducts.
It might be helpful to rename this function to more clearly reflect its purpose, e.g. updateBumpProducts or toggleUpsellProduct. This improves discoverability and maintainability.


31-32: Consider optional chaining for clarity.
Currently, the code checks if (data && data.success) …. You could simplify to if (data?.success) …, though this is a minor readability preference in modern JS.

- if (data && data.success) {
+ if (data?.success) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 32-32: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 59550f2 and e72edf3.

📒 Files selected for processing (4)
  • Includes/Modules/UpsellOrderBump/Includes/Ajax.php (2 hunks)
  • Includes/Modules/UpsellOrderBump/Includes/OrderBump.php (2 hunks)
  • Includes/Modules/UpsellOrderBump/assets/js/order-bump-custom.js (1 hunks)
  • Includes/Modules/UpsellOrderBump/templates/bump-product-front-view.php (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
Includes/Modules/UpsellOrderBump/Includes/OrderBump.php (1)
Includes/Modules/UpsellOrderBump/Includes/Ajax.php (1) (1)
  • bump_list (79:101)
🪛 Biome (1.9.4)
Includes/Modules/UpsellOrderBump/assets/js/order-bump-custom.js

[error] 32-32: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (23)
Includes/Modules/UpsellOrderBump/assets/js/order-bump-custom.js (4)

4-8: Good input validation.
Checking for a valid product_id early prevents unnecessary AJAX calls. This improves reliability and user feedback.


16-21: Solid approach to sanitizing and defaulting values.
By falling back to sensible defaults (0, false, etc.), you reduce the chance of runtime errors or malformed requests.


34-40: Effective error handling and UI rollback.
Re-enabling the checkbox and reverting the check state ensures the UI remains consistent when the operation fails. This enhances user experience and prevents stale UI states.


47-53: Fail callback is well-handled.
Logging the error and restoring the UI state is crucial for debugging and user feedback.

Includes/Modules/UpsellOrderBump/templates/bump-product-front-view.php (6)

8-10: Initialize variables consistently.
Defining $product_offer_id and $variation_id upfront makes the code more readable and prevents uninitialized variable warnings.


12-24: Robust handling of various product types.
This block correctly differentiates among ‘variation’, ‘simple’, and others. Good practice to cover all product types, reducing future edge-case errors.


27-30: Early return for invalid products.
Exiting when $product_offer_id is empty prevents meaningless template output, improving performance and avoiding undefined behavior.


32-46: Use of wp_parse_args for default properties is consistent.
Providing defaults for $bump_info ensures robust fallback behavior and prevents undefined index issues.


72-72: Safe fallback image logic.
Ensuring $image_url falls back to a local asset avoids broken images when offer_image_url is invalid.


89-89: Display default product title when missing.
This maintains a consistent user interface in the event offer_product_title is not set.

Includes/Modules/UpsellOrderBump/Includes/OrderBump.php (6)

54-58: Avoid further processing when cart is empty.
The early return at line 56 conserves resources and is a clean way to short-circuit if there are no products in the cart.


59-65: Validate $bump_info shape before usage.
Skipping invalid bump data reduces risk of runtime errors. Good practice to ensure $bump_info is an array or object first.


67-73: Graceful handling of missing offer product.
The isset checks and default assignments reduce potential PHP notices, and skipping empty $offer_product_id is appropriate.


80-84: Proper product existence check.
Continuing the loop on a missing or invalid product prevents broken logic and enhances overall stability.


113-119: Simplified approach for matching target products.
Using array_intersect clarifies the condition and avoids confusion about whether all or any matches are needed. This is more readable than counting differences.


122-128: Consistent logic for matching categories.
Similar to the product matching logic, array_intersect is a clear and understandable approach for verifying category matches.

Includes/Modules/UpsellOrderBump/Includes/Ajax.php (7)

120-121: Good practice: track product/category IDs in arrays.
Initializing $all_cart_product_ids and $all_cart_category_ids increases clarity when re-checking or validating cart contents.


131-134: Appropriate defaults for missing fields.
Gracefully falling back to 0 or false avoids undefined behavior and fosters consistent input handling.


136-142: Product existence validation is crucial.
Early error response if the product doesn’t exist ensures the checkout remains consistent. This also saves unnecessary computations.


143-156: Well-structured removal logic for checked condition.
Looping through cart items and removing both product and possible variation ensures accurate cart state. The success response is well-defined.


157-186: Robust addition flow for upsell.
Including a custom price, recalculating totals, and ensuring cart session updates are excellent steps to maintain correct cart data.


188-189: Graceful exception handling.
Catching exceptions and sending a JSON error fosters clear debugging and a stable user experience.


191-192: Logical final safeguard.
wp_die() ensures that no unexpected code executes past the multiple wp_send_json_* calls.

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.

Offer product doesn't appear
1 participant