Exemple #1
0
 public function resetStockAvailable()
 {
     $products = WarehouseProductLocation::getProducts((int) $this->id);
     foreach ($products as $product) {
         StockAvailable::synchronize((int) $product['id_product']);
     }
 }
Exemple #2
0
    public function addAttribute($price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1, array $id_shop_list = array(), $available_date = null)
    {
        if (!$this->id) {
            return;
        }
        $price = str_replace(',', '.', $price);
        $weight = str_replace(',', '.', $weight);
        $combination = new Combination();
        $combination->id_product = (int) $this->id;
        $combination->price = (double) $price;
        $combination->ecotax = (double) $ecotax;
        $combination->quantity = 0;
        $combination->weight = (double) $weight;
        $combination->unit_price_impact = (double) $unit_impact;
        $combination->reference = pSQL($reference);
        $combination->location = pSQL($location);
        $combination->ean13 = pSQL($ean13);
        $combination->upc = pSQL($upc);
        $combination->default_on = (int) $default;
        $minimal_quantity = str_replace(',', '.', $minimal_quantity);
        $this->setMinQty($minimal_quantity, $combination);
        $combination->available_date = $available_date;
        if (count($id_shop_list)) {
            $combination->id_shop_list = array_unique($id_shop_list);
        }
        $combination->add();
        if (!$combination->id) {
            return false;
        }
        $total_quantity = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
			SELECT SUM(quantity + quantity_remainder) as quantity
			FROM ' . _DB_PREFIX_ . 'stock_available
			WHERE id_product = ' . (int) $this->id . '
			AND id_product_attribute <> 0 ');
        if (!$total_quantity) {
            Db::getInstance()->update('stock_available', array('quantity' => 0, 'quantity_remainder' => 0), '`id_product` = ' . $this->id);
        }
        $id_default_attribute = Product::updateDefaultAttribute($this->id);
        if ($id_default_attribute) {
            $this->cache_default_attribute = $id_default_attribute;
            if (!$combination->available_date) {
                $this->setAvailableDate();
            }
        }
        if (!empty($id_images)) {
            $combination->setImages($id_images);
        }
        Tools::clearColorListCache($this->id);
        if (Configuration::get('PS_DEFAULT_WAREHOUSE_NEW_PRODUCT') != 0 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
            $warehouse_location_entity = new WarehouseProductLocation();
            $warehouse_location_entity->id_product = $this->id;
            $warehouse_location_entity->id_product_attribute = (int) $combination->id;
            $warehouse_location_entity->id_warehouse = Configuration::get('PS_DEFAULT_WAREHOUSE_NEW_PRODUCT');
            $warehouse_location_entity->location = pSQL('');
            $warehouse_location_entity->save();
        }
        return (int) $combination->id;
    }
 /**
  * AdminController::postProcess() override
  * @see AdminController::postProcess()
  */
 public function postProcess()
 {
     parent::postProcess();
     // Checks access
     if (Tools::isSubmit('addStock') && !($this->tabAccess['add'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to add stock.');
     }
     if (Tools::isSubmit('removeStock') && !($this->tabAccess['delete'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to delete stock');
     }
     if (Tools::isSubmit('transferStock') && !($this->tabAccess['edit'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to transfer stock.');
     }
     if (count($this->errors)) {
         return;
     }
     // Global checks when add / remove / transfer product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') || Tools::isSubmit('transferstock')) && Tools::isSubmit('is_post')) {
         // get product ID
         $id_product = (int) Tools::getValue('id_product', 0);
         if ($id_product <= 0) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get product_attribute ID
         $id_product_attribute = (int) Tools::getValue('id_product_attribute', 0);
         // check the product hash
         $check = Tools::getValue('check', '');
         $check_valid = md5(_COOKIE_KEY_ . $id_product . $id_product_attribute);
         if ($check != $check_valid) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get quantity and check that the post value is really an integer
         // If it's not, we have nothing to do
         $quantity = Tools::getValue('quantity', 0);
         if (!is_numeric($quantity) || (int) $quantity <= 0) {
             $this->errors[] = Tools::displayError('The quantity value is not valid.');
         }
         $quantity = (int) $quantity;
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         $redirect = self::$currentIndex . '&token=' . $token;
     }
     // Global checks when add / remove product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock')) && Tools::isSubmit('is_post')) {
         // get warehouse id
         $id_warehouse = (int) Tools::getValue('id_warehouse', 0);
         if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) {
             $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
         }
         // get stock movement reason id
         $id_stock_mvt_reason = (int) Tools::getValue('id_stock_mvt_reason', 0);
         if ($id_stock_mvt_reason <= 0 || !StockMvtReason::exists($id_stock_mvt_reason)) {
             $this->errors[] = Tools::displayError('The reason is not valid.');
         }
         // get usable flag
         $usable = Tools::getValue('usable', null);
         if (is_null($usable)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity is usable for sale on shops or not.');
         }
         $usable = (bool) $usable;
     }
     if (Tools::isSubmit('addstock') && Tools::isSubmit('is_post')) {
         // get product unit price
         $price = str_replace(',', '.', Tools::getValue('price', 0));
         if (!is_numeric($price)) {
             $this->errors[] = Tools::displayError('The product price is not valid.');
         }
         $price = round(floatval($price), 6);
         // get product unit price currency id
         $id_currency = (int) Tools::getValue('id_currency', 0);
         if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
             $this->errors[] = Tools::displayError('The selected currency is not valid.');
         }
         // if all is ok, add stock
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             // convert price to warehouse currency if needed
             if ($id_currency != $warehouse->id_currency) {
                 // First convert price to the default currency
                 $price_converted_to_default_currency = Tools::convertPrice($price, $id_currency, false);
                 // Convert the new price from default currency to needed currency
                 $price = Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true);
             }
             // add stock
             $stock_manager = StockManagerFactory::getManager();
             if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $usable)) {
                 // Create warehouse_product_location entry if we add stock to a new warehouse
                 $id_wpl = (int) WarehouseProductLocation::getIdByProductAndWarehouse($id_product, $id_product_attribute, $id_warehouse);
                 if (!$id_wpl) {
                     $wpl = new WarehouseProductLocation();
                     $wpl->id_product = (int) $id_product;
                     $wpl->id_product_attribute = (int) $id_product_attribute;
                     $wpl->id_warehouse = (int) $id_warehouse;
                     $wpl->save();
                 }
                 StockAvailable::synchronize($id_product);
                 if (Tools::isSubmit('addstockAndStay')) {
                     $redirect = self::$currentIndex . '&id_product=' . (int) $id_product;
                     if ($id_product_attribute) {
                         $redirect .= '&id_product_attribute=' . (int) $id_product_attribute;
                     }
                     $redirect .= '&addstock&token=' . $token;
                 }
                 Tools::redirectAdmin($redirect . '&conf=1');
             } else {
                 $this->errors[] = Tools::displayError('An error occurred. No stock was added.');
             }
         }
     }
     if (Tools::isSubmit('removestock') && Tools::isSubmit('is_post')) {
         // if all is ok, remove stock
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             // remove stock
             $stock_manager = StockManagerFactory::getManager();
             $removed_products = $stock_manager->removeProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $usable);
             if (count($removed_products) > 0) {
                 StockAvailable::synchronize($id_product);
                 Tools::redirectAdmin($redirect . '&conf=2');
             } else {
                 $physical_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
                 $usable_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
                 $not_usable_quantity = $physical_quantity_in_stock - $usable_quantity_in_stock;
                 if ($usable_quantity_in_stock < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $usable_quantity_in_stock);
                 } elseif ($not_usable_quantity < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $not_usable_quantity);
                 } else {
                     $this->errors[] = Tools::displayError('It is not possible to remove the specified quantity. Therefore no stock was removed.');
                 }
             }
         }
     }
     if (Tools::isSubmit('transferstock') && Tools::isSubmit('is_post')) {
         // get source warehouse id
         $id_warehouse_from = (int) Tools::getValue('id_warehouse_from', 0);
         if ($id_warehouse_from <= 0 || !Warehouse::exists($id_warehouse_from)) {
             $this->errors[] = Tools::displayError('The source warehouse is not valid.');
         }
         // get destination warehouse id
         $id_warehouse_to = (int) Tools::getValue('id_warehouse_to', 0);
         if ($id_warehouse_to <= 0 || !Warehouse::exists($id_warehouse_to)) {
             $this->errors[] = Tools::displayError('The destination warehouse is not valid.');
         }
         // get usable flag for source warehouse
         $usable_from = Tools::getValue('usable_from', null);
         if (is_null($usable_from)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your source warehouse(s) is ready for sale or not.');
         }
         $usable_from = (bool) $usable_from;
         // get usable flag for destination warehouse
         $usable_to = Tools::getValue('usable_to', null);
         if (is_null($usable_to)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your destination warehouse(s) is ready for sale or not.');
         }
         $usable_to = (bool) $usable_to;
         // if we can process stock transfers
         if (count($this->errors) == 0) {
             // transfer stock
             $stock_manager = StockManagerFactory::getManager();
             $is_transfer = $stock_manager->transferBetweenWarehouses($id_product, $id_product_attribute, $quantity, $id_warehouse_from, $id_warehouse_to, $usable_from, $usable_to);
             StockAvailable::synchronize($id_product);
             if ($is_transfer) {
                 Tools::redirectAdmin($redirect . '&conf=3');
             } else {
                 $this->errors[] = Tools::displayError('It is not possible to transfer the specified quantity. No stock was transferred.');
             }
         }
     }
 }
 public function ajaxProcessEditProductOnOrder()
 {
     // Return value
     $res = true;
     $order = new Order((int) Tools::getValue('id_order'));
     $order_detail = new OrderDetail((int) Tools::getValue('product_id_order_detail'));
     if (Tools::isSubmit('product_invoice')) {
         $order_invoice = new OrderInvoice((int) Tools::getValue('product_invoice'));
     }
     // Check fields validity
     $this->doEditProductValidation($order_detail, $order, isset($order_invoice) ? $order_invoice : null);
     // If multiple product_quantity, the order details concern a product customized
     $product_quantity = 0;
     if (is_array(Tools::getValue('product_quantity'))) {
         foreach (Tools::getValue('product_quantity') as $id_customization => $qty) {
             // Update quantity of each customization
             Db::getInstance()->update('customization', array('quantity' => (int) $qty), 'id_customization = ' . (int) $id_customization);
             // Calculate the real quantity of the product
             $product_quantity += $qty;
         }
     } else {
         $product_quantity = Tools::getValue('product_quantity');
     }
     $product_price_tax_incl = Tools::ps_round(Tools::getValue('product_price_tax_incl'), 2);
     $product_price_tax_excl = Tools::ps_round(Tools::getValue('product_price_tax_excl'), 2);
     $total_products_tax_incl = $product_price_tax_incl * $product_quantity;
     $total_products_tax_excl = $product_price_tax_excl * $product_quantity;
     // Calculate differences of price (Before / After)
     $diff_price_tax_incl = $total_products_tax_incl - $order_detail->total_price_tax_incl;
     $diff_price_tax_excl = $total_products_tax_excl - $order_detail->total_price_tax_excl;
     // Apply change on OrderInvoice
     if (isset($order_invoice)) {
         // If OrderInvoice to use is different, we update the old invoice and new invoice
         if ($order_detail->id_order_invoice != $order_invoice->id) {
             $old_order_invoice = new OrderInvoice($order_detail->id_order_invoice);
             // We remove cost of products
             $old_order_invoice->total_products -= $order_detail->total_price_tax_excl;
             $old_order_invoice->total_products_wt -= $order_detail->total_price_tax_incl;
             $old_order_invoice->total_paid_tax_excl -= $order_detail->total_price_tax_excl;
             $old_order_invoice->total_paid_tax_incl -= $order_detail->total_price_tax_incl;
             $res &= $old_order_invoice->update();
             $order_invoice->total_products += $order_detail->total_price_tax_excl;
             $order_invoice->total_products_wt += $order_detail->total_price_tax_incl;
             $order_invoice->total_paid_tax_excl += $order_detail->total_price_tax_excl;
             $order_invoice->total_paid_tax_incl += $order_detail->total_price_tax_incl;
             $order_detail->id_order_invoice = $order_invoice->id;
         }
     }
     if ($diff_price_tax_incl != 0 && $diff_price_tax_excl != 0) {
         $order_detail->unit_price_tax_excl = $product_price_tax_excl;
         $order_detail->unit_price_tax_incl = $product_price_tax_incl;
         $order_detail->total_price_tax_incl += $diff_price_tax_incl;
         $order_detail->total_price_tax_excl += $diff_price_tax_excl;
         if (isset($order_invoice)) {
             // Apply changes on OrderInvoice
             $order_invoice->total_products += $diff_price_tax_excl;
             $order_invoice->total_products_wt += $diff_price_tax_incl;
             $order_invoice->total_paid_tax_excl += $diff_price_tax_excl;
             $order_invoice->total_paid_tax_incl += $diff_price_tax_incl;
         }
         // Apply changes on Order
         $order = new Order($order_detail->id_order);
         $order->total_products += $diff_price_tax_excl;
         $order->total_products_wt += $diff_price_tax_incl;
         $order->total_paid += $diff_price_tax_incl;
         $order->total_paid_tax_excl += $diff_price_tax_excl;
         $order->total_paid_tax_incl += $diff_price_tax_incl;
         $res &= $order->update();
     }
     $old_quantity = $order_detail->product_quantity;
     $order_detail->product_quantity = $product_quantity;
     $order_detail->reduction_percent = 0;
     // update taxes
     $res &= $order_detail->updateTaxAmount($order);
     // Save order detail
     $res &= $order_detail->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         $res &= $order_carrier->update();
         if ($res) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Save order invoice
     if (isset($order_invoice)) {
         $res &= $order_invoice->update();
     }
     // Update product available quantity
     StockAvailable::updateQuantity($order_detail->product_id, $order_detail->product_attribute_id, $old_quantity - $order_detail->product_quantity, $order->id_shop);
     $products = $this->getProducts($order);
     // Get the last product
     $product = $products[$order_detail->id];
     $resume = OrderSlip::getProductSlipResume($order_detail->id);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail($order_detail->id);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
         $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
         if (!empty($warehouse_location)) {
             $product['warehouse_location'] = $warehouse_location;
         } else {
             $product['warehouse_location'] = false;
         }
     } else {
         $product['warehouse_name'] = '--';
         $product['warehouse_location'] = false;
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         /** @var OrderInvoice $invoice */
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     if (!$res) {
         die(Tools::jsonEncode(array('result' => $res, 'error' => Tools::displayError('An error occurred while editing the product line.'))));
     }
     if (is_array(Tools::getValue('product_quantity'))) {
         $view = $this->createTemplate('_customized_data.tpl')->fetch();
     } else {
         $view = $this->createTemplate('_product_line.tpl')->fetch();
     }
     $this->sendChangedNotification($order);
     die(Tools::jsonEncode(array('result' => $res, 'view' => $view, 'can_edit' => $this->tabAccess['add'], 'invoices_collection' => $invoice_collection, 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'customized_product' => is_array(Tools::getValue('product_quantity')))));
 }
Exemple #5
0
 public function initFormWarehouses($obj)
 {
     $data = $this->createTemplate($this->tpl_form);
     if ($obj->id) {
         if ($this->product_exists_in_shop) {
             // Get all id_product_attribute
             $attributes = $obj->getAttributesResume($this->context->language->id);
             if (empty($attributes)) {
                 $attributes[] = array('id_product' => $obj->id, 'id_product_attribute' => 0, 'attribute_designation' => '');
             }
             $product_designation = array();
             foreach ($attributes as $attribute) {
                 $product_designation[$attribute['id_product_attribute']] = rtrim($obj->name[$this->context->language->id] . ' - ' . $attribute['attribute_designation'], ' - ');
             }
             // Get all available warehouses
             $warehouses = Warehouse::getWarehouses(true);
             // Get already associated warehouses
             $associated_warehouses_collection = WarehouseProductLocation::getCollection($obj->id);
             $data->assign(array('attributes' => $attributes, 'warehouses' => $warehouses, 'associated_warehouses' => $associated_warehouses_collection, 'product_designation' => $product_designation, 'product' => $obj, 'link' => $this->context->link, 'token' => $this->token));
         } else {
             $this->displayWarning($this->l('You must save the product in this shop before managing warehouses.'));
         }
     } else {
         $this->displayWarning($this->l('You must save this product before managing warehouses.'));
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
Exemple #6
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = (int)$line['count'];

        $product->advanced_stock_management = 1; //использовать Advanced Stock management
        $product->depends_on_stock = 1; //1 - доступное количество на основе ASM. 0 - указывается вручную
        $product->out_of_stock = 1; //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)

        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 1); //1 - id значения "переплёт" у харакатеристики "Переплёт"
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        //$available->id_shop = Context::getContext()->shop->id;
        $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
        $available->save();

        StockAvailable::setProductDependsOnStock($product->id, true, null);
        StockAvailable::setProductOutOfStock($product->id, 1, null); //allow

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }

        /*
        Db::getInstance()->update('stock_available', array(
           'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
            'out_of_stock' => (int)1, //1-allow
        ), 'id_product='.$product->id.'');
         $affrows = Db::getInstance()->Affected_Rows();
         var_dump($affrows);
         */

        //var_dump($product->reference);
        //echo "<br/><br/><br/><br/>";
    }
    protected function attributeImportOne($info, $default_language, &$groups, &$attributes, $regenerate, $shop_is_feature_active, $validateOnly = false)
    {
        AdminImportController::setDefaultValues($info);
        if (!$shop_is_feature_active) {
            $info['shop'] = 1;
        } elseif (!isset($info['shop']) || empty($info['shop'])) {
            $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
        }
        // Get shops for each attributes
        $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
        $id_shop_list = array();
        if (is_array($info['shop']) && count($info['shop'])) {
            foreach ($info['shop'] as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $id_shop_list[] = Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $id_shop_list[] = $shop;
                }
            }
        }
        if (isset($info['id_product']) && $info['id_product']) {
            $product = new Product((int) $info['id_product'], false, $default_language);
        } elseif (Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) {
            $datas = Db::getInstance()->getRow('
				SELECT p.`id_product`
				FROM `' . _DB_PREFIX_ . 'product` p
				' . Shop::addSqlAssociation('product', 'p') . '
				WHERE p.`reference` = "' . pSQL($info['product_reference']) . '"
			', false);
            if (isset($datas['id_product']) && $datas['id_product']) {
                $product = new Product((int) $datas['id_product'], false, $default_language);
            }
        } else {
            return;
        }
        $id_image = array();
        if (isset($info['image_url']) && $info['image_url']) {
            $info['image_url'] = explode($this->multiple_value_separator, $info['image_url']);
            if (is_array($info['image_url']) && count($info['image_url'])) {
                foreach ($info['image_url'] as $key => $url) {
                    $url = trim($url);
                    $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                    $image = new Image();
                    $image->id_product = (int) $product->id;
                    $image->position = Image::getHighestPosition($product->id) + 1;
                    $image->cover = !$product_has_images ? true : false;
                    if (isset($info['image_alt'])) {
                        $alt = self::split($info['image_alt']);
                        if (isset($alt[$key]) && strlen($alt[$key]) > 0) {
                            $alt = self::createMultiLangField($alt[$key]);
                            $image->legend = $alt;
                        }
                    }
                    $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                    $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                    if ($field_error === true && $lang_field_error === true && !$validateOnly && $image->add()) {
                        $image->associateTo($id_shop_list);
                        // FIXME: 2s/image !
                        if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !$regenerate)) {
                            $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url);
                            $image->delete();
                        } else {
                            $id_image[] = (int) $image->id;
                        }
                        // until here
                    } else {
                        if (!$validateOnly) {
                            $this->warnings[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                        }
                        if ($field_error !== true || $lang_field_error !== true) {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                        }
                    }
                }
            }
        } elseif (isset($info['image_position']) && $info['image_position']) {
            $info['image_position'] = explode($this->multiple_value_separator, $info['image_position']);
            if (is_array($info['image_position']) && count($info['image_position'])) {
                foreach ($info['image_position'] as $position) {
                    // choose images from product by position
                    $images = $product->getImages($default_language);
                    if ($images) {
                        foreach ($images as $row) {
                            if ($row['position'] == (int) $position) {
                                $id_image[] = (int) $row['id_image'];
                                break;
                            }
                        }
                    }
                    if (empty($id_image)) {
                        $this->warnings[] = sprintf($this->trans('No image was found for combination with id_product = %s and image position = %s.', array(), 'Admin.Parameters.Notification'), $product->id, (int) $position);
                    }
                }
            }
        }
        $id_attribute_group = 0;
        // groups
        $groups_attributes = array();
        if (isset($info['group'])) {
            foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                if (empty($group)) {
                    continue;
                }
                $tab_group = explode(':', $group);
                $group = trim($tab_group[0]);
                if (!isset($tab_group[1])) {
                    $type = 'select';
                } else {
                    $type = trim($tab_group[1]);
                }
                // sets group
                $groups_attributes[$key]['group'] = $group;
                // if position is filled
                if (isset($tab_group[2])) {
                    $position = trim($tab_group[2]);
                } else {
                    $position = false;
                }
                if (!isset($groups[$group])) {
                    $obj = new AttributeGroup();
                    $obj->is_color_group = false;
                    $obj->group_type = pSQL($type);
                    $obj->name[$default_language] = $group;
                    $obj->public_name[$default_language] = $group;
                    $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                    if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                        // here, cannot avoid attributeGroup insertion to avoid an error during validation step.
                        //if (!$validateOnly) {
                        $obj->add();
                        $obj->associateTo($id_shop_list);
                        $groups[$group] = $obj->id;
                        //}
                    } else {
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                    }
                    // fills groups attributes
                    $id_attribute_group = $obj->id;
                    $groups_attributes[$key]['id'] = $id_attribute_group;
                } else {
                    // already exists
                    $id_attribute_group = $groups[$group];
                    $groups_attributes[$key]['id'] = $id_attribute_group;
                }
            }
        }
        // inits attribute
        $id_product_attribute = 0;
        $id_product_attribute_update = false;
        $attributes_to_add = array();
        // for each attribute
        if (isset($info['attribute'])) {
            foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                if (empty($attribute)) {
                    continue;
                }
                $tab_attribute = explode(':', $attribute);
                $attribute = trim($tab_attribute[0]);
                // if position is filled
                if (isset($tab_attribute[1])) {
                    $position = trim($tab_attribute[1]);
                } else {
                    $position = false;
                }
                if (isset($groups_attributes[$key])) {
                    $group = $groups_attributes[$key]['group'];
                    if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                        $id_attribute_group = $groups_attributes[$key]['id'];
                        $obj = new Attribute();
                        // sets the proper id (corresponding to the right key)
                        $obj->id_attribute_group = $groups_attributes[$key]['id'];
                        $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                        $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            if (!$validateOnly) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            }
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                    }
                    $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                    $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                    $info['price'] = str_replace(',', '.', $info['price']);
                    $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                    $info['weight'] = str_replace(',', '.', $info['weight']);
                    $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null;
                    if (!Validate::isEan13($info['ean13'])) {
                        $this->warnings[] = sprintf($this->trans('EAN13 "%1s" has incorrect value for product with id %2d.', array(), 'Admin.Parameters.Notification'), $info['ean13'], $product->id);
                        $info['ean13'] = '';
                    }
                    if ($info['default_on'] && !$validateOnly) {
                        $product->deleteDefaultAttributes();
                    }
                    // if a reference is specified for this product, get the associate id_product_attribute to UPDATE
                    if (isset($info['reference']) && !empty($info['reference'])) {
                        $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference']));
                        // updates the attribute
                        if ($id_product_attribute && !$validateOnly) {
                            // gets all the combinations of this product
                            $attribute_combinations = $product->getAttributeCombinations($default_language);
                            foreach ($attribute_combinations as $attribute_combination) {
                                if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                    // FIXME: ~3s/declinaison
                                    $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list);
                                    $id_product_attribute_update = true;
                                    if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                        $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                                    }
                                    // until here
                                }
                            }
                        }
                    }
                    // if no attribute reference is specified, creates a new one
                    if (!$id_product_attribute && !$validateOnly) {
                        $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']);
                        if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                            $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                        }
                    }
                    // fills our attributes array, in order to add the attributes to the product_attribute afterwards
                    if (isset($attributes[$group . '_' . $attribute])) {
                        $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                    }
                    // after insertion, we clean attribute position and group attribute position
                    if (!$validateOnly) {
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
        }
        $product->checkDefaultAttributes();
        if (!$product->cache_default_attribute && !$validateOnly) {
            Product::updateDefaultAttribute($product->id);
        }
        if ($id_product_attribute) {
            if (!$validateOnly) {
                // now adds the attributes in the attribute_combination table
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')', false);
                }
            }
            // set advanced stock managment
            if (isset($info['advanced_stock_management'])) {
                if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!$validateOnly) {
                    $product->setAdvancedStockManagement($info['advanced_stock_management']);
                }
                // automaticly disable depends on stock, if a_s_m set to disabled
                if (!$validateOnly && StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                    StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                }
            }
            // Check if warehouse exists
            if (isset($info['warehouse']) && $info['warehouse']) {
                if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse is not set on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } else {
                    if (Warehouse::exists($info['warehouse'])) {
                        $warehouse_location_entity = new WarehouseProductLocation();
                        $warehouse_location_entity->id_product = $product->id;
                        $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                        $warehouse_location_entity->id_warehouse = $info['warehouse'];
                        if (!$validateOnly) {
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        }
                    } else {
                        $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                    }
                }
            }
            // stock available
            if (isset($info['depends_on_stock'])) {
                if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                    $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Notifications.Error'), $product->name[$default_language]);
                } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                } elseif (!$validateOnly) {
                    StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                }
                // This code allows us to set qty and disable depends on stock
                if (isset($info['quantity']) && (int) $info['quantity']) {
                    // if depends on stock and quantity, add quantity to stock
                    if ($info['depends_on_stock'] == 1) {
                        $stock_manager = StockManagerFactory::getManager();
                        $price = str_replace(',', '.', $info['wholesale_price']);
                        if ($price == 0) {
                            $price = 1.0E-6;
                        }
                        $price = round(floatval($price), 6);
                        $warehouse = new Warehouse($info['warehouse']);
                        if (!$validateOnly && $stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) {
                            StockAvailable::synchronize((int) $product->id);
                        }
                    } elseif (!$validateOnly) {
                        if ($shop_is_feature_active) {
                            foreach ($id_shop_list as $shop) {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                            }
                        } else {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                        }
                    }
                }
            } elseif (!$validateOnly) {
                // if not depends_on_stock set, use normal qty
                if ($shop_is_feature_active) {
                    foreach ($id_shop_list as $shop) {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                    }
                } else {
                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                }
            }
        }
    }
    public function productImport()
    {
        // do standard stuff; need to copy/paste
        // because silly PS does not allow to hook inside of the import loop...
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
        if (!Validate::isUnsignedId($id_lang)) {
            $id_lang = $default_language_id;
        }
        AdminImportController::setLocale();
        $shop_ids = Shop::getCompleteListOfShopsID();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) {
                $product = new Product((int) $info['id']);
            } elseif (Tools::getValue('match_ref') && array_key_exists('reference', $info)) {
                $datas = Db::getInstance()->getRow('
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($info['reference']) . '"
				');
                if (isset($datas['id_product']) && $datas['id_product']) {
                    $product = new Product((int) $datas['id_product']);
                } else {
                    $product = new Product();
                }
            } elseif (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                $product = new Product((int) $info['id']);
            } else {
                $product = new Product();
            }
            if (isset($product->id) && $product->id && Product::existsInDatabase((int) $product->id, 'product')) {
                $product->loadStockData();
                $category_data = Product::getProductCategories((int) $product->id);
                if (is_array($category_data)) {
                    foreach ($category_data as $tmp) {
                        if (!isset($product->category) || !$product->category || is_array($product->category)) {
                            $product->category[] = $tmp;
                        }
                    }
                }
            }
            AdminImportController::setEntityDefaultValues($product);
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
            /*
             * 2015-03-26 - JLE SPECIFIC :
             * Import language specific infos
             */
            foreach ($this->csv_translated_fields as $field) {
                foreach ($this->csv_languages as $lang) {
                    if (isset($info[$field . "_" . $lang])) {
                        $lang_id = Language::getIdByIso($lang);
                        $product->{$field}[$lang_id] = $info[$field . "_" . $lang];
                    }
                }
            }
            /*
             * END SPECIFIC
             */
            if (!Shop::isFeatureActive()) {
                $product->shop = 1;
            } elseif (!isset($product->shop) || empty($product->shop)) {
                $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            if (!Shop::isFeatureActive()) {
                $product->id_shop_default = 1;
            } else {
                $product->id_shop_default = (int) Context::getContext()->shop->id;
            }
            // link product to shops
            $product->id_shop_list = array();
            foreach (explode($this->multiple_value_separator, $product->shop) as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $product->id_shop_list[] = Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $product->id_shop_list[] = $shop;
                }
            }
            if ((int) $product->id_tax_rules_group != 0) {
                if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                    $address = $this->context->shop->getAddress();
                    $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group);
                    $product_tax_calculator = $tax_manager->getTaxCalculator();
                    $product->tax_rate = $product_tax_calculator->getTotalRate();
                } else {
                    $this->addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID. You first need to create a group with this ID.'));
                }
            }
            if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) {
                $product->id_manufacturer = (int) $product->manufacturer;
            } elseif (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) {
                if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                    $product->id_manufacturer = (int) $manufacturer;
                } else {
                    $manufacturer = new Manufacturer();
                    $manufacturer->name = $product->manufacturer;
                    if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) {
                        $product->id_manufacturer = (int) $manufacturer->id;
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int) $product->supplier)) {
                $product->id_supplier = (int) $product->supplier;
            } elseif (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) {
                if ($supplier = Supplier::getIdByName($product->supplier)) {
                    $product->id_supplier = (int) $supplier;
                } else {
                    $supplier = new Supplier();
                    $supplier->name = $product->supplier;
                    $supplier->active = true;
                    if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) {
                        $product->id_supplier = (int) $supplier->id;
                        $supplier->associateTo($product->id_shop_list);
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->price_tex) && !isset($product->price_tin)) {
                $product->price = $product->price_tex;
            } elseif (isset($product->price_tin) && !isset($product->price_tex)) {
                $product->price = $product->price_tin;
                // If a tax is already included in price, withdraw it from price
                if ($product->tax_rate) {
                    $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
                }
            } elseif (isset($product->price_tin) && isset($product->price_tex)) {
                $product->price = $product->price_tex;
            }
            if (!Configuration::get('PS_USE_ECOTAX')) {
                $product->ecotax = 0;
            }
            if (isset($product->category) && is_array($product->category) && count($product->category)) {
                $product->id_category = array();
                // Reset default values array
                foreach ($product->category as $value) {
                    if (is_numeric($value)) {
                        if (Category::categoryExists((int) $value)) {
                            $product->id_category[] = (int) $value;
                        } else {
                            $category_to_create = new Category();
                            $category_to_create->id = (int) $value;
                            $category_to_create->name = AdminImportController::createMultiLangField($value);
                            $category_to_create->active = 1;
                            $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                            // Default parent is home for unknown category to create
                            $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]);
                            $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                            if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) {
                                $product->id_category[] = (int) $category_to_create->id;
                            } else {
                                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    } elseif (is_string($value) && !empty($value)) {
                        $category = Category::searchByPath($default_language_id, trim($value), $this, 'productImportCreateCat');
                        if ($category['id_category']) {
                            $product->id_category[] = (int) $category['id_category'];
                        } else {
                            $this->errors[] = sprintf(Tools::displayError('%1$s cannot be saved'), trim($value));
                        }
                    }
                }
                $product->id_category = array_values(array_unique($product->id_category));
            }
            if (!isset($product->id_category_default) || !$product->id_category_default) {
                $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : (int) Configuration::get('PS_HOME_CATEGORY');
            }
            $link_rewrite = is_array($product->link_rewrite) && isset($product->link_rewrite[$id_lang]) ? trim($product->link_rewrite[$id_lang]) : '';
            $valid_link = Validate::isLinkRewrite($link_rewrite);
            if (isset($product->link_rewrite[$id_lang]) && empty($product->link_rewrite[$id_lang]) || !$valid_link) {
                $link_rewrite = Tools::link_rewrite($product->name[$id_lang]);
                if ($link_rewrite == '') {
                    $link_rewrite = 'friendly-url-autogeneration-failed';
                }
            }
            if (!$valid_link) {
                $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite);
            }
            if (!(Tools::getValue('match_ref') || Tools::getValue('forceIDs')) || !(is_array($product->link_rewrite) && count($product->link_rewrite) && !empty($product->link_rewrite[$id_lang]))) {
                $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
            }
            // replace the value of separator by coma
            if ($this->multiple_value_separator != ',') {
                if (is_array($product->meta_keywords)) {
                    foreach ($product->meta_keywords as &$meta_keyword) {
                        if (!empty($meta_keyword)) {
                            $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword);
                        }
                    }
                }
            }
            // Convert comma into dot for all floating values
            foreach (Product::$definition['fields'] as $key => $array) {
                if ($array['type'] == Product::TYPE_FLOAT) {
                    $product->{$key} = str_replace(',', '.', $product->{$key});
                }
            }
            // Indexation is already 0 if it's a new product, but not if it's an update
            $product->indexed = 0;
            $res = false;
            $field_error = $product->validateFields(UNFRIENDLY_ERROR, true);
            $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
            if ($field_error === true && $lang_field_error === true) {
                // check quantity
                if ($product->quantity == null) {
                    $product->quantity = 0;
                }
                // If match ref is specified && ref product && ref product already in base, trying to update
                if (Tools::getValue('match_ref') && $product->reference && $product->existsRefInDatabase($product->reference)) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`, p.`id_product`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`reference` = "' . pSQL($product->reference) . '"
					');
                    $product->id = (int) $datas['id_product'];
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                } elseif ($product->id && Product::existsInDatabase((int) $product->id, 'product')) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`id_product` = ' . (int) $product->id);
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                }
                // If no id_product or update failed
                $product->force_id = (bool) Tools::getValue('forceIDs');
                if (!$res) {
                    if (isset($product->date_add) && $product->date_add != '') {
                        $res = $product->add(false);
                    } else {
                        $res = $product->add();
                    }
                }
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    StockAvailable::setProductOutOfStock((int) $product->id, 1);
                } else {
                    StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock);
                }
            }
            $shops = array();
            $product_shop = explode($this->multiple_value_separator, $product->shop);
            foreach ($product_shop as $shop) {
                if (empty($shop)) {
                    continue;
                }
                $shop = trim($shop);
                if (!empty($shop) && !is_numeric($shop)) {
                    $shop = Shop::getIdByName($shop);
                }
                if (in_array($shop, $shop_ids)) {
                    $shops[] = $shop;
                } else {
                    $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid'));
                }
            }
            if (empty($shops)) {
                $shops = Shop::getContextListShopID();
            }
            // If both failed, mysql error
            if (!$res) {
                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
            } else {
                // Product supplier
                if (isset($product->id) && $product->id && isset($product->id_supplier) && property_exists($product, 'supplier_reference')) {
                    $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                    if ($id_product_supplier) {
                        $product_supplier = new ProductSupplier($id_product_supplier);
                    } else {
                        $product_supplier = new ProductSupplier();
                    }
                    $product_supplier->id_product = (int) $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = (int) $product->id_supplier;
                    $product_supplier->product_supplier_price_te = $product->wholesale_price;
                    $product_supplier->product_supplier_reference = $product->supplier_reference;
                    $product_supplier->save();
                }
                // SpecificPrice (only the basic reduction feature is supported by the import)
                if (!Shop::isFeatureActive()) {
                    $info['shop'] = 1;
                } elseif (!isset($info['shop']) || empty($info['shop'])) {
                    $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
                }
                // Get shops for each attributes
                $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
                $id_shop_list = array();
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = (int) Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
                if (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                    foreach ($id_shop_list as $id_shop) {
                        $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, 0, 1, 0, 0, 0, 0);
                        if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                            $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                        } else {
                            $specific_price = new SpecificPrice();
                        }
                        $specific_price->id_product = (int) $product->id;
                        $specific_price->id_specific_price_rule = 0;
                        $specific_price->id_shop = $id_shop;
                        $specific_price->id_currency = 0;
                        $specific_price->id_country = 0;
                        $specific_price->id_group = 0;
                        $specific_price->price = -1;
                        $specific_price->id_customer = 0;
                        $specific_price->from_quantity = 1;
                        $specific_price->reduction = isset($info['reduction_price']) && $info['reduction_price'] ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                        $specific_price->reduction_type = isset($info['reduction_price']) && $info['reduction_price'] ? 'amount' : 'percentage';
                        $specific_price->from = isset($info['reduction_from']) && Validate::isDate($info['reduction_from']) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                        $specific_price->to = isset($info['reduction_to']) && Validate::isDate($info['reduction_to']) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                        if (!$specific_price->save()) {
                            $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                        }
                    }
                }
                /*
                 * 2015-03-26 - JLE SPECIFIC :
                 * Import group specific prices
                 */
                foreach ($this->groups as $group) {
                    if (isset($info['group' . $group['id_group'] . "_price"])) {
                        //	$group_price = str_replace(',', '.', $info['group'.$group['id_group']."_price"]);
                        $group_price = (double) str_replace(',', '.', trim($info['group' . $group['id_group'] . "_price"]));
                        foreach ($id_shop_list as $id_shop) {
                            $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, $group['id_group'], 1, 0, 0, 0, 0);
                            if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                                $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                            } else {
                                $specific_price = new SpecificPrice();
                            }
                            $specific_price->id_product = (int) $product->id;
                            $specific_price->id_specific_price_rule = 0;
                            $specific_price->id_shop = $id_shop;
                            $specific_price->id_currency = 0;
                            $specific_price->id_country = 0;
                            $specific_price->id_group = $group['id_group'];
                            $specific_price->price = $group_price;
                            $specific_price->id_customer = 0;
                            $specific_price->from_quantity = 1;
                            $specific_price->reduction = 0;
                            $specific_price->reduction_type = 'amount';
                            $specific_price->from = '0000-00-00 00:00:00';
                            $specific_price->to = '0000-00-00 00:00:00';
                            if (!$specific_price->save()) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                            }
                        }
                    }
                }
                /*
                 * END SPECIFIC 2015-03-26
                 */
                if (isset($product->tags) && !empty($product->tags)) {
                    if (isset($product->id) && $product->id) {
                        $tags = Tag::getProductTags($product->id);
                        if (is_array($tags) && count($tags)) {
                            if (!empty($product->tags)) {
                                $product->tags = explode($this->multiple_value_separator, $product->tags);
                            }
                            if (is_array($product->tags) && count($product->tags)) {
                                foreach ($product->tags as $key => $tag) {
                                    if (!empty($tag)) {
                                        $product->tags[$key] = trim($tag);
                                    }
                                }
                                $tags[$id_lang] = $product->tags;
                                $product->tags = $tags;
                            }
                        }
                    }
                    // Delete tags for this id product, for no duplicating error
                    Tag::deleteTagsForProduct($product->id);
                    if (!is_array($product->tags) && !empty($product->tags)) {
                        $product->tags = AdminImportController::createMultiLangField($product->tags);
                        foreach ($product->tags as $key => $tags) {
                            $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid'));
                                break;
                            }
                        }
                    } else {
                        foreach ($product->tags as $key => $tags) {
                            $str = '';
                            foreach ($tags as $one_tag) {
                                $str .= $one_tag . $this->multiple_value_separator;
                            }
                            $str = rtrim($str, $this->multiple_value_separator);
                            $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), (int) $product->id, 'Invalid tag(s) (' . $str . ')');
                                break;
                            }
                        }
                    }
                }
                //delete existing images if "delete_existing_images" is set to 1
                if (isset($product->delete_existing_images)) {
                    if ((bool) $product->delete_existing_images) {
                        $product->deleteImages();
                    }
                }
                if (isset($product->image) && is_array($product->image) && count($product->image)) {
                    $product_has_images = (bool) Image::getImages($this->context->language->id, (int) $product->id);
                    foreach ($product->image as $key => $url) {
                        $url = trim($url);
                        $error = false;
                        if (!empty($url)) {
                            $url = str_replace(' ', '%20', $url);
                            $image = new Image();
                            $image->id_product = (int) $product->id;
                            $image->position = Image::getHighestPosition($product->id) + 1;
                            $image->cover = !$key && !$product_has_images ? true : false;
                            // file_exists doesn't work with HTTP protocol
                            if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) {
                                // associate image to selected shops
                                $image->associateTo($shops);
                                if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                                    $image->delete();
                                    $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                                }
                            } else {
                                $error = true;
                            }
                        } else {
                            $error = true;
                        }
                        if ($error) {
                            $this->warnings[] = sprintf(Tools::displayError('Product #%1$d: the picture (%2$s) cannot be saved.'), $image->id_product, $url);
                        }
                    }
                }
                if (isset($product->id_category) && is_array($product->id_category)) {
                    $product->updateCategories(array_map('intval', $product->id_category));
                }
                $product->checkDefaultAttributes();
                if (!$product->cache_default_attribute) {
                    Product::updateDefaultAttribute($product->id);
                }
                // Features import
                $features = get_object_vars($product);
                if (isset($features['features']) && !empty($features['features'])) {
                    foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) {
                        if (empty($single_feature)) {
                            continue;
                        }
                        $tab_feature = explode(':', $single_feature);
                        $feature_name = isset($tab_feature[0]) ? trim($tab_feature[0]) : '';
                        $feature_value = isset($tab_feature[1]) ? trim($tab_feature[1]) : '';
                        $position = isset($tab_feature[2]) ? (int) $tab_feature[2] - 1 : false;
                        $custom = isset($tab_feature[3]) ? (int) $tab_feature[3] : false;
                        if (!empty($feature_name) && !empty($feature_value)) {
                            $id_feature = (int) Feature::addFeatureImport($feature_name, $position);
                            $id_product = null;
                            if (Tools::getValue('forceIDs') || Tools::getValue('match_ref')) {
                                $id_product = (int) $product->id;
                            }
                            $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
                            Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                        }
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
                // set advanced stock managment
                if (isset($product->advanced_stock_management)) {
                    if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product %1$s '), $product->name[$default_language_id]);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        $product->setAdvancedStockManagement($product->advanced_stock_management);
                    }
                    // automaticly disable depends on stock, if a_s_m set to disabled
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0);
                    }
                }
                // Check if warehouse exists
                if (isset($product->warehouse) && $product->warehouse) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        if (Warehouse::exists($product->warehouse)) {
                            // Get already associated warehouses
                            $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                            // Delete any entry in warehouse for this product
                            foreach ($associated_warehouses_collection as $awc) {
                                $awc->delete();
                            }
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = 0;
                            $warehouse_location_entity->id_warehouse = $product->warehouse;
                            if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language_id]);
                        }
                    }
                }
                // stock available
                if (isset($product->depends_on_stock)) {
                    if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, cannot set "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                    }
                    // This code allows us to set qty and disable depends on stock
                    if (isset($product->quantity) && (int) $product->quantity) {
                        // if depends on stock and quantity, add quantity to stock
                        if ($product->depends_on_stock == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $product->wholesale_price);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round(floatval($price), 6);
                            $warehouse = new Warehouse($product->warehouse);
                            if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, (int) $product->quantity, 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($shops as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
    public function attributeImport()
    {
        $default_language = Configuration::get('PS_LANG_DEFAULT');
        $groups = array();
        foreach (AttributeGroup::getAttributesGroups($default_language) as $group) {
            $groups[$group['name']] = (int) $group['id_attribute_group'];
        }
        $attributes = array();
        foreach (Attribute::getAttributes($default_language) as $attribute) {
            $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute'];
        }
        $this->receiveTab();
        $handle = $this->openCsvFile();
        AdminImportController::setLocale();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (count($line) == 1 && empty($line[0])) {
                continue;
            }
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            $info = array_map('trim', $info);
            AdminImportController::setDefaultValues($info);
            if (!Shop::isFeatureActive()) {
                $info['shop'] = 1;
            } elseif (!isset($info['shop']) || empty($info['shop'])) {
                $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            // Get shops for each attributes
            $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
            $id_shop_list = array();
            if (is_array($info['shop']) && count($info['shop'])) {
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
            }
            if (isset($info['id_product'])) {
                $product = new Product((int) $info['id_product'], false, $default_language);
            } else {
                continue;
            }
            $id_image = null;
            //delete existing images if "delete_existing_images" is set to 1
            if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) {
                $product->deleteImages();
                $this->cache_image_deleted[(int) $product->id] = true;
            }
            if (isset($info['image_url']) && $info['image_url']) {
                $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                $url = $info['image_url'];
                $image = new Image();
                $image->id_product = (int) $product->id;
                $image->position = Image::getHighestPosition($product->id) + 1;
                $image->cover = !$product_has_images ? true : false;
                $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                if ($field_error === true && $lang_field_error === true && $image->add()) {
                    $image->associateTo($id_shop_list);
                    if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                        $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                        $image->delete();
                    } else {
                        $id_image = array($image->id);
                    }
                } else {
                    $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                    $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                }
            } elseif (isset($info['image_position']) && $info['image_position']) {
                $images = $product->getImages($default_language);
                if ($images) {
                    foreach ($images as $row) {
                        if ($row['position'] == (int) $info['image_position']) {
                            $id_image = array($row['id_image']);
                            break;
                        }
                    }
                }
                if (!$id_image) {
                    $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']);
                }
            }
            $id_attribute_group = 0;
            // groups
            $groups_attributes = array();
            if (isset($info['group'])) {
                foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                    if (empty($group)) {
                        continue;
                    }
                    $tab_group = explode(':', $group);
                    $group = trim($tab_group[0]);
                    if (!isset($tab_group[1])) {
                        $type = 'select';
                    } else {
                        $type = trim($tab_group[1]);
                    }
                    // sets group
                    $groups_attributes[$key]['group'] = $group;
                    // if position is filled
                    if (isset($tab_group[2])) {
                        $position = trim($tab_group[2]);
                    } else {
                        $position = false;
                    }
                    if (!isset($groups[$group])) {
                        $obj = new AttributeGroup();
                        $obj->is_color_group = false;
                        $obj->group_type = pSQL($type);
                        $obj->name[$default_language] = $group;
                        $obj->public_name[$default_language] = $group;
                        $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            $obj->add();
                            $obj->associateTo($id_shop_list);
                            $groups[$group] = $obj->id;
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                        // fills groups attributes
                        $id_attribute_group = $obj->id;
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    } else {
                        $id_attribute_group = $groups[$group];
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    }
                }
            }
            // inits attribute
            $id_product_attribute = 0;
            $id_product_attribute_update = false;
            $attributes_to_add = array();
            // for each attribute
            if (isset($info['attribute'])) {
                foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                    if (empty($attribute)) {
                        continue;
                    }
                    $tab_attribute = explode(':', $attribute);
                    $attribute = trim($tab_attribute[0]);
                    // if position is filled
                    if (isset($tab_attribute[1])) {
                        $position = trim($tab_attribute[1]);
                    } else {
                        $position = false;
                    }
                    if (isset($groups_attributes[$key])) {
                        $group = $groups_attributes[$key]['group'];
                        if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                            $id_attribute_group = $groups_attributes[$key]['id'];
                            $obj = new Attribute();
                            // sets the proper id (corresponding to the right key)
                            $obj->id_attribute_group = $groups_attributes[$key]['id'];
                            $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                            $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                            if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            } else {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                            }
                        }
                        $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                        $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                        $info['price'] = str_replace(',', '.', $info['price']);
                        $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                        $info['weight'] = str_replace(',', '.', $info['weight']);
                        // if a reference is specified for this product, get the associate id_product_attribute to UPDATE
                        if (isset($info['reference']) && !empty($info['reference'])) {
                            $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference']));
                            // updates the attribute
                            if ($id_product_attribute) {
                                // gets all the combinations of this product
                                $attribute_combinations = $product->getAttributeCombinations($default_language);
                                foreach ($attribute_combinations as $attribute_combination) {
                                    if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                        $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], 0, null, $id_shop_list);
                                        $id_product_attribute_update = true;
                                        if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                            $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                                        }
                                    }
                                }
                            }
                        }
                        // if no attribute reference is specified, creates a new one
                        if (!$id_product_attribute) {
                            $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list);
                            if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                            }
                        }
                        // fills our attributes array, in order to add the attributes to the product_attribute afterwards
                        if (isset($attributes[$group . '_' . $attribute])) {
                            $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                        }
                        // after insertion, we clean attribute position and group attribute position
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
            $product->checkDefaultAttributes();
            if (!$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            if ($id_product_attribute) {
                // now adds the attributes in the attribute_combination table
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')');
                }
                // set advanced stock managment
                if (isset($info['advanced_stock_management'])) {
                    if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product with id %s '), $product->id);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, can not enable on product with id %s '), $product->id);
                    } else {
                        $product->setAdvancedStockManagement($info['advanced_stock_management']);
                    }
                    // automaticly disable depends on stock, if a_s_m set to disabled
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                    }
                }
                // Check if warehouse exists
                if ($info['warehouse']) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product with id %s '), $product->id);
                    } else {
                        if (Warehouse::exists($info['warehouse'])) {
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                            $warehouse_location_entity->id_warehouse = $info['warehouse'];
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s '), $product->name[$default_language_id]);
                        }
                    }
                }
                // stock available
                if (isset($info['depends_on_stock'])) {
                    if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for depends on stock for product %1$s '), $product->name[$default_language_id]);
                    } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, can not set depends on stock %1$s '), $product->name[$default_language_id]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                    }
                    // This code allows us to set qty and disable depends on stock
                    if (isset($info['quantity']) && $info['depends_on_stock'] == 0) {
                        if (Shop::isFeatureActive()) {
                            foreach ($shops as $shop) {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                            }
                        } else {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                        }
                    } elseif (isset($info['quantity']) && $info['depends_on_stock'] == 1) {
                        // add stock
                        $stock_manager = StockManagerFactory::getManager();
                        $price = str_replace(',', '.', $info['wholesale_price']);
                        if ($price == 0) {
                            $price = 1.0E-6;
                        }
                        $price = round(floatval($price), 6);
                        $warehouse = new Warehouse($info['warehouse']);
                        if ($stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) {
                            StockAvailable::synchronize((int) $product->id);
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
Exemple #10
0
 private function upsert($line)
 {
     $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
     $product = new Product($product);
     $product->reference = $line['reference'];
     $product->name = array('1' => $line['name'], '2' => $line['name'], '3' => $line['name']);
     $product->description = array('1' => $line['description'], '2' => $line['description'], '3' => $line['description']);
     $product->description_short = array('1' => $line['description_short'], '2' => $line['description_short'], '3' => $line['description_short']);
     $product->link_rewrite = array('1' => Tools::link_rewrite($line['name']), '2' => Tools::link_rewrite($line['name']), '3' => Tools::link_rewrite($line['name']));
     $product->available_now = array('1' => "Есть в наличии", '2' => "Есть в наличии", '3' => "Есть в наличии");
     $product->id_category_default = $line['category'];
     $product->quantity = (int) $line['count'];
     $product->advanced_stock_management = 1;
     //использовать Advanced Stock management
     $product->depends_on_stock = 1;
     //1 - доступное количество на основе ASM. 0 - указывается вручную
     $product->out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)
     $product->price = $line['price'];
     $product->weight = $line['weight'] / 1000;
     $product->id_tax_rules_group = $line['id_tax'];
     $product->save();
     $product->updateCategories(array($line['category']));
     $product->deleteFeatures();
     if ($line['author']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 9, $id_feature_value);
     }
     if ($line['year']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 10, $id_feature_value);
     }
     if ($line['paperback']) {
         if ($line['paperback'] == 1) {
             $id_feature_value = 1;
         } else {
             $id_feature_value = 2;
         }
         //$id_feature_value = FeatureValue::addFeatureValueImport(11, $line['paperback'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 11, $id_feature_value);
         //1 - id значения "твёрдый переплёт" у харакатеристики "Переплёт", 149226 - мягкая обложка
     }
     if ($line['pages']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 12, $id_feature_value);
     }
     /*
     if ($line['weight']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 4, $id_feature_value);
     }
     */
     if ($line['isbn']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 13, $id_feature_value);
     }
     if ($line['publishing']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 14, $id_feature_value);
     }
     $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
     $location = new WarehouseProductLocation($location);
     $location->id_product = $product->id;
     $location->id_product_attribute = 0;
     $location->id_warehouse = $line['warehouse'];
     $location->save();
     /*
     $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
     $stock = new Stock($stock);
     $stock->id_product = $product->id;
     $stock->id_product_attribute = 0;
     $stock->id_warehouse = $line['warehouse'];
     $stock->physical_quantity = $line['count'];
     $stock->usable_quantity = $line['count'];
     $stock->price_te = 0;
     $stock->save();
     */
     //установить зависимость количества товара от остатка на складе для каждого магазинеа
     //исходим из того, что в настройках Мультимагазина остаток НЕ единый на все магазины
     $id_product = $product->id;
     $depends_on_stock = true;
     $out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (ставь 1, т.к. 2 (как в Preferences) не дает заказать товар на сайте)
     for ($id_shop = 1; $id_shop <= 4; $id_shop++) {
         StockAvailable::setProductDependsOnStock($id_product, $depends_on_stock, $id_shop);
     }
     //разрешить или запретить продажу товара без остатка
     /*  для магазина 2,3 запретить продажу, если нет в наличии. out_of_stock = 0
             2   Second shop Gelikon 
             3   First shop Gelikon
         */
     $out_of_stock = 0;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 2);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 3);
     /*
         Для online и заказов по телефону разрешить заказ товара, которого нет в наличии
         1 Gelikon DE online
         4 Заказы по телефону
     */
     $out_of_stock = 1;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 1);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 4);
     //Добавить партию товара на склад с записью в журнал движения товаров
     $id_product = $product->id;
     $id_product_attribute = 0;
     $id_stock_mvt_reason = 1;
     $price = 1;
     $id_currency = 1;
     $id_warehouse = $line['warehouse'];
     $warehouse = new Warehouse($id_warehouse);
     $stock_manager = StockManagerFactory::getManager();
     if ($line['count'] != 0) {
         //echo "добавляем товар ";
         $is_usable = true;
         $quantity = $line['count'];
         // add stock
         if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $is_usable)) {
             StockAvailable::synchronize($id_product);
         } else {
             $errors[] = Tools::displayError('An error occurred. No stock was added.');
         }
     }
     /*
             $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
             $available = new StockAvailable($available);
             $available->id_product = $product->id;
             $available->id_product_attribute = 0;
             //$available->id_shop = Context::getContext()->shop->id;
             $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
             $available->save();
     
             StockAvailable::setProductDependsOnStock($product->id, true, null);
             StockAvailable::setProductOutOfStock($product->id, 1, null); //allow
     */
     while (strlen($line['reference']) < 9) {
         $line['reference'] = '0' . $line['reference'];
     }
     if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
         $product->deleteImages();
         $image = new Image();
         $image->id_product = $product->id;
         $image->cover = 1;
         $image->position = 0;
         $image->save();
         $name = $image->getPathForCreation();
         copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '.' . $image->image_format);
         $types = ImageType::getImagesTypes('products');
         foreach ($types as $type) {
             ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
         }
     }
     /*
             Db::getInstance()->update('stock_available', array(
       'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
        'out_of_stock' => (int)1, //1-allow
             ), 'id_product='.$product->id.'');
     $affrows = Db::getInstance()->Affected_Rows();
     var_dump($affrows);
     */
     //var_dump($product->reference);
     //echo "<br/><br/><br/><br/>";
 }
    public function attributeImport()
    {
        $default_language = Configuration::get('PS_LANG_DEFAULT');
        $groups = array();
        foreach (AttributeGroup::getAttributesGroups($default_language) as $group) {
            $groups[$group['name']] = (int) $group['id_attribute_group'];
        }
        $attributes = array();
        foreach (Attribute::getAttributes($default_language) as $attribute) {
            $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute'];
        }
        $this->receiveTab();
        $handle = $this->openCsvFile();
        AdminImportController::setLocale();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (count($line) == 1 && empty($line[0])) {
                continue;
            }
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            $info = array_map('trim', $info);
            if (self::ignoreRow($info)) {
                continue;
            }
            AdminImportController::setDefaultValues($info);
            if (!Shop::isFeatureActive()) {
                $info['shop'] = 1;
            } elseif (!isset($info['shop']) || empty($info['shop'])) {
                $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
            $id_shop_list = array();
            if (is_array($info['shop']) && count($info['shop'])) {
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
            }
            if (isset($info['id_product']) && is_string($info['id_product'])) {
                $prod = self::findProductByName($default_language, $info['id_product']);
                if ($prod['id_product']) {
                    $info['id_product'] = $prod['id_product'];
                } else {
                    unset($info['id_product']);
                }
            }
            if (!isset($info['id_product']) && Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) {
                $datas = Db::getInstance()->getRow('
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($info['product_reference']) . '"
				');
                if (isset($datas['id_product']) && $datas['id_product']) {
                    $info['id_product'] = $datas['id_product'];
                }
            }
            if (isset($info['id_product'])) {
                $product = new Product((int) $info['id_product'], false, $default_language);
            } else {
                continue;
            }
            $id_image = array();
            if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) {
                $product->deleteImages();
                $this->cache_image_deleted[(int) $product->id] = true;
            }
            if (isset($info['image_url']) && $info['image_url']) {
                $info['image_url'] = explode(',', $info['image_url']);
                if (is_array($info['image_url']) && count($info['image_url'])) {
                    foreach ($info['image_url'] as $url) {
                        $url = trim($url);
                        $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                        $image = new Image();
                        $image->id_product = (int) $product->id;
                        $image->position = Image::getHighestPosition($product->id) + 1;
                        $image->cover = !$product_has_images ? true : false;
                        $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                        $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                        if ($field_error === true && $lang_field_error === true && $image->add()) {
                            $image->associateTo($id_shop_list);
                            if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                                $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                                $image->delete();
                            } else {
                                $id_image[] = (int) $image->id;
                            }
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                        }
                    }
                }
            } elseif (isset($info['image_position']) && $info['image_position']) {
                $info['image_position'] = explode(',', $info['image_position']);
                if (is_array($info['image_position']) && count($info['image_position'])) {
                    foreach ($info['image_position'] as $position) {
                        $images = $product->getImages($default_language);
                        if ($images) {
                            foreach ($images as $row) {
                                if ($row['position'] == (int) $position) {
                                    $id_image[] = (int) $row['id_image'];
                                    break;
                                }
                            }
                        }
                        if (empty($id_image)) {
                            $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $position);
                        }
                    }
                }
            }
            $id_attribute_group = 0;
            $groups_attributes = array();
            if (isset($info['group'])) {
                foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                    if (empty($group)) {
                        continue;
                    }
                    $tab_group = explode(':', $group);
                    $group = trim($tab_group[0]);
                    if (!isset($tab_group[1])) {
                        $type = 'select';
                    } else {
                        $type = trim($tab_group[1]);
                    }
                    $groups_attributes[$key]['group'] = $group;
                    if (isset($tab_group[2])) {
                        $position = trim($tab_group[2]);
                    } else {
                        $position = false;
                    }
                    if (!isset($groups[$group])) {
                        $obj = new AttributeGroup();
                        $obj->is_color_group = false;
                        $obj->group_type = pSQL($type);
                        $obj->name[$default_language] = $group;
                        $obj->public_name[$default_language] = $group;
                        $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            $obj->add();
                            $obj->associateTo($id_shop_list);
                            $groups[$group] = $obj->id;
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                        $id_attribute_group = $obj->id;
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    } else {
                        $id_attribute_group = $groups[$group];
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    }
                }
            }
            $id_product_attribute = 0;
            $id_product_attribute_update = false;
            $attributes_to_add = array();
            if (isset($info['attribute'])) {
                foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                    if (empty($attribute)) {
                        continue;
                    }
                    $tab_attribute = explode(':', $attribute);
                    $attribute = trim($tab_attribute[0]);
                    if (isset($tab_attribute[1])) {
                        $position = trim($tab_attribute[1]);
                    } else {
                        $position = false;
                    }
                    if (isset($groups_attributes[$key])) {
                        $group = $groups_attributes[$key]['group'];
                        if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                            $id_attribute_group = $groups_attributes[$key]['id'];
                            $obj = new Attribute();
                            $obj->id_attribute_group = $groups_attributes[$key]['id'];
                            $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                            $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                            if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            } else {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                            }
                        }
                        $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                        $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                        $info['price'] = str_replace(',', '.', $info['price']);
                        $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                        $info['weight'] = str_replace(',', '.', $info['weight']);
                        $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null;
                        if (!Validate::isEan13($info['ean13'])) {
                            $this->warnings[] = sprintf(Tools::displayError('EAN13 "%1s" has incorrect value for product with id %2d.'), $info['ean13'], $product->id);
                            $info['ean13'] = '';
                        }
                        if ($info['default_on']) {
                            $product->deleteDefaultAttributes();
                        }
                        if (isset($info['reference']) && !empty($info['reference'])) {
                            $id_product_attribute = Combination::getIdByReference($product->id, (string) $info['reference']);
                            if ($id_product_attribute) {
                                $attribute_combinations = $product->getAttributeCombinations($default_language);
                                foreach ($attribute_combinations as $attribute_combination) {
                                    if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                        $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, (string) $info['reference'], (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list);
                                        $id_product_attribute_update = true;
                                        if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                            $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                                        }
                                    }
                                }
                            }
                        }
                        if (!$id_product_attribute) {
                            $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, (string) $info['reference'], 0, (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']);
                            if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                            }
                        }
                        if (isset($attributes[$group . '_' . $attribute])) {
                            $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                        }
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
            $product->checkDefaultAttributes();
            if (!$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            if ($id_product_attribute) {
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')');
                }
                if (isset($info['advanced_stock_management'])) {
                    if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product with id %d.'), $product->id);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product with id %d.'), $product->id);
                    } else {
                        $product->setAdvancedStockManagement($info['advanced_stock_management']);
                    }
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                    }
                }
                if (isset($info['warehouse']) && $info['warehouse']) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse is not set on product with id %d.'), $product->id);
                    } else {
                        if (Warehouse::exists($info['warehouse'])) {
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                            $warehouse_location_entity->id_warehouse = $info['warehouse'];
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language]);
                        }
                    }
                }
                if (isset($info['depends_on_stock'])) {
                    if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for depends on stock for product %1$s '), $product->name[$default_language]);
                    } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot set depends on stock %1$s '), $product->name[$default_language]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                    }
                    if (isset($info['quantity']) && $info['quantity']) {
                        if ($info['depends_on_stock'] == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $info['wholesale_price']);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round((double) $price, 6);
                            $warehouse = new Warehouse($info['warehouse']);
                            if ($stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, $info['quantity'], 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($id_shop_list as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($id_shop_list as $shop) {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
Exemple #12
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = $line['count'];
        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 70);
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        $available->id_shop = Context::getContext()->shop->id;
        $available->quantity = $line['count'];
        $available->save();

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }
    }
Exemple #13
0
 /**
  * Post treatment for warehouses
  */
 public function processWarehouses()
 {
     $app = JFactory::getApplication();
     $product = new JeproshopProductModelProduct((int) $app->input->get('product_id'));
     if ((int) $app->input->get('warehouse_loaded') === 1 && JeproshopTools::isLoadedObject($product, 'product_id')) {
         // Get all id_product_attribute
         $warehouse_attributes = $product->getAttributesResume($this->context->language->lang_id);
         if (empty($warehouse_attributes)) {
             $attribute = new JObject();
             $attribute->set('product_attribute_id', 0);
             $attribute->set('attribute_designation', '');
             $warehouse_attributes[] = $attribute;
         }
         // Get all available warehouses
         $warehouses = JeproshopWarehouseModelWarehouse::getWarehouses(true);
         // Get already associated warehouses
         $associated_warehouses_collection = JeproshopWarehouseProductLocationModelWarehouseProductLocation::getCollection($product->product_id);
         $elements_to_manage = array();
         // get form information
         foreach ($warehouse_attributes as $attribute) {
             foreach ($warehouses as $warehouse) {
                 $key = $warehouse->warehouse_id . '_' . $product->product_id . '_' . $attribute->product_attribute_id;
                 // get elements to manage
                 if ($app->input->get('check_warehouse_' . $key)) {
                     $location = $app->input->get('location_warehouse_' . $key, '');
                     $elements_to_manage[$key] = $location;
                 }
             }
         }
         // Delete entry if necessary
         foreach ($associated_warehouses_collection as $awc) {
             if (!array_key_exists($awc->warehouse_id . '_' . $awc->product_id . '_' . $awc->product_attribute_id, $elements_to_manage)) {
                 $awc->delete();
             }
         }
         // Manage locations
         foreach ($elements_to_manage as $key => $location) {
             $params = explode('_', $key);
             $wpl_id = (int) JeproshopWarehouseProductLocationModelWarehouseProductLocation::getIdByProductAndWarehouse((int) $params[1], (int) $params[2], (int) $params[0]);
             if (empty($wpl_id)) {
                 //create new record
                 $warehouse_location_entity = new JeproshopWarehouseProductLocationModelWarehouseProductLocation();
                 $warehouse_location_entity->product_id = (int) $params[1];
                 $warehouse_location_entity->product_attribute_id = (int) $params[2];
                 $warehouse_location_entity->warehouse_id = (int) $params[0];
                 $warehouse_location_entity->location = JFactory::getDBO()->query($location);
                 $warehouse_location_entity->save();
             } else {
                 $warehouse_location_entity = new WarehouseProductLocation((int) $wpl_id);
                 $location = $location;
                 if ($location != $warehouse_location_entity->location) {
                     $warehouse_location_entity->location = $location;
                     $warehouse_location_entity->update();
                 }
             }
         }
         JeproshopStockAvailableModelStockAvailable::synchronize((int) $product->product_id);
     }
 }
 public function postProcess()
 {
     $this->adminControllerPostProcess();
     if (Tools::isSubmit('addStock') && !($this->tabAccess['add'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to add stock.');
     }
     if (Tools::isSubmit('removeStock') && !($this->tabAccess['delete'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to delete stock');
     }
     if (Tools::isSubmit('transferStock') && !($this->tabAccess['edit'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to transfer stock.');
     }
     if (count($this->errors)) {
         return;
     }
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') || Tools::isSubmit('transferstock')) && Tools::isSubmit('is_post')) {
         $id_product = (int) Tools::getValue('id_product', 0);
         if ($id_product <= 0) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         $id_product_attribute = (int) Tools::getValue('id_product_attribute', 0);
         $check = Tools::getValue('check', '');
         $check_valid = md5(_COOKIE_KEY_ . $id_product . $id_product_attribute);
         if ($check != $check_valid) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         $quantity = Tools::getValue('quantity', 0);
         $quantity = PP::normalizeProductQty($quantity, $id_product);
         if (!is_numeric($quantity) || $quantity <= 0) {
             $this->errors[] = Tools::displayError('The quantity value is not valid.');
         }
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         $redirect = self::$currentIndex . '&token=' . $token;
     }
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock')) && Tools::isSubmit('is_post')) {
         $id_warehouse = (int) Tools::getValue('id_warehouse', 0);
         if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) {
             $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
         }
         $id_stock_mvt_reason = (int) Tools::getValue('id_stock_mvt_reason', 0);
         if ($id_stock_mvt_reason <= 0 || !StockMvtReason::exists($id_stock_mvt_reason)) {
             $this->errors[] = Tools::displayError('The reason is not valid.');
         }
         $usable = Tools::getValue('usable', null);
         if (is_null($usable)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity is usable for sale on shops or not.');
         }
         $usable = (bool) $usable;
     }
     if (Tools::isSubmit('addstock') && Tools::isSubmit('is_post')) {
         $price = str_replace(',', '.', Tools::getValue('price', 0));
         if (!is_numeric($price)) {
             $this->errors[] = Tools::displayError('The product price is not valid.');
         }
         $price = round((double) $price, 6);
         $id_currency = (int) Tools::getValue('id_currency', 0);
         if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
             $this->errors[] = Tools::displayError('The selected currency is not valid.');
         }
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             if ($id_currency != $warehouse->id_currency) {
                 $price_converted_to_default_currency = Tools::convertPrice($price, $id_currency, false);
                 $price = Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true);
             }
             $stock_manager = StockManagerFactory::getManager();
             if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $usable)) {
                 $id_wpl = (int) WarehouseProductLocation::getIdByProductAndWarehouse($id_product, $id_product_attribute, $id_warehouse);
                 if (!$id_wpl) {
                     $wpl = new WarehouseProductLocation();
                     $wpl->id_product = (int) $id_product;
                     $wpl->id_product_attribute = (int) $id_product_attribute;
                     $wpl->id_warehouse = (int) $id_warehouse;
                     $wpl->save();
                 }
                 StockAvailable::synchronize($id_product);
                 if (Tools::isSubmit('addstockAndStay')) {
                     $redirect = self::$currentIndex . '&id_product=' . (int) $id_product;
                     if ($id_product_attribute) {
                         $redirect .= '&id_product_attribute=' . (int) $id_product_attribute;
                     }
                     $redirect .= '&addstock&token=' . $token;
                 }
                 Tools::redirectAdmin($redirect . '&conf=1');
             } else {
                 $this->errors[] = Tools::displayError('An error occurred. No stock was added.');
             }
         }
     }
     if (Tools::isSubmit('removestock') && Tools::isSubmit('is_post')) {
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             $stock_manager = StockManagerFactory::getManager();
             $removed_products = $stock_manager->removeProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $usable);
             if (count($removed_products) > 0) {
                 StockAvailable::synchronize($id_product);
                 Tools::redirectAdmin($redirect . '&conf=2');
             } else {
                 $physical_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
                 $usable_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
                 $not_usable_quantity = $physical_quantity_in_stock - $usable_quantity_in_stock;
                 if ($usable_quantity_in_stock < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $usable_quantity_in_stock);
                 } elseif ($not_usable_quantity < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $not_usable_quantity);
                 } else {
                     $this->errors[] = Tools::displayError('It is not possible to remove the specified quantity. Therefore no stock was removed.');
                 }
             }
         }
     }
     if (Tools::isSubmit('transferstock') && Tools::isSubmit('is_post')) {
         $id_warehouse_from = (int) Tools::getValue('id_warehouse_from', 0);
         if ($id_warehouse_from <= 0 || !Warehouse::exists($id_warehouse_from)) {
             $this->errors[] = Tools::displayError('The source warehouse is not valid.');
         }
         $id_warehouse_to = (int) Tools::getValue('id_warehouse_to', 0);
         if ($id_warehouse_to <= 0 || !Warehouse::exists($id_warehouse_to)) {
             $this->errors[] = Tools::displayError('The destination warehouse is not valid.');
         }
         $usable_from = Tools::getValue('usable_from', null);
         if (is_null($usable_from)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your source warehouse(s) is ready for sale or not.');
         }
         $usable_from = (bool) $usable_from;
         $usable_to = Tools::getValue('usable_to', null);
         if (is_null($usable_to)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your destination warehouse(s) is ready for sale or not.');
         }
         $usable_to = (bool) $usable_to;
         if (count($this->errors) == 0) {
             $stock_manager = StockManagerFactory::getManager();
             $is_transfer = $stock_manager->transferBetweenWarehouses($id_product, $id_product_attribute, $quantity, $id_warehouse_from, $id_warehouse_to, $usable_from, $usable_to);
             StockAvailable::synchronize($id_product);
             if ($is_transfer) {
                 Tools::redirectAdmin($redirect . '&conf=3');
             } else {
                 $this->errors[] = Tools::displayError('It is not possible to transfer the specified quantity. No stock was transferred.');
             }
         }
     }
 }