craftcms/commerce

[5.x]: Incorrect total quantity calculation when adding items beyond the maximum limit

Closed this issue · 2 comments

What happened?

Description

In Craft Commerce 5, if I attempt to add an item in a quantity that exceeds the maximum allowed, an error is generated. However, even though the cart is empty, cart.totalQty returns the quantity I tried to add. How can I display the total number of items in the cart, counting only those that are actually valid and added?

Steps to reproduce

  1. Attempt to add an item to the cart with a quantity exceeding the maximum allowed.

Expected behavior

The cart.totalQty should only count and return the quantities of items that are valid and actually added to the cart.

Actual behavior

The cart.totalQty returns the quantity that was attempted to be added, even if the addition was invalid and the cart remains empty.

Craft CMS version

5.2.9

Craft Commerce version

5.0.14

PHP version

No response

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

The cart that gets returned can have validation errors attached and get in an invalid state in memory returned to the page, but the cart in the database is the original unedited cart.

This is so you can check cart.hasErrors() and show the line item with the incorrect amount set as the qty, and let the user correct the errors.

The example cart page shows the cart with those errors but hides things like totals that don’t make sense in an invalid state like totalQty.

In your example templates you always have the ability to get the original values of an order (saved in a valid state) by doing craft.orders.number(cart.number).one() to get the saved/stored cart.

An alternative to that is to use the order’s "stored" values which are also available on the order:

cart.storedTotalPrice
cart.storedTotal
cart.storedTotalPaid
cart.storedItemTotal
cart.storedItemSubtotal
cart.storedTotalShippingCost
cart.storedTotalDiscount
cart.storedTotalTax
cart.storedTotalTaxIncluded
cart.storedTotalQty

Hope that helps.