public function hookHeader($params) { $shop_id = $this->getShopId(); $buttons_code = $this->client->getButtonsCode(); if (Configuration::get('ADDSHOPPERS_OPENGRAPH') == '1') { $this->context->smarty->assign('buttons_opengraph', $buttons_code['buttons']['open-graph']); } if (Configuration::get('ADDSHOPPERS_BUTTONS') == '1') { $this->context->smarty->assign('buttons_social', $buttons_code['buttons']['button2']); } $id_lang = (int) Tools::getValue('id_lang', (int) Configuration::get('PS_LANG_DEFAULT')); $this->context->smarty->assign(array('shop_id' => Tools::safeOutput($shop_id), 'default_account' => $shop_id == $this->client->getDefaultShopId(), 'social' => Tools::safeOutput(Configuration::get('ADDSHOPPERS_BUTTONS')), 'opengraph' => Tools::safeOutput(Configuration::get('ADDSHOPPERS_OPENGRAPH')), 'actual_url' => Tools::safeOutput($this->_getCurrentUrl()), 'absolute_base_url' => Tools::safeOutput($this->_getAbsoluteBaseUrl()), 'id_lang' => (int) $id_lang)); if (Tools::isSubmit('id_product')) { $product = new Product((int) Tools::getValue('id_product')); if (Validate::isLoadedObject($product)) { $currency = new Currency((int) $this->context->cookie->id_currency); $this->context->smarty->assign(array('id_product' => (int) $product->id, 'stock' => isset($product->available_now) ? Tools::safeOutput(AddshoppersClient::WIDGET_STOCK_IN_STOCK) : Tools::safeOutput(AddshoppersClient::WIDGET_STOCK_OUT_OF_STOCK), 'price' => Tools::safeOutput($currency->sign) . number_format((double) $product->getPrice(), 2), 'product_name' => Tools::safeOutput($product->name[$id_lang]), 'product_description' => Tools::safeOutput($product->description[$id_lang]), 'is_product_page' => true)); $quantity = (int) StockAvailable::getQuantityAvailableByProduct((int) $product->id); if ($quantity > 0) { $this->context->smarty->assign('instock', (int) $quantity); } $images = Image::getImages((int) $id_lang, (int) $product->id); if (is_array($images) && isset($images[0])) { $this->context->smarty->assign('id_image', (int) $images[0]['id_image']); } } else { $this->context->smarty->assign('is_product_page', false); } } else { $this->context->smarty->assign('is_product_page', false); } return $this->display(__FILE__, 'header.tpl'); }
public function getAttributeCombinations($id_lang) { if (!Combination::isFeatureActive()) { return array(); } $sql = 'SELECT pa.*, product_attribute_shop.*, ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, al.`name` AS attribute_name, a.`id_attribute`, pa.`unit_price_impact` FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int) $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int) $id_lang . ') WHERE pa.`id_product` = ' . (int) $this->id . ' GROUP BY pa.`id_product_attribute`, ag.`id_attribute_group` ORDER BY pa.`id_product_attribute`'; $res = Db::getInstance()->executeS($sql); //Get quantity of each variations foreach ($res as $key => $row) { $cache_key = $row['id_product'] . '_' . $row['id_product_attribute'] . '_quantity'; if (!Cache::isStored($cache_key)) { Cache::store($cache_key, StockAvailable::getQuantityAvailableByProduct($row['id_product'], $row['id_product_attribute'])); } $res[$key]['quantity'] = Cache::retrieve($cache_key); } return $res; }
public function ajaxProcessSearchProducts() { Context::getContext()->customer = new Customer((int) Tools::getValue('id_customer')); $currency = new Currency((int) Tools::getValue('id_currency')); if ($products = Product::searchByName((int) $this->context->language->id, pSQL(Tools::getValue('product_search')))) { foreach ($products as &$product) { // Formatted price $product['formatted_price'] = Tools::displayPrice(Tools::convertPrice($product['price_tax_incl'], $currency), $currency); // Concret price $product['price_tax_incl'] = Tools::ps_round(Tools::convertPrice($product['price_tax_incl'], $currency), 2); $product['price_tax_excl'] = Tools::ps_round(Tools::convertPrice($product['price_tax_excl'], $currency), 2); $productObj = new Product((int) $product['id_product'], false, (int) $this->context->language->id); $combinations = array(); $attributes = $productObj->getAttributesGroups((int) $this->context->language->id); // Tax rate for this customer if (Tools::isSubmit('id_address')) { $product['tax_rate'] = $productObj->getTaxesRate(new Address(Tools::getValue('id_address'))); } $product['warehouse_list'] = array(); foreach ($attributes as $attribute) { if (!isset($combinations[$attribute['id_product_attribute']]['attributes'])) { $combinations[$attribute['id_product_attribute']]['attributes'] = ''; } $combinations[$attribute['id_product_attribute']]['attributes'] .= $attribute['attribute_name'] . ' - '; $combinations[$attribute['id_product_attribute']]['id_product_attribute'] = $attribute['id_product_attribute']; $combinations[$attribute['id_product_attribute']]['default_on'] = $attribute['default_on']; if (!isset($combinations[$attribute['id_product_attribute']]['price'])) { $price_tax_incl = Product::getPriceStatic((int) $product['id_product'], true, $attribute['id_product_attribute']); $price_tax_excl = Product::getPriceStatic((int) $product['id_product'], false, $attribute['id_product_attribute']); $combinations[$attribute['id_product_attribute']]['price_tax_incl'] = Tools::ps_round(Tools::convertPrice($price_tax_incl, $currency), 2); $combinations[$attribute['id_product_attribute']]['price_tax_excl'] = Tools::ps_round(Tools::convertPrice($price_tax_excl, $currency), 2); $combinations[$attribute['id_product_attribute']]['formatted_price'] = Tools::displayPrice(Tools::convertPrice($price_tax_excl, $currency), $currency); } if (!isset($combinations[$attribute['id_product_attribute']]['qty_in_stock'])) { $combinations[$attribute['id_product_attribute']]['qty_in_stock'] = StockAvailable::getQuantityAvailableByProduct((int) $product['id_product'], $attribute['id_product_attribute'], (int) $this->context->shop->id); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) $product['advanced_stock_management'] == 1) { $product['warehouse_list'][$attribute['id_product_attribute']] = Warehouse::getProductWarehouseList($product['id_product'], $attribute['id_product_attribute']); } else { $product['warehouse_list'][$attribute['id_product_attribute']] = array(); } $product['stock'][$attribute['id_product_attribute']] = Product::getRealQuantity($product['id_product'], $attribute['id_product_attribute']); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) $product['advanced_stock_management'] == 1) { $product['warehouse_list'][0] = Warehouse::getProductWarehouseList($product['id_product']); } else { $product['warehouse_list'][0] = array(); } $product['stock'][0] = StockAvailable::getQuantityAvailableByProduct((int) $product['id_product'], 0, (int) $this->context->shop->id); foreach ($combinations as &$combination) { $combination['attributes'] = rtrim($combination['attributes'], ' - '); } $product['combinations'] = $combinations; if ($product['customizable']) { $product_instance = new Product((int) $product['id_product']); $product['customization_fields'] = $product_instance->getCustomizationFields($this->context->language->id); } } $to_return = array('products' => $products, 'found' => true); } else { $to_return = array('found' => false); } $this->content = Tools::jsonEncode($to_return); }
/** * Get products grouped by package and by addresses to be sent individualy (one package = one shipping cost). * * @return array array( * 0 => array( // First address * 0 => array( // First package * 'product_list' => array(...), * 'carrier_list' => array(...), * 'id_warehouse' => array(...), * ), * ), * ); * @todo Add avaibility check */ public function getPackageList($flush = false) { static $cache = array(); if (isset($cache[(int) $this->id . '_' . (int) $this->id_address_delivery]) && $cache[(int) $this->id . '_' . (int) $this->id_address_delivery] !== false && !$flush) { return $cache[(int) $this->id . '_' . (int) $this->id_address_delivery]; } $product_list = $this->getProducts(); // Step 1 : Get product informations (warehouse_list and carrier_list), count warehouse // Determine the best warehouse to determine the packages // For that we count the number of time we can use a warehouse for a specific delivery address $warehouse_count_by_address = array(); $warehouse_carrier_list = array(); $stock_management_active = Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'); foreach ($product_list as &$product) { if ((int) $product['id_address_delivery'] == 0) { $product['id_address_delivery'] = (int) $this->id_address_delivery; } if (!isset($warehouse_count_by_address[$product['id_address_delivery']])) { $warehouse_count_by_address[$product['id_address_delivery']] = array(); } $product['warehouse_list'] = array(); if ($stock_management_active && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement((int) $product['id_product']))) { $warehouse_list = Warehouse::getProductWarehouseList($product['id_product'], $product['id_product_attribute'], $this->id_shop); if (count($warehouse_list) == 0) { $warehouse_list = Warehouse::getProductWarehouseList($product['id_product'], $product['id_product_attribute']); } // Does the product is in stock ? // If yes, get only warehouse where the product is in stock $warehouse_in_stock = array(); $manager = StockManagerFactory::getManager(); foreach ($warehouse_list as $key => $warehouse) { $product_real_quantities = $manager->getProductRealQuantities($product['id_product'], $product['id_product_attribute'], array($warehouse['id_warehouse']), true); if ($product_real_quantities > 0 || Pack::isPack((int) $product['id_product'])) { $warehouse_in_stock[] = $warehouse; } } if (!empty($warehouse_in_stock)) { $warehouse_list = $warehouse_in_stock; $product['in_stock'] = true; } else { $product['in_stock'] = false; } } else { //simulate default warehouse $warehouse_list = array(0); $product['in_stock'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], $product['id_product_attribute']) > 0; } foreach ($warehouse_list as $warehouse) { if (!isset($warehouse_carrier_list[$warehouse['id_warehouse']])) { $warehouse_object = new Warehouse($warehouse['id_warehouse']); $warehouse_carrier_list[$warehouse['id_warehouse']] = $warehouse_object->getCarriers(); } $product['warehouse_list'][] = $warehouse['id_warehouse']; if (!isset($warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']])) { $warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']] = 0; } $warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']]++; } } unset($product); arsort($warehouse_count_by_address); // Step 2 : Group product by warehouse $grouped_by_warehouse = array(); foreach ($product_list as &$product) { if (!isset($grouped_by_warehouse[$product['id_address_delivery']])) { $grouped_by_warehouse[$product['id_address_delivery']] = array('in_stock' => array(), 'out_of_stock' => array()); } $product['carrier_list'] = array(); $id_warehouse = 0; foreach ($warehouse_count_by_address[$product['id_address_delivery']] as $id_war => $val) { if (in_array((int) $id_war, $product['warehouse_list'])) { $product['carrier_list'] = array_merge($product['carrier_list'], Carrier::getAvailableCarrierList(new Product($product['id_product']), $id_war, $product['id_address_delivery'], null, $this)); if (!$id_warehouse) { $id_warehouse = (int) $id_war; } } } if (!isset($grouped_by_warehouse[$product['id_address_delivery']]['in_stock'][$id_warehouse])) { $grouped_by_warehouse[$product['id_address_delivery']]['in_stock'][$id_warehouse] = array(); $grouped_by_warehouse[$product['id_address_delivery']]['out_of_stock'][$id_warehouse] = array(); } if (!$this->allow_seperated_package) { $key = 'in_stock'; } else { $key = $product['in_stock'] ? 'in_stock' : 'out_of_stock'; } if (empty($product['carrier_list'])) { $product['carrier_list'] = array(0); } $grouped_by_warehouse[$product['id_address_delivery']][$key][$id_warehouse][] = $product; } unset($product); // Step 3 : grouped product from grouped_by_warehouse by available carriers $grouped_by_carriers = array(); foreach ($grouped_by_warehouse as $id_address_delivery => $products_in_stock_list) { if (!isset($grouped_by_carriers[$id_address_delivery])) { $grouped_by_carriers[$id_address_delivery] = array('in_stock' => array(), 'out_of_stock' => array()); } foreach ($products_in_stock_list as $key => $warehouse_list) { if (!isset($grouped_by_carriers[$id_address_delivery][$key])) { $grouped_by_carriers[$id_address_delivery][$key] = array(); } foreach ($warehouse_list as $id_warehouse => $product_list) { if (!isset($grouped_by_carriers[$id_address_delivery][$key][$id_warehouse])) { $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse] = array(); } foreach ($product_list as $product) { $package_carriers_key = implode(',', $product['carrier_list']); if (!isset($grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key])) { $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key] = array('product_list' => array(), 'carrier_list' => $product['carrier_list'], 'warehouse_list' => $product['warehouse_list']); } $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key]['product_list'][] = $product; } } } } $package_list = array(); // Step 4 : merge product from grouped_by_carriers into $package to minimize the number of package foreach ($grouped_by_carriers as $id_address_delivery => $products_in_stock_list) { if (!isset($package_list[$id_address_delivery])) { $package_list[$id_address_delivery] = array('in_stock' => array(), 'out_of_stock' => array()); } foreach ($products_in_stock_list as $key => $warehouse_list) { if (!isset($package_list[$id_address_delivery][$key])) { $package_list[$id_address_delivery][$key] = array(); } // Count occurance of each carriers to minimize the number of packages $carrier_count = array(); foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers) { foreach ($products_grouped_by_carriers as $data) { foreach ($data['carrier_list'] as $id_carrier) { if (!isset($carrier_count[$id_carrier])) { $carrier_count[$id_carrier] = 0; } $carrier_count[$id_carrier]++; } } } arsort($carrier_count); foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers) { if (!isset($package_list[$id_address_delivery][$key][$id_warehouse])) { $package_list[$id_address_delivery][$key][$id_warehouse] = array(); } foreach ($products_grouped_by_carriers as $data) { foreach ($carrier_count as $id_carrier => $rate) { if (in_array($id_carrier, $data['carrier_list'])) { if (!isset($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier])) { $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier] = array('carrier_list' => $data['carrier_list'], 'warehouse_list' => $data['warehouse_list'], 'product_list' => array()); } $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['carrier_list'] = array_intersect($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['carrier_list'], $data['carrier_list']); $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['product_list'] = array_merge($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['product_list'], $data['product_list']); break; } } } } } } // Step 5 : Reduce depth of $package_list $final_package_list = array(); foreach ($package_list as $id_address_delivery => $products_in_stock_list) { if (!isset($final_package_list[$id_address_delivery])) { $final_package_list[$id_address_delivery] = array(); } foreach ($products_in_stock_list as $key => $warehouse_list) { foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers) { foreach ($products_grouped_by_carriers as $data) { $final_package_list[$id_address_delivery][] = array('product_list' => $data['product_list'], 'carrier_list' => $data['carrier_list'], 'warehouse_list' => $data['warehouse_list'], 'id_warehouse' => $id_warehouse); } } } } $cache[(int) $this->id] = $final_package_list; return $final_package_list; }
/** * * This method allow to add stock information on a product detail * * If advanced stock management is active, get physical stock of this product in the warehouse associated to the ptoduct for the current order * Else get the available quantity of the product in fucntion of the shop associated to the order * * @param array &$product */ protected function setProductCurrentStock(&$product) { if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int) $product['advanced_stock_management'] == 1 && (int) $product['id_warehouse'] > 0) { $product['current_stock'] = StockManagerFactory::getManager()->getProductPhysicalQuantities($product['product_id'], $product['product_attribute_id'], (int) $product['id_warehouse'], true); } else { $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], (int) $this->id_shop); } }
/** * Convert the entities data into an xml object and return the xml object as a string * * @param array $aEntity Entity data */ public function formatEntityToXML($aEntity) { $sReturn = ''; $dom = new DOMDocument('1.0', 'utf-8'); $bUseRoutes = (bool) Configuration::get('PS_REWRITING_SETTINGS'); $oDispatcher = Dispatcher::getInstance(); // Force the dispatcher to use custom routes because the use of custom routes is disabled in the BO Context foreach ($oDispatcher->default_routes as $route_id => $route_data) { if ($custom_route = Configuration::get('PS_ROUTE_' . $route_id)) { foreach (Language::getLanguages() as $lang) { $oDispatcher->addRoute($route_id, $custom_route, $route_data['controller'], $lang['id_lang'], $route_data['keywords'], isset($route_data['params']) ? $route_data['params'] : array()); } } } $oPrediggoConfig = $this->aPrediggoConfigs[(int) $aEntity['id_shop']]; $link = $oPrediggoConfig->getContext()->link; $oProduct = new Product((int) $aEntity['id_product'], true, null, (int) $aEntity['id_shop'], $oPrediggoConfig->getContext()); if ((int) StockAvailable::getQuantityAvailableByProduct((int) $aEntity['id_product'], 0, (int) $aEntity['id_shop']) < (int) $oPrediggoConfig->export_product_min_quantity) { $this->nbEntitiesTreated--; $this->nbEntities--; return ' '; } $ps_tax = (int) Configuration::get('PS_TAX'); foreach ($this->aLanguages as $aLanguage) { $id_lang = (int) $aLanguage['id_lang']; // Set the root of the XML $root = $dom->createElement($this->sEntity); $dom->appendChild($root); $root->setAttribute('timestamp', (int) strtotime($oProduct->date_add)); $id = $dom->createElement('id', (int) $oProduct->id); $root->appendChild($id); $profile = $dom->createElement('profile', (int) $aEntity['id_shop']); $root->appendChild($profile); $name = $dom->createElement('name'); $name->appendChild($dom->createCDATASection($oProduct->name[$id_lang])); $root->appendChild($name); $oCategory = new Category((int) $oProduct->id_category_default); $aCategories = $oCategory->getParentsCategories($id_lang); if (is_array($aCategories) && count($aCategories) > 0) { foreach ($aCategories as $aCategory) { $oCategoryTmp = new Category((int) $aCategory['id_category'], $id_lang); if (!empty($oCategoryTmp->name)) { $genre = $dom->createElement('genre'); $genre->appendChild($dom->createCDATASection($oCategoryTmp->name)); $root->appendChild($genre); } unset($oCategoryTmp); } } unset($aCategories); unset($oCategory); if (!empty($oProduct->ean13)) { $ean = $dom->createElement('ean'); $ean->appendChild($dom->createCDATASection($oProduct->ean13)); $root->appendChild($ean); } $price = $dom->createElement('price', number_format($oProduct->getPrice($ps_tax), 2, '.', '')); $root->appendChild($price); if (isset($oProduct->tags[$id_lang]) && ($aTags = $oProduct->tags[$id_lang])) { $tag = $dom->createElement('tag'); $tag->appendChild($dom->createCDATASection(join(',', $aTags))); $root->appendChild($tag); } $sDesc = trim(strip_tags($oProduct->description[$id_lang])); if ($oPrediggoConfig->export_product_description && !empty($sDesc)) { $description = $dom->createElement('description'); $description->appendChild($dom->createCDATASection($sDesc)); $root->appendChild($description); } if (!empty($oProduct->id_manufacturer)) { $supplierid = $dom->createElement('supplierid', (int) $oProduct->id_manufacturer); $root->appendChild($supplierid); } $recommendable = $dom->createElement('recommendable', in_array((int) $oProduct->id, explode(',', $oPrediggoConfig->products_ids_not_recommendable)) ? 'false' : 'true'); $root->appendChild($recommendable); $searchable = $dom->createElement('searchable', in_array((int) $oProduct->id, explode(',', $oPrediggoConfig->products_ids_not_searchable)) ? 'false' : 'true'); $root->appendChild($searchable); // Set product URL $attribute = $dom->createElement('attribute'); $root->appendChild($attribute); $attName = $dom->createElement('attName', 'producturl'); $attribute->appendChild($attName); $attValue = $dom->createElement('attValue'); $attValue->appendChild($dom->createCDATASection($link->getProductLink((int) $oProduct->id, $oProduct->link_rewrite[$id_lang], Category::getLinkRewrite((int) $oProduct->id_category_default, $id_lang), NULL, $id_lang, (int) $aEntity['id_shop'], 0, $bUseRoutes))); $attribute->appendChild($attValue); // Set product picture if ($oPrediggoConfig->export_product_image) { $attribute = $dom->createElement('attribute'); $root->appendChild($attribute); $attName = $dom->createElement('attName', 'imageurl'); $attribute->appendChild($attName); $aCover = $oProduct->getCover((int) $oProduct->id); $attValue = $dom->createElement('attValue'); $attValue->appendChild($dom->createCDATASection($link->getImageLink($oProduct->link_rewrite[$id_lang], (int) $aCover['id_image'], 'large'))); $attribute->appendChild($attValue); } // Set combinations $aProductCombinations = Product::getAttributesInformationsByProduct((int) $oProduct->id); if (sizeof($aProductCombinations)) { foreach ($aProductCombinations as $aProductCombination) { if (!empty($oPrediggoConfig->attributes_groups_ids) && in_array((int) $aProductCombination['id_attribute_group'], explode(',', $oPrediggoConfig->attributes_groups_ids))) { $attribute = $dom->createElement('attribute'); $root->appendChild($attribute); $attName = $dom->createElement('attName'); $attName->appendChild($dom->createCDATASection($aProductCombination['group'])); $attribute->appendChild($attName); $attValue = $dom->createElement('attValue'); $attValue->appendChild($dom->createCDATASection($aProductCombination['attribute'])); $attribute->appendChild($attValue); } } } unset($aProductCombinations); // Set features $aProductFeatures = $oProduct->getFrontFeatures($id_lang); if (sizeof($aProductFeatures)) { foreach ($aProductFeatures as $aProductFeature) { if (!empty($oPrediggoConfig->features_ids) && in_array((int) $aProductFeature['id_feature'], explode(',', $oPrediggoConfig->features_ids))) { $attribute = $dom->createElement('attribute'); $root->appendChild($attribute); $attName = $dom->createElement('attName'); $attName->appendChild($dom->createCDATASection($aProductFeature['name'])); $attribute->appendChild($attName); $attValue = $dom->createElement('attValue'); $attValue->appendChild($dom->createCDATASection($aProductFeature['value'])); $attribute->appendChild($attValue); } } } unset($aProductFeatures); $aAccessories = Product::getAccessoriesLight($id_lang, (int) $oProduct->id); if (sizeof($aAccessories)) { foreach ($aAccessories as $aAccessory) { $attribute = $dom->createElement('attribute'); $root->appendChild($attribute); $attName = $dom->createElement('attName'); $attName->appendChild($dom->createCDATASection('accessory')); $attribute->appendChild($attName); $attValue = $dom->createElement('attValue'); $attValue->appendChild($dom->createCDATASection((int) $aAccessory['id_product'])); $attribute->appendChild($attValue); } } unset($aAccessories); $sReturn .= $dom->saveXML($root); } unset($dom); unset($oProduct); return $sReturn; }
public function initFormQuantities($obj) { if (!$this->default_form_language) { $this->getLanguages(); } $data = $this->createTemplate($this->tpl_form); $data->assign('default_form_language', $this->default_form_language); if ($obj->id) { if ($this->product_exists_in_shop) { // Get all id_product_attribute $attributes = $obj->getAttributesResume($this->context->language->id); if (empty($attributes)) { $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => ''); } // Get available quantities $available_quantity = array(); $product_designation = array(); foreach ($attributes as $attribute) { // Get available quantity for the current product attribute in the current shop $available_quantity[$attribute['id_product_attribute']] = StockAvailable::getQuantityAvailableByProduct((int) $obj->id, $attribute['id_product_attribute']); // Get all product designation $product_designation[$attribute['id_product_attribute']] = rtrim($obj->name[$this->context->language->id] . ' - ' . $attribute['attribute_designation'], ' - '); } $show_quantities = true; $shop_context = Shop::getContext(); $shop_group = new ShopGroup((int) Shop::getContextShopGroupID()); // if we are in all shops context, it's not possible to manage quantities at this level if (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_ALL) { $show_quantities = false; } elseif (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_GROUP) { // if quantities are not shared between shops of the group, it's not possible to manage them at group level if (!$shop_group->share_stock) { $show_quantities = false; } } else { // if quantities are shared between shops of the group, it's not possible to manage them for a given shop if ($shop_group->share_stock) { $show_quantities = false; } } $data->assign('ps_stock_management', Configuration::get('PS_STOCK_MANAGEMENT')); $data->assign('has_attribute', $obj->hasAttributes()); // Check if product has combination, to display the available date only for the product or for each combination if (Combination::isFeatureActive()) { $data->assign('countAttributes', (int) Db::getInstance()->getValue('SELECT COUNT(id_product) FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int) $obj->id)); } else { $data->assign('countAttributes', false); } // if advanced stock management is active, checks associations $advanced_stock_management_warning = false; if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $obj->advanced_stock_management) { $p_attributes = Product::getProductAttributesIds($obj->id); $warehouses = array(); if (!$p_attributes) { $warehouses[] = Warehouse::getProductWarehouseList($obj->id, 0); } foreach ($p_attributes as $p_attribute) { $ws = Warehouse::getProductWarehouseList($obj->id, $p_attribute['id_product_attribute']); if ($ws) { $warehouses[] = $ws; } } $warehouses = Tools::arrayUnique($warehouses); if (empty($warehouses)) { $advanced_stock_management_warning = true; } } if ($advanced_stock_management_warning) { $this->displayWarning($this->l('If you wish to use the advanced stock management, you must:')); $this->displayWarning('- ' . $this->l('associate your products with warehouses.')); $this->displayWarning('- ' . $this->l('associate your warehouses with carriers.')); $this->displayWarning('- ' . $this->l('associate your warehouses with the appropriate shops.')); } $pack_quantity = null; // if product is a pack if (Pack::isPack($obj->id)) { $items = Pack::getItems((int) $obj->id, Configuration::get('PS_LANG_DEFAULT')); // gets an array of quantities (quantity for the product / quantity in pack) $pack_quantities = array(); foreach ($items as $item) { if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) { $pack_id_product_attribute = Product::getDefaultAttribute($item->id, 1); $pack_quantities[] = Product::getQuantity($item->id, $pack_id_product_attribute) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1); } } // gets the minimum if (count($pack_quantities)) { $pack_quantity = $pack_quantities[0]; foreach ($pack_quantities as $value) { if ($pack_quantity > $value) { $pack_quantity = $value; } } } if (!Warehouse::getPackWarehouses((int) $obj->id)) { $this->displayWarning($this->l('You must have a common warehouse between this pack and its product.')); } } $data->assign(array('attributes' => $attributes, 'available_quantity' => $available_quantity, 'pack_quantity' => $pack_quantity, 'stock_management_active' => Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'product_designation' => $product_designation, 'product' => $obj, 'show_quantities' => $show_quantities, 'order_out_of_stock' => Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'token_preferences' => Tools::getAdminTokenLite('AdminPPreferences'), 'token' => $this->token, 'languages' => $this->_languages, 'id_lang' => $this->context->language->id)); } else { $this->displayWarning($this->l('You must save the product in this shop before managing quantities.')); } } else { $this->displayWarning($this->l('You must save this product before managing quantities.')); } $this->tpl_form_vars['custom_form'] = $data->fetch(); }
public function ajaxProcessDeleteProductAttribute() { if (!Combination::isFeatureActive()) { return; } if ($this->tabAccess['delete'] === '1') { $id_product = (int) Tools::getValue('id_product'); $id_product_attribute = (int) Tools::getValue('id_product_attribute'); if ($id_product && Validate::isUnsignedId($id_product) && Validate::isLoadedObject($product = new Product($id_product))) { if (($depends_on_stock = StockAvailable::dependsOnStock($id_product)) && StockAvailable::getQuantityAvailableByProduct($id_product, $id_product_attribute)) { $json = array('status' => 'error', 'message' => $this->l('It is not possible to delete a combination while it still has some quantities in the Advanced Stock Management. You must delete its stock first.')); } else { $product->deleteAttributeCombination((int) $id_product_attribute); $product->checkDefaultAttributes(); Tools::clearColorListCache((int) $product->id); if (!$product->hasAttributes()) { $product->cache_default_attribute = 0; $product->update(); } else { Product::updateDefaultAttribute($id_product); } if ($depends_on_stock && !Stock::deleteStockByIds($id_product, $id_product_attribute)) { $json = array('status' => 'error', 'message' => $this->l('Error while deleting the stock')); } else { $json = array('status' => 'ok', 'message' => $this->_conf[1], 'id_product_attribute' => (int) $id_product_attribute); } } } else { $json = array('status' => 'error', 'message' => $this->l('You cannot delete this attribute.')); } } else { $json = array('status' => 'error', 'message' => $this->l('You do not have permission to delete this.')); } die(Tools::jsonEncode($json)); }
<th>' . $erpip->l('Usable Stock') . '</th> <th>' . $erpip->l('Real Stock') . '</th>'; } else { $message .= '<th>' . $erpip->l('Stock') . '</th>'; } $message .= '</tr>'; foreach ($produits as &$prod) { $objProd = new Product($prod['product_id']); $message .= '<tr>'; /* If order neither sent nor cancelled nor current order */ $message .= '<td>' . $objProd->reference . '</td><td>' . $objProd->getProductName($prod['product_id'], $prod['product_attribute_id']) . '</td><td>' . $prod['product_quantity'] . '</td>'; if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $manager = StockManagerFactory::getManager(); $message .= '<td>' . $manager->getProductPhysicalQuantities($prod['product_id'], $prod['product_attribute_id']) . '</td>' . '<td>' . $manager->getProductPhysicalQuantities($prod['product_id'], $prod['product_attribute_id'], null, true) . '</td>' . '<td>' . $manager->getProductRealQuantities($prod['product_id'], $prod['product_attribute_id']) . '</td>'; } else { $message .= '<td>' . StockAvailable::getQuantityAvailableByProduct($prod['product_id'], $prod['product_attribute_id']) . '</td>'; } $message .= '</tr>'; } $message .= '</table>'; print $message; } break; case 'productSupplierPrice': /* If we have called the script with a term to search */ if (Tools::isSubmit('id_product') && Tools::isSubmit('id_product_attribute')) { $id_product = Tools::getValue('id_product'); $id_product_attribute = Tools::getValue('id_product_attribute'); $id_currency = Tools::getValue('id_currency', false) ? Tools::getValue('id_currency') : Configuration::get('PS_CURRENCY_DEFAULT'); /* Prices of all suppliers for the product */ $supplier_prices = ErpProductSupplier::getAllProductSupplierPrice($id_product, $id_product_attribute, true);
public static function getProductProperties($id_lang, $row) { if (!$row['id_product']) { return false; } // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) { $row['id_product_attribute'] = $ipa_default; } if (!isset($row['id_product_attribute'])) { $row['id_product_attribute'] = 0; } // Tax $usetax = Tax::excludeTaxeOption(); $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax; if (array_key_exists($cacheKey, self::$producPropertiesCache)) { return self::$producPropertiesCache[$cacheKey]; } // Datas $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang); if (!preg_match("/^1.3.*/", _PS_VERSION_)) { // Not available in Prestashop 1.3.x $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices); $row['specific_prices'] = $specific_prices; } if ($row['id_product_attribute']) { $row['quantity_all_versions'] = $row['quantity']; $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL); } $row['id_image'] = Product::defineProductImage($row, $id_lang); $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']); // Pack management $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack']; $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; if ($row['pack'] and !Pack::isInStock($row['id_product'])) { $row['quantity'] = 0; } $sql_combination = ' SELECT pa.id_product_attribute, pa.price, pa.quantity, pa.id_product FROM `' . _DB_PREFIX_ . 'product` p LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`) WHERE p.`id_product` =' . $row['id_product']; $result_combination = ProductExtended::getDbInstance()->ExecuteS($sql_combination); $row['combinations'] = array(); if ($result_combination) { foreach ($result_combination as $combination) { $combination['attributes'] = array(); /* New combinations system Prestashop 1.5.x */ if (!preg_match("/^1.(3|4).*/", _PS_VERSION_)) { $combination['quantity'] = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $combination['id_product_attribute']); } if (isset($combination['id_product_attribute'])) { $sql_attribute = ' SELECT pa.id_product_attribute, agl.id_attribute_group, al.name as name_value, agl.name as name_option FROM `' . _DB_PREFIX_ . 'product_attribute` pa LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute` = pac.`id_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute` = a.`id_attribute` AND al.`id_lang` = ' . $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group` = ag.`id_attribute_group` AND agl.`id_lang` = ' . $id_lang . ') WHERE pa.`id_product_attribute` =' . $combination['id_product_attribute']; $result_attribute = ProductExtended::getDbInstance()->ExecuteS($sql_attribute); if ($result_attribute) { foreach ($result_attribute as $attribute) { array_push($combination['attributes'], $attribute); } } array_push($row['combinations'], $combination); } } } $sql_image = ' SELECT DISTINCT i.*, pl.link_rewrite FROM `' . _DB_PREFIX_ . 'product` p LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (p.`id_product` = i.`id_product`) LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product`) WHERE p.`id_product` =' . $row['id_product']; $result_image = ProductExtended::getDbInstance()->ExecuteS($sql_image); $row['images'] = array(); $lang = new Language($id_lang); $row['url_locale'] = $lang->iso_code; if ($result_image) { $link = preg_match("/^1.(3|4).*/", _PS_VERSION_) ? new Link() : Context::getContext()->link; foreach ($result_image as $image) { if (!preg_match("/^1.3.*/", _PS_VERSION_)) { // Image URL gives relative version using 1.3.x- $image['image_url'] = $link->getImageLink($image['link_rewrite'], $image['id_product'] . '-' . $image['id_image']); } array_push($row['images'], $image); } } self::$producPropertiesCache[$cacheKey] = $row; return self::$producPropertiesCache[$cacheKey]; }
public function startImport() { global $cookie; @ini_set('max_execution_time', 0); ini_set('memory_limit', '256M'); self::$_exportStartTime = time(); $this->_header = self::$_serviceData['header'] == 1; self::$_sef = (int) Configuration::get('PS_REWRITING_SETTINGS'); self::$_exportStore = (int) self::$_serviceData['id_store']; self::$_exportShop = (int) self::$_serviceData['id_shop']; self::$_exportGroup = (int) self::$_serviceData['id_group']; self::$_exportLanguage = (int) self::$_serviceData['id_lang']; self::$_carrierId = (int) self::$_serviceData['id_carrier']; self::$_carrierTax = self::getShippingTax(self::$_carrierId); $carrier = new Carrier((int) self::$_carrierId); self::$_carrierMethod = $carrier->getShippingMethod(); self::$_exportCountry = (int) self::$_serviceData['id_country']; self::$_exportCurrency = (int) self::getCurrencyByCountry(self::$_exportCountry); self::$_exportState = (int) self::$_serviceData['id_state']; self::$_exportCondition = self::$_serviceData['condition']; self::$_zone = Country::getIdZone(self::$_exportCountry); self::$_billingMode = (int) Configuration::get('PS_SHIPPING_METHOD'); self::$_shippingCarrierData = self::getCarrierShippingRanges(); self::$_existingPictures = self::getExistingPictures(); self::$_existingCategories = self::getExistingCategories(self::$_exportLanguage); self::$_specificPrices = self::getSpecificPrices(self::$_exportShop); self::$_productPriorities = self::getProductsPriorities(); self::$_taxRates = self::getTaxes(); self::$_exportCategories = MoussiqFreeService::getCategories($this->service_id); self::$_productCategories = self::getProductCategories(); self::$_exportLanguageObj = new Language(self::$_exportLanguage); if (self::$_exportCurrency == 0) { self::$_exportCurrency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); } if (sizeof(self::$_productCategories)) { $chunk_size = 3000; $current_size = 0; $this->beforeImport(self::$_serviceData['template'], array()); do { $products = self::getProducts(self::$_exportLanguage, $current_size, $chunk_size, 'date_add', 'ASC', false, self::$_serviceData['export_inactive'] == true ? false : true, self::$_exportCountry, self::$_exportShop, self::$_exportCondition); $current_size += $chunk_size; $fileName = $this->filename; $fileDir = dirname(__FILE__) . '/../export/'; if (!self::checkDir($fileDir)) { $this->_errors[] = Tools::displayError('The directory is not writeable'); return false; } foreach ($products as $product) { if (array_key_exists($product['id_product'], self::$_productCategories)) { $product['categories'] = self::$_productCategories[$product['id_product']]; $product['reduction'] = self::getProductSpecificPrice($product['id_product'], self::$_exportStore, Configuration::get('PS_CURRENCY_DEFAULT'), self::$_exportCountry, self::$_exportGroup); $product['quantity'] = (int) StockAvailable::getQuantityAvailableByProduct($product['id_product'], null, self::$_exportShop); //to fix, get cover id_image $product['id_image'] = self::getProductCoverWs($product['id_product']); $product['id_product_image'] = $product['id_product']; $features = self::collectFeatures(self::$_exportLanguage, $product['id_product']); if (is_array($features)) { foreach ($features as $id_feature => $feature) { $product['ft' . $id_feature] = trim($feature); } } $this->addProductLine($product, self::$_serviceData['template']); } } } while ($chunk_size == count($products)); $this->postProcess(); return $this->saveFile(); } }
include dirname(__FILE__) . '/../../../init.php'; header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); $now = date("Y-m-d"); $period = Configuration::get('PS_COLLECT_REVIEW_PERIOD_DAY'); $minus = date('Y-m-d', strtotime($now . ' - ' . $period . ' day')); if ($orders = CollectReview::getAllOrderByDay($minus)) { $link = new Link(); foreach ($orders as $value) { $order = new Order($value); $customer = new Customer($order->id_customer); $emailTo = $customer->email; $products_order = $order->getProducts(); $products = array(); foreach ($products_order as $item) { $cover = Product::getCover($item['product_id']); array_push($products, array('name' => $item['product_name'], 'price' => Tools::displayPrice($item['price']), 'quantity' => StockAvailable::getQuantityAvailableByProduct($item['product_id']), 'link' => $link->getProductLink($item['product_id']) . '#reviews', 'image' => $link->getImageLink($item['image']->id, $cover['id_image'], 'large_default'))); } $template = 'collectReview'; $subject = 'Оставьте отзыв'; $product_list_html = CollectReview::getEmailTemplateContent('collectReview.tpl', Mail::TYPE_HTML, $products); $templateVars = array('{products}' => $product_list_html); $admin_mails = Configuration::get('PS_SHOP_EMAIL'); $te = Mail::Send(1, $template, $subject, $templateVars, $emailTo); } $r = CollectReview::deactivate($orders); echo 'Письма отправлены'; } else { echo 'Не кому отправлять письма'; }
/** * @param ShopgateCart $cart * @return array */ public function checkStock(ShopgateCart $cart) { $result = array(); foreach ($cart->getItems() as $item) { $cartItem = new ShopgateCartItem(); $cartItem->setItemNumber($item->getItemNumber()); list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item); /** @var ProductCore $product */ if (version_compare(_PS_VERSION_, '1.5.2.0', '<')) { $product = new BWProduct($productId, true, $this->getPlugin()->getLanguageId()); } else { $product = new Product($productId, $this->getPlugin()->getLanguageId()); } if (empty($attributeId) && !empty($productId) && $product->hasAttributes()) { $result[] = $cartItem; continue; } $product->loadStockData(); /** * validate attributes */ if ($product->hasAttributes()) { $invalidAttribute = false; $message = ''; if (!$attributeId) { $cartItem->setError(ShopgateLibraryException::UNKNOWN_ERROR_CODE); $cartItem->setErrorText('attributeId required'); $message = 'attributeId required'; $invalidAttribute = true; } else { $validAttributeId = false; if (version_compare(_PS_VERSION_, '1.5.0', '<')) { $attributeIds = BWProduct::getProductAttributesIds($productId); } else { $attributeIds = $product->getProductAttributesIds($productId, true); } foreach ($attributeIds as $attribute) { if ($attributeId == $attribute['id_product_attribute']) { $validAttributeId = true; continue; } } if (!$validAttributeId) { $invalidAttribute = true; $message = 'invalid attributeId'; } } if ($invalidAttribute) { $cartItem->setError(ShopgateLibraryException::UNKNOWN_ERROR_CODE); $cartItem->setErrorText($message); $result[] = $cartItem; continue; } } if ($product->id) { if (version_compare(_PS_VERSION_, '1.5.0', '<')) { $quantity = $product->getStockAvailable(); //getQuantityAvailableByProduct($productId, $attributeId, $this->getPlugin()->getContext()->shop->id); } else { $quantity = StockAvailable::getQuantityAvailableByProduct($productId, $attributeId, $this->getPlugin()->getContext()->shop->id); } $cartItem->setStockQuantity($quantity); $cartItem->setIsBuyable($product->available_for_order && ($attributeId ? Attribute::checkAttributeQty($attributeId, ShopgateItemsCartExportJson::DEFAULT_QTY_TO_CHECK) : $product->checkQty(ShopgateItemsCartExportJson::DEFAULT_QTY_TO_CHECK)) || Product::isAvailableWhenOutOfStock($product->out_of_stock) ? 1 : 0); } else { $cartItem->setError(ShopgateLibraryException::CART_ITEM_PRODUCT_NOT_FOUND); $cartItem->setErrorText(ShopgateLibraryException::getMessageFor($cartItem->getError())); } $result[] = $cartItem; } return $result; }
private function getItemXML($product, $lang, $id_curr, $id_shop, $combination = false) { $xml_googleshopping = ''; $id_lang = (int) $lang['id_lang']; $title_limit = 70; $description_limit = 4990; $languages = Language::getLanguages(); $tailleTabLang = sizeof($languages); $this->context->language->id = $id_lang; $this->context->shop->id = $id_shop; $p = new Product($product['id_product'], true, $id_lang, $id_shop, $this->context); // Get module configuration for this shop if (!$combination) { $product['quantity'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0, $id_shop); } // Exclude non-available products if ($this->module_conf['export_nap'] === 0 && $product['quantity'] < 1) { $this->nb_not_exported_products++; return; } // Check minimum product price $price = Product::getPriceStatic((int) $product['id_product'], true); if ((double) $this->module_conf['export_min_price'] > 0 && (double) $this->module_conf['export_min_price'] > (double) $price) { return; } $cat_link_rew = Category::getLinkRewrite($product['id_gcategory'], (int) $lang); $product_link = $this->context->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $cat_link_rew, $product['ean13'], (int) $product['id_lang'], $id_shop, $combination, true); // Product name $title_crop = $product['name']; // Product color attribute, if any if (!empty($product['color'])) { $title_crop .= ' ' . $product['color']; } if (!empty($product['material'])) { $title_crop .= ' ' . $product['material']; } if (!empty($product['pattern'])) { $title_crop .= ' ' . $product['pattern']; } if (!empty($product['size'])) { $title_crop .= ' ' . $product['size']; } if (Tools::strlen($product['name']) > $title_limit) { $title_crop = Tools::substr($title_crop, 0, $title_limit - 1); $title_crop = Tools::substr($title_crop, 0, strrpos($title_crop, " ")); } // Description type if ($this->module_conf['description'] == 'long') { $description_crop = $product['description']; } else { if ($this->module_conf['description'] == 'short') { $description_crop = $product['description_short']; } else { if ($this->module_conf['description'] == 'meta') { $description_crop = $product['meta_description']; } } } $description_crop = $this->rip_tags($description_crop); if (Tools::strlen($description_crop) > $description_limit) { $description_crop = Tools::substr($description_crop, 0, $description_limit - 1); $description_crop = Tools::substr($description_crop, 0, strrpos($description_crop, " ")) . ' ...'; } $xml_googleshopping .= '<item>' . "\n"; $xml_googleshopping .= '<g:id>' . $product['gid'] . '</g:id>' . "\n"; $xml_googleshopping .= '<title><![CDATA[' . $title_crop . ']]></title>' . "\n"; $xml_googleshopping .= '<description><![CDATA[' . $description_crop . ']]></description>' . "\n"; $xml_googleshopping .= '<link><![CDATA[' . htmlspecialchars($product_link, self::REPLACE_FLAGS, self::CHARSET, false) . ']]></link>' . "\n"; // Image links $images = Image::getImages($lang['id_lang'], $product['id_product'], $combination); $indexTabLang = 0; if ($tailleTabLang > 1) { while (sizeof($images) < 1 && $indexTabLang < $tailleTabLang) { if ($languages[$indexTabLang]['id_lang'] != $lang['id_lang']) { $images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']); } $indexTabLang++; } } $nbimages = 0; $image_type = $this->module_conf['img_type']; if ($image_type == '') { $image_type = 'large_default'; } foreach ($images as $im) { $image = $this->context->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $im['id_image'], $image_type); $image = preg_replace('*http://' . Tools::getHttpHost() . '/*', $this->uri, $image); if ($im['cover'] == 1) { $xml_googleshopping .= '<g:image_link><![CDATA[' . $image . ']]></g:image_link>' . "\n"; } else { $xml_googleshopping .= '<g:additional_image_link><![CDATA[' . $image . ']]></g:additional_image_link>' . "\n"; } // max images by product if (++$nbimages == 10) { break; } } // Product condition, or category's condition attribute, or its parent one... // Product condition = new, used, refurbished if (empty($product['condition'])) { $product['condition'] = $this->categories_values[$product['id_gcategory']]['gcat_condition']; } if (!empty($product['condition'])) { $xml_googleshopping .= '<g:condition><![CDATA[' . $product['condition'] . ']]></g:condition>' . "\n"; } // Shop category $breadcrumb = GCategories::getPath($product['id_gcategory'], '', $id_lang, $id_shop, $this->id_root); $product_type = ''; if (!empty($this->module_conf['product_type[]'][$id_lang])) { $product_type = $this->module_conf['product_type[]'][$id_lang]; if (!empty($breadcrumb)) { $product_type .= " > "; } } $product_type .= $breadcrumb; $xml_googleshopping .= '<g:product_type><![CDATA[' . $product_type . ']]></g:product_type>' . "\n"; // Matching Google category, or parent categories' one $product['gcategory'] = $this->categories_values[$product['category_default']]['gcategory']; $xml_googleshopping .= '<g:google_product_category><![CDATA[' . $product['gcategory'] . ']]></g:google_product_category>' . "\n"; // Product quantity & availability if (empty($this->categories_values[$product['category_default']]['gcat_avail'])) { if ($this->module_conf['quantity'] == 1) { $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n"; } if ($product['quantity'] > 0 && $product['available_for_order']) { $xml_googleshopping .= '<g:availability>in stock</g:availability>' . "\n"; } elseif ($p->isAvailableWhenOutOfStock((int) $p->out_of_stock) && $product['available_for_order']) { $xml_googleshopping .= '<g:availability>preorder</g:availability>' . "\n"; } else { $xml_googleshopping .= '<g:availability>out of stock</g:availability>' . "\n"; } } else { if ($this->module_conf['quantity'] == 1 && $product['quantity'] > 0) { $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n"; } $xml_googleshopping .= '<g:availability>' . $this->categories_values[$product['category_default']]['gcat_avail'] . '</g:availability>' . "\n"; } // Price(s) $currency = new Currency((int) $id_curr); $use_tax = $product['tax_included'] ? true : false; $no_tax = !$use_tax ? true : false; $product['price'] = (double) $p->getPriceStatic($product['id_product'], $use_tax, $combination) * $currency->conversion_rate; $product['price_without_reduct'] = (double) $p->getPriceWithoutReduct($no_tax, $combination) * $currency->conversion_rate; $product['price'] = number_format(round($product['price'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' '); $product['price_without_reduct'] = number_format(round($product['price_without_reduct'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' '); if ((double) $product['price'] < (double) $product['price_without_reduct']) { $xml_googleshopping .= '<g:price>' . $product['price_without_reduct'] . ' ' . $currency->iso_code . '</g:price>' . "\n"; $xml_googleshopping .= '<g:sale_price>' . $product['price'] . ' ' . $currency->iso_code . '</g:sale_price>' . "\n"; } else { $xml_googleshopping .= '<g:price>' . $product['price'] . ' ' . $currency->iso_code . '</g:price>' . "\n"; } $identifier_exists = 0; // GTIN (EAN, UPC, JAN, ISBN) if (!empty($product['ean13'])) { $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n"; $identifier_exists++; } // Brand if ($this->module_conf['no_brand'] != 0 && !empty($product['id_manufacturer'])) { $xml_googleshopping .= '<g:brand><![CDATA[' . htmlspecialchars(Manufacturer::getNameById((int) $product['id_manufacturer']), self::REPLACE_FLAGS, self::CHARSET, false) . ']]></g:brand>' . "\n"; $identifier_exists++; } // MPN if (empty($product['supplier_reference'])) { $product['supplier_reference'] = ProductSupplier::getProductSupplierReference($product['id_product'], 0, $product['id_supplier']); } if ($this->module_conf['mpn_type'] == 'reference' && !empty($product['reference'])) { $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['reference'] . ']]></g:mpn>' . "\n"; $identifier_exists++; } else { if ($this->module_conf['mpn_type'] == 'supplier_reference' && !empty($product['supplier_reference'])) { $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['supplier_reference'] . ']]></g:mpn>' . "\n"; $identifier_exists++; } } // Tag "identifier_exists" if ($this->module_conf['id_exists_tag'] && $identifier_exists < 2) { $xml_googleshopping .= '<g:identifier_exists>FALSE</g:identifier_exists>' . "\n"; } // Product gender and age_group attributes association $product_features = $this->getProductFeatures($product['id_product'], $id_lang, $id_shop); $product['gender'] = $this->categories_values[$product['category_default']]['gcat_gender']; $product['age_group'] = $this->categories_values[$product['category_default']]['gcat_age_group']; foreach ($product_features as $feature) { switch ($feature['id_feature']) { case $this->module_conf['gender']: $product['gender'] = $feature['value']; continue 2; case $this->module_conf['age_group']: $product['age_group'] = $feature['value']; continue 2; } if (!$product['color']) { foreach ($this->module_conf['color[]'] as $id => $v) { if ($v == $feature['id_feature']) { $product['color'] = $feature['value']; } } } if (!$product['material']) { foreach ($this->module_conf['material[]'] as $id => $v) { if ($v == $feature['id_feature']) { $product['material'] = $feature['value']; } } } if (!$product['pattern']) { foreach ($this->module_conf['pattern[]'] as $id => $v) { if ($v == $feature['id_feature']) { $product['pattern'] = $feature['value']; } } } if (!$product['size']) { foreach ($this->module_conf['size[]'] as $id => $v) { if ($v == $feature['id_feature']) { $product['size'] = $feature['value']; } } } } // Product gender attribute, or category gender attribute, or parent's one if (!empty($product['gender'])) { $xml_googleshopping .= '<g:gender><![CDATA[' . $product['gender'] . ']]></g:gender>' . "\n"; } // Product age_group attribute, or category age_group attribute, or parent's one if (!empty($product['age_group'])) { $xml_googleshopping .= '<g:age_group><![CDATA[' . $product['age_group'] . ']]></g:age_group>' . "\n"; } // Product attributes combination groups if ($combination && !empty($product['item_group_id'])) { $xml_googleshopping .= '<g:item_group_id>' . $product['item_group_id'] . '</g:item_group_id>' . "\n"; } // Product color attribute, or category color attribute, or parent's one if (!empty($product['color'])) { $xml_googleshopping .= '<g:color><![CDATA[' . $product['color'] . ']]></g:color>' . "\n"; } // Product material attribute, or category material attribute, or parent's one if (!empty($product['material'])) { $xml_googleshopping .= '<g:material><![CDATA[' . $product['material'] . ']]></g:material>' . "\n"; } // Product pattern attribute, or category pattern attribute, or parent's one if (!empty($product['pattern'])) { $xml_googleshopping .= '<g:pattern><![CDATA[' . $product['pattern'] . ']]></g:pattern>' . "\n"; } // Product size attribute, or category size attribute, or parent's one if (!empty($product['size'])) { $xml_googleshopping .= '<g:size><![CDATA[' . $product['size'] . ']]></g:size>' . "\n"; } // Featured products if ($this->module_conf['featured_products'] == 1 && $product['on_sale'] != '0') { $xml_googleshopping .= '<g:featured_product>true</g:featured_product>' . "\n"; } // Shipping $xml_googleshopping .= '<g:shipping>' . "\n"; $xml_googleshopping .= "\t" . '<g:country>' . $this->module_conf['shipping_country'] . '</g:country>' . "\n"; $xml_googleshopping .= "\t" . '<g:service>Standard</g:service>' . "\n"; $xml_googleshopping .= "\t" . '<g:price>' . number_format($this->module_conf['shipping_price'], 2, '.', ' ') . ' ' . $currency->iso_code . '</g:price>' . "\n"; $xml_googleshopping .= '</g:shipping>' . "\n"; // Shipping weight if ($product['weight'] != '0') { $xml_googleshopping .= '<g:shipping_weight>' . number_format($product['weight'], 2, '.', '') . ' ' . Configuration::get('PS_WEIGHT_UNIT') . '</g:shipping_weight>' . "\n"; } $xml_googleshopping .= '</item>' . "\n\n"; if ($combination) { $this->nb_combinations++; $this->nb_prd_w_attr[$product['id_product']] = 1; } $this->nb_total_products++; return $xml_googleshopping; }
private function generateFile($lang) { $path_parts = pathinfo(__FILE__); if (Configuration::get('GENERATE_FILE_IN_ROOT')) { $generate_file_path = dirname(__FILE__) . '/../../' . $this->_getOutputFileName($lang['iso_code']); } else { $generate_file_path = dirname(__FILE__) . '/file_exports/' . $this->_getOutputFileName($lang['iso_code']); } //Google Shopping XML $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n"; $xml .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0" encoding="UTF-8" >' . "\n"; $xml .= '<title>' . Configuration::get('PS_SHOP_NAME') . '</title>' . "\n"; $xml .= '<link href="' . htmlspecialchars($this->uri, self::REPLACE_FLAGS, self::CHARSET, false) . '" rel="alternate" type="text/html"/>' . "\n"; $xml .= '<modified>' . date('Y-m-d') . 'T01:01:01Z</modified><author><name>' . Configuration::get('PS_SHOP_NAME') . '</name></author>' . "\n"; $googleshoppingfile = fopen($generate_file_path, 'w'); // add UTF-8 byte order mark fwrite($googleshoppingfile, pack("CCC", 0xef, 0xbb, 0xbf)); //file header fwrite($googleshoppingfile, $xml); $sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'product p' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product' . ' WHERE p.active = 1 AND pl.id_lang=' . $lang['id_lang']; $products = Db::getInstance()->ExecuteS($sql); $title_limit = 70; $description_limit = 10000; $languages = Language::getLanguages(); $tailleTabLang = sizeof($languages); foreach ($products as $product) { $xml_googleshopping = ''; $cat_link_rew = Category::getLinkRewrite($product['id_category_default'], intval($lang)); //continue if product not have price $price = Product::getPriceStatic($product['id_product'], true, NULL, 2); if (empty($price)) { continue; } $product_link = $this->context->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $cat_link_rew, $product['ean13'], (int) $product['id_lang'], 1, 0, true); $title_crop = $product['name']; if (strlen($product['name']) > $title_limit) { $title_crop = substr($title_crop, 0, $title_limit - 1); $title_crop = substr($title_crop, 0, strrpos($title_crop, " ")); } if (intval(Configuration::get('DESCRIPTION')) === intval(2)) { $description_crop = $product['description']; } else { $description_crop = $product['description_short']; } $description_crop = $this->rip_tags($description_crop); if (strlen($description_crop) > $description_limit) { $description_crop = substr($description_crop, 0, $description_limit - 1); $description_crop = substr($description_crop, 0, strrpos($description_crop, " ")); } $xml_googleshopping .= '<entry>' . "\n"; $xml_googleshopping .= '<g:id>' . $product['id_product'] . '-' . $lang['iso_code'] . '</g:id>' . "\n"; $xml_googleshopping .= '<title>' . htmlentities(ucfirst(mb_strtolower($title_crop, self::CHARSET)), self::REPLACE_FLAGS, self::CHARSET) . '</title>' . "\n"; $xml_googleshopping .= '<link>' . htmlspecialchars($product_link, self::REPLACE_FLAGS, self::CHARSET, false) . '</link>' . "\n"; $xml_googleshopping .= '<g:price>' . $price . '</g:price>' . "\n"; $xml_googleshopping .= '<g:description>' . htmlentities($description_crop, self::REPLACE_FLAGS, self::CHARSET) . '</g:description>' . "\n"; $xml_googleshopping .= '<g:condition>new</g:condition>' . "\n"; // condition = new, used, refurbished $images = Image::getImages($lang['id_lang'], $product['id_product']); $indexTabLang = 0; if ($tailleTabLang > 1) { while (sizeof($images) < 1 && $indexTabLang < $tailleTabLang) { if ($languages[$indexTabLang]['id_lang'] != $lang['id_lang']) { $images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']); } $indexTabLang++; } } $nbimages = 0; $image_type = Configuration::get('GS_IMAGE'); if ($image_type == '') { $image_type = 'large_default'; } /* create image links */ foreach ($images as $im) { $image = $this->context->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $im['id_image'], $image_type); $xml_googleshopping .= '<g:image_link>' . $image . '</g:image_link>' . "\n"; //max images by product if (++$nbimages == 10) { break; } } if (Configuration::get('QUANTITY') == 1) { $quantity = StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0); if ($quantity > 0) { $xml_googleshopping .= '<g:quantity>' . $quantity . '</g:quantity>' . "\n"; $xml_googleshopping .= '<g:availability>in stock</g:availability>' . "\n"; } else { $xml_googleshopping .= '<g:quantity>0</g:quantity>' . "\n"; $xml_googleshopping .= '<g:availability>out of stock</g:availability>' . "\n"; } } // Brand $identifier_exists = false; if (Configuration::get('BRAND') && $product['id_manufacturer'] != '0') { $xml_googleshopping .= '<g:brand>' . htmlspecialchars(Manufacturer::getNameById(intval($product['id_manufacturer'])), self::REPLACE_FLAGS, self::CHARSET, false) . '</g:brand>' . "\n"; $identifier_exists = true; } if (Configuration::get('MPN') && $product['supplier_reference'] != '') { $xml_googleshopping .= '<g:mpn>' . $product['supplier_reference'] . '</g:mpn>'; $identifier_exists = true; } if (Configuration::get('GTIN') && $product['ean13'] != '') { $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n"; $identifier_exists = true; } if (!$identifier_exists) { $xml_googleshopping .= '<g:identifier_exists>FALSE</g:identifier_exists>' . "\n"; } // Category google if (Configuration::get('GS_PRODUCT_TYPE_' . $lang['iso_code'])) { $product_type = str_replace('>', '>', Configuration::get('GS_PRODUCT_TYPE_' . $lang['iso_code'])); $product_type = str_replace('&', '&', $product_type); $xml_googleshopping .= '<g:google_product_category>' . $product_type . '</g:google_product_category>' . "\n"; } // Category shop if (Configuration::get('CATEGORY_SHOP')) { $categories = $this->getBreadcrumbCategory($product['id_category_default'], $product['id_lang']); $categories = str_replace('>', '>', $categories); $categories = str_replace('&', '&', $categories); $xml_googleshopping .= '<g:product_type>' . $categories . '</g:product_type>' . "\n"; } //Shipping $xml_googleshopping .= '<g:shipping>' . "\n"; $xml_googleshopping .= '<g:country>' . Configuration::get('GS_COUNTRY') . '</g:country>' . "\n"; $xml_googleshopping .= '<g:service>Standard</g:service>' . "\n"; $xml_googleshopping .= '<g:price>' . Configuration::get('GS_SHIPPING') . '</g:price>' . "\n"; $xml_googleshopping .= '</g:shipping>' . "\n"; //weight if ($product['weight'] != '0') { $xml_googleshopping .= '<g:shipping_weight>' . $product['weight'] . ' kilograms</g:shipping_weight>' . "\n"; } //featured product if (Configuration::get('FEATURED_PRODUCT') == 1 && $product['on_sale'] != '0') { $xml_googleshopping .= '<g:featured_product>true</g:featured_product>' . "\n"; } if (Configuration::get('GTIN') && $product['ean13'] != '') { $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n"; } $xml_googleshopping .= '</entry>' . "\n"; // Write element fwrite($googleshoppingfile, $xml_googleshopping); } $xml = '</feed>'; fwrite($googleshoppingfile, $xml); fclose($googleshoppingfile); @chmod($generate_file_path, 0777); return true; }
/** * @deprecated 1.5.0, use StockAvailable::getQuantityAvailableByProduct() */ public static function getAttributeQty($id_product) { Tools::displayAsDeprecated(); return StockAvailable::getQuantityAvailableByProduct($id_product); }
public function ajaxGetProducts() { if (Tools::isSubmit('id_order')) { $product_return_template = array(); require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/order/ErpOrder.php'; $objOrder = new ErpOrder((int) Tools::getValue('id_order')); $produits = $objOrder->getListOfProductsWithQuantity(); if (!empty($produits)) { foreach ($produits as $key => &$prod) { $objProd = new Product($prod['product_id']); // If order is neither sent, nor cancelled, nor the current one $product_return_template[$key]['reference'] = $objProd->reference; $product_return_template[$key]['name'] = $objProd->getProductName($prod['product_id'], $prod['product_attribute_id']); $product_return_template[$key]['quantity'] = $prod['product_quantity']; if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $manager = StockManagerFactory::getManager(); $product_return_template[$key]['physical_stock'] = $manager->getProductPhysicalQuantities($prod['product_id'], $prod['product_attribute_id']); $product_return_template[$key]['usable_stock'] = $manager->getProductPhysicalQuantities($prod['product_id'], $prod['product_attribute_id'], null, true); $product_return_template[$key]['real_stock'] = $manager->getProductRealQuantities($prod['product_id'], $prod['product_attribute_id']); } else { $product_return_template[$key]['stock'] = StockAvailable::getQuantityAvailableByProduct($prod['product_id'], $prod['product_attribute_id']); } } } $this->context->smarty->assign(array('products' => $product_return_template)); echo $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'erpillicopresta/views/templates/admin/advanced_order/quick_view.tpl'); die; } }
public function hookDisplayProductPriceBlock($param) { if (!isset($param['product']) || !isset($param['type'])) { return; } $product = $param['product']; $hook_type = $param['type']; if (is_array($product)) { $product_repository = $this->entity_manager->getRepository('Product'); $product = $product_repository->findOne((int) $product['id_product']); } if (!Validate::isLoadedObject($product)) { return; } $smartyVars = array(); /* Handle Product Combinations label */ if ($param['type'] == 'before_price' && (bool) Configuration::get('AEUC_LABEL_COMBINATION_FROM') === true) { if ($product->hasAttributes()) { $need_display = false; $combinations = $product->getAttributeCombinations($this->context->language->id); if ($combinations && is_array($combinations)) { foreach ($combinations as $combination) { if ((double) $combination['price'] != 0) { $need_display = true; break; } } unset($combinations); if ($need_display) { $smartyVars['before_price'] = array(); $smartyVars['before_price']['from_str_i18n'] = $this->l('From', 'ps_legalcompliance'); return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type); } } return; } } /* Handle Specific Price label*/ if ($param['type'] == 'old_price' && (bool) Configuration::get('AEUC_LABEL_SPECIFIC_PRICE') === true && 'catalog/_partials/miniatures/product.tpl' != $param['smarty']->template_resource) { $smartyVars['old_price'] = array(); $smartyVars['old_price']['before_str_i18n'] = $this->l('Our previous price', 'ps_legalcompliance'); return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type); } /* Handle Shipping Inc./Exc.*/ if ($param['type'] == 'price') { $smartyVars['price'] = array(); $need_shipping_label = true; if ((bool) Configuration::get('AEUC_LABEL_SHIPPING_INC_EXC') === true && $need_shipping_label === true) { if (!$product->is_virtual) { $cms_role_repository = $this->entity_manager->getRepository('CMSRole'); $cms_repository = $this->entity_manager->getRepository('CMS'); $cms_page_associated = $cms_role_repository->findOneByName(self::LEGAL_SHIP_PAY); if (isset($cms_page_associated->id_cms) && $cms_page_associated->id_cms != 0) { $cms_ship_pay_id = (int) $cms_page_associated->id_cms; $cms_revocations = $cms_repository->i10nFindOneById($cms_ship_pay_id, $this->context->language->id, $this->context->shop->id); $is_ssl_enabled = (bool) Configuration::get('PS_SSL_ENABLED'); $link_ship_pay = $this->context->link->getCMSLink($cms_revocations, $cms_revocations->link_rewrite, $is_ssl_enabled); $smartyVars['ship'] = array(); $smartyVars['ship']['link_ship_pay'] = $link_ship_pay; $smartyVars['ship']['ship_str_i18n'] = $this->l('Shipping excluded', 'ps_legalcompliance'); } } } return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type); } /* Handle Delivery time label */ if ($param['type'] == 'after_price' && !$product->is_virtual) { $context_id_lang = $this->context->language->id; $is_product_available = StockAvailable::getQuantityAvailableByProduct($product->id) >= 1 ? true : false; $smartyVars['after_price'] = array(); if ($is_product_available) { $contextualized_content = Configuration::get('AEUC_LABEL_DELIVERY_TIME_AVAILABLE', (int) $context_id_lang); $smartyVars['after_price']['delivery_str_i18n'] = $contextualized_content; } else { $contextualized_content = Configuration::get('AEUC_LABEL_DELIVERY_TIME_OOS', (int) $context_id_lang); $smartyVars['after_price']['delivery_str_i18n'] = $contextualized_content; } $delivery_addtional_info = Configuration::get('AEUC_LABEL_DELIVERY_ADDITIONAL', (int) $context_id_lang); if (trim($delivery_addtional_info) != '') { $smartyVars['after_price']['delivery_str_i18n'] .= '*'; } return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type); } /* Handle Taxes Inc./Exc.*/ if ($param['type'] == 'list_taxes') { $smartyVars['list_taxes'] = array(); if ((bool) Configuration::get('AEUC_LABEL_TAX_INC_EXC') === true) { $customer_default_group_id = (int) $this->context->customer->id_default_group; $customer_default_group = new Group($customer_default_group_id); if ((bool) Configuration::get('PS_TAX') === true && $this->context->country->display_tax_label && !(Validate::isLoadedObject($customer_default_group) && (bool) $customer_default_group->price_display_method === true)) { $smartyVars['list_taxes']['tax_str_i18n'] = $this->l('Tax included', 'ps_legalcompliance'); } else { $smartyVars['list_taxes']['tax_str_i18n'] = $this->l('Tax excluded', 'ps_legalcompliance'); } } return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type); } /* Handle Unit prices */ if ($param['type'] == 'unit_price') { if (!empty($product->unity) && $product->unit_price_ratio > 0.0) { $smartyVars['unit_price'] = array(); if ((bool) Configuration::get('AEUC_LABEL_UNIT_PRICE') === true) { if (!(isset($this->context->controller->php_self) && $this->context->controller->php_self == 'product')) { $priceDisplay = Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer); if (!$priceDisplay || $priceDisplay == 2) { $productPrice = $product->getPrice(true, null, 6); } else { $productPrice = $product->getPrice(false, null, 6); } $smartyVars['unit_price']['unit_price'] = $param['product']['unit_price_full']; $smartyVars['unit_price']['unity'] = $product->unity; } } return $this->dumpHookDisplayProductPriceBlock($smartyVars, $hook_type, $product->id); } } }
public function hookBeforeCarrier($params) { if (!isset($params['delivery_option_list']) || !count($params['delivery_option_list'])) { return false; } $package_list = $params['cart']->getPackageList(); $datesDelivery = array(); foreach ($params['delivery_option_list'] as $id_address => $by_address) { $datesDelivery[$id_address] = array(); foreach ($by_address as $key => $delivery_option) { $date_from = null; $date_to = null; $datesDelivery[$id_address][$key] = array(); foreach ($delivery_option['carrier_list'] as $id_carrier => $carrier) { foreach ($carrier['package_list'] as $id_package) { $package = $package_list[$id_address][$id_package]; $oos = false; // For out of stock management foreach ($package['product_list'] as $product) { if (StockAvailable::getQuantityAvailableByProduct($product['id_product'], $product['id_product_attribute']) <= 0) { $oos = true; break; } } $date_range = $this->_getDatesOfDelivery($id_carrier, $oos); if (is_null($date_from) || $date_from < $date_range[0]) { $date_from = $date_range[0][1]; $datesDelivery[$id_address][$key][0] = $date_range[0]; } if (is_null($date_to) || $date_to < $date_range[1]) { $date_to = $date_range[1][1]; $datesDelivery[$id_address][$key][1] = $date_range[1]; } } } } } $this->smarty->assign(array('nbPackages' => $params['cart']->getNbOfPackages(), 'datesDelivery' => $datesDelivery, 'delivery_option' => $params['delivery_option'])); return $this->display(__FILE__, 'beforeCarrier.tpl'); }
public function hookDisplayProductPriceBlock($param) { if (!isset($param['product']) || !isset($param['type'])) { return; } $product = $param['product']; if (is_array($product)) { $product_repository = $this->entity_manager->getRepository('Product'); $product = $product_repository->findOne((int) $product['id_product']); } if (!Validate::isLoadedObject($product)) { return; } $smartyVars = array(); /* Handle Product Combinations label */ if ($param['type'] == 'before_price' && (bool) Configuration::get('AEUC_LABEL_COMBINATION_FROM') === true) { if ($product->hasAttributes()) { $need_display = false; $combinations = $product->getAttributeCombinations($this->context->language->id); if ($combinations && is_array($combinations)) { foreach ($combinations as $combination) { if ((double) $combination['price'] > 0) { $need_display = true; break; } } unset($combinations); if ($need_display) { $smartyVars['before_price'] = array(); $smartyVars['before_price']['from_str_i18n'] = $this->l('From', 'advancedeucompliance'); return $this->dumpHookDisplayProductPriceBlock($smartyVars); } } return; } } /* Handle Specific Price label*/ if ($param['type'] == 'old_price' && (bool) Configuration::get('AEUC_LABEL_SPECIFIC_PRICE') === true) { $smartyVars['old_price'] = array(); $smartyVars['old_price']['before_str_i18n'] = $this->l('Before', 'advancedeucompliance'); return $this->dumpHookDisplayProductPriceBlock($smartyVars); } /* Handle taxes Inc./Exc. and Shipping Inc./Exc.*/ if ($param['type'] == 'price') { $smartyVars['price'] = array(); $need_shipping_label = true; if ((bool) Configuration::get('AEUC_LABEL_TAX_INC_EXC') === true) { $customer_default_group_id = (int) $this->context->customer->id_default_group; $customer_default_group = new Group($customer_default_group_id); if ((bool) Configuration::get('PS_TAX') === true && !(Validate::isLoadedObject($customer_default_group) && (bool) $customer_default_group->price_display_method === true)) { $smartyVars['price']['tax_str_i18n'] = $this->l('Tax included', 'advancedeucompliance'); } else { $smartyVars['price']['tax_str_i18n'] = $this->l('Tax excluded', 'advancedeucompliance'); } if (isset($param['from']) && $param['from'] == 'blockcart') { $smartyVars['price']['css_class'] = 'aeuc_tax_label_blockcart'; $need_shipping_label = false; } } if ((bool) Configuration::get('AEUC_LABEL_SHIPPING_INC_EXC') === true && $need_shipping_label === true) { if (!$product->is_virtual) { $cms_role_repository = $this->entity_manager->getRepository('CMSRole'); $cms_repository = $this->entity_manager->getRepository('CMS'); $cms_page_associated = $cms_role_repository->findOneByName(Advancedeucompliance::LEGAL_SHIP_PAY); if (isset($cms_page_associated->id_cms) && $cms_page_associated->id_cms != 0) { $cms_ship_pay_id = (int) $cms_page_associated->id_cms; $cms_revocations = $cms_repository->i10nFindOneById($cms_ship_pay_id, $this->context->language->id, $this->context->shop->id); $is_ssl_enabled = (bool) Configuration::get('PS_SSL_ENABLED'); $link_ship_pay = $this->context->link->getCMSLink($cms_revocations, $cms_revocations->link_rewrite, $is_ssl_enabled); if (!strpos($link_ship_pay, '?')) { $link_ship_pay .= '?content_only=1'; } else { $link_ship_pay .= '&content_only=1'; } $smartyVars['ship'] = array(); $smartyVars['ship']['link_ship_pay'] = $link_ship_pay; $smartyVars['ship']['ship_str_i18n'] = $this->l('Shipping excluded', 'advancedeucompliance'); } } } return $this->dumpHookDisplayProductPriceBlock($smartyVars); } /* Handles product's weight */ if ($param['type'] == 'weight' && (bool) Configuration::get('PS_DISPLAY_PRODUCT_WEIGHT') === true && isset($param['hook_origin']) && $param['hook_origin'] == 'product_sheet') { if ((double) $product->weight) { $smartyVars['weight'] = array(); $rounded_weight = round((double) $product->weight, Configuration::get('PS_PRODUCT_WEIGHT_PRECISION')); $smartyVars['weight']['rounded_weight_str_i18n'] = $rounded_weight . ' ' . Configuration::get('PS_WEIGHT_UNIT'); return $this->dumpHookDisplayProductPriceBlock($smartyVars); } } /* Handle Estimated delivery time label */ if ($param['type'] == 'after_price') { $context_id_lang = $this->context->language->id; $is_product_available = StockAvailable::getQuantityAvailableByProduct($product->id) >= 1 ? true : false; $smartyVars['after_price'] = array(); if ($is_product_available) { $contextualized_content = Configuration::get('AEUC_LABEL_DELIVERY_TIME_AVAILABLE', (int) $context_id_lang); $smartyVars['after_price']['delivery_str_i18n'] = $contextualized_content; } else { $contextualized_content = Configuration::get('AEUC_LABEL_DELIVERY_TIME_OOS', (int) $context_id_lang); $smartyVars['after_price']['delivery_str_i18n'] = $contextualized_content; } return $this->dumpHookDisplayProductPriceBlock($smartyVars); } }
/** * Creating order details of order * @param $neteven_order * @param $id_order * @return mixed */ private function createOrderDetails($neteven_order, $id_order) { global $cookie; $date_now = date('Y-m-d H:i:s'); if (in_array($neteven_order->Status, $this->getValue('t_list_order_status'))) { return; } // If order detail doesn't exist if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = ' . (int) $neteven_order->OrderLineID))) { // If product exist $ref_temp = $neteven_order->SKU; $type_temp = substr($ref_temp, 0, 1); $id_p_temp = str_replace($type_temp, '', $ref_temp); $where_req = ''; if ($type_temp == 'D') { $where_req = 'pa.`id_product_attribute` = ' . (int) $id_p_temp; } if ($type_temp == 'P') { $where_req = 'p.`id_product` = ' . (int) $id_p_temp; } if (self::$type_sku == 'reference') { $where_req = ' (p.`reference` = "' . pSQL($ref_temp) . '" OR pa.`reference` = "' . pSQL($ref_temp) . '") '; } if (empty($where_req)) { return; } $res_product = Db::getInstance()->getRow(' SELECT pl.`name` as name_product, p.`id_product`, pa.`id_product_attribute`, p.`reference` as product_reference, pa.`reference` as product_attribute_reference, p.`weight` as weight, GROUP_CONCAT(CONCAT(agl.`name`," : ",al.`name`) SEPARATOR ", ") as attribute_name FROM `' . _DB_PREFIX_ . 'product` p INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON(p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $this->getValue('id_lang') . ') LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (pa.`id_product` = p.`id_product`) LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute`=pa.`id_product_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute`=pac.`id_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute`=a.`id_attribute` AND al.`id_lang`=' . (int) $this->getValue('id_lang') . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group`=a.`id_attribute_group` AND agl.`id_lang`=' . (int) $this->getValue('id_lang') . ') WHERE p.`active` = 1 AND ' . $where_req . ' GROUP BY pa.`id_product_attribute`, p.`id_product` '); if ($res_product) { // Get order detail informations $product_reference = $res_product['product_reference']; $id_product_attribute = 0; $name = $res_product['name_product']; $control_attribute_product = false; if (!empty($res_product['id_product_attribute'])) { $product_reference = $res_product['product_attribute_reference']; $id_product_attribute = $res_product['id_product_attribute']; if (!empty($res_product['attribute_name'])) { $name .= ' - ' . $res_product['attribute_name']; } $control_attribute_product = true; } // Add product in cart $order = new Order($id_order); if (!Db::getInstance()->getRow('SELECT `id_cart` FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $order->id_cart . ' AND `id_product` = ' . (int) $res_product['id_product'] . ' AND `id_product_attribute` = ' . (int) $id_product_attribute)) { Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'cart_product` (`id_cart`, `id_product`, `id_product_attribute`, `quantity`, `date_add`) VALUES (' . (int) $order->id_cart . ', ' . (int) $res_product['id_product'] . ', ' . (int) $id_product_attribute . ', ' . (int) $neteven_order->Quantity . ', "' . pSQL($date_now) . '")'); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Order information') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Add order detail $tax = new Tax(Configuration::get('PS_TAX'), $cookie->id_lang); $price_product = ($neteven_order->Price->_ - floatval($neteven_order->VAT->_)) / $neteven_order->Quantity; $order_detail = new OrderDetail(); $order_detail->id_order = $id_order; $order_detail->product_id = $res_product['id_product']; $order_detail->product_attribute_id = $id_product_attribute; $order_detail->product_name = $name; $order_detail->product_quantity = $neteven_order->Quantity; $order_detail->product_quantity_in_stock = $neteven_order->Quantity; $order_detail->product_quantity_refunded = 0; $order_detail->product_quantity_return = 0; $order_detail->product_quantity_reinjected = 0; $order_detail->product_price = number_format((double) $price_product, 4, '.', ''); $order_detail->total_price_tax_excl = number_format((double) $price_product, 4, '.', ''); $order_detail->unit_price_tax_incl = number_format((double) $price_product, 4, '.', ''); $order_detail->unit_price_tax_excl = $tax->rate ? number_format((double) $price_product / ((double) $tax->rate / 100), 4, '.', '') : $price_product; $order_detail->reduction_percent = 0; $order_detail->reduction_amount = 0; $order_detail->group_reduction = 0; $order_detail->product_quantity_discount = 0; $order_detail->product_ean13 = NULL; $order_detail->product_upc = NULL; $order_detail->product_reference = $product_reference; $order_detail->product_supplier_reference = NULL; $order_detail->product_weight = !empty($res_product['weight']) ? (double) $res_product['weight'] : 0; $order_detail->tax_name = $tax->name; $order_detail->tax_rate = (double) $tax->rate; $order_detail->ecotax = 0; $order_detail->ecotax_tax_rate = 0; $order_detail->discount_quantity_applied = 0; $order_detail->download_hash = ''; $order_detail->download_nb = 0; $order_detail->download_deadline = '0000-00-00 00:00:00'; $order_detail->id_warehouse = 0; if (Configuration::get('PS_SHOP_ENABLE')) { $order_detail->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT'); } if (!$order_detail->add()) { Toolbox::addLogLine(self::getL('Failed for creation of order detail / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID); } else { if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order detail') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } $id_order_detail_temp = $order_detail->id; Toolbox::addLogLine(self::getL('Creation of order detail for NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); // Update quantity of product if (class_exists('StockAvailable')) { // Update quantity of product if ($control_attribute_product) { StockAvailable::setQuantity($res_product['id_product'], $id_product_attribute, StockAvailable::getQuantityAvailableByProduct($res_product['id_product'], $id_product_attribute) - $neteven_order->Quantity); } else { StockAvailable::setQuantity($res_product['id_product'], 0, StockAvailable::getQuantityAvailableByProduct($res_product['id_product']) - $neteven_order->Quantity); } } else { $t_info_product = array(); $t_info_product['id_product'] = $res_product["id_product"]; $t_info_product['cart_quantity'] = $neteven_order->Quantity; $t_info_product['id_product_attribute'] = NULL; if ($control_attribute_product) { $t_info_product['id_product_attribute'] = $id_product_attribute; } Product::updateQuantity($t_info_product); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Cart product') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Insert order in orders_gateway table if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order . ', ' . (int) $neteven_order->OrderLineID . ', "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) { Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); } else { Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID); } } } } else { Toolbox::addLogLine(self::getL('Failed for creation of order detail of NetEven order Id') . $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID . ' ' . self::getL('Product not found SKU') . ' ' . $neteven_order->SKU); } $order = new Order($id_order); $products = $order->getProductsDetail(); if (count($products) == 0 && $this->getValue('mail_active')) { $this->sendDebugMail($this->getValue('mail_list_alert'), self::getL('Order imported is empty'), self::getL('Order Id') . ' ' . (int) $order->id); } }
public function initContentForQuantities() { if ($this->object->id) { $tfowlgstly = "show_quantities"; ${"GLOBALS"}["ygzeqkb"] = "show_quantities"; $gmgclvkrjy = "attributes"; ${"GLOBALS"}["jhngqfjufp"] = "attributes"; $cggvbxsk = "attributes"; ${${"GLOBALS"}["jhngqfjufp"]} = $this->object->getAttributesResume($this->context->language->id); ${"GLOBALS"}["aofqmvff"] = "attribute"; ${"GLOBALS"}["vyyogyvfbtx"] = "attributes"; $nfdcluhk = "attributes"; $khzorwi = "shop_context"; if (empty(${$nfdcluhk})) { ${$cggvbxsk}[] = array("id_product_attribute" => 0, "attribute_designation" => ""); } ${"GLOBALS"}["klqbahrije"] = "shop_context"; ${${"GLOBALS"}["ldfuknydnzr"]} = array(); ${${"GLOBALS"}["ymshseez"]} = array(); ${"GLOBALS"}["lztnksxrb"] = "group_shop"; foreach (${${"GLOBALS"}["vyyogyvfbtx"]} as ${${"GLOBALS"}["aofqmvff"]}) { $rvrxkz = "product_designation"; $ycvvjwmxtnm = "attribute"; $dxuqsu = "available_quantity"; ${$dxuqsu}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = StockAvailable::getQuantityAvailableByProduct((int) $this->object->id, ${$ycvvjwmxtnm}["id_product_attribute"]); ${$rvrxkz}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = rtrim($this->object->name[$this->context->language->id] . " - " . ${${"GLOBALS"}["iixdipeiyldv"]}["attribute_designation"], " - "); } ${${"GLOBALS"}["ueicxl"]} = true; ${$khzorwi} = Shop::getContext(); ${${"GLOBALS"}["lztnksxrb"]} = $this->context->shop->getGroup(); $wktpughd = "pack_quantity"; ${"GLOBALS"}["eukvwdf"] = "advanced_stock_management_warning"; if (${${"GLOBALS"}["klqbahrije"]} == Shop::CONTEXT_ALL) { ${$tfowlgstly} = false; } elseif (${${"GLOBALS"}["ohyfjtkcy"]} == Shop::CONTEXT_GROUP) { if (!$group_shop->share_stock) { ${${"GLOBALS"}["ueicxl"]} = false; } } else { $eksumjgu = "show_quantities"; if ($group_shop->share_stock) { ${$eksumjgu} = false; } } self::$smarty->assign("ps_stock_management", Configuration::get("PS_STOCK_MANAGEMENT")); self::$smarty->assign("has_attribute", $this->object->hasAttributes()); if (Combination::isFeatureActive()) { self::$smarty->assign("countAttributes", (int) Db::getInstance()->getValue("SELECT COUNT(id_product) FROM " . _DB_PREFIX_ . "product_attribute WHERE id_product = " . (int) $this->object->id)); } ${${"GLOBALS"}["eukvwdf"]} = false; if (Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && $this->object->advanced_stock_management) { ${"GLOBALS"}["awunkp"] = "p_attributes"; ${"GLOBALS"}["qxobmbos"] = "warehouses"; ${"GLOBALS"}["cjtetqei"] = "warehouses"; $ukjfpwyojlf = "p_attribute"; ${${"GLOBALS"}["iczelyves"]} = Product::getProductAttributesIds($this->object->id); ${"GLOBALS"}["kcjlbgqb"] = "advanced_stock_management_warning"; ${"GLOBALS"}["dlsnuhn"] = "warehouses"; ${${"GLOBALS"}["qxobmbos"]} = array(); ${"GLOBALS"}["ojmjigmfve"] = "p_attributes"; if (!${${"GLOBALS"}["awunkp"]}) { ${${"GLOBALS"}["mdrvdmghqrtc"]}[] = Warehouse::getProductWarehouseList($this->object->id, 0); } foreach (${${"GLOBALS"}["ojmjigmfve"]} as ${$ukjfpwyojlf}) { ${"GLOBALS"}["uevlubu"] = "ws"; ${"GLOBALS"}["fpbyfow"] = "warehouses"; ${"GLOBALS"}["inddsyj"] = "ws"; ${${"GLOBALS"}["yrbmurnh"]} = Warehouse::getProductWarehouseList($this->object->id, ${${"GLOBALS"}["bhprusfblhn"]}["id_product_attribute"]); if (${${"GLOBALS"}["uevlubu"]}) { ${${"GLOBALS"}["fpbyfow"]}[] = ${${"GLOBALS"}["inddsyj"]}; } } ${${"GLOBALS"}["dlsnuhn"]} = array_unique(${${"GLOBALS"}["cjtetqei"]}); if (empty(${${"GLOBALS"}["mdrvdmghqrtc"]})) { ${${"GLOBALS"}["kcjlbgqb"]} = true; } } if (${${"GLOBALS"}["uucoxnutvd"]}) { $this->displayWarning($this->getMessage("If you wish to use the advanced stock management, you have to:")); $this->displayWarning("- " . $this->getMessage("associate your products with warehouses")); $this->displayWarning("- " . $this->getMessage("associate your warehouses with carriers")); $this->displayWarning("- " . $this->getMessage("associate your warehouses with the appropriate shops")); } ${${"GLOBALS"}["qbmqjuoutyh"]} = null; if (Pack::isPack($this->object->id)) { ${"GLOBALS"}["wdcmwsfvsft"] = "pack_quantity"; $mdjqucflf = "items"; ${${"GLOBALS"}["wfbswtei"]} = Pack::getItems((int) $this->object->id, Configuration::get("PS_LANG_DEFAULT")); $mhikkwxp = "pack_quantities"; ${"GLOBALS"}["kamnnzyptd"] = "pack_quantities"; ${${"GLOBALS"}["kamnnzyptd"]} = array(); foreach (${$mdjqucflf} as ${${"GLOBALS"}["gpnqjgaosuld"]}) { if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) { $gkwutr = "pack_id_product_attribute"; ${${"GLOBALS"}["wkyidmmlbbc"]} = Product::getDefaultAttribute($item->id, 1); ${${"GLOBALS"}["pnfrmcr"]}[] = Product::getQuantity($item->id, ${$gkwutr}) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1); } } $oissvbm = "pack_quantities"; ${${"GLOBALS"}["wdcmwsfvsft"]} = ${$oissvbm}[0]; foreach (${$mhikkwxp} as ${${"GLOBALS"}["kzwkbwmzgtl"]}) { ${"GLOBALS"}["iwrwjuvdmi"] = "value"; if (${${"GLOBALS"}["qbmqjuoutyh"]} > ${${"GLOBALS"}["iwrwjuvdmi"]}) { ${${"GLOBALS"}["qbmqjuoutyh"]} = ${${"GLOBALS"}["kzwkbwmzgtl"]}; } } if (!Warehouse::getPackWarehouses((int) $this->object->id)) { $this->displayWarning($this->getMessage("You must have a common warehouse between this pack and its product.")); } } ${${"GLOBALS"}["lixyhrpqnh"]} = new Language($this->id_language); self::$smarty->assign("iso_code", $lang->iso_code ? $lang->iso_code : "en"); self::$smarty->assign(array("attributes" => ${$gmgclvkrjy}, "available_quantity" => ${${"GLOBALS"}["ldfuknydnzr"]}, "pack_quantity" => ${$wktpughd}, "stock_management_active" => Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT"), "product_designation" => ${${"GLOBALS"}["ymshseez"]}, "show_quantities" => ${${"GLOBALS"}["ygzeqkb"]}, "order_out_of_stock" => Configuration::get("PS_ORDER_OUT_OF_STOCK"))); } else { $this->displayWarning($this->getMessage("You must save this product before managing quantities.")); } }
/** * Get quantity for a given attribute combination * Check if quantity is enough to serve the customer * * @param int $idProductAttribute Product attribute combination id * @param int $qty Quantity needed * @param Shop $shop Shop * * @return bool Quantity is available or not */ public static function checkAttributeQty($idProductAttribute, $qty, Shop $shop = null) { if (!$shop) { $shop = Context::getContext()->shop; } $result = StockAvailable::getQuantityAvailableByProduct(null, (int) $idProductAttribute, $shop->id); return $result && $qty <= $result; }
/** * Fill the variables used for stock management */ public function loadStockData() { if (Validate::isLoadedObject($this)) { // By default, the product quantity correspond to the available quantity to sell in the current shop $this->quantity = StockAvailable::getQuantityAvailableByProduct($this->id, 0); $this->out_of_stock = StockAvailable::outOfStock($this->id); $this->depends_on_stock = StockAvailable::dependsOnStock($this->id); if (Context::getContext()->shop->getContext() == Shop::CONTEXT_GROUP && Context::getContext()->shop->getContextShopGroup()->share_stock == 1) { $this->advanced_stock_management = $this->useAdvancedStockManagement(); } } }
public function renderView() { if (!($cart = $this->loadObject(true))) { return; } $customer = new Customer($cart->id_customer); $currency = new Currency($cart->id_currency); $this->context->cart = $cart; $this->context->currency = $currency; $this->context->customer = $customer; $this->toolbar_title = sprintf($this->l('Cart #%06d'), $this->context->cart->id); $products = $cart->getProducts(); $customized_datas = Product::getAllCustomizedDatas((int) $cart->id); Product::addCustomizationPrice($products, $customized_datas); $summary = $cart->getSummaryDetails(); /* Display order information */ $id_order = (int) Order::getOrderByCartId($cart->id); $order = new Order($id_order); if (Validate::isLoadedObject($order)) { $tax_calculation_method = $order->getTaxCalculationMethod(); $id_shop = (int) $order->id_shop; } else { $id_shop = (int) $cart->id_shop; $tax_calculation_method = Group::getPriceDisplayMethod(Group::getCurrent()->id); } if ($tax_calculation_method == PS_TAX_EXC) { $total_products = $summary['total_products']; $total_discounts = $summary['total_discounts_tax_exc']; $total_wrapping = $summary['total_wrapping_tax_exc']; $total_price = $summary['total_price_without_tax']; $total_shipping = $summary['total_shipping_tax_exc']; } else { $total_products = $summary['total_products_wt']; $total_discounts = $summary['total_discounts']; $total_wrapping = $summary['total_wrapping']; $total_price = $summary['total_price']; $total_shipping = $summary['total_shipping']; } foreach ($products as $k => &$product) { if ($tax_calculation_method == PS_TAX_EXC) { $product['product_price'] = $product['price']; $product['product_total'] = $product['total']; } else { $product['product_price'] = $product['price_wt']; $product['product_total'] = $product['total_wt']; } $image = array(); if (isset($product['id_product_attribute']) && (int) $product['id_product_attribute']) { $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'product_attribute_image WHERE id_product_attribute = ' . (int) $product['id_product_attribute']); } if (!isset($image['id_image'])) { $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'image WHERE id_product = ' . (int) $product['id_product'] . ' AND cover = 1'); } $product_obj = new Product($product['id_product']); $product['qty_in_stock'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], isset($product['id_product_attribute']) ? $product['id_product_attribute'] : null, (int) $id_shop); $image_product = new Image($image['id_image']); $product['image'] = isset($image['id_image']) ? ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $image_product->getExistingImgPath() . '.jpg', 'product_mini_' . (int) $product['id_product'] . (isset($product['id_product_attribute']) ? '_' . (int) $product['id_product_attribute'] : '') . '.jpg', 45, 'jpg') : '--'; } $helper = new HelperKpi(); $helper->id = 'box-kpi-cart'; $helper->icon = 'icon-shopping-cart'; $helper->color = 'color1'; $helper->title = $this->l('Total Cart', null, null, false); $helper->subtitle = sprintf($this->l('Cart #%06d', null, null, false), $cart->id); $helper->value = Tools::displayPrice($total_price, $currency); $kpi = $helper->generate(); $this->tpl_view_vars = array('kpi' => $kpi, 'products' => $products, 'discounts' => $cart->getCartRules(), 'order' => $order, 'cart' => $cart, 'currency' => $currency, 'customer' => $customer, 'customer_stats' => $customer->getStats(), 'total_products' => $total_products, 'total_discounts' => $total_discounts, 'total_wrapping' => $total_wrapping, 'total_price' => $total_price, 'total_shipping' => $total_shipping, 'customized_datas' => $customized_datas); return parent::renderView(); }
/** * Fill the variables used for stock management */ public function loadStockData() { if (Validate::isLoadedObject($this)) { // By default, the product quantity correspond to the available quantity to sell in the current shop $this->quantity = StockAvailable::getQuantityAvailableByProduct($this->id, 0); $this->out_of_stock = StockAvailable::outOfStock($this->id); $this->depends_on_stock = StockAvailable::dependsOnStock($this->id); if (Context::getContext()->shop->getContext() == Shop::CONTEXT_GROUP && Context::getContext()->shop->getContextShopGroup()->share_stock == 1) { $this->advanced_stock_management = Db::getInstance()->getValue('SELECT `advanced_stock_management` FROM ' . _DB_PREFIX_ . 'product_shop WHERE id_product=' . (int) $this->id . Shop::addSqlRestriction()); } } }
private function _checkProducts($productsNode) { $available = true; foreach ($productsNode->Product as $product) { if (strpos($product->SKU, '_') !== false) { $skus = explode('_', $product->SKU); $quantity = StockAvailable::getQuantityAvailableByProduct((int) $skus[0], (int) $skus[1]); if ($quantity - $product->Quantity < 0) { StockAvailable::updateQuantity((int) $skus[0], (int) $skus[1], (int) $product->Quantity); } } else { $quantity = StockAvailable::getQuantityAvailableByProduct((int) $product->SKU); if ($quantity - $product->Quantity < 0) { StockAvailable::updateQuantity((int) $skus[0], 0, (int) $product->Quantity); } } } return $available; }
public function orderAccept($data) { $array = array(); $items = $data->order->items; if (count($items)) { $d = $this->addData($data, true, 'order'); $cart = $d['cart']; $customer = $d['customer']; $address = $d['address']; foreach ($items as $item) { $id_a = null; $id = explode('c', $item->offerId); $product = new Product($id[0], true, $this->context->cookie->id_lang); if (isset($id[1])) { $id_a = (int) $id[1]; } $count_shop = StockAvailable::getQuantityAvailableByProduct($product->id, $id_a); if (!$product->active || $count_shop < (int) $item->count) { continue; } $result = $cart->updateQty((int) $item->count, (int) $id[0], $id_a); if ($result) { $cart->update(); } } if (count($items) == count($cart->getProducts()) && isset($data->order->paymentMethod) && isset($data->order->paymentType)) { $resultat = false; if ($data->order->delivery->id > 0) { $do = array($address->id => $data->order->delivery->id . ','); $cart->setDeliveryOption($do); } $message = ''; if (isset($data->order->notes)) { $message = $data->order->notes ? $data->order->notes : null; } $total = (double) $cart->getOrderTotal(true, Cart::BOTH); $order = new YaOrderCreate(); $order->name = $data->order->paymentType . '_' . $data->order->paymentMethod; $order->module = 'yamodule'; $total = $this->context->cart->getOrderTotal(true, Cart::BOTH); $res = $order->validateOrder((int) $cart->id, $this->module->status['RESERVATION'], $total, 'Yandex.Market.Order', $message, array(), null, false, $cart->secure_key ? $cart->secure_key : ($customer->secure_key ? $customer->secure_key : false)); if ($res) { $values_to_insert = array('id_order' => (int) $order->currentOrder, 'id_market_order' => (int) $data->order->id, 'ptype' => $data->order->paymentType, 'pmethod' => $data->order->paymentMethod, 'home' => isset($data->order->delivery->address->house) ? $data->order->delivery->address->house : 0, 'outlet' => isset($data->order->delivery->outlet->id) ? $data->order->delivery->outlet->id : '', 'currency' => $data->order->currency); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'pokupki_orders', $values_to_insert, 'INSERT'); $resultat = true; } else { $resultat = false; } } else { $resultat = false; } } else { $resultat = false; } if ($resultat) { $array = array('order' => array('accepted' => true, 'id' => '' . $order->currentOrder . '')); } else { $array = array('order' => array('accepted' => false, 'reason' => 'OUT_OF_DATE')); } die(Tools::jsonEncode($array)); }
function getPriceList() { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); if ($currency->iso_code == 'RUB') { $currency->iso_code = 'RUR'; } $desc_type = Configuration::get('YAMARKET_DESC_TYPE'); $link = $this->context->link; $this->ensureHttpPrefix($link); // Get products $products = Product::getProducts($this->id_lang, 0, 0, 'name', 'asc'); $xml = $this->getDocBody(); // Offers $offers = $xml->createElement("offers"); foreach ($products as $product) { // Get home category $category = $product['id_category_default']; if ($category == 1) { $temp_categories = Product::getProductCategories($product['id_product']); foreach ($temp_categories as $category) { if ($category != 1) { break; } } if ($category == 1) { continue; } } if (in_array($category, $this->excluded_cats)) { continue; } $prod_obj = new Product($product['id_product']); $crewrite = Category::getLinkRewrite($product['id_category_default'], $this->id_lang); $accessories = $this->getAccessories($product); $features = $this->getFeatures($product['id_product']); $combinations = $this->getCombinations($prod_obj, $currency); // template array $product_item = array('name' => html_entity_decode($product['name']), 'description' => html_entity_decode($product['description']), 'id_category_default' => $category, 'ean13' => $product['ean13'], 'accessories' => implode(',', $accessories), 'vendor' => $product['manufacturer_name']); if ($desc_type == 1) { $product_item['description'] = html_entity_decode($product['description_short']); } if ($this->country_of_origin_attr != '' && array_key_exists($this->country_of_origin_attr, $features)) { $product_item['country_of_origin'] = $features[$this->country_of_origin_attr]; unset($features[$this->country_of_origin_attr]); } if ($this->model_name_attr != '' && array_key_exists($this->model_name_attr, $features)) { $product_item['name'] = $features[$this->model_name_attr]; unset($features[$this->model_name_attr]); } if (!$product['available_for_order'] or !$product['active']) { continue; } if (!empty($combinations)) { foreach ($combinations as $combination) { $prod_obj->id_product_attribute = $combination['id_product_attribute']; $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], $combination['id_product_attribute']); if (!$available_for_order && !$prod_obj->checkQty(1)) { continue; } $params = $this->getParams($combination); $pictures = array(); foreach ($combination['id_images'] as $id_image) { $pictures[] = $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $id_image, $this->image_type); } $mainPicture = array_shift($pictures); $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite, null, null, null, $combination['id_product_attribute']); $extra_product_item = array('id_product' => $product['id_product'] . 'c' . $combination['id_product_attribute'], 'available_for_order' => $available_for_order, 'price' => $prod_obj->getPrice(true, $combination['id_product_attribute']), 'pictures' => $pictures, 'main_picture' => $mainPicture, 'params' => array_merge($params, $features), 'url' => $url); $offer = array_merge($product_item, $extra_product_item); $offers->appendChild($this->getOfferElem($offer, $xml, $currency)); } } else { $pictures = $this->getPictures($product['id_product'], $product['link_rewrite']); $mainPicture = array_shift($pictures); $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0); if (!$available_for_order && !$prod_obj->checkQty(1)) { continue; } $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite); $extra_product_item = array('id_product' => $product['id_product'], 'available_for_order' => $available_for_order, 'price' => $prod_obj->getPrice(), 'pictures' => $pictures, 'main_picture' => $mainPicture, 'params' => $features, 'url' => $url); $offer = array_merge($product_item, $extra_product_item); $offers->appendChild($this->getOfferElem($offer, $xml, $currency)); } $prod_obj->clearCache(true); } $shop = $xml->getElementsByTagName("shop")->item(0); $shop->appendChild($offers); return $xml->saveXML(); }
public function hookHeader($params) { $shop_id = $this->getShopId(); $buttons_code = $this->client->getButtonsCode(); $this->context->controller->addCSS($this->_path . '/static/css/shop.css', 'all'); if (Configuration::get('ADDSHOPPERS_OPENGRAPH') == '1') { $this->context->smarty->assign('buttons_opengraph', $buttons_code['buttons']['open-graph']); } if (Configuration::get('ADDSHOPPERS_BUTTONS') == '1') { $this->context->smarty->assign('buttons_social', $buttons_code['buttons']['button2']); } $id_lang = (int) Tools::getValue('id_lang', (int) Configuration::get('PS_LANG_DEFAULT')); $this->context->smarty->assign(array('shop_id' => Tools::safeOutput($shop_id), 'default_account' => $shop_id == $this->client->getDefaultShopId(), 'social' => Tools::safeOutput(Configuration::get('ADDSHOPPERS_BUTTONS')), 'floating_buttons' => Tools::safeOutput(Configuration::get('ADDSHOPPERS_FLOATING_BUTTONS')), 'opengraph' => Tools::safeOutput(Configuration::get('ADDSHOPPERS_OPENGRAPH')), 'actual_url' => Tools::safeOutput($this->_getCurrentUrl()), 'absolute_base_url' => Tools::safeOutput($this->_getAbsoluteBaseUrl()), 'id_lang' => (int) $id_lang)); if (Tools::isSubmit('id_product')) { $product = new Product((int) Tools::getValue('id_product')); if (Validate::isLoadedObject($product)) { $currency = new Currency((int) $this->context->cookie->id_currency); $this->context->smarty->assign(array('id_product' => (int) $product->id, 'stock' => isset($product->available_now) ? Tools::safeOutput(AddshoppersClient::WIDGET_STOCK_IN_STOCK) : Tools::safeOutput(AddshoppersClient::WIDGET_STOCK_OUT_OF_STOCK), 'price' => Tools::safeOutput($currency->sign) . number_format((double) $product->getPrice(), 2), 'product_name' => Tools::safeOutput($product->name[$id_lang]), 'product_description' => Tools::safeOutput($product->description[$id_lang]), 'is_product_page' => true)); $quantity = (int) StockAvailable::getQuantityAvailableByProduct((int) $product->id); if ($quantity > 0) { $this->context->smarty->assign('instock', (int) $quantity); } $images = Image::getImages((int) $id_lang, (int) $product->id); $id_image = Product::getCover($product->id); // get Image by id if (sizeof($id_image) > 0) { $image = new Image($id_image['id_image']); // get image full URL $image_url = _PS_BASE_URL_ . _THEME_PROD_DIR_ . $image->getExistingImgPath() . ".jpg"; $this->context->smarty->assign('image_url', $image_url); } } else { $this->context->smarty->assign('is_product_page', false); } } else { $this->context->smarty->assign('is_product_page', false); } return $this->display(__FILE__, 'header.tpl'); }