protected function generateProductsData() { $delimiter = ';'; $titles = array(); $id_lang = $this->use_lang; $new_path = new Sampledatainstall(); $f = fopen($new_path->sendPath() . 'output/products.vsc', 'w'); foreach ($this->product_fields as $field => $array) { $titles[] = $array['label']; } fputcsv($f, $titles, $delimiter, '"'); $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', false, true); foreach ($products as $product) { $line = array(); $p = new Product($product['id_product'], true, $id_lang, 1); foreach ($this->product_fields as $field => $array) { $line[$field] = property_exists('Product', $field) && !is_array($p->{$field}) && !Tools::isEmpty($p->{$field}) ? $p->{$field} : ''; } $cats = $p->getProductCategoriesFull($p->id, 1); $cat_array = array(); foreach ($cats as $cat) { $cat_array[] = $cat['id_category']; } $line['categories'] = implode(',', $cat_array); $line['price_tex'] = $p->getPrice(false); $line['price_tin'] = $p->getPrice(true); $line['upc'] = $p->upc ? $p->upc : ''; $line['features'] = ''; $features = $p->getFrontFeatures($id_lang); $position = 1; $devider = ''; foreach ($features as $feature) { $sql = 'SELECT `id_feature` FROM ' . _DB_PREFIX_ . 'feature_lang WHERE `name` = "' . pSql($feature['name']) . '"'; $sql1 = 'SELECT `id_feature_value` FROM ' . _DB_PREFIX_ . 'feature_value_lang WHERE `value` = "' . pSql($feature['value']) . '"'; $id_feature = Db::getInstance()->getValue($sql); $id_feature_value = Db::getInstance()->getValue($sql1); $line['features'] .= $devider . $id_feature . ':' . $id_feature_value . ':' . $position; $devider = ','; $position++; } $specificPrice = SpecificPrice::getSpecificPrice($p->id, 1, 0, 0, 0, 0); $line['reduction_price'] = ''; $line['reduction_percent'] = ''; $line['reduction_from'] = ''; $line['reduction_to'] = ''; if ($specificPrice) { if ($specificPrice['reduction_type'] == 'amount') { $line['reduction_price'] = $specificPrice['reduction']; } elseif ($specificPrice['reduction_type'] == 'percent') { $line['reduction_percent'] = $specificPrice['reduction']; } if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') { $line['reduction_from'] = $specificPrice['from']; $line['reduction_to'] = $specificPrice['to']; } } $tags = $p->getTags($id_lang); $line['tags'] = $tags; $link = new Link(); $imagelinks = array(); $images = $p->getImages($id_lang); foreach ($images as $image) { $imagelink = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']); $this->copyConverFileName($imagelink); $imagelinks[] = $imagelink; } $line['image'] = implode(',', $imagelinks); $line['delete_existing_images'] = 0; $line['shop'] = 1; $warehouses = Warehouse::getWarehousesByProductId($p->id); $line['warehouse'] = ''; if (!empty($warehouses)) { $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses)); } $values = array(); $accesories = $p->getAccessories($id_lang); if (isset($accesories) && $accesories && count($accesories)) { foreach ($accesories as $accesorie) { $values[] = $accesorie['id_product']; } } $line['accessories'] = $values ? implode(',', $values) : ''; $values = array(); $carriers = $p->getCarriers(); if (isset($carriers) && $carriers && count($carriers)) { foreach ($carriers as $carrier) { $values[] = $carrier['id_carrier']; } } $line['carriers'] = $values ? implode(',', $values) : ''; $values = array(); $customization_fields_ids = $p->getCustomizationFieldIds(); if (class_exists('CustomizationField') && isset($customization_fields_ids) && $customization_fields_ids && count($customization_fields_ids)) { foreach ($customization_fields_ids as $customization_field_id) { $cf = new CustomizationField($customization_field_id['id_customization_field'], $this->use_lang); $values[] = $cf->id . ':' . $cf->type . ':' . $cf->required . ':' . $cf->name; } } $line['customization_fields_ids'] = $values ? implode(',', $values) : ''; $values = array(); $attachments = $p->getAttachments($this->use_lang); if (isset($attachments) && $attachments && count($attachments)) { foreach ($attachments as $attachment) { $values[] = $attachment['id_attachment']; } } $line['attachments'] = $values ? implode(',', $values) : ''; if (!property_exists('Product', 'base_price')) { // for versions < 1.6.0.13 $line['base_price'] = !is_array($p->base_price) && !Tools::isEmpty($p->base_price) ? $p->base_price : ''; } if (!$line[$field]) { $line[$field] = ''; } fputcsv($f, $line, $delimiter, '"'); } fclose($f); }
/** * Return cart products * * @result array Products */ public function getProducts($refresh = false, $id_product = false, $id_country = null) { if (!$this->id) { return array(); } // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries if ($this->_products !== null && !$refresh) { // Return product row with specified ID if it exists if (is_int($id_product)) { foreach ($this->_products as $product) { if ($product['id_product'] == $id_product) { return array($product); } } return array(); } return $this->_products; } // Build query $sql = new DbQuery(); // Build SELECT $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`, cp.`price_more`,cp.`price_more_text`, cp.price_more_id, pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`, p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`, product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`, p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category, CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery, product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference'); // Build FROM $sql->from('cart_product', 'cp'); // Build JOIN $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)'); $sql->leftJoin('product_lang', 'pl', ' p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop')); $sql->leftJoin('category_lang', 'cl', ' product_shop.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop')); $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`'); // @todo test if everything is ok, then refactorise call of this method $sql->join(Product::sqlStock('cp', 'cp')); // Build WHERE clauses $sql->where('cp.`id_cart` = ' . (int) $this->id); if ($id_product) { $sql->where('cp.`id_product` = ' . (int) $id_product); } $sql->where('p.`id_product` IS NOT NULL'); // Build ORDER BY $sql->orderBy('cp.`date_add`, cp.`id_product`, cp.`id_product_attribute` ASC'); if (Customization::isFeatureActive()) { $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity'); $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id); $sql->groupBy('cp.`id_product_attribute`, cp.`id_product`, cp.`id_shop`'); } else { $sql->select('NULL AS customization_quantity, NULL AS id_customization'); } if (Combination::isFeatureActive()) { $sql->select(' product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr, IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference, (p.`weight`+ pa.`weight`) weight_attribute, IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13, IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc, IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity, IF(product_attribute_shop.wholesale_price > 0, product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price '); $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)'); } else { $sql->select('p.`reference` AS reference, p.`ean13`, p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price'); } $sql->select('image_shop.`id_image` id_image, il.`legend`'); $sql->leftJoin('image_shop', 'image_shop', 'image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $this->id_shop); $sql->leftJoin('image_lang', 'il', 'il.`id_image` = image_shop.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang); $result = Db::getInstance()->executeS($sql); // Reset the cache before the following return, or else an empty cart will add dozens of queries $products_ids = array(); $pa_ids = array(); if ($result) { foreach ($result as $key => $row) { $products_ids[] = $row['id_product']; $pa_ids[] = $row['id_product_attribute']; $specific_price = SpecificPrice::getSpecificPrice($row['id_product'], $this->id_shop, $this->id_currency, $id_country, $this->id_shop_group, $row['cart_quantity'], $row['id_product_attribute'], $this->id_customer, $this->id); if ($specific_price) { $reduction_type_row = array('reduction_type' => $specific_price['reduction_type']); } else { $reduction_type_row = array('reduction_type' => 0); } $result[$key] = array_merge($row, $reduction_type_row); } } // Thus you can avoid one query per product, because there will be only one query for all the products of the cart Product::cacheProductsFeatures($products_ids); Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang); $this->_products = array(); if (empty($result)) { return array(); } $ecotax_rate = (double) Tax::getProductEcotaxRate($this->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $apply_eco_tax = Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX'); $cart_shop_context = Context::getContext()->cloneContext(); foreach ($result as &$row) { if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) { $row['ecotax'] = (double) $row['ecotax_attr']; } $row['stock_quantity'] = (int) $row['quantity']; // for compatibility with 1.2 themes $row['quantity'] = (int) $row['cart_quantity']; if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) { $row['weight'] = (double) $row['weight_attribute']; } if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') { $address_id = (int) $this->id_address_invoice; } else { $address_id = (int) $row['id_address_delivery']; } if (!Address::addressExists($address_id)) { $address_id = null; } if ($cart_shop_context->shop->id != $row['id_shop']) { $cart_shop_context->shop = new Shop((int) $row['id_shop']); } $address = Address::initialize($address_id, true); $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context); $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator(); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, false, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, true, true, $cart_shop_context); $row['price_with_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, true, true, $cart_shop_context); $row['price'] = $row['price_with_reduction_without_tax'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, true, true, $cart_shop_context); if ($row['price_more']) { $row['price'] += $row['price_more']; } switch (Configuration::get('PS_ROUND_TYPE')) { case Order::ROUND_TOTAL: $row['total'] = $row['price_with_reduction_without_tax'] * (int) $row['cart_quantity']; $row['total_wt'] = $row['price_with_reduction'] * (int) $row['cart_quantity']; break; case Order::ROUND_LINE: $row['total'] = Tools::ps_round($row['price_with_reduction_without_tax'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); $row['total_wt'] = Tools::ps_round($row['price_with_reduction'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); break; case Order::ROUND_ITEM: default: $row['total'] = Tools::ps_round($row['price_with_reduction_without_tax'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity']; $row['total_wt'] = Tools::ps_round($row['price_with_reduction'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity']; break; } $row['price_wt'] = $row['price_with_reduction']; $row['description_short'] = Tools::nl2br($row['description_short']); if ($row['price_more']) { $row['price_wt'] += $row['price_more']; } // check if a image associated with the attribute exists if ($row['id_product_attribute']) { $row2 = Image::getBestImageAttribute($row['id_shop'], $this->id_lang, $row['id_product'], $row['id_product_attribute']); if ($row2) { $row = array_merge($row, $row2); } } $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction']; $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity']; $row['id_image'] = Product::defineProductImage($row, $this->id_lang); $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); $row['features'] = Product::getFeaturesStatic((int) $row['id_product']); if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) { $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]); } $row = Product::getTaxesInformations($row, $cart_shop_context); $this->_products[] = $row; } return $this->_products; }
public static function isDiscounted($id_product, $quantity = 1) { global $cookie, $cart; $id_customer = (Validate::isCookie($cookie) and isset($cookie->id_customer) and $cookie->id_customer) ? (int) $cookie->id_customer : NULL; $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_; $cart_quantity = !$cart ? 0 : Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' SELECT SUM(`quantity`) FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' AND `id_cart` = ' . (int) $cart->id); $quantity = $cart_quantity ? $cart_quantity : $quantity; $id_currency = (int) (Validate::isLoadedObject($cart) ? $cart->id_currency : ((isset($cookie->id_currency) and (int) $cookie->id_currency) ? $cookie->id_currency : Configuration::get('PS_CURRENCY_DEFAULT'))); $ids = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $id_country = (int) ($ids['id_country'] ? $ids['id_country'] : Configuration::get('PS_COUNTRY_DEFAULT')); $id_shop = (int) Shop::getCurrentShop(); return (bool) SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity); }
protected function productImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, $shop_ids, $match_ref, &$accessories, $validateOnly = false) { if ($force_ids && isset($info['id']) && (int) $info['id']) { $product = new Product((int) $info['id']); } elseif ($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']) . '" ', false); 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(); } $update_advanced_stock_management_value = false; if (isset($product->id) && $product->id && Product::existsInDatabase((int) $product->id, 'product')) { $product->loadStockData(); $update_advanced_stock_management_value = true; $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); if (!$shop_is_feature_active) { $product->shop = (int) Configuration::get('PS_SHOP_DEFAULT'); } elseif (!isset($product->shop) || empty($product->shop)) { $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID()); } if (!$shop_is_feature_active) { $product->id_shop_default = (int) Configuration::get('PS_SHOP_DEFAULT'); } 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, $this->trans('Unknown tax rule group ID. You need to create a group with this ID first.', array(), 'Admin.Parameters.Notification')); } } 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; $manufacturer->active = true; if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $manufacturer->add()) { $product->id_manufacturer = (int) $manufacturer->id; $manufacturer->associateTo($product->id_shop_list); } else { if (!$validateOnly) { $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $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 && !$validateOnly && $supplier->add()) { $product->id_supplier = (int) $supplier->id; $supplier->associateTo($product->id_shop_list); } else { if (!$validateOnly) { $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $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 && !$validateOnly && $category_to_create->add()) { $product->id_category[] = (int) $category_to_create->id; } else { if (!$validateOnly) { $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } } elseif (!$validateOnly && 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($this->trans('%1$s cannot be saved', array(), 'Admin.Parameters.Notification'), trim($value)); } } } $product->id_category = array_values(array_unique($product->id_category)); // Will update default category if category column is not ignored AND if there is categories that are set in the import file row. if (isset($product->id_category[0])) { $product->id_category_default = (int) $product->id_category[0]; } else { $defaultProductShop = new Shop($product->id_shop_default); $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id; } } // Will update default category if there is none set here. Home if no category at all. if (!isset($product->id_category_default) || !$product->id_category_default) { // this if will avoid ereasing default category if category column is not present in the CSV file (or ignored) if (isset($product->id_category[0])) { $product->id_category_default = (int) $product->id_category[0]; } else { $defaultProductShop = new Shop($product->id_shop_default); $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id; } } $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->informations[] = sprintf($this->trans('Rewrite link for %1$s (ID %2$s): re-written as %3$s.', array(), 'Admin.Parameters.Notification'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite); } if (!$valid_link || !($match_ref || $force_ids) || !(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; $productExistsInDatabase = false; if ($product->id && Product::existsInDatabase((int) $product->id, 'product')) { $productExistsInDatabase = true; } if ($match_ref && $product->reference && $product->existsRefInDatabase($product->reference) || $productExistsInDatabase) { $product->date_upd = date('Y-m-d H:i:s'); } $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 ($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) . '" ', false); $product->id = (int) $datas['id_product']; $product->date_add = pSQL($datas['date_add']); $res = $validateOnly || $product->update(); } elseif ($productExistsInDatabase) { $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, false); $product->date_add = pSQL($datas['date_add']); $res = $validateOnly || $product->update(); } // If no id_product or update failed $product->force_id = (bool) $force_ids; if (!$res) { if (isset($product->date_add) && $product->date_add != '') { $res = $validateOnly || $product->add(false); } else { $res = $validateOnly || $product->add(); } } if (!$validateOnly) { if ($product->getType() == Product::PTYPE_VIRTUAL) { StockAvailable::setProductOutOfStock((int) $product->id, 1); } else { StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock); } if ($product_download_id = ProductDownload::getIdFromIdProduct((int) $product->id)) { $product_download = new ProductDownload($product_download_id); $product_download->delete(true); } if ($product->getType() == Product::PTYPE_VIRTUAL) { $product_download = new ProductDownload(); $product_download->filename = ProductDownload::getNewFilename(); Tools::copy($info['file_url'], _PS_DOWNLOAD_DIR_ . $product_download->filename); $product_download->id_product = (int) $product->id; $product_download->nb_downloadable = (int) $info['nb_downloadable']; $product_download->date_expiration = $info['date_expiration']; $product_download->nb_days_accessible = (int) $info['nb_days_accessible']; $product_download->display_filename = basename($info['file_url']); $product_download->add(); } } } $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($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), 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 (!$validateOnly && 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_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(); 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 (!$validateOnly && !$specific_price->save()) { $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid')); } } } if (!$validateOnly && 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 (!$validateOnly && isset($product->delete_existing_images)) { if ((bool) $product->delete_existing_images) { $product->deleteImages(); } } if (!$validateOnly && 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; $alt = $product->image_alt[$key]; if (strlen($alt) > 0) { $image->legend = self::createMultiLangField($alt); } // 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', !$regenerate)) { $image->delete(); $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url); } } else { $error = true; } } else { $error = true; } if ($error) { $this->warnings[] = sprintf($this->trans('Product #%1$d: the picture (%2$s) cannot be saved.', array(), 'Admin.Parameters.Notification'), $image->id_product, $url); } } } if (!$validateOnly && isset($product->id_category) && is_array($product->id_category)) { $product->updateCategories(array_map('intval', $product->id_category)); } $product->checkDefaultAttributes(); if (!$validateOnly && !$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } // Features import $features = get_object_vars($product); if (!$validateOnly && 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 ($force_ids || $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 (!$validateOnly && isset($product->advanced_stock_management)) { if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) { $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]); } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]); } elseif ($update_advanced_stock_management_value) { $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($this->trans('Advanced stock management is not enabled, warehouse not set on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]); } elseif (!$validateOnly) { 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($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $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($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]); } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->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_id]); } elseif (!$validateOnly) { StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock); } // This code allows us to set qty and disable depends on stock if (!$validateOnly && 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_is_feature_active) { 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); } } } } elseif (!$validateOnly) { // if not depends_on_stock set, use normal qty if ($shop_is_feature_active) { 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); } } // Accessories linkage if (isset($product->accessories) && !$validateOnly && is_array($product->accessories) && count($product->accessories)) { $accessories[$product->id] = $product->accessories; } } }
public static function isDiscounted($id_product, $quantity = 1, Context $context = null) { if (!$context) { $context = Context::getContext(); } $id_group = $context->customer->id_default_group; $cart_quantity = !$context->cart ? 0 : Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' SELECT SUM(`quantity`) FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' AND `id_cart` = ' . (int) $context->cart->id); $quantity = $cart_quantity ? $cart_quantity : $quantity; $id_currency = (int) $context->currency->id; $ids = Address::getCountryAndState((int) $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $id_country = (int) ($ids['id_country'] ? $ids['id_country'] : Configuration::get('PS_COUNTRY_DEFAULT')); return (bool) SpecificPrice::getSpecificPrice((int) $id_product, $context->shop->id, $id_currency, $id_country, $id_group, $quantity); }
if ((double) substr(_PS_VERSION_, 0, 3) < 1.6) { $reference = '\'' . $reference . '\''; } $combination = $product_attribute_id . '|' . $quantity . '|' . $new_price . '|0|' . $image . '|' . $reference . '|0.00|' . $minimal_quantity . '|'; // Add for Prestashop 1.5 version and above if ((double) substr(_PS_VERSION_, 0, 3) >= 1.5) { // Add product attribute shop Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'product_attribute_shop (id_product_attribute, id_shop, price, wholesale_price, weight, minimal_quantity, available_date) VALUES (' . $product_attribute_id . ', ' . $shop_id . ', ' . $new_price . ', ' . $wholesale_price . ', ' . $weight . ', ' . $minimal_quantity . ', "0000-00-00")'); // Add stock availability $product_tmp = new Product($request_product); Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'stock_available (id_product, id_product_attribute, id_shop, id_shop_group, quantity, out_of_stock) VALUES (' . $request_product . ', ' . $product_attribute_id . ', ' . $shop_id . ', 0, ' . $quantity . ', ' . $product_tmp->out_of_stock . ')'); // Update stock for base product Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'stock_available SET quantity = quantity + ' . $quantity . ' WHERE id_product = ' . $request_product . ' AND id_product_attribute = 0 AND ' . 'id_shop = ' . $shop_id); // Specific price $country_id = (int) Db::getInstance()->getValue('SELECT id_country FROM ' . _DB_PREFIX_ . 'address WHERE id_customer = ' . (int) $cookie->id_customer . ' AND active = 1 ORDER by id_address ASC'); $specific_price = SpecificPrice::getSpecificPrice($request_product, $shop_id, (int) $cookie->id_currency, $country_id, $group_id, $quantity, $product_attribute_id, (int) $cookie->id_customer); if (!empty($specific_price)) { if ($specific_price['reduction_type'] == 'percentage') { $specific_price_combination = (double) $specific_price['reduction'] * 100 . '|0|' . (double) $specific_price['price'] . '|percentage|'; } else { $specific_price_combination = '0|' . (double) $specific_price['reduction'] . '|' . (double) $specific_price['price'] . '|amount|'; } } else { $specific_price_combination = '0|0|0|\'\'|'; } // Attribute datas $group_name = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'attribute_group_lang WHERE id_attribute_group = ' . $group . ' AND id_lang = ' . (int) $cookie->id_lang); $attribute = $attribute_id . '|\'' . $request_value . '\'|\'' . $group_name . '\'|\'' . $group . '\'|'; // Return string $combination .= '0000-00-00|' . $specific_price_combination . $attribute; // Add weight, attributes names for Prestashop 1.6.0.6 and above
/** * Price calculation / Get product price * * @param integer $id_shop Shop id * @param integer $id_product Product id * @param integer $id_product_attribute Product attribute id * @param integer $id_country Country id * @param integer $id_state State id * @param integer $id_currency Currency id * @param integer $id_group Group id * @param integer $quantity Quantity Required for Specific prices : quantity discount application * @param boolean $use_tax with (1) or without (0) tax * @param integer $decimals Number of decimals returned * @param boolean $only_reduc Returns only the reduction amount * @param boolean $use_reduc Set if the returned amount will include reduction * @param boolean $with_ecotax insert ecotax in price output. * @param variable_reference $specific_price_output * If a specific price applies regarding the previous parameters, this variable is filled with the corresponding SpecificPrice object * @return float Product price **/ public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0) { static $address = null; static $context = null; if ($address === null) $address = new Address(); if ($context == null) $context = Context::getContext()->cloneContext(); if ($id_shop !== null && $context->shop->id != (int)$id_shop) $context->shop = new Shop((int)$id_shop); if (!$use_customer_price) $id_customer = 0; if ($id_product_attribute === null) $id_product_attribute = Product::getDefaultAttribute($id_product); $cache_id = $id_product.'-'.$id_shop.'-'.$id_currency.'-'.$id_country.'-'.$id_state.'-'.$zipcode.'-'.$id_group. '-'.$quantity.'-'.$id_product_attribute.'-'.($use_tax?'1':'0').'-'.$decimals.'-'.($only_reduc?'1':'0'). '-'.($use_reduc?'1':'0').'-'.$with_ecotax.'-'.$id_customer.'-'.(int)$use_group_reduction.'-'.(int)$id_cart.'-'.(int)$real_quantity; // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice( (int)$id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity ); if (isset(self::$_prices[$cache_id])) return self::$_prices[$cache_id]; // fetch price & attribute price $cache_id_2 = $id_product.'-'.$id_shop; if (!isset(self::$_pricesLevel2[$cache_id_2])) { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = '.(int)$id_shop.')'); $sql->where('p.`id_product` = '.(int)$id_product); if (Combination::isFeatureActive()) { $sql->select('product_attribute_shop.id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on'); $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product` = p.`id_product`'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product_attribute = pa.id_product_attribute AND product_attribute_shop.id_shop = '.(int)$id_shop.')'); } else $sql->select('0 as id_product_attribute'); $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); foreach ($res as $row) { $array_tmp = array( 'price' => $row['price'], 'ecotax' => $row['ecotax'], 'attribute_price' => (isset($row['attribute_price']) ? $row['attribute_price'] : null) ); self::$_pricesLevel2[$cache_id_2][(int)$row['id_product_attribute']] = $array_tmp; if (isset($row['default_on']) && $row['default_on'] == 1) self::$_pricesLevel2[$cache_id_2][0] = $array_tmp; } } if (!isset(self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute])) return; $result = self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute]; if (!$specific_price || $specific_price['price'] < 0) $price = (float)$result['price']; else $price = (float)$specific_price['price']; // convert only if the specific price is in the default currency (id_currency = 0) if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) $price = Tools::convertPrice($price, $id_currency); // Attribute price if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) { $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (float)$result['attribute_price'] : 0, $id_currency); // If you want the default combination, please use NULL value instead if ($id_product_attribute !== false) $price += $attribute_price; } // Tax $address->id_country = $id_country; $address->id_state = $id_state; $address->postcode = $zipcode; $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int)$id_product, $context)); $product_tax_calculator = $tax_manager->getTaxCalculator(); // Add Tax if ($use_tax) $price = $product_tax_calculator->addTaxes($price); // Reduction $specific_price_reduction = 0; if (($only_reduc || $use_reduc) && $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); $specific_price_reduction = !$use_tax ? $product_tax_calculator->removeTaxes($reduction_amount) : $reduction_amount; } else $specific_price_reduction = $price * $specific_price['reduction']; } if ($use_reduc) $price -= $specific_price_reduction; // Group reduction if ($use_group_reduction) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if($context->customer->id){ $id_group = array(); $customer_groups = Db::getInstance()->executeS("SELECT id_group FROM ps_customer_group WHERE id_customer={$context->customer->id}"); foreach ($customer_groups as $row_group) $id_group[] = $row_group['id_group']; }else $id_group = array($id_group); if ($reduction_from_category !== false) $group_reduction = $price * (float)$reduction_from_category; else // apply group reduction if there is no group reduction for this category $group_reduction = (($reduc = Group::getReductionByIdGroup($id_group)) != 0) ? ($price * $reduc / 100) : 0; } else $group_reduction = 0; if ($only_reduc) return Tools::ps_round($group_reduction + $specific_price_reduction, $decimals); if ($use_reduc) $price -= $group_reduction; // Eco Tax if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) $ecotax = $result['attribute_ecotax']; if ($id_currency) $ecotax = Tools::convertPrice($ecotax, $id_currency); if ($use_tax) { // reinit the tax manager for ecotax handling $tax_manager = TaxManagerFactory::getManager( $address, (int)Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID') ); $ecotax_tax_calculator = $tax_manager->getTaxCalculator(); $price += $ecotax_tax_calculator->addTaxes($ecotax); } else $price += $ecotax; } $price = Tools::ps_round($price, $decimals); if ($price < 0) $price = 0; self::$_prices[$cache_id] = $price; return self::$_prices[$cache_id]; }
public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0, $service_date = null, $service_time_from = null, $service_time_to = null) { require_once dirname(__FILE__) . '/../../modules/aphrodinet/classes/AphCustomPrice.php'; static $address = null; static $context = null; if ($address === null) { $address = new Address(); } if ($context == null) { $context = Context::getContext()->cloneContext(); } if ($id_shop !== null && $context->shop->id != (int) $id_shop) { $context->shop = new Shop((int) $id_shop); } if (!$use_customer_price) { $id_customer = 0; } if ($id_product_attribute === null) { $id_product_attribute = Product::getDefaultAttribute($id_product); } if (!empty($id_cart)) { $res = Db::getInstance()->executeS('SELECT `delivery_date`, `delivery_time_from`, `delivery_time_to` ' . 'FROM ' . _DB_PREFIX_ . 'cart_product ' . 'WHERE `id_cart` = ' . (int) $id_cart . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute . ' ' . 'LIMIT 1'); if (!empty($res) && empty($service_date)) { $res = $res[0]; if (!empty($res)) { $service_date = $res['delivery_date']; $service_time_from = $res['delivery_time_from']; $service_time_to = $res['delivery_time_to']; } } } if (!empty($service_time_from) && strlen($service_time_from) == 5) { $service_time_from .= ':00'; } if (!empty($service_time_to) && strlen($service_time_to) == 5) { $service_time_to .= ':00'; } $cache_id = (int) $id_product . '-' . (int) $id_shop . '-' . (int) $id_currency . '-' . (int) $id_country . '-' . $id_state . '-' . $zipcode . '-' . (int) $id_group . '-' . (int) $quantity . '-' . (int) $id_product_attribute . '-' . (int) $with_ecotax . '-' . (int) $id_customer . '-' . (int) $use_group_reduction . '-' . (int) $id_cart . '-' . (int) $real_quantity . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . ($use_tax ? '1' : '0') . '-' . (int) $decimals . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : ''); // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity); if (isset(self::$_prices[$cache_id])) { if (isset($specific_price['price']) && $specific_price['price'] > 0) { $specific_price['price'] = self::$_prices[$cache_id]; } return self::$_prices[$cache_id]; } $cache_id_2 = $id_product . '-' . $id_shop . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : ''); if (!isset(self::$_pricesLevel2[$cache_id_2])) { $base_price_wt = 0; $service_date_ts = strtotime($service_date); $service_date_week_day = date('w', $service_date_ts); if (!empty($service_date) && $service_date != '0000-00-00') { // cerco il prezzo del giorno $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, NULL, 1); if (!empty($custom_prices)) { $base_price_wt = $custom_prices[0]['price_wt']; } } if (!empty($service_date) && $service_date != '0000-00-00') { $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, 0, 1); } if (!empty($service_date) && $service_date != '0000-00-00') { $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, 0, 1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from); } if (!empty($offer_prices)) { $res = $offer_prices; } elseif (!empty($custom_prices)) { $res = $custom_prices; } else { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = ' . (int) $id_shop . ')'); $sql->where('p.`id_product` = ' . (int) $id_product); if (Combination::isFeatureActive()) { $sql->select('IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product = p.id_product AND product_attribute_shop.id_shop = ' . (int) $id_shop . ')'); } else { $sql->select('0 as id_product_attribute'); } $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); } if (is_array($res) && count($res)) { foreach ($res as $row) { if ($row['price'] < 0) { if ($row['reduction_type'] == 'amount') { $row['price'] = 0; //$base_price_wt - $row['reduction']; } else { $row['price'] = 0; //$base_price_wt - (($row['reduction'] * $base_price_wt) / 100); } } else { $row['price'] = 0; //$row['price_wt']; } $array_tmp = array('price' => $row['price'], 'ecotax' => !empty($row['ecotax']), 'attribute_price' => isset($row['attribute_price']) ? $row['attribute_price'] : null); self::$_pricesLevel2[$cache_id_2][(int) $row['id_product_attribute']] = $array_tmp; if (isset($row['default_on']) && $row['default_on'] == 1) { self::$_pricesLevel2[$cache_id_2][0] = $array_tmp; } } } } if (!isset(self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute])) { return; } $result = self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute]; if (!$specific_price || $specific_price['price'] < 0) { $price = (double) $result['price']; } else { $price = (double) $specific_price['price']; } if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) { $price = Tools::convertPrice($price, $id_currency); if (isset($specific_price['price'])) { $specific_price['price'] = $price; } } if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) { $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (double) $result['attribute_price'] : 0, $id_currency); if ($id_product_attribute !== false) { $price += $attribute_price; } } $address->id_country = $id_country; $address->id_state = $id_state; $address->postcode = $zipcode; $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $id_product, $context)); $product_tax_calculator = $tax_manager->getTaxCalculator(); if ($use_tax) { $price = $product_tax_calculator->addTaxes($price); } if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) { $ecotax = $result['attribute_ecotax']; } if ($id_currency) { $ecotax = Tools::convertPrice($ecotax, $id_currency); } if ($use_tax) { $tax_manager = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID')); $ecotax_tax_calculator = $tax_manager->getTaxCalculator(); $price += $ecotax_tax_calculator->addTaxes($ecotax); } else { $price += $ecotax; } } $specific_price_reduction = 0; if (($only_reduc || $use_reduc) && $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) { $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); } $specific_price_reduction = $reduction_amount; if (!$use_tax && $specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->removeTaxes($specific_price_reduction); } if ($use_tax && !$specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->addTaxes($specific_price_reduction); } } else { $specific_price_reduction = $price * $specific_price['reduction']; } } if ($use_reduc) { $price -= $specific_price_reduction; } if ($use_group_reduction) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if ($reduction_from_category !== false) { $group_reduction = $price * (double) $reduction_from_category; } else { // apply group reduction if there is no group reduction for this category $group_reduction = ($reduc = Group::getReductionByIdGroup($id_group)) != 0 ? $price * $reduc / 100 : 0; } $price -= $group_reduction; } if ($only_reduc) { return Tools::ps_round($specific_price_reduction, $decimals); } $price = Tools::ps_round($price, $decimals); if ($price < 0) { $price = 0; } self::$_prices[$cache_id] = $price; return self::$_prices[$cache_id]; }
public function postProcess() { if (Tools::isSubmit('submitExport')) { $delimiter = Tools::getValue('export_delimiter'); $id_lang = Tools::getValue('export_language'); $id_shop = (int) $this->context->shop->id; set_time_limit(0); $fileName = 'products_' . date("Y_m_d_H_i_s") . '.csv'; header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Description: File Transfer'); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename={$fileName}"); header("Expires: 0"); header("Pragma: public"); $f = fopen('php://output', 'w'); foreach ($this->available_fields as $field => $array) { $titles[] = $array['label']; } fputcsv($f, $titles, $delimiter, '"'); $export_active = Tools::getValue('export_active') == 0 ? false : true; $export_category = Tools::getValue('export_category') == 99999 ? false : Tools::getValue('export_category'); $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', $export_category, $export_active); foreach ($products as $product) { $line = array(); $p = new Product($product['id_product'], true, $id_lang, $id_shop); $p->loadStockData(); foreach ($this->available_fields as $field => $array) { if (isset($p->{$field}) && !is_array($p->{$field})) { $line[$field] = $p->{$field} ? $p->{$field} : ' '; } else { switch ($field) { case 'categories': $cats = $p->getProductCategoriesFull($p->id, $id_lang); $cat_array = array(); foreach ($cats as $cat) { $cat_array[] = $cat['name']; } $line['categories'] = implode(",", $cat_array); break; case 'price_tex': $line['price_tex'] = $p->getPrice(false); $line['price_tin'] = $p->getPrice(true); break; case 'upc': $line['upc'] = $p->upc ? $p->upc : ' '; break; case 'features': $line['features'] = ''; $features = $p->getFrontFeatures($id_lang); $position = 1; foreach ($features as $feature) { $line['features'] .= $feature['name'] . ':' . $feature['value'] . ':' . $position; $position++; } break; case 'reduction_price': $specificPrice = SpecificPrice::getSpecificPrice($p->id, $id_shop, 0, 0, 0, 0); $line['reduction_price'] = ''; $line['reduction_percent'] = ''; $line['reduction_from'] = ''; $line['reduction_to'] = ''; if ($specificPrice['reduction_type'] == "amount") { $line['reduction_price'] = $specificPrice['reduction']; } elseif ($specificPrice['reduction_type'] == "percent") { $line['reduction_percent'] = $specificPrice['reduction']; } if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') { $line['reduction_from'] = date_format(date_create($specificPrice['from']), "Y-m-d"); $line['reduction_to'] = date_format(date_create($specificPrice['to']), "Y-m-d"); } break; case 'tags': $tags = $p->getTags($id_lang); $line['tags'] = $tags; break; case 'image': $link = new Link(); $imagelinks = array(); $images = $p->getImages($id_lang); foreach ($images as $image) { $imagelinks[] = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']); } $line['image'] = implode(",", $imagelinks); break; case 'delete_existing_images': $line['delete_existing_images'] = 0; break; case 'shop': $line['shop'] = $id_shop; break; case 'warehouse': $warehouses = Warehouse::getWarehousesByProductId($p->id); $line['warehouse'] = ''; if (!empty($warehouses)) { $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses)); } break; case 'date_added': $date = new DateTime($p->date_add); $line['date_add'] = $date->format("Y-m-d"); break; } } } if (!$line[$field]) { $line[$field] = ''; } fputcsv($f, $line, $delimiter, '"'); } fclose($f); die; } }
/** * Update product quantity * * @param int $quantity Quantity to add (or substract) * @param int $id_product Product ID * @param int $id_product_attribute Attribute ID if needed * @param string $operator Indicate if quantity must be increased or decreased */ public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true) { //error_log(__LINE__.'@'.__FILE__); if (!$shop) { $shop = Context::getContext()->shop; } if (Context::getContext()->customer->id) { if ($id_address_delivery == 0 && (int) $this->id_address_delivery) { // The $id_address_delivery is null, use the cart delivery address $id_address_delivery = $this->id_address_delivery; } elseif ($id_address_delivery == 0) { // The $id_address_delivery is null, get the default customer address $id_address_delivery = (int) Address::getFirstCustomerAddressId((int) Context::getContext()->customer->id); } elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) { // The $id_address_delivery must be linked with customer $id_address_delivery = 0; } } $quantity = (int) $quantity; $id_product = (int) $id_product; $id_product_attribute = (int) $id_product_attribute; $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id); if ($id_product_attribute) { $combination = new Combination((int) $id_product_attribute); if ($combination->id_product != $id_product) { return false; } } /* If we have a product combination, the minimal quantity is set with the one of this combination */ if (!empty($id_product_attribute)) { $minimal_quantity = (int) Attribute::getAttributeMinimalQty($id_product_attribute); } else { $minimal_quantity = (int) $product->minimal_quantity; } if (!Validate::isLoadedObject($product)) { die(Tools::displayError()); } if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } Hook::exec('actionBeforeCartUpdateQty', array('cart' => $this, 'product' => $product, 'id_product_attribute' => $id_product_attribute, 'id_customization' => $id_customization, 'quantity' => $quantity, 'operator' => $operator, 'id_address_delivery' => $id_address_delivery, 'shop' => $shop, 'auto_add_cart_rule' => $auto_add_cart_rule)); if ((int) $quantity <= 0) { return $this->deleteProduct($id_product, $id_product_attribute, (int) $id_customization); } elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE') && !defined('_PS_ADMIN_DIR_')) { return false; } else { /* Check if the product is already in the cart */ $result = $this->containsProduct($id_product, $id_product_attribute, (int) $id_customization, (int) $id_address_delivery); /* Update quantity if product already exist */ if ($result) { if ($operator == 'up') { $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'product p ' . Product::sqlStock('p', $id_product_attribute, true, $shop) . ' WHERE p.id_product = ' . $id_product; $result2 = Db::getInstance()->getRow($sql); $product_qty = (int) $result2['quantity']; // Quantity for product pack if (Pack::isPack($id_product)) { $product_qty = Pack::getQuantity($id_product, $id_product_attribute); } $new_qty = (int) $result['quantity'] + (int) $quantity; $qty = '+ ' . (int) $quantity; if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ($new_qty > $product_qty) { return false; } } } elseif ($operator == 'down') { $qty = '- ' . (int) $quantity; $new_qty = (int) $result['quantity'] - (int) $quantity; if ($new_qty < $minimal_quantity && $minimal_quantity > 1) { return -1; } } else { return false; } /* Delete product from cart */ if ($new_qty <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } elseif ($new_qty < $minimal_quantity) { return -1; } else { Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'cart_product` SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW() WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = ' . (int) $id_address_delivery : '') . ' LIMIT 1'); } } elseif ($operator == 'up') { $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'product p ' . Product::sqlStock('p', $id_product_attribute, true, $shop) . ' WHERE p.id_product = ' . $id_product; $result2 = Db::getInstance()->getRow($sql); // Quantity for product pack if (Pack::isPack($id_product)) { $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute); } if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ((int) $quantity > $result2['quantity']) { return false; } } if ((int) $quantity < $minimal_quantity) { return -1; } $context = Context::getContext(); $context->shop->id = Tools::getIsset('ids') ? Tools::getValue('ids') : $shop->id; $specific_price = SpecificPrice::getSpecificPrice($id_product, $context->shop->id, null, null, null, 1, null, 0, 0, 0); $delivery_date = Tools::getIsset('delivery_date') ? Tools::getValue('delivery_date') : ''; $delivery_time_from = Tools::getIsset('delivery_time_from') ? Tools::getValue('delivery_time_from') : ''; $delivery_time_to = Tools::getIsset('delivery_time_to') ? Tools::getValue('delivery_time_to') : ''; // $price = Product::getPriceStatic($id_product, true, 0, 2, null, false, true, 1, false, null, null, null, $specific_price, true, true, $context, true, $delivery_date, $delivery_time_from, $delivery_time_to); // if (empty($price)) // $price = $product->price; $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'id_address_delivery' => (int) $id_address_delivery, 'id_shop' => Tools::getIsset('ids') ? Tools::getValue('ids') : $shop->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s'), 'delivery_date' => $delivery_date, 'delivery_time_from' => $delivery_time_from, 'delivery_time_to' => $delivery_time_to)); if (!$result_add) { return false; } } } // refresh cache of self::_products $this->_products = $this->getProducts(true); $this->update(); $context = Context::getContext()->cloneContext(); $context->cart = $this; Cache::clean('getContextualValue_*'); if ($auto_add_cart_rule) { CartRule::autoAddToCart($context); } if ($product->customizable) { return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery, $operator); } else { return true; } }
public function productImport() { $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); foreach ($category_data as $tmp) { $product->category[] = $tmp; } } AdminImportController::setEntityDefaultValues($product); AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product); 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; } else { if (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; } else { if (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; } else { if (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, '.', ''); } } else { if (isset($product->price_tin) && isset($product->price_tex)) { $product->price = $product->price_tex; } } } 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(); } } } else { if (is_string($value) && !empty($value)) { $category = Category::searchByName($id_lang, trim($value), true); if ($category['id_category']) { $product->id_category[] = (int) $category['id_category']; } else { $category_to_create = new Category(); if (!Shop::isFeatureActive()) { $category_to_create->id_shop_default = 1; } else { $category_to_create->id_shop_default = (int) Context::getContext()->shop->id; } $category_to_create->name = AdminImportController::createMultiLangField(trim($value)); $category_to_create->active = 1; $category_to_create->id_parent = (int) 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(); } } } } } } $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : ''; $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') || !(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') == 1 && $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(); } else { if ($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 if (!$res) { if (isset($product->date_add) && $product->date_add != '') { $res = $product->add(false); } else { $res = $product->add(); } } } $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_supplier) && property_exists($product, 'supplier_reference')) { $id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier); if ($id_product_supplier) { $product_supplier = new ProductSupplier((int) $id_product_supplier); } else { $product_supplier = new ProductSupplier(); } $product_supplier->id_product = $product->id; $product_supplier->id_product_attribute = 0; $product_supplier->id_supplier = $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')); } } } 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(); } else { if (isset($product->image) && is_array($product->image) && count($product->image)) { $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 n°%1$d: the picture cannot be saved: %2$s'), $image->id_product, $url); } } } if (isset($product->id_category)) { $product->updateCategories(array_map('intval', $product->id_category)); } // 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] : 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(); } // stock available if (Shop::isFeatureActive()) { foreach ($shops as $shop) { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, $this->context->shop->id); } } $this->closeCsvFile($handle); }
public static function setProductsSpecificPrices($id_search, $id_criterion_group, $id_product = false) { $specific_prices_cache = Db::getInstance()->ExecuteS(' SELECT * FROM `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` app, `' . _DB_PREFIX_ . 'pm_advancedsearch_cache_product_' . $id_search . '` acp WHERE app.`id_cache_product`=acp.`id_cache_product` AND app.`is_specific`=1 ' . ($id_product != false ? ' AND acp.`id_product`=' . (int) $id_product : '') . ' ' . (version_compare(_PS_VERSION_, '1.5.0.0', '>=') ? ' AND app.`id_shop`=' . (int) self::getShopBySearch($id_search) : '') . ' GROUP BY acp.`id_product`, app.`id_shop`, app.`id_currency`, app.`id_country`, app.`id_group`'); if ($id_product == false) { Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` SET `valid_id_specific_price`=0'); } else { Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` app, `' . _DB_PREFIX_ . 'pm_advancedsearch_cache_product_' . $id_search . '` acp SET app.`valid_id_specific_price`=0 WHERE app.`id_cache_product`=acp.`id_cache_product` AND acp.`id_product`=' . (int) $id_product); } if ($specific_prices_cache && AdvancedSearchCoreClass::_isFilledArray($specific_prices_cache)) { foreach ($specific_prices_cache as $row) { if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) { $specific_price = SpecificPrice::getSpecificPrice((int) $row['id_product'], (int) $row['id_shop'], (int) $row['id_currency'], (int) $row['id_country'], (int) $row['id_group'], 1, null, 0, 0, 1); } else { $specific_price = SpecificPrice::getSpecificPrice((int) $row['id_product'], (int) $row['id_shop'], (int) $row['id_currency'], (int) $row['id_country'], (int) $row['id_group'], 1); } if ($specific_price && AdvancedSearchCoreClass::_isFilledArray($specific_price)) { Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` SET `valid_id_specific_price`=1 WHERE `id_group`=' . (int) $row['id_group'] . ' AND `id_cache_product`=' . (int) $row['id_cache_product'] . ' AND `id_specific_price`=' . (int) $specific_price['id_specific_price']); } else { Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` SET `has_no_specific`=1 WHERE `id_group`=' . (int) $row['id_group'] . ' AND `id_cache_product`=' . (int) $row['id_cache_product'] . (version_compare(_PS_VERSION_, '1.5.0.0', '>=') ? ' AND `id_shop`=' . (int) $row['id_shop'] : '')); Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` WHERE `id_group`=' . (int) $row['id_group'] . ' AND `is_specific`=1 AND `id_cache_product`=' . (int) $row['id_cache_product'] . (version_compare(_PS_VERSION_, '1.5.0.0', '>=') ? ' AND `id_shop`=' . (int) $row['id_shop'] : '')); } } } Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` app JOIN (SELECT `id_cache_product`, `id_shop`, `id_group` FROM `' . _DB_PREFIX_ . 'pm_advancedsearch_product_price_' . $id_search . '` GROUP BY `id_cache_product`, `id_shop`, `id_group` HAVING SUM(`is_specific`)=0) as app2 ON (app.`id_cache_product`=app2.`id_cache_product` AND app.`id_shop`=app2.`id_shop` AND app.`id_group`=app2.`id_group`) SET app.`has_no_specific`=1 '); }
public function productImport() { $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 (self::ignoreRow($info)) { continue; } 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(); } } else { if (array_key_exists('id', $info) && is_string($info['id'])) { $prod = self::findProductByName($default_language_id, $info['id'], $info['name']); if ($prod['id_product']) { $info['id'] = (int) $prod['id_product']; } } if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) { $product = new Product((int) $info['id']); $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; } } } } else { $product = new Product(); } } AdminImportController::setEntityDefaultValues($product); AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product); 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; } $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 ($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; } $properties = $product->productProperties(); if ((double) $properties['pp_unit_price_ratio'] > 0) { $product->unit_price = (double) $product->price / (double) $properties['pp_unit_price_ratio']; } if (isset($product->category) && is_array($product->category) && count($product->category)) { $product->id_category = 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'); $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); } 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); } } } } foreach (Product::$definition['fields'] as $key => $array) { if ($array['type'] == Product::TYPE_FLOAT) { $product->{$key} = str_replace(',', '.', $product->{$key}); } } $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) { if ($product->quantity == null) { $product->quantity = 0; } 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(); } $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 (!$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 { 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 (!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(); 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')); } } } 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; } } } 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; } } } } 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; if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) { $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 = 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); } } } Feature::cleanPositions(); 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); } if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } } 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)) { $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id); 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]); } } } 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); } if (isset($product->quantity) && $product->quantity) { 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((double) $price, 6); $warehouse = new Warehouse($product->warehouse); if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, $product->quantity, 1, $price, true)) { StockAvailable::synchronize((int) $product->id); } } else { if (Shop::isFeatureActive()) { foreach ($shops as $shop) { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id); } } } } else { if (Shop::isFeatureActive()) { foreach ($shops as $shop) { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id); } } } } $this->closeCsvFile($handle); }