public function onBeforeUpdate($cart_item) { // Check that item is not out of stock or has enough stock if ($cart_item->Quantity) { $item = $cart_item->FindStockItem(); $stock = $item->StockLevel ? $item->StockLevel : 0; if ($stock < $cart_item->Quantity && !CommerceStockKeeping::config()->allow_adding) { // Set quantity to the level we have in stock $cart_item->Quantity = $stock; throw new ValidationException(_t("StockKeeping.NotEnoughStock", "There are not enough '{title}' in stock", "Message to show that an item hasn't got enough stock", array('title' => $item->Title))); } } }
public function onBeforeWrite() { parent::onBeforeWrite(); $status = CommerceStockKeeping::config()->completion_status; $allow_negative = CommerceStockKeeping::config()->allow_negative; // If we have just changed the order status and it matches loop // all products and update quantities. if ($this->owner->isChanged("Status") && $this->owner->Status == $status) { foreach ($this->owner->Items() as $order_item) { $product = $order_item->Product(); if ($order_item->Quantity && $product->ID) { $product->StockLevel = $product->StockLevel - $order_item->Quantity; if (!$allow_negative && $product->StockLevel < 0) { $product->StockLevel == 0; } $product->write(); } } } }