Skip to content

Instantly share code, notes, and snippets.

@LeeSaferite
Last active August 29, 2015 14:13
Show Gist options
  • Save LeeSaferite/56a57cd8e066cf2770a5 to your computer and use it in GitHub Desktop.
Save LeeSaferite/56a57cd8e066cf2770a5 to your computer and use it in GitHub Desktop.
Mage_CatalogInventory_Model_Stock_Item::suggestQty update
<?php
public function suggestQty($qty)
{
// We do not manage stock
if ($qty <= 0 || !$this->getManageStock()) {
return $qty;
}
$qtyIncrements = (int)$this->getQtyIncrements(); // Currently only integer increments supported
if ($qtyIncrements < 2) {
return $qty;
}
$minQty = max($this->getMinSaleQty(), $qtyIncrements);
$divisibleMin = ceil($minQty / $qtyIncrements) * $qtyIncrements;
$maxQty = min($this->getQty() - $this->getMinQty(), $this->getMaxSaleQty());
$divisibleMax = floor($maxQty / $qtyIncrements) * $qtyIncrements;
if ($qty < $minQty || $qty > $maxQty || $divisibleMin > $divisibleMax) {
// Do not perform rounding for qty that does not satisfy min/max conditions to not confuse customer
return $qty;
}
// Suggest value closest to given qty
$closestDivisibleLeft = floor($qty / $qtyIncrements) * $qtyIncrements;
$closestDivisibleRight = $closestDivisibleLeft + $qtyIncrements;
$acceptableLeft = min(max($divisibleMin, $closestDivisibleLeft), $divisibleMax);
$acceptableRight = max(min($divisibleMax, $closestDivisibleRight), $divisibleMin);
return abs($acceptableLeft - $qty) < abs($acceptableRight - $qty) ? $acceptableLeft : $acceptableRight;
}
<?php
public function suggestQty($qty)
{
// Handle only number quantities and only if stock management is enabled
if (is_numeric($qty) && $this->getManageStock()) {
// Grab and type-cast the qty increment to a float
$qtyIncrements = (float)$this->getQtyIncrements();
// If increment is 0 (or less) then increments are disabled, no need to round the qty
if ($qtyIncrements > 0) {
// Type-cast the qty to a float
$qty = (float)$qty;
// Get a min that respects the increment
$minQty = ceil((float)$this->getMinSaleQty() / $qtyIncrements) * $qtyIncrements;
// Get a max that respects the increment
$maxQty = floor((float)$this->getMaxSaleQty() / $qtyIncrements) * $qtyIncrements;
// If the qty is out of range of min/max or min/max is invalid then skip the rounding
if ($minQty < $maxQty && $qty > $minQty && $qty < $maxQty) {
// Get a qty that respects the increment
$qty = round($qty / $qtyIncrements) * $qtyIncrements;
}
}
}
return $qty;
}
@LeeSaferite
Copy link
Author

This one fully handles fractional increments and doesn't use the crazy decision logic in the old one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment