craftcms / commerce

Fully integrated ecommerce for Craft CMS.
https://craftcms.com/commerce
Other
226 stars 170 forks source link

[4.x]: cart.totalQty is counted up, even on error #2972

Closed vandres closed 2 years ago

vandres commented 2 years ago

What happened?

Description

This is kind of a bug. I am having a product with maxQty. When I add more than that qty, I get an error message stating that. So far so good.

On top of the page, I am displaying a cart icon with the count of products inside the cart.

{% set cart = craft.commerce.carts.cart %}
{% set qty = cart.totalQty %}

<a href="" class="header__cart">
    {% include '_includes/icons/cart' %}

    <span class="badge">{{ qty }}</span>
</a>

Now when adding a product with a higher quantity than allowed, the qty stills counts up, despite the error.

After refreshing the page, it goes back to the real number.

Steps to reproduce

  1. Create a product with maxQty (e.g. 5)
  2. Add that product 5 times to the cart
  3. Try adding it a sixth time

Expected behavior

cart.totalQty should be 5

Actual behavior

cart.totalQty is 6

Craft CMS version

4.2.4

Craft Commerce version

4.1.2

PHP version

8.1

Operating system and version

MacOS, Debian Docker

Database type and version

MariaDB 10.5

Image driver and version

-

Installed plugins and versions

  "require": {
    "craftcms/cms": "^4.2.0.2",
    "craftcms/commerce": "^4.1.0",
    "craftcms/commerce-paypal-checkout": "^2.1.0.2",
    "craftcms/redactor": "^3.0",
    "mmikkel/cp-field-inspect": "^1.4",
    "nystudio107/craft-vite": "^4.0",
    "php-http/curl-client": "^2.2",
    "putyourlightson/craft-sprig": "^2.1",
    "sebastianlenz/linkfield": "^2.1",
    "spatie/craft-ray": "^2.0",
    "spicyweb/craft-neo": "^3.2",
    "typesense/typesense-php": "^4.8",
    "vaersaagod/geomate": "^2.0",
    "verbb/expanded-singles": "^2.0",
    "verbb/field-manager": "^3.0",
    "verbb/tablemaker": "^4.0",
    "verbb/wishlist": "^2.0",
    "vlucas/phpdotenv": "^5.4.0"
  },
  "require-dev": {
    "deployer/deployer": "^7.0",
    "roave/security-advisories": "dev-master",
    "yiisoft/yii2-shell": "^2.0.3"
  },
lukeholder commented 2 years ago

Hi @vandres

That is correct behavior at the moment, right now the cart could be returned to the template in a invalidate state due to a validation error like maxqty when editing it.

You could do this:

{% if cart.hasErrors() %}
  {% craft.orders.number(cart.number).one().totalQty %} 
{% else %}
  {{ cart.totalQty }}
{% endif %}

to get the current DB saved (validated) version of the cart total.

vandres commented 2 years ago

Thank you for the workaround!