Exemple #1
0
    /**
     * Update product quantity
     *
     * @param integer $quantity Quantity to add (or substract)
     * @param integer $id_product Product ID
     * @param integer $id_product_attribute Attribute ID if needed
     * @param string $operator Indicate if quantity must be increased or decreased
     */
    public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true)
    {
        if (!$shop) {
            $shop = Context::getContext()->shop;
        }
        if (Context::getContext()->customer->id) {
            if ($id_address_delivery == 0 && (int) $this->id_address_delivery) {
                // The $id_address_delivery is null, use the cart delivery address
                $id_address_delivery = $this->id_address_delivery;
            } elseif ($id_address_delivery == 0) {
                // The $id_address_delivery is null, get the default customer address
                $id_address_delivery = (int) Address::getFirstCustomerAddressId((int) Context::getContext()->customer->id);
            } elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) {
                // The $id_address_delivery must be linked with customer
                $id_address_delivery = 0;
            }
        }
        $quantity = (int) $quantity;
        $id_product = (int) $id_product;
        $id_product_attribute = (int) $id_product_attribute;
        $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id);
        if ($id_product_attribute) {
            $combination = new Combination((int) $id_product_attribute);
            if ($combination->id_product != $id_product) {
                return false;
            }
        }
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($id_product_attribute)) {
            $minimal_quantity = (int) Attribute::getAttributeMinimalQty($id_product_attribute);
        } else {
            $minimal_quantity = (int) $product->minimal_quantity;
        }
        if (!Validate::isLoadedObject($product)) {
            die(Tools::displayError());
        }
        if (isset(self::$_nbProducts[$this->id])) {
            unset(self::$_nbProducts[$this->id]);
        }
        if (isset(self::$_totalWeight[$this->id])) {
            unset(self::$_totalWeight[$this->id]);
        }
        if ((int) $quantity <= 0) {
            return $this->deleteProduct($id_product, $id_product_attribute, (int) $id_customization);
        } elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE')) {
            return false;
        } else {
            /* Check if the product is already in the cart */
            $result = $this->containsProduct($id_product, $id_product_attribute, (int) $id_customization, (int) $id_address_delivery);
            /* Update quantity if product already exist */
            if ($result) {
                if ($operator == 'up') {
                    $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
							FROM ' . _DB_PREFIX_ . 'product p
							' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
							WHERE p.id_product = ' . $id_product;
                    $result2 = Db::getInstance()->getRow($sql);
                    $product_qty = (int) $result2['quantity'];
                    // Quantity for product pack
                    if (Pack::isPack($id_product)) {
                        $product_qty = Pack::getQuantity($id_product, $id_product_attribute);
                    }
                    $new_qty = (int) $result['quantity'] + (int) $quantity;
                    $qty = '+ ' . (int) $quantity;
                    if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                        if ($new_qty > $product_qty) {
                            return false;
                        }
                    }
                } else {
                    if ($operator == 'down') {
                        $qty = '- ' . (int) $quantity;
                        $new_qty = (int) $result['quantity'] - (int) $quantity;
                        if ($new_qty < $minimal_quantity && $minimal_quantity > 1) {
                            return -1;
                        }
                    } else {
                        return false;
                    }
                }
                /* Delete product from cart */
                if ($new_qty <= 0) {
                    return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization);
                } else {
                    if ($new_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        Db::getInstance()->execute('
						UPDATE `' . _DB_PREFIX_ . 'cart_product`
						SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW()
						WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . '
						AND `id_cart` = ' . (int) $this->id . (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = ' . (int) $id_address_delivery : '') . '
						LIMIT 1');
                    }
                }
            } elseif ($operator == 'up') {
                $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
						FROM ' . _DB_PREFIX_ . 'product p
						' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
						WHERE p.id_product = ' . $id_product;
                $result2 = Db::getInstance()->getRow($sql);
                // Quantity for product pack
                if (Pack::isPack($id_product)) {
                    $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute);
                }
                if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                    if ((int) $quantity > $result2['quantity']) {
                        return false;
                    }
                }
                if ((int) $quantity < $minimal_quantity) {
                    return -1;
                }
                $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'id_address_delivery' => (int) $id_address_delivery, 'id_shop' => $shop->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s')));
                if (!$result_add) {
                    return false;
                }
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update(true);
        $context = Context::getContext()->cloneContext();
        $context->cart = $this;
        Cache::clean('getContextualValue_*');
        if ($auto_add_cart_rule) {
            CartRule::autoAddToCart($context);
        }
        if ($product->customizable) {
            return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery, $operator);
        } else {
            return true;
        }
    }
Exemple #2
0
    /**
     * Update product quantity
     *
     * @param integer $quantity Quantity to add (or substract)
     * @param $product_id
     * @param null $product_attribute_id
     * @param bool $customization_id
     * @param string $operator Indicate if quantity must be increased or decreased
     * @param int $address_delivery_id
     * @param JeproshopShopModelShop $shop
     * @param bool $auto_add_cart_rule
     * @return bool|int
     * @internal param int $id_product Product ID
     * @internal param int $id_product_attribute Attribute ID if needed
     */
    public function updateQuantity($quantity, $product_id, $product_attribute_id = null, $customization_id = false, $operator = 'up', $address_delivery_id = 0, JeproshopShopModelShop $shop = null, $auto_add_cart_rule = true)
    {
        if (!$shop) {
            $shop = JeproshopContext::getContext()->shop;
        }
        $db = JFactory::getDBO();
        if (JeproshopContext::getContext()->customer->customer_id) {
            if ($address_delivery_id == 0 && (int) $this->address_delivery_id) {
                // The $id_address_delivery is null, use the cart delivery address
                $address_delivery_id = $this->address_delivery_id;
            } elseif ($address_delivery_id == 0) {
                // The $id_address_delivery is null, get the default customer address
                $address_delivery_id = (int) JeproshopAddressModelAddress::getCustomerFirstAddressId((int) JeproshopContext::getContext()->customer->customer_id);
            } elseif (!JeproshopCustomerModelCustomer::customerHasAddress(JeproshopContext::getContext()->customer->customer_id, $address_delivery_id)) {
                // The $id_address_delivery must be linked with customer
                $address_delivery_id = 0;
            }
        }
        $quantity = (int) $quantity;
        $product_id = (int) $product_id;
        $product_attribute_id = (int) $product_attribute_id;
        $product = new JeproshopProductModelProduct($product_id, false, JeproshopSettingModelSetting::getValue('default_lang'), $shop->shop_id);
        if ($product_attribute_id) {
            $combination = new JeproshopCombinationModelCombination((int) $product_attribute_id);
            if ($combination->product_id != $product_id) {
                return false;
            }
        }
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($product_attribute_id)) {
            $minimal_quantity = (int) JeproshopAttributeModelAttribute::getAttributeMinimalQty($product_attribute_id);
        } else {
            $minimal_quantity = (int) $product->minimal_quantity;
        }
        if (!JeproshopValidator::isLoadedObject($product, 'product_id')) {
            die(Tools::displayError());
        }
        if (isset(self::$_nbProducts[$this->cart_id])) {
            unset(self::$_nbProducts[$this->cart_id]);
        }
        if (isset(self::$_totalWeight[$this->cart_id])) {
            unset(self::$_totalWeight[$this->cart_id]);
        }
        if ((int) $quantity <= 0) {
            return $this->deleteProduct($product_id, $product_attribute_id, (int) $customization_id);
        } elseif (!$product->available_for_order || JeproshopSettingModelSeting::getValue('catalog_mode')) {
            return false;
        } else {
            /* Check if the product is already in the cart */
            $result = $this->containsProduct($product_id, $product_attribute_id, (int) $customization_id, (int) $address_delivery_id);
            /* Update quantity if product already exist */
            if ($result) {
                if ($operator == 'up') {
                    $query = "SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM " . $db->quoteName('#__jeproshop_product') . " AS product" . JeproshopProductModelProduct::sqlStock('p', $product_attribute_id, true, $shop);
                    $query .= " WHERE product.product_id = " . $product_id;
                    $db->setQuery($query);
                    $result2 = $db->loadObject();
                    $product_qty = (int) $result2->quantity;
                    // Quantity for product pack
                    if (JeproshopProductPack::isPack($product_id)) {
                        $product_qty = JeproshopProductPack::getQuantity($product_id, $product_attribute_id);
                    }
                    $new_qty = (int) $result->quantity + (int) $quantity;
                    $qty = '+ ' . (int) $quantity;
                    if (!JeproshopProductModelProduct::isAvailableWhenOutOfStock((int) $result2->out_of_stock)) {
                        if ($new_qty > $product_qty) {
                            return false;
                        }
                    }
                } else {
                    if ($operator == 'down') {
                        $qty = '- ' . (int) $quantity;
                        $new_qty = (int) $result->quantity - (int) $quantity;
                        if ($new_qty < $minimal_quantity && $minimal_quantity > 1) {
                            return -1;
                        }
                    } else {
                        return false;
                    }
                }
                /* Delete product from cart */
                if ($new_qty <= 0) {
                    return $this->deleteProduct((int) $product_id, (int) $product_attribute_id, (int) $customization_id);
                } else {
                    if ($new_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        $query = "UPDATE " . $db->quoteName('#__jeproshop_cart_product') . " SET " . $db->quoteName('quantity') . " = " . $db->quoteName('quantity') . $qty . ", ";
                        $query .= $db->quoteName('date_add') . " = NOW() WHERE " . $db->quoteName('product_id') . " = " . (int) $product_id;
                        $query .= (!empty($product_attribute_id) ? " AND " . $db->quoteName('product_attribute_id') . " = " . (int) $product_attribute_id : "") . " AND " . $db->quoteName('cart_id') . " = " . (int) $this->cart_id;
                        $query .= (JeproshopSettingModelSeting::getValue('allow_multi_shipping') && $this->isMultiAddressDelivery() ? " AND " . $db->quoteName('address_delivery_id') . " = " . (int) $address_delivery_id : "") . " LIMIT 1";
                        $db->setQuery($query);
                        $db->query();
                    }
                }
            } elseif ($operator == 'up') {
                $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
						FROM ' . _DB_PREFIX_ . 'product p
						' . Product::sqlStock('p', $product_attribute_id, true, $shop) . '
						WHERE p.id_product = ' . $product_id;
                $result2 = Db::getInstance()->getRow($sql);
                // Quantity for product pack
                if (Pack::isPack($product_id)) {
                    $result2['quantity'] = Pack::getQuantity($product_id, $product_attribute_id);
                }
                if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                    if ((int) $quantity > $result2['quantity']) {
                        return false;
                    }
                }
                if ((int) $quantity < $minimal_quantity) {
                    return -1;
                }
                $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $product_id, 'id_product_attribute' => (int) $product_attribute_id, 'id_cart' => (int) $this->cart_id, 'id_address_delivery' => (int) $address_delivery_id, 'id_shop' => $shop->shop_id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s')));
                if (!$result_add) {
                    return false;
                }
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update(true);
        $context = Context::getContext()->cloneContext();
        $context->cart = $this;
        Cache::clean('getContextualValue_*');
        if ($auto_add_cart_rule) {
            CartRule::autoAddToCart($context);
        }
        if ($product->customizable) {
            return $this->updateCustomizationQuantity((int) $quantity, (int) $customization_id, (int) $product_id, (int) $product_attribute_id, (int) $address_delivery_id, $operator);
        } else {
            return true;
        }
    }
    /**
     * @see StockManagerInterface::removeProduct()
     *
     * @param int           $id_product
     * @param int|null      $id_product_attribute
     * @param Warehouse     $warehouse
     * @param int           $quantity
     * @param int           $id_stock_mvt_reason
     * @param bool          $is_usable
     * @param int|null      $id_order
     * @param int           $ignore_pack
     * @param Employee|null $employee
     *
     * @return array
     * @throws PrestaShopException
     */
    public function removeProduct($id_product, $id_product_attribute = null, Warehouse $warehouse, $quantity, $id_stock_mvt_reason, $is_usable = true, $id_order = null, $ignore_pack = 0, $employee = null)
    {
        $return = array();
        if (!Validate::isLoadedObject($warehouse) || !$quantity || !$id_product) {
            return $return;
        }
        if (!StockMvtReason::exists($id_stock_mvt_reason)) {
            $id_stock_mvt_reason = Configuration::get('PS_STOCK_MVT_DEC_REASON_DEFAULT');
        }
        $context = Context::getContext();
        // Special case of a pack
        if (Pack::isPack((int) $id_product) && !$ignore_pack) {
            if (Validate::isLoadedObject($product = new Product((int) $id_product))) {
                // Gets items
                if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                    $products_pack = Pack::getItems((int) $id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                    // Foreach item
                    foreach ($products_pack as $product_pack) {
                        if ($product_pack->advanced_stock_management == 1) {
                            $product_warehouses = Warehouse::getProductWarehouseList($product_pack->id, $product_pack->id_pack_product_attribute);
                            $warehouse_stock_found = false;
                            foreach ($product_warehouses as $product_warehouse) {
                                if (!$warehouse_stock_found) {
                                    if (Warehouse::exists($product_warehouse['id_warehouse'])) {
                                        $current_warehouse = new Warehouse($product_warehouse['id_warehouse']);
                                        $return[] = $this->removeProduct($product_pack->id, $product_pack->id_pack_product_attribute, $current_warehouse, $product_pack->pack_quantity * $quantity, $id_stock_mvt_reason, $is_usable, $id_order);
                                        // The product was found on this warehouse. Stop the stock searching.
                                        $warehouse_stock_found = !empty($return[count($return) - 1]);
                                    }
                                }
                            }
                        }
                    }
                }
                if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                    $return = array_merge($return, $this->removeProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $is_usable, $id_order, 1));
                }
            } else {
                return false;
            }
        } else {
            // gets total quantities in stock for the current product
            $physical_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
            $usable_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
            // check quantity if we want to decrement unusable quantity
            if (!$is_usable) {
                $quantity_in_stock = $physical_quantity_in_stock - $usable_quantity_in_stock;
            } else {
                $quantity_in_stock = $usable_quantity_in_stock;
            }
            // checks if it's possible to remove the given quantity
            if ($quantity_in_stock < $quantity) {
                return $return;
            }
            $stock_collection = $this->getStockCollection($id_product, $id_product_attribute, $warehouse->id);
            $stock_collection->getAll();
            // check if the collection is loaded
            if (count($stock_collection) <= 0) {
                return $return;
            }
            $stock_history_qty_available = array();
            $mvt_params = array();
            $stock_params = array();
            $quantity_to_decrement_by_stock = array();
            $global_quantity_to_decrement = $quantity;
            // switch on MANAGEMENT_TYPE
            switch ($warehouse->management_type) {
                // case CUMP mode
                case 'WA':
                    /** @var Stock $stock */
                    // There is one and only one stock for a given product in a warehouse in this mode
                    $stock = $stock_collection->current();
                    $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $quantity, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'last_wa' => $stock->price_te, 'current_wa' => $stock->price_te, 'id_employee' => (int) $context->employee->id ? (int) $context->employee->id : $employee->id, 'employee_firstname' => $context->employee->firstname ? $context->employee->firstname : $employee->firstname, 'employee_lastname' => $context->employee->lastname ? $context->employee->lastname : $employee->lastname, 'sign' => -1);
                    $stock_params = array('physical_quantity' => $stock->physical_quantity - $quantity, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $quantity : $stock->usable_quantity);
                    // saves stock in warehouse
                    $stock->hydrate($stock_params);
                    $stock->update();
                    // saves stock mvt
                    $stock_mvt = new StockMvt();
                    $stock_mvt->hydrate($mvt_params);
                    $stock_mvt->save();
                    $return[$stock->id]['quantity'] = $quantity;
                    $return[$stock->id]['price_te'] = $stock->price_te;
                    break;
                case 'LIFO':
                case 'FIFO':
                    // for each stock, parse its mvts history to calculate the quantities left for each positive mvt,
                    // according to the instant available quantities for this stock
                    foreach ($stock_collection as $stock) {
                        /** @var Stock $stock */
                        $left_quantity_to_check = $stock->physical_quantity;
                        if ($left_quantity_to_check <= 0) {
                            continue;
                        }
                        $resource = Db::getInstance(_PS_USE_SQL_SLAVE_)->query('
							SELECT sm.`id_stock_mvt`, sm.`date_add`, sm.`physical_quantity`,
								IF ((sm2.`physical_quantity` is null), sm.`physical_quantity`, (sm.`physical_quantity` - SUM(sm2.`physical_quantity`))) as qty
							FROM `' . _DB_PREFIX_ . 'stock_mvt` sm
							LEFT JOIN `' . _DB_PREFIX_ . 'stock_mvt` sm2 ON sm2.`referer` = sm.`id_stock_mvt`
							WHERE sm.`sign` = 1
							AND sm.`id_stock` = ' . (int) $stock->id . '
							GROUP BY sm.`id_stock_mvt`
							ORDER BY sm.`date_add` DESC');
                        while ($row = Db::getInstance()->nextRow($resource)) {
                            // break - in FIFO mode, we have to retreive the oldest positive mvts for which there are left quantities
                            if ($warehouse->management_type == 'FIFO') {
                                if ($row['qty'] == 0) {
                                    break;
                                }
                            }
                            // converts date to timestamp
                            $date = new DateTime($row['date_add']);
                            $timestamp = $date->format('U');
                            // history of the mvt
                            $stock_history_qty_available[$timestamp] = array('id_stock' => $stock->id, 'id_stock_mvt' => (int) $row['id_stock_mvt'], 'qty' => (int) $row['qty']);
                            // break - in LIFO mode, checks only the necessary history to handle the global quantity for the current stock
                            if ($warehouse->management_type == 'LIFO') {
                                $left_quantity_to_check -= (int) $row['qty'];
                                if ($left_quantity_to_check <= 0) {
                                    break;
                                }
                            }
                        }
                    }
                    if ($warehouse->management_type == 'LIFO') {
                        // orders stock history by timestamp to get newest history first
                        krsort($stock_history_qty_available);
                    } else {
                        // orders stock history by timestamp to get oldest history first
                        ksort($stock_history_qty_available);
                    }
                    // checks each stock to manage the real quantity to decrement for each of them
                    foreach ($stock_history_qty_available as $entry) {
                        if ($entry['qty'] >= $global_quantity_to_decrement) {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $global_quantity_to_decrement;
                            $global_quantity_to_decrement = 0;
                        } else {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $entry['qty'];
                            $global_quantity_to_decrement -= $entry['qty'];
                        }
                        if ($global_quantity_to_decrement <= 0) {
                            break;
                        }
                    }
                    // for each stock, decrements it and logs the mvts
                    foreach ($stock_collection as $stock) {
                        if (array_key_exists($stock->id, $quantity_to_decrement_by_stock) && is_array($quantity_to_decrement_by_stock[$stock->id])) {
                            $total_quantity_for_current_stock = 0;
                            foreach ($quantity_to_decrement_by_stock[$stock->id] as $id_mvt_referrer => $qte) {
                                $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $qte, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'sign' => -1, 'referer' => $id_mvt_referrer, 'id_employee' => (int) $context->employee->id ? (int) $context->employee->id : $employee->id);
                                // saves stock mvt
                                $stock_mvt = new StockMvt();
                                $stock_mvt->hydrate($mvt_params);
                                $stock_mvt->save();
                                $total_quantity_for_current_stock += $qte;
                            }
                            $stock_params = array('physical_quantity' => $stock->physical_quantity - $total_quantity_for_current_stock, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $total_quantity_for_current_stock : $stock->usable_quantity);
                            $return[$stock->id]['quantity'] = $total_quantity_for_current_stock;
                            $return[$stock->id]['price_te'] = $stock->price_te;
                            // saves stock in warehouse
                            $stock->hydrate($stock_params);
                            $stock->update();
                        }
                    }
                    break;
            }
            if (Pack::isPacked($id_product, $id_product_attribute)) {
                $packs = Pack::getPacksContainingItem($id_product, $id_product_attribute, (int) Configuration::get('PS_LANG_DEFAULT'));
                foreach ($packs as $pack) {
                    // Decrease stocks of the pack only if pack is in linked stock mode (option called 'Decrement both')
                    if (!((int) $pack->pack_stock_type == 2) && !((int) $pack->pack_stock_type == 3 && (int) Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                        continue;
                    }
                    // Decrease stocks of the pack only if there is not enough items to constituate the actual pack stocks.
                    // How many packs can be constituated with the remaining product stocks
                    $quantity_by_pack = $pack->pack_item_quantity;
                    $stock_available_quantity = $quantity_in_stock - $quantity;
                    $max_pack_quantity = max(array(0, floor($stock_available_quantity / $quantity_by_pack)));
                    $quantity_delta = Pack::getQuantity($pack->id) - $max_pack_quantity;
                    if ($pack->advanced_stock_management == 1 && $quantity_delta > 0) {
                        $product_warehouses = Warehouse::getPackWarehouses($pack->id);
                        $warehouse_stock_found = false;
                        foreach ($product_warehouses as $product_warehouse) {
                            if (!$warehouse_stock_found) {
                                if (Warehouse::exists($product_warehouse)) {
                                    $current_warehouse = new Warehouse($product_warehouse);
                                    $return[] = $this->removeProduct($pack->id, null, $current_warehouse, $quantity_delta, $id_stock_mvt_reason, $is_usable, $id_order, 1);
                                    // The product was found on this warehouse. Stop the stock searching.
                                    $warehouse_stock_found = !empty($return[count($return) - 1]);
                                }
                            }
                        }
                    }
                }
            }
        }
        // if we remove a usable quantity, exec hook
        if ($is_usable) {
            Hook::exec('actionProductCoverage', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'warehouse' => $warehouse));
        }
        return $return;
    }
Exemple #4
0
    public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true, $id_cart_product = 0, $ext_prop_quantities = null, $ext_qty = 0)
    {
        if (!$shop) {
            $shop = Context::getContext()->shop;
        }
        if (Context::getContext()->customer->id) {
            if ($id_address_delivery == 0 && (int) $this->id_address_delivery) {
                // The $id_address_delivery is null, use the cart delivery address
                $id_address_delivery = $this->id_address_delivery;
            } elseif ($id_address_delivery == 0) {
                // The $id_address_delivery is null, get the default customer address
                $id_address_delivery = (int) Address::getFirstCustomerAddressId((int) Context::getContext()->customer->id);
            } elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) {
                // The $id_address_delivery must be linked with customer
                $id_address_delivery = 0;
            }
        }
        //$quantity = (int)$quantity;
        $id_product = (int) $id_product;
        $id_product_attribute = (int) $id_product_attribute;
        $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id);
        if ($id_product_attribute) {
            $combination = new Combination((int) $id_product_attribute);
            if ($combination->id_product != $id_product) {
                return false;
            }
        }
        $properties = $product->productProperties();
        $quantity = $product->normalizeQty($quantity);
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($id_product_attribute)) {
            $minimal_quantity = $product->attributeMinQty($id_product_attribute);
        } else {
            $minimal_quantity = $product->minQty();
        }
        if (!Validate::isLoadedObject($product)) {
            die(Tools::displayError());
        }
        if (isset(self::$_nbProducts[$this->id])) {
            unset(self::$_nbProducts[$this->id]);
        }
        if (isset(self::$_totalWeight[$this->id])) {
            unset(self::$_totalWeight[$this->id]);
        }
        Hook::exec('actionBeforeCartUpdateQty', array('cart' => $this, 'product' => $product, 'id_product_attribute' => $id_product_attribute, 'id_customization' => $id_customization, 'quantity' => $quantity, 'operator' => $operator, 'id_address_delivery' => $id_address_delivery, 'shop' => $shop, 'auto_add_cart_rule' => $auto_add_cart_rule));
        if ($quantity <= 0) {
            return $this->deleteProduct($id_product, $id_product_attribute, (int) $id_customization, 0, $id_cart_product);
        } elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE') && !defined('_PS_ADMIN_DIR_')) {
            return false;
        } else {
            if ($id_cart_product == 0 && !PP::qtyPolicyLegacy($properties['pp_qty_policy'])) {
                $result = false;
            } else {
                /* Check if the product is already in the cart */
                $result = $this->containsProduct($id_product, $id_product_attribute, (int) $id_customization, (int) $id_address_delivery, PP::productQtyPolicyLegacy($product) ? 0 : $quantity, $id_cart_product);
            }
            /* Update quantity if product already exist */
            if ($result) {
                if ($operator == 'up' || $operator == 'update') {
                    $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, IFNULL(stock.quantity_remainder, 0) as quantity_remainder
							FROM ' . _DB_PREFIX_ . 'product p
							' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
							WHERE p.id_product = ' . $id_product;
                    $result2 = Db::getInstance()->getRow($sql);
                    $product_qty = (int) $result2['quantity'] + (double) $result2['quantity_remainder'];
                    // Quantity for product pack
                    if (Pack::isPack($id_product)) {
                        $product_qty = Pack::getQuantity($id_product, $id_product_attribute);
                    }
                    if ($operator == 'up') {
                        $q = $id_cart_product > 0 || PP::qtyPolicyLegacy($properties['pp_qty_policy']) ? (int) $quantity : 1;
                        $new_qty = PP::resolveQty((int) $result['quantity'] + $q, $result['quantity_fractional']);
                        $new_min_qty = $properties['pp_ext'] == 1 ? (int) $result['quantity'] + $q : $new_qty;
                        $qty = '+ ' . (int) $q;
                    } else {
                        $new_qty = $new_min_qty = $qty = $quantity;
                    }
                    if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                        if ($new_qty > $product_qty) {
                            return false;
                        }
                    }
                } else {
                    if ($operator == 'down') {
                        $q = $id_cart_product > 0 ? (int) $quantity : 1;
                        $new_qty = PP::resolveQty((int) $result['quantity'] - $q, $result['quantity_fractional']);
                        $new_min_qty = $properties['pp_ext'] == 1 ? (int) $result['quantity'] - $q : $new_qty;
                        $qty = '- ' . (int) $q;
                        if ($new_min_qty < $minimal_quantity && (PP::qtyPolicyLegacy($properties['pp_qty_policy'] || $properties['pp_ext'] == 1) ? $minimal_quantity > 1 : $new_qty > 0)) {
                            return -1;
                        }
                    } else {
                        return false;
                    }
                }
                /* Delete product from cart */
                if (($properties['pp_ext'] == 1 ? $new_min_qty : $new_qty) <= 0) {
                    return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization, $id_address_delivery, $id_cart_product);
                } else {
                    if ($new_min_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        if ($operator == 'up' || $operator == 'down') {
                            Db::getInstance()->execute('
								UPDATE `' . _DB_PREFIX_ . 'cart_product`
								SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW()
								WHERE `id_cart_product` = ' . (int) $result['id_cart_product'] . '
								LIMIT 1');
                        } else {
                            Db::getInstance()->execute('
							UPDATE `' . _DB_PREFIX_ . 'cart_product`
							SET `quantity_fractional` = ' . $qty . ', `date_add` = NOW()
							WHERE `id_cart_product` = ' . (int) $result['id_cart_product'] . '
							LIMIT 1');
                        }
                    }
                }
                $id_cart_product = (int) $result['id_cart_product'];
            } elseif ($operator == 'up') {
                $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, IFNULL(stock.quantity_remainder, 0) as quantity_remainder
						FROM ' . _DB_PREFIX_ . 'product p
						' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
						WHERE p.id_product = ' . $id_product;
                $result2 = Db::getInstance()->getRow($sql);
                // Quantity for product pack
                if (Pack::isPack($id_product)) {
                    $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute);
                }
                $total_quantity = PP::qtyPolicyLegacy($properties['pp_qty_policy']) ? $quantity : ($ext_prop_quantities !== null && $ext_qty > 0 ? $quantity * $ext_qty : $quantity);
                if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                    if ($total_quantity > $result2['quantity'] + (PP::qtyPolicyFractional($properties['pp_qty_policy']) ? (double) $result2['quantity_remainder'] : 0)) {
                        return false;
                    }
                }
                if (PP::qtyPolicyFractional($properties['pp_qty_policy']) && $ext_prop_quantities !== null && $ext_qty > 0) {
                    if ($ext_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        if ($total_quantity < $minimal_quantity) {
                            return -1;
                        }
                    }
                }
                $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'id_address_delivery' => (int) $id_address_delivery, 'id_shop' => $shop->id, 'quantity' => PP::qtyPolicyLegacy($properties['pp_qty_policy']) ? $quantity : ($ext_prop_quantities !== null && $ext_qty > 0 ? $ext_qty : 1), 'quantity_fractional' => PP::qtyPolicyLegacy($properties['pp_qty_policy']) ? 0 : $quantity, 'date_add' => date('Y-m-d H:i:s')));
                if (!$result_add) {
                    return false;
                }
                $id_cart_product = Db::getInstance()->Insert_ID();
                if (count($ext_prop_quantities)) {
                    $db = Db::getInstance();
                    foreach ($ext_prop_quantities as $index => $value) {
                        $db->insert('pp_product_ext', array('id_cart_product' => (int) $id_cart_product, 'position' => (int) $index, 'quantity' => (double) $value));
                    }
                }
            }
            $this->last_icp = $id_cart_product;
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update();
        $context = Context::getContext()->cloneContext();
        $context->cart = $this;
        Cache::clean('getContextualValue_*');
        if ($auto_add_cart_rule) {
            CartRule::autoAddToCart($context);
        }
        if ($product->customizable) {
            return $this->_updateCustomizationQuantity($quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery, $operator, $id_cart_product);
        } else {
            return true;
        }
    }