Je ne trouve pas ou on peut limiter la quantité d’un article par rapport au stock que l’on dispose.
Je m’explique, j’ai par exemple en stock un produit avec 5 dans le stock, et quand je veux les mettre dans mon panier d’achat, je peux sélectionner 20 ou plus. J’aimerais ne pas pouvoir sélectionner plus que la quantité de mon stock pour l’article, donc mon exemple 5 maximum.
Certains thèmes le proposent, comme notamment le thème Venture que j’utilise.
Voici la partie de theme.js qui correspond à cette fonctionnalité :
QtySelector.prototype.validateAvailability = function(line, quantity) {
var product = theme.cartObject.items[line - 1]; // 0-based index in API
var handle = product.handle; // needed for the ajax request
var id = product.id; // needed to find right variant from ajax results
var params = {
type: 'GET',
url: '/products/' + handle + '.js',
dataType: 'json',
success: $.proxy(function(cartProduct) {
this.validateAvailabilityCallback(line, quantity, id, cartProduct);
}, this)
};
$.ajax(params);
};
QtySelector.prototype.validateAvailabilityCallback = function(
line,
quantity,
id,
product
) {
var quantityIsAvailable = true;
// This returns all variants of a product.
// Loop through them to get our desired one.
for (var i = 0; i < product.variants.length; i++) {
var variant = product.variants[i];
if (variant.id === id) {
break;
}
}
// If the variant tracks inventory and does not sell when sold out
// we can compare the requested with available quantity
if (
variant.inventory_management !== null &&
variant.inventory_policy === 'deny'
) {
if (variant.inventory_quantity < quantity) {
// Show notification with error message
theme.Notify.open('error', theme.strings.noStockAvailable, true);
// Set quantity to max amount available
this.$wrapper.find('.js-qty__input').val(variant.inventory_quantity);
quantityIsAvailable = false;
this.$wrapper.removeClass(this.settings.loadingClass);
}
}
if (quantityIsAvailable) {
this.updateItemQuantity(line, quantity);
}
};
La partie intéressante est sur l’appel Ajax au endpoint /products dans validateAvailability(), et dans le callback, le second argument donne la quantité disponible.