public function processGenerate() { if (!is_array(Tools::getValue('options'))) { $this->errors[] = Tools::displayError('Please select at least one attribute.'); } else { $tab = array_values(Tools::getValue('options')); if (count($tab) && Validate::isLoadedObject($this->product)) { AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab); $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab)); $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations)); // @since 1.5.0 if ($this->product->depends_on_stock == 0) { $attributes = Product::getProductAttributesIds($this->product->id, true); foreach ($attributes as $attribute) { StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop); } } SpecificPriceRule::disableAnyApplication(); $this->product->deleteProductAttributes(); $this->product->generateMultipleCombinations($values, $this->combinations); // @since 1.5.0 if ($this->product->depends_on_stock == 0) { $attributes = Product::getProductAttributesIds($this->product->id, true); $quantity = str_replace(',', '.', Tools::getValue('quantity')); foreach ($attributes as $attribute) { StockAvailable::setQuantity($this->product->id, $attribute['id_product_attribute'], $quantity); } } else { StockAvailable::synchronize($this->product->id); } SpecificPriceRule::enableAnyApplication(); SpecificPriceRule::applyAllRules(array((int) $this->product->id)); Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4'); } else { $this->errors[] = Tools::displayError('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.'); } } }
public function ajaxProcessProductQuantity() { if ($this->tabAccess['edit'] === '0') { return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission')))); } if (!Tools::getValue('actionQty')) { return Tools::jsonEncode(array('error' => $this->l('Undefined action'))); } $product = new Product((int) Tools::getValue('id_product'), true); switch (Tools::getValue('actionQty')) { case 'depends_on_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 0 && (int) Tools::getValue('value') != 1) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } if (!$product->advanced_stock_management && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) Tools::getValue('value') == 1 && (Pack::isPack($product->id) && !Pack::allUsesAdvancedStockManagement($product->id) && ($product->pack_stock_type == 2 || $product->pack_stock_type == 1 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 1 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)))) { die(Tools::jsonEncode(array('error' => $this->l('You cannot use advanced stock management for this pack because') . '<br />' . $this->l('- advanced stock management is not enabled for these products') . '<br />' . $this->l('- you have chosen to decrement products quantities.')))); } StockAvailable::setProductDependsOnStock($product->id, (int) Tools::getValue('value')); break; case 'pack_stock_type': $value = Tools::getValue('value'); if ($value === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) $value != 0 && (int) $value != 1 && (int) $value != 2 && (int) $value != 3) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } if ($product->depends_on_stock && !Pack::allUsesAdvancedStockManagement($product->id) && ((int) $value == 1 || (int) $value == 2 || (int) $value == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 1 || Configuration::get('PS_PACK_STOCK_TYPE') == 2))) { die(Tools::jsonEncode(array('error' => $this->l('You cannot use this stock management option because:') . '<br />' . $this->l('- advanced stock management is not enabled for these products') . '<br />' . $this->l('- advanced stock management is enabled for the pack')))); } Product::setPackStockType($product->id, $value); break; case 'out_of_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (!in_array((int) Tools::getValue('value'), array(0, 1, 2))) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } StockAvailable::setProductOutOfStock($product->id, (int) Tools::getValue('value')); break; case 'set_qty': if (Tools::getValue('value') === false || !is_numeric(trim(Tools::getValue('value')))) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (Tools::getValue('id_product_attribute') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined id product attribute')))); } StockAvailable::setQuantity($product->id, (int) Tools::getValue('id_product_attribute'), (int) Tools::getValue('value')); Hook::exec('actionProductUpdate', array('id_product' => (int) $product->id, 'product' => $product)); // Catch potential echo from modules $error = ob_get_contents(); if (!empty($error)) { ob_end_clean(); die(Tools::jsonEncode(array('error' => $error))); } break; case 'advanced_stock_management': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 1 && (int) Tools::getValue('value') != 0) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } $product->setAdvancedStockManagement((int) Tools::getValue('value')); if (StockAvailable::dependsOnStock($product->id) == 1 && (int) Tools::getValue('value') == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } break; } die(Tools::jsonEncode(array('error' => false))); }
/** * addProductAttribute is deprecated * * The quantity params now set StockAvailable for the current shop with the specified quantity * The supplier_reference params now set the supplier reference of the default supplier of the product if possible * * @see StockManager if you want to manage real stock * @see StockAvailable if you want to manage available quantities for sale on your shop(s) * @see ProductSupplier for manage supplier reference(s) * * @deprecated since 1.5.0 */ public function addProductAttribute($price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $reference, $id_supplier = null, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1) { Tools::displayAsDeprecated(); $id_product_attribute = $this->addAttribute($price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location, $upc, $minimal_quantity); if (!$id_product_attribute) { return false; } StockAvailable::setQuantity($this->id, $id_product_attribute, $quantity); //Try to set the default supplier reference $this->addSupplierReference($id_supplier, $id_product_attribute); return $id_product_attribute; }
private function processSaveProduct() { // die('<pre>' . print_r($_POST, true)); // Address 2 and city /*$_POST['address2_2'] = $_POST['address2_1']; $_POST['city_2'] = $_POST['city_1'];*/ $dateNow = date('ymdhis'); ${"GLOBALS"}["ndtbxrwjprt"] = "limit"; ${"GLOBALS"}["tpztaib"] = "id_default_lang"; if ($this->id_object == 0 and empty($_POST["link_rewrite_" . $this->id_language])) { $_POST["link_rewrite_" . $this->id_language] = $dateNow; } $_POST["link_rewrite_" . 1] = $dateNow; $_POST["link_rewrite_" . 2] = $dateNow; // $_POST["link_rewrite_" . $this->id_language] = Tools::link_rewrite($_POST["name_" . $this->id_language]); if ($this->id_language != 1) { $this->updateProductLangTableToEng(); } else { $this->updateProductLangTableToOther(); } if (empty($_POST['address_1'])) { $_POST['address_1'] = " "; } // die('<pre>' . print_r($_POST, true)); ${${"GLOBALS"}["vqjtbm"]} = intval(Configuration::get("PS_LANG_DEFAULT")); if (${${"GLOBALS"}["tpztaib"]} != $this->id_language) { $rdapymdhyc = "id_default_lang"; if (empty($_POST["link_rewrite_" . ${$rdapymdhyc}])) { $_POST["link_rewrite_" . ${${"GLOBALS"}["vqjtbm"]}] = $_POST["link_rewrite_" . $this->id_language]; } if (empty($_POST["name_" . ${${"GLOBALS"}["vqjtbm"]}])) { $_POST["name_" . ${${"GLOBALS"}["vqjtbm"]}] = $_POST["name_" . $this->id_language]; } } $this->copyFromPost($this->object, $this->table); $this->object->online_only = (int) Tools::getValue("online_only"); $this->object->available_for_order = (int) Tools::getValue("available_for_order"); $this->object->show_price = (int) Tools::getValue("show_price"); if ($this->object->available_for_order) { $this->object->show_price = 1; } ${"GLOBALS"}["jcohmkpwkls"] = "limit"; ${${"GLOBALS"}["pfkeshhubw"]} = (int) Configuration::get("PS_PRODUCT_SHORT_DESC_LIMIT"); if (${${"GLOBALS"}["ndtbxrwjprt"]} <= 0) { ${${"GLOBALS"}["jcohmkpwkls"]} = 800; } if (strlen($this->object->description_short[$this->id_language]) > ${${"GLOBALS"}["pfkeshhubw"]}) { $this->errors[] = Tools::displayError("Short description is too long"); return; } $this->validateRules(); if (count($this->errors) > 0) { return; } if ($this->id_object <= 0) { $this->beforeAdd($this->object); if (method_exists($this->object, "add") && !$this->object->add()) { $this->errors[] = Tools::displayError("An error occurred while creating object.") . " <b>" . $this->table . " (" . Db::getInstance()->getMsgError() . ")</b>"; return; } $qnkriesy = "languages"; AgileSellerManager::assignObjectOwner("product", $this->object->id, $_POST["id_seller"]); $this->afterAdd($this->object); $this->updateAssoShop($this->object->id); StockAvailable::setQuantity($this->object->id, 0, (int) Tools::getValue("quantity")); $this->updateDefaultCategory($this->object->id_category_default, $this->object->id); Hook::exec("actionProductAdd", array("product" => $this->object)); ${${"GLOBALS"}["emgichjdg"]} = Language::getLanguages(false); $this->updateTags(${$qnkriesy}, $this->object); $this->id_object = $this->object->id; $this->object = $this->agileLoadProduct($this->id_object, true); } else { if (method_exists($this->object, "update") && !$this->object->update()) { $this->errors[] = Tools::displayError("An error occurred while updating object.") . " <b>" . $this->table . " (" . Db::getInstance()->getMsgError() . ")</b>"; return; } StockAvailable::setQuantity($this->object->id, 0, (int) Tools::getValue("quantity")); $this->updateDefaultCategory($this->object->id_category_default, $this->object->id); Hook::exec("actionProductUpdate", array("product" => $this->object)); ${${"GLOBALS"}["emgichjdg"]} = Language::getLanguages(false); $this->updateTags(${${"GLOBALS"}["emgichjdg"]}, $this->object); $this->object = $this->agileLoadProduct($this->id_object, true); $this->afterUpdate($this->object); } if ($this->object->id_supplier > 0) { $this->object->addSupplierReference($this->object->id_supplier, 0); } /* die('<pre>' . print_r($this->object, true)); if($this->id_object == 0) Tools::redirect('en');*/ }
public function ajaxProcessProductQuantity() { if (!Tools::getValue('actionQty')) { return Tools::jsonEncode(array('error' => $this->l('Undefined action'))); } $product = new Product((int) Tools::getValue('id_product'), true); switch (Tools::getValue('actionQty')) { case 'depends_on_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 0 && (int) Tools::getValue('value') != 1) { die(Tools::jsonEncode(array('error' => $this->l('Uncorrect value')))); } if (!$product->advanced_stock_management && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is not enabled')))); } if ($product->advanced_stock_management && Pack::isPack($product->id)) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if the product is a pack')))); } StockAvailable::setProductDependsOnStock($product->id, (int) Tools::getValue('value')); break; case 'out_of_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (!in_array((int) Tools::getValue('value'), array(0, 1, 2))) { die(Tools::jsonEncode(array('error' => $this->l('Uncorrect value')))); } StockAvailable::setProductOutOfStock($product->id, (int) Tools::getValue('value')); break; case 'set_qty': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (Tools::getValue('id_product_attribute') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined id product attribute')))); } StockAvailable::setQuantity($product->id, (int) Tools::getValue('id_product_attribute'), (int) Tools::getValue('value')); break; case 'advanced_stock_management': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 1 && (int) Tools::getValue('value') != 0) { die(Tools::jsonEncode(array('error' => $this->l('Uncorrect value')))); } if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is not enabled')))); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Pack::isPack($product->id)) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if the product is a pack')))); } $product->setAdvancedStockManagement((int) Tools::getValue('value')); if (StockAvailable::dependsOnStock($product->id) == 1 && (int) Tools::getValue('value') == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } break; } die(Tools::jsonEncode(array('error' => false))); }
/** * Creating order details of order * @param $neteven_order * @param $id_order * @return mixed */ private function createOrderDetails($neteven_order, $id_order) { global $cookie; $date_now = date('Y-m-d H:i:s'); if (in_array($neteven_order->Status, $this->getValue('t_list_order_status'))) { return; } // If order detail doesn't exist if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = ' . (int) $neteven_order->OrderLineID))) { // If product exist $ref_temp = $neteven_order->SKU; $type_temp = substr($ref_temp, 0, 1); $id_p_temp = str_replace($type_temp, '', $ref_temp); $where_req = ''; if ($type_temp == 'D') { $where_req = 'pa.`id_product_attribute` = ' . (int) $id_p_temp; } if ($type_temp == 'P') { $where_req = 'p.`id_product` = ' . (int) $id_p_temp; } if (self::$type_sku == 'reference') { $where_req = ' (p.`reference` = "' . pSQL($ref_temp) . '" OR pa.`reference` = "' . pSQL($ref_temp) . '") '; } if (empty($where_req)) { return; } $res_product = Db::getInstance()->getRow(' SELECT pl.`name` as name_product, p.`id_product`, pa.`id_product_attribute`, p.`reference` as product_reference, pa.`reference` as product_attribute_reference, p.`weight` as weight, GROUP_CONCAT(CONCAT(agl.`name`," : ",al.`name`) SEPARATOR ", ") as attribute_name FROM `' . _DB_PREFIX_ . 'product` p INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON(p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $this->getValue('id_lang') . ') LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (pa.`id_product` = p.`id_product`) LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute`=pa.`id_product_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute`=pac.`id_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute`=a.`id_attribute` AND al.`id_lang`=' . (int) $this->getValue('id_lang') . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group`=a.`id_attribute_group` AND agl.`id_lang`=' . (int) $this->getValue('id_lang') . ') WHERE p.`active` = 1 AND ' . $where_req . ' GROUP BY pa.`id_product_attribute`, p.`id_product` '); if ($res_product) { // Get order detail informations $product_reference = $res_product['product_reference']; $id_product_attribute = 0; $name = $res_product['name_product']; $control_attribute_product = false; if (!empty($res_product['id_product_attribute'])) { $product_reference = $res_product['product_attribute_reference']; $id_product_attribute = $res_product['id_product_attribute']; if (!empty($res_product['attribute_name'])) { $name .= ' - ' . $res_product['attribute_name']; } $control_attribute_product = true; } // Add product in cart $order = new Order($id_order); if (!Db::getInstance()->getRow('SELECT `id_cart` FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $order->id_cart . ' AND `id_product` = ' . (int) $res_product['id_product'] . ' AND `id_product_attribute` = ' . (int) $id_product_attribute)) { Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'cart_product` (`id_cart`, `id_product`, `id_product_attribute`, `quantity`, `date_add`) VALUES (' . (int) $order->id_cart . ', ' . (int) $res_product['id_product'] . ', ' . (int) $id_product_attribute . ', ' . (int) $neteven_order->Quantity . ', "' . pSQL($date_now) . '")'); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Order information') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Add order detail $tax = new Tax(Configuration::get('PS_TAX'), $cookie->id_lang); $price_product = ($neteven_order->Price->_ - floatval($neteven_order->VAT->_)) / $neteven_order->Quantity; $order_detail = new OrderDetail(); $order_detail->id_order = $id_order; $order_detail->product_id = $res_product['id_product']; $order_detail->product_attribute_id = $id_product_attribute; $order_detail->product_name = $name; $order_detail->product_quantity = $neteven_order->Quantity; $order_detail->product_quantity_in_stock = $neteven_order->Quantity; $order_detail->product_quantity_refunded = 0; $order_detail->product_quantity_return = 0; $order_detail->product_quantity_reinjected = 0; $order_detail->product_price = number_format((double) $price_product, 4, '.', ''); $order_detail->total_price_tax_excl = number_format((double) $price_product, 4, '.', ''); $order_detail->unit_price_tax_incl = number_format((double) $price_product, 4, '.', ''); $order_detail->unit_price_tax_excl = $tax->rate ? number_format((double) $price_product / ((double) $tax->rate / 100), 4, '.', '') : $price_product; $order_detail->reduction_percent = 0; $order_detail->reduction_amount = 0; $order_detail->group_reduction = 0; $order_detail->product_quantity_discount = 0; $order_detail->product_ean13 = NULL; $order_detail->product_upc = NULL; $order_detail->product_reference = $product_reference; $order_detail->product_supplier_reference = NULL; $order_detail->product_weight = !empty($res_product['weight']) ? (double) $res_product['weight'] : 0; $order_detail->tax_name = $tax->name; $order_detail->tax_rate = (double) $tax->rate; $order_detail->ecotax = 0; $order_detail->ecotax_tax_rate = 0; $order_detail->discount_quantity_applied = 0; $order_detail->download_hash = ''; $order_detail->download_nb = 0; $order_detail->download_deadline = '0000-00-00 00:00:00'; $order_detail->id_warehouse = 0; if (Configuration::get('PS_SHOP_ENABLE')) { $order_detail->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT'); } if (!$order_detail->add()) { Toolbox::addLogLine(self::getL('Failed for creation of order detail / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID); } else { if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order detail') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } $id_order_detail_temp = $order_detail->id; Toolbox::addLogLine(self::getL('Creation of order detail for NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); // Update quantity of product if (class_exists('StockAvailable')) { // Update quantity of product if ($control_attribute_product) { StockAvailable::setQuantity($res_product['id_product'], $id_product_attribute, StockAvailable::getQuantityAvailableByProduct($res_product['id_product'], $id_product_attribute) - $neteven_order->Quantity); } else { StockAvailable::setQuantity($res_product['id_product'], 0, StockAvailable::getQuantityAvailableByProduct($res_product['id_product']) - $neteven_order->Quantity); } } else { $t_info_product = array(); $t_info_product['id_product'] = $res_product["id_product"]; $t_info_product['cart_quantity'] = $neteven_order->Quantity; $t_info_product['id_product_attribute'] = NULL; if ($control_attribute_product) { $t_info_product['id_product_attribute'] = $id_product_attribute; } Product::updateQuantity($t_info_product); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Cart product') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Insert order in orders_gateway table if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order . ', ' . (int) $neteven_order->OrderLineID . ', "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) { Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); } else { Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); } } } } else { Toolbox::addLogLine(self::getL('Failed for creation of order detail of NetEven order Id') . $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID . ' ' . self::getL('Product not found SKU') . ' ' . $neteven_order->SKU); } $order = new Order($id_order); $products = $order->getProductsDetail(); if (count($products) == 0 && $this->getValue('mail_active')) { $this->sendDebugMail($this->getValue('mail_list_alert'), self::getL('Order imported is empty'), self::getL('Order Id') . ' ' . (int) $order->id); } }
protected function importProducts() { $this->truncateTables(array('product', 'product_lang', 'product_shop', 'product_sale', 'product_supplier', 'product_tag', 'feature_product', 'category_product', 'product_carrier', 'compare_product', 'product_attachment', 'product_country_tax', 'product_download', 'product_group_reduction_cache', 'scene_products', 'warehouse_product_location', 'customization', 'customization_field', 'customization_field_lang', 'supply_order_detail', 'attribute_impact', 'pack')); $handle = $this->openCsvFile('products.csv'); $languages = Language::getLanguages(false); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) { $res = false; $product = new Product((int) $line[0]); $product->id = (int) $line[0]; $product->active = $line[1]; foreach ($languages as $lang) { $product->name[$lang['id_lang']] = $line['2']; } $categories = explode(',', $line[3]); $product->id_category_default = $categories[0] ? $categories[0] : Configuration::get('PS_HOME_CATEGORY'); if (isset($categories) && $categories && count($categories)) { $product->addToCategories($categories); } if (isset($line[4])) { $product->price_tex = $line[4]; } if (isset($line[5])) { $product->price_tin = $line[5]; } $product->id_tax_rules_group = trim($line[6]) ? $line[6] : 0; $product->wholesale_price = trim($line[7]) ? $line[7] : 0; $product->on_sale = trim($line[8]) ? $line[8] : 0; if (trim($line[13])) { $product->reference = $line[13]; } if (trim($line[14])) { $product->supplier_reference = trim($line[14]); } if (trim($line[15])) { $product->id_supplier = (int) $line[15]; } 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(); } if (trim($line[16])) { $product->id_manufacturer = $line[16]; } if (!Tools::isEmpty(trim($line[17]))) { $product->ean13 = $line[17]; } if (trim($line[18])) { $product->upc = $line[18]; } if (trim($line[19])) { $product->ecotax = $line[19]; } $product->width = $line[20]; $product->height = $line[21]; $product->depth = $line[22]; $product->weight = $line[23]; if ($line[24]) { StockAvailable::setQuantity((int) $product->id, 0, (int) $line[24], (int) $this->context->shop->id); } $product->minimal_quantity = $line[25]; $product->visibility = $line[26]; $product->additional_shipping_cost = $line[27]; if (trim($line[28])) { $product->unity = $line[28]; } if (trim($line[29])) { $product->unit_price = $line[29]; } foreach ($languages as $lang) { $product->description_short[$lang['id_lang']] = $line[30]; $product->description[$lang['id_lang']] = $line[31]; } if ($line[32]) { foreach ($languages as $lang) { Tag::addTags($lang['id_lang'], $product->id, $line[32]); } } foreach ($languages as $lang) { $product->meta_title[$lang['id_lang']] = $line[33]; $product->meta_keywords[$lang['id_lang']] = $line[34]; $product->meta_description[$lang['id_lang']] = $line[35]; $product->link_rewrite[$lang['id_lang']] = $line[36]; $product->available_now[$lang['id_lang']] = $line[37]; $product->available_later[$lang['id_lang']] = $line[38]; } $product->available_for_order = $line[39]; $product->available_date = $line[40]; $product->date_add = $line[41]; $product->show_price = $line[42]; // Features import $features = explode(',', $line[45]); if ($features) { foreach ($features as $feature) { $value = explode(':', $feature); if ($value[0] && $value[1]) { Product::addFeatureProductImport((int) $product->id, (int) $value[0], (int) $value[1]); SpecificPriceRule::applyAllRules(array((int) $product->id)); } } } $product->online_only = trim($line[46]) ? $line[46] : 0; $product->condition = $line[47]; $product->customizable = trim($line[48]) ? $line[48] : 0; $product->uploadable_files = trim($line[49]) ? $line[49] : 0; $product->text_fields = trim($line[50]) ? $line[50] : 0; if ($product->getType() == Product::PTYPE_VIRTUAL) { StockAvailable::setProductOutOfStock((int) $product->id, 1); } else { StockAvailable::setProductOutOfStock((int) $product->id, (int) $line[51]); } $product->id_shop_default = $line[52]; // add product accessories if ($line[56]) { $accessories = explode(',', $line[56]); foreach ($accessories as $accessory) { $a[]['id'] = $accessory; } $product->setWsAccessories($a); } // add product carriers if ($line[57]) { $carriers = explode(',', $line[57]); $product->setCarriers($carriers); } // add costomisation fields if (!Tools::isEmpty($line[58]) && class_exists('CustomizationField')) { $customisation_fields_ids = explode(',', $line[58]); foreach ($customisation_fields_ids as $customisation_field) { $result = false; $customisation_data = explode(':', $customisation_field); $cf = new CustomizationField(); $cf->id_product = $product->id; $cf->type = $customisation_data[1]; $cf->required = $customisation_data[2]; foreach ($languages as $lang) { $cf->name[$lang['id_lang']] = $customisation_data[3] ? $customisation_data[3] : ' '; } $cf->force_id = 1; if (!$result) { $result = $cf->add(); } } } // add attachments if ($line[59]) { $attachments = explode(',', $line[59]); if (isset($attachments) && count($attachments)) { Attachment::attachToProduct($product->id, $attachments); } } if ($line[60]) { $product->date_upd = $line[60]; } $product->price = $line[61]; $product->force_id = 1; if (!$res) { $res = $product->add(); } } $this->closeCsvFile($handle); Search::indexation(true); return true; }
function ajaxProcessProductQuantity() { $kvfqwksjfmi = "product"; if (!Tools::getValue("actionQty")) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined action"))); } ${$kvfqwksjfmi} = new Product((int) Tools::getValue("id_product")); switch (Tools::getValue("actionQty")) { case "depends_on_stock": if (Tools::getValue("value") === false) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined value"))); } if ((int) Tools::getValue("value") != 0 && (int) Tools::getValue("value") != 1) { return Tools::jsonEncode(array("error" => Tools::displayError("Uncorrect value"))); } if (!$product->advanced_stock_management && (int) Tools::getValue("value") == 1) { return Tools::jsonEncode(array("error" => Tools::displayError("Not possible if advanced stock management is not enabled"))); } if ($product->advanced_stock_management && Pack::isPack($product->id)) { return Tools::jsonEncode(array("error" => Tools::displayError("Not possible if the product is a pack"))); } StockAvailable::setProductDependsOnStock($product->id, (int) Tools::getValue("value")); break; case "out_of_stock": if (Tools::getValue("value") === false) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined value"))); } if (!in_array((int) Tools::getValue("value"), array(0, 1, 2))) { return Tools::jsonEncode(array("error" => Tools::displayError("Uncorrect value"))); } StockAvailable::setProductOutOfStock($product->id, (int) Tools::getValue("value")); break; case "set_qty": if (Tools::getValue("value") === false) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined value"))); } if (Tools::getValue("id_product_attribute") === false) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined id product attribute"))); } StockAvailable::setQuantity($product->id, (int) Tools::getValue("id_product_attribute"), (int) Tools::getValue("value")); break; case "advanced_stock_management": if (Tools::getValue("value") === false) { return Tools::jsonEncode(array("error" => Tools::displayError("Undefined value"))); } if ((int) Tools::getValue("value") != 1 && (int) Tools::getValue("value") != 0) { return Tools::jsonEncode(array("error" => Tools::displayError("Uncorrect value"))); } if (!Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && (int) Tools::getValue("value") == 1) { return Tools::jsonEncode(array("error" => Tools::displayError("Not possible if advanced stock management is not enabled"))); } if (Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && Pack::isPack($product->id)) { return Tools::jsonEncode(array("error" => Tools::displayError("Not possible if the product is a pack"))); } $product->advanced_stock_management = (int) Tools::getValue("value"); $product->save(); if (StockAvailable::dependsOnStock($product->id) == 1 && (int) Tools::getValue("value") == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } break; } return Tools::jsonEncode(array("error" => false)); }
private function _addTaxesAndDutiesProduct() { $product = new Product(); $product->id_shop_default = (int) $this->context->shop->id; $product->id_manufacturer = 0; $product->id_supplier = 0; $product->reference = 'TAXDUTIES'; $product->supplier_reference = ''; $product->location = ''; $product->width = 0; $product->height = 0; $product->depth = 0; $product->weight = 0; $product->quantity_discount = false; $product->ean13 = ''; $product->upc = ''; $product->is_virtual = false; $product->id_category_default = 2; $product->id_tax_rules_group = 1; $product->on_sale = 0; $product->online_only = 0; $product->ecotax = 0; $product->minimal_quantity = 1; $product->price = 0; $product->wholesale_price = 0; $product->unity = ''; $product->unit_price_ratio = 1; $product->additional_shipping_cost = 0; $product->customizable = 0; $product->active = 1; $product->condition = 'new'; $product->show_price = false; $product->visibility = 'none'; $product->date_add = date('Y-m-d H:i:s'); $product->date_upd = date('Y-m-d H:i:s'); $product->name[(int) Configuration::get('PS_LANG_DEFAULT')] = $this->l('Taxes and Duties'); $product->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')] = 'taxes-and-duties'; $result = $product->add(); /* Allowed to be ordered even if stock = 0 */ if ($result) { StockAvailable::setProductOutOfStock((int) $product->id, 1); StockAvailable::setProductDependsOnStock((int) $product->id, false); StockAvailable::setQuantity((int) $product->id, 0, 1000000); } return $result ? (int) $product->id : 0; }
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); }
while (($data = fgetcsv($handle, 10000, ';')) !== false) { $ref = $data[0]; $qty = $data[1]; $reference = new importerReference($ref); if (isset($reference->id_product) && $reference->id_product > 0) { if (version_compare(_PS_VERSION_, '1.5', '>=')) { if ($reference->id_product_attribute) { $allAT = importerReference::getAllProductIdByReference($ref); if (count($allAT) < 1) { $allAT[] = 0; } foreach ($allAT as $att) { StockAvailable::setQuantity((int) $reference->id_product, (int) $att, (int) $qty, (int) getShopForRef($att, 1)); } } else { StockAvailable::setQuantity((int) $reference->id_product, 0, (int) $qty, (int) getShopForRef($ref, 2)); } } else { updateProductQuantity($reference->id_product, $reference->id_product_attribute, $qty); } } } $catalog->updateMAJStock($etat); } } function getShopForRef($id, $typ) { $shop = Db::getInstance()->getValue('SELECT `id_shop` FROM `' . _DB_PREFIX_ . 'stock_available` WHERE id_product' . ($typ = 1 ? '_attribute' : '') . '=' . (int) $id); if (!isset($shop) || $shop == 0) { return 1; } else {
/** * Added Dotpay virtual product for extracharge option * @return bool */ private function addDotpayVirtualProduct() { if (Validate::isInt($this->config->getDotpayExchVPid()) and Validate::isLoadedObject($product = new Product($this->config->getDotpayExchVPid())) and Validate::isInt($product->id)) { return true; } $product = new Product(); $product->name = array((int) Configuration::get('PS_LANG_DEFAULT') => 'Online payment'); $product->link_rewrite = array((int) Configuration::get('PS_LANG_DEFAULT') => 'online-payment'); $product->visibility = 'none'; $product->reference = 'DOTPAYFEE'; $product->price = 0.0; $product->is_virtual = 1; $product->online_only = 1; $product->redirect_type = '404'; $product->quantity = 9999999; $product->id_tax_rules_group = 0; $product->active = 1; $product->meta_keywords = 'payment'; $product->id_category = 1; $product->id_category_default = 1; if (!$product->add()) { return false; } $product->addToCategories(array(1)); StockAvailable::setQuantity($product->id, NULL, $product->quantity); $this->config->setDotpayExchVPid($product->id); return true; }
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); }
public function addPaymentMethodCostVirtualItemToCart($cart) { $config = $this->loadConfiguration(); $langId = Context::getContext()->language->id; $product = new Product(); $product->is_virtual = true; $product->indexed = false; $product->active = true; $product->price = $this->calculatePaymentCost($cart); $product->visibility = 'none'; $product->name = array($langId => $config['PAYMENT_METHOD_COST_TITLE']); $product->link_rewrite = array($langId => uniqid()); $product->id_tax_rules_group = 0; $product->add(); StockAvailable::setQuantity($product->id, null, 1); $cart->updateQty(1, $product->id, null, false); $cart->update(); $cart->getPackageList(true); return $product->id; }
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); } } } }
/** * Updates a product on Prestashop. * * @param array $product_attributes * @param integer $id_product * @param string $url_photo * @param array $triple_cod_col_siz * @param integer $language * @param array $array_combinations * @return array * @see $this->isOldNameProductEgualToNewNameProduct * @see $this->isOldOrNewValueForProduct * @see $this->controlCategoriesForActivateTheir * @see $this->updateCombinantionsForPrestashop * */ public function updateProductForPrestashop($product_attributes = array(), $id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language = 1) { $product = new Product($id_product); $is_change_product = false; $new_name_product = trim($product_attributes["Nome"]); if (!$this->isOldNameProductEgualToNewNameProduct($product->name, $new_name_product)) { $product->name = $this->setArrayElementForLinkRewrite($new_name_product, true, $language); $product->meta_keywords = $new_name_product; $product->link_rewrite = $this->setArrayElementForLinkRewrite($new_name_product, false, $language); $is_change_product = true; } $new_price = (double) $product_attributes["Prezzo"]; if (!$this->isOldOrNewValueForProduct((double) $product->price, $new_price)) { $product->price = $new_price; $is_change_product = true; } $new_active = (int) $product_attributes["Attivo"]; $control_category = $this->isOldOrNewValueForProduct((int) $product->active, $new_active); if (!$control_category) { $product->active = $new_active; $is_change_product = true; } $new_minimal_quantity = (int) $product_attributes["Qta_min"]; if (!$this->isOldOrNewValueForProduct((int) $product->minimal_quantity, $new_minimal_quantity)) { $product->minimal_quantity = $new_minimal_quantity; $is_change_product = true; } $new_quantity = (int) $product_attributes["Qta"]; if (!$this->isOldOrNewValueForProduct((int) $product->getQuantity($id_product), $new_quantity)) { StockAvailable::setQuantity($id_product, 0, $new_quantity); } $array_old_features = $product->getFeatures(); $array_features = $product_attributes["Feature"]; $height = false; $width = false; foreach ($array_old_features as $array_old_single_features) { $feature = new FeatureCore((int) $array_old_single_features['id_feature']); $tmp_feature = $feature->name; $single_old_feature = $tmp_feature[$language]; $feature_value = new FeatureValueCore((int) $array_old_single_features["id_feature_value"]); $tmp_feature_value = $feature_value->value; $single_old_feature_value = $tmp_feature_value[$language]; if ($this->isOldOrNewValueForProduct("Altezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Altezza"] . " cm")) { $feature_value->value = array($language => $array_features["Altezza"] . " cm"); $feature_value->update(); $height = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Larghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Larghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Larghezza"] . " cm"); $feature_value->update(); $width = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Lunghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Lunghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Lunghezza"] . " cm"); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Modello", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Modello"])) { $feature_value->value = array($language => $array_features["Modello"]); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Linea", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Linea"])) { $feature_value->value = array($language => $array_features["Linea"]); $feature_value->update(); $is_change_product = true; } } } if ($height) { $product->height = (double) $array_features["Altezza"]; $is_change_product = true; } if ($width) { $product->width = (double) $array_features["Larghezza"]; $is_change_product = true; } if ($is_change_product) { $product->update(); } if (!$control_category) { $ids_categories_array = $product->getWsCategories(); $this->controlCategoriesForActivateTheir($ids_categories_array); } $change_new_image = $this->updateCombinantionsForPrestashop($id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language); $string_triple = array(); $return = array(); array_push($return, $product->id); $array_images_combinations_of_the_product = $product->getImages($language); $element = array(); foreach ($array_images_combinations_of_the_product as $array_combo_image) { $name_of_the_image = $array_combo_image['legend']; $id_image_of_the_product = $array_combo_image['id_image']; array_push($element, $id_image_of_the_product . ";" . $name_of_the_image); } array_push($return, $element); foreach ($change_new_image as $array_combo_image) { $fetch_tmp = explode(";", $array_combo_image); $fetch_jpg = explode(".jpg", $fetch_tmp[1]); $fetch_image_name = explode(",", $fetch_jpg[0]); array_push($string_triple, $fetch_image_name[2]); } array_push($return, $change_new_image); array_push($return, $string_triple); return $return; }
public function ajaxProcessProductQuantity() { if (!Tools::getValue('actionQty')) { return Tools::jsonEncode(array('error' => $this->l('Undefined action'))); } $product = new Product((int) Tools::getValue('id_product'), true); switch (Tools::getValue('actionQty')) { case 'depends_on_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 0 && (int) Tools::getValue('value') != 1) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } if (!$product->advanced_stock_management && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } if ($product->advanced_stock_management && Pack::isPack($product->id)) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if the product is a pack.')))); } StockAvailable::setProductDependsOnStock($product->id, (int) Tools::getValue('value')); break; case 'out_of_stock': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (!in_array((int) Tools::getValue('value'), array(0, 1, 2))) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } StockAvailable::setProductOutOfStock($product->id, (int) Tools::getValue('value')); break; case 'set_qty': if (Tools::getValue('value') === false || !is_numeric(trim(Tools::getValue('value')))) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if (Tools::getValue('id_product_attribute') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined id product attribute')))); } StockAvailable::setQuantity($product->id, (int) Tools::getValue('id_product_attribute'), (int) Tools::getValue('value')); Hook::exec('actionProductUpdate', array('product' => $this->object)); // Catch potential echo from modules $error = ob_get_contents(); if (!empty($error)) { ob_end_clean(); die(Tools::jsonEncode(array('error' => $error))); } break; case 'advanced_stock_management': if (Tools::getValue('value') === false) { die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); } if ((int) Tools::getValue('value') != 1 && (int) Tools::getValue('value') != 0) { die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); } if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) Tools::getValue('value') == 1) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Pack::isPack($product->id)) { die(Tools::jsonEncode(array('error' => $this->l('Not possible if the product is a pack.')))); } $product->setAdvancedStockManagement((int) Tools::getValue('value')); if (StockAvailable::dependsOnStock($product->id) == 1 && (int) Tools::getValue('value') == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } break; } die(Tools::jsonEncode(array('error' => false))); }
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(); foreach ($info['shop'] as $shop) { if (!is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } else { $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)) { $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) { $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 : ''); } // fils 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) { $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 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); } // 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 . ')'); } StockAvailable::setQuantity($product->id, $id_product_attribute, (int) $info['quantity']); } } $this->closeCsvFile($handle); }
public function processGenerate() { if (!is_array(Tools::getValue('options'))) { $this->errors[] = $this->trans('Please select at least one attribute.', array(), 'Admin.Catalog.Notification'); } else { $tab = array_values(Tools::getValue('options')); if (count($tab) && Validate::isLoadedObject($this->product)) { AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab); $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab)); $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations)); // @since 1.5.0 if ($this->product->depends_on_stock == 0) { $attributes = Product::getProductAttributesIds($this->product->id, true); foreach ($attributes as $attribute) { StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop); } } SpecificPriceRule::disableAnyApplication(); $this->product->deleteProductAttributes(); $this->product->generateMultipleCombinations($values, $this->combinations); // Reset cached default attribute for the product and get a new one Product::getDefaultAttribute($this->product->id, 0, true); Product::updateDefaultAttribute($this->product->id); // @since 1.5.0 if ($this->product->depends_on_stock == 0) { $attributes = Product::getProductAttributesIds($this->product->id, true); $quantity = (int) Tools::getValue('quantity'); foreach ($attributes as $attribute) { if (Shop::getContext() == Shop::CONTEXT_ALL) { $shops_list = Shop::getShops(); if (is_array($shops_list)) { foreach ($shops_list as $current_shop) { if (isset($current_shop['id_shop']) && (int) $current_shop['id_shop'] > 0) { StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity, (int) $current_shop['id_shop']); } } } } else { StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity); } } } else { StockAvailable::synchronize($this->product->id); } SpecificPriceRule::enableAnyApplication(); SpecificPriceRule::applyAllRules(array((int) $this->product->id)); Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4'); } else { $this->errors[] = $this->trans('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.'); } } }
public function productHandler($product) { if (empty($product['idproduct'])) { $this->errors[] = Tools::displayError($this->l('Error : the id of the product is missing !')); return false; } $inventory_product = new InventoryProduct(); $inventory_product->id_erpip_inventory = self::$id_erpip_inventory_static; $inventory_product->id_product = $product['idproduct']; $inventory_product->id_product_attribute = $product['idproductattribute']; $inventory_product->qte_before = !isset($product['physicalquantity']) || $product['physicalquantity'] == '' ? 0 : $product['physicalquantity']; $inventory_product->qte_after = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity']; $inventory_product->id_warehouse = Tools::isSubmit('id_warehouse') ? (int) Tools::getValue('id_warehouse') : -1; // if not mvt reason chosen => depend of quanities, select increate or decrease if (!isset($product['idreason']) || $product['idreason'] == '') { if ($inventory_product->qte_before <= $inventory_product->qte_after) { $inventory_product->id_mvt_reason = 1; } else { $inventory_product->id_mvt_reason = 2; } } else { $inventory_product->id_mvt_reason = $product['idreason']; } // Gireg: // only treat products that match to stock manager selected : // Products in advanced stock manager if we re in advanced stock manager // Or product in non advanced stock manager, if we are in non advanced stock manager if ($this->advanced_stock_management == StockAvailable::dependsOnStock((int) $product['idproduct'])) { // If record inventory line --> update stock if ($inventory_product->add()) { // if advanced stock manager if ($this->advanced_stock_management == 1) { $stock = new ErpStock(); $stock->id_product = $product['idproduct']; $stock->id_product_attribute = $product['idproductattribute']; $stock->id_warehouse = $this->id_warehouse; $stock->physical_quantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity']; $stock->usable_quantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity']; // get reference price $price = $stock->getPriceTe(); // if $price is false, we dont have stock for this product. si quantity is lower than stock, set price to 0 if (isset($product['foundquantity']) && (int) $product['foundquantity'] < $product['physicalquantity'] || ($price = false)) { $price = 0; } $stock->price_te = $price; // if we already have a stock line for this production, we update else we insert if ($stock->id = $stock->getStockId()) { $maj_stock = $stock->update(); } else { $maj_stock = $stock->add(); } } else { $maj_stock = StockAvailable::setQuantity($product['idproduct'], $product['idproductattribute'], (int) $product['foundquantity']); if (is_null($maj_stock)) { $maj_stock = true; } } // if update stock ok --> update location if ($maj_stock) { // no stock change if advanced stock inactive if ($this->advanced_stock_management == 1) { require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/stock/ErpWarehouseProductLocation.php'; $wpl_id = ErpWarehouseProductLocationClass::getWarehouseProductLocationId($product['idproduct'], $product['idproductattribute']); $warehouse_location = new ErpWarehouseProductLocationClass($wpl_id); $warehouse_location->id_product = $product['idproduct']; $warehouse_location->id_product_attribute = $product['idproductattribute']; $warehouse_location->id_warehouse = $this->id_warehouse; /*if ($product['area'] != '--') $warehouse_location->zone = $product['area']; if ($product['subarea'] != '--') $warehouse_location->sous_zone = $product['subarea'];*/ $warehouse_location->location = $product['location']; $warehouse_location->id_warehouse_product_location = $wpl_id; // if update location ok & advanced stock active -> generate stock movement if ($warehouse_location->update()) { //echo 'Maj location OK'; // No stock movement if advanced stock inactive if ($this->advanced_stock_management == 1) { $stock_mvt = new ErpStockMvt(); $stock_mvt->id_stock = $stock->id; $stock_mvt->id_order = 0; $stock_mvt->id_supply_order = 0; // if not mvt reason selected => depend of quantity to increase or decrease if (!isset($product['idreason']) || $product['idreason'] == '') { if ($inventory_product->qte_before <= $inventory_product->qte_after) { $stock_mvt->id_stock_mvt_reason = 1; } else { $stock_mvt->id_stock_mvt_reason = 2; } } else { $stock_mvt->id_stock_mvt_reason = $product['idreason']; } $stock_mvt->id_employee = $this->id_employee; $stock_mvt->employee_firstname = $this->firstname; $stock_mvt->employee_lastname = $this->lastname; $stock_mvt->price_te = $price; $stock_mvt->current_wa = $price; // Récupération du sign (flèche up / down) // Get sign (arrow up/down) if (isset($product['foundquantity']) && ((int) $product['foundquantity'] >= (int) $product['physicalquantity'] || (int) $product['foundquantity'] == 0)) { $stock_mvt->sign = 1; } else { $stock_mvt->sign = -1; } // calculate the quantity movement of stock $foundquantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity']; $physicalquantity = !isset($product['physicalquantity']) || $product['physicalquantity'] == '' ? 0 : (int) $product['physicalquantity']; $mvt = abs($foundquantity - $physicalquantity); $stock_mvt->physical_quantity = $mvt; // Synchronise available stock if ($stock_mvt->add(true)) { StockAvailable::synchronize($product['idproduct']); } else { $this->errors[] = Tools::displayError($this->l('Error while inserting stock movement. Please try again.')); } } else { $this->errors[] = Tools::displayError($this->l('No stock movement. You need to activate the advanced stock management in Preference > Products')); } } else { $this->errors[] = Tools::displayError($this->l('Error while updating product location')); } } } else { $this->errors[] = Tools::displayError($this->l('Error while updating stock')); } } else { $this->errors[] = Tools::displayError($this->l('Error while inserting product inventory row')); } } }