/** * Assign price and tax to the template */ protected function assignPriceAndTax() { die('coucou'); $id_customer = isset($this->context->customer) ? (int) $this->context->customer->id : 0; $id_group = (int) Group::getCurrent()->id; $id_country = $id_customer ? (int) Customer::getCurrentCountry($id_customer) : (int) Tools::getCountry(); $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group); if ($group_reduction === false) { $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100; } // Tax $tax = (double) $this->product->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $this->context->smarty->assign('tax_rate', $tax); $product_price_with_tax = Product::getPriceStatic($this->product->id, true, null, 6) * 10; if (Product::$_taxCalculationMethod == PS_TAX_INC) { $product_price_with_tax = Tools::ps_round($product_price_with_tax, 2); } $product_price_without_eco_tax = (double) $product_price_with_tax - $this->product->ecotax; $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $ecotax_tax_amount = Tools::ps_round($this->product->ecotax, 2); if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) { $ecotax_tax_amount = Tools::ps_round($ecotax_tax_amount * (1 + $ecotax_rate / 100), 2); } $id_currency = (int) $this->context->cookie->id_currency; $id_product = (int) $this->product->id; $id_shop = $this->context->shop->id; $quantity_discounts = SpecificPrice::getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group, null, true, (int) $this->context->customer->id); foreach ($quantity_discounts as &$quantity_discount) { if ($quantity_discount['id_product_attribute']) { $combination = new Combination((int) $quantity_discount['id_product_attribute']); $attributes = $combination->getAttributesName((int) $this->context->language->id); foreach ($attributes as $attribute) { $quantity_discount['attributes'] = $attribute['name'] . ' - '; } $quantity_discount['attributes'] = rtrim($quantity_discount['attributes'], ' - '); } if ((int) $quantity_discount['id_currency'] == 0 && $quantity_discount['reduction_type'] == 'amount') { $quantity_discount['reduction'] = Tools::convertPriceFull($quantity_discount['reduction'], null, Context::getContext()->currency); } } $product_price = $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false) * 10; $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $this->context->smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (double) $tax, $ecotax_tax_amount), 'ecotax_tax_inc' => $ecotax_tax_amount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'productPriceWithoutEcoTax' => (double) $product_price_without_eco_tax, 'group_reduction' => $group_reduction, 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'ecotax' => !count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'), 'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group))); }
public static function setProductReduction($id_product, $id_group = null, $id_category, $reduction = null) { $res = true; GroupReduction::deleteProductReduction((int) $id_product); $reductions = GroupReduction::getGroupsByCategoryId((int) $id_category); if ($reductions) { foreach ($reductions as $reduction) { $res &= Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'product_group_reduction_cache` (`id_product`, `id_group`, `reduction`) VALUES (' . (int) $id_product . ', ' . (int) $reduction['id_group'] . ', ' . (double) $reduction['reduction'] . ')'); } } return $res; }
/** * Price calculation / Get product price * * @param integer $id_shop Shop id * @param integer $id_product Product id * @param integer $id_product_attribute Product attribute id * @param integer $id_country Country id * @param integer $id_state State id * @param integer $id_currency Currency id * @param integer $id_group Group id * @param integer $quantity Quantity Required for Specific prices : quantity discount application * @param boolean $use_tax with (1) or without (0) tax * @param integer $decimals Number of decimals returned * @param boolean $only_reduc Returns only the reduction amount * @param boolean $use_reduc Set if the returned amount will include reduction * @param boolean $with_ecotax insert ecotax in price output. * @param variable_reference $specific_price_output If a specific price applies regarding the previous parameters, this variable is filled with the corresponding SpecificPrice object * @return float Product price **/ public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $id_county, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $id_affiliate) { //Checking product tags $tags = Tag::getProductTags((int) $id_product); $tags = $tags[1]; if (is_array($tags) && in_array('buy1get1', $tags) && empty($id_affiliate)) { $b1g1 = true; $use_reduc = false; } // Caching if ($id_product_attribute === NULL) { $product_attribute_label = 'NULL'; } else { $product_attribute_label = $id_product_attribute === false ? 'false' : $id_product_attribute; } $cacheId = $id_product . '-' . $id_shop . '-' . $id_currency . '-' . $id_country . '-' . $id_state . '-' . $id_county . '-' . $id_group . '-' . $quantity . '-' . $product_attribute_label . '-' . ($use_tax ? '1' : '0') . '-' . $decimals . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . $with_ecotax . '-' . (int) $id_affiliate; // Cache for specific prices $cacheId3 = $id_product . '-' . $id_shop . '-' . $id_currency . '-' . $id_country . '-' . $id_group . '-' . $quantity; // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_affiliate); if (isset(self::$_prices[$cacheId])) { return self::$_prices[$cacheId]; } // fetch price & attribute price $cacheId2 = $id_product . '-' . $id_product_attribute; if (!isset(self::$_pricesLevel2[$cacheId2])) { self::$_pricesLevel2[$cacheId2] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT p.`price`, ' . ($id_product_attribute ? 'pa.`price`' : 'IFNULL((SELECT pa.price FROM `' . _DB_PREFIX_ . 'product_attribute` pa WHERE id_product = ' . (int) $id_product . ' AND default_on = 1), 0)') . ' AS attribute_price, p.`ecotax` ' . ($id_product_attribute ? ', pa.`ecotax` AS attribute_ecotax' : '') . ' FROM `' . _DB_PREFIX_ . 'product` p ' . ($id_product_attribute ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.`id_product_attribute` = ' . (int) $id_product_attribute : '') . ' WHERE p.`id_product` = ' . (int) $id_product); } $result = self::$_pricesLevel2[$cacheId2]; $price = (double) (!$specific_price or $specific_price['price'] == 0) ? $result['price'] : $specific_price['price']; // convert only if the specific price is in the default currency (id_currency = 0) if (!$specific_price or !($specific_price['price'] > 0 and $specific_price['id_currency'])) { $price = Tools::convertPrice($price, $id_currency); } // Attribute price $attribute_price = Tools::convertPrice(array_key_exists('attribute_price', $result) ? (double) $result['attribute_price'] : 0, $id_currency); if ($id_product_attribute !== false) { // If you want the default combination, please use NULL value instead $price += $attribute_price; } // TaxRate calculation $tax_rate = Tax::getProductTaxRateViaRules((int) $id_product, (int) $id_country, (int) $id_state, (int) $id_county); if ($tax_rate === false) { $tax_rate = 0; } // Add Tax if ($use_tax) { $price = $price * (1 + $tax_rate / 100); } $price = Tools::ps_round($price, $decimals); // Reduction $reduc = 0; if (($only_reduc or $use_reduc) and $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) { $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); } $reduc = Tools::ps_round(!$use_tax ? $reduction_amount / (1 + $tax_rate / 100) : $reduction_amount, $decimals); } else { $reduc = Tools::ps_round($price * $specific_price['reduction'], $decimals); } } if ($only_reduc && !empty($b1g1)) { return 0; } else { if ($only_reduc) { return $reduc; } } if ($use_reduc) { $price -= $reduc; } // Group reduction if ($reductionFromCategory = (double) GroupReduction::getValueForProduct($id_product, $id_group)) { $price -= $price * $reductionFromCategory; } else { // apply group reduction if there is no group reduction for this category $price *= (100 - Group::getReductionByIdGroup($id_group)) / 100; } $price = Tools::ps_round($price, $decimals); // Eco Tax if (($result['ecotax'] or isset($result['attribute_ecotax'])) and $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) { $ecotax = $result['ecotax']; } if ($id_currency) { $ecotax = Tools::convertPrice($ecotax, $id_currency); } if ($use_tax) { $taxRate = TaxRulesGroup::getTaxesRate((int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'), (int) $id_country, (int) $id_state, (int) $id_county); $price += $ecotax * (1 + $taxRate / 100); } else { $price += $ecotax; } } $price = Tools::ps_round($price, $decimals); if ($price < 0) { $price = 0; } self::$_prices[$cacheId] = $price; return self::$_prices[$cacheId]; }
/** * postProcess handle every checks before saving products information * * @param mixed $token * @return void */ public function postProcess($token = null) { global $cookie, $currentIndex; // Add a new product if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) { if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')) { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitAddAttachments')) { if ($this->tabAccess['add'] === '1') { $languages = Language::getLanguages(false); $is_attachment_name_valid = false; foreach ($languages as $language) { $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']); if (strlen($attachment_name_lang) > 0) { $is_attachment_name_valid = true; } if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid Name'); } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) { $this->_errors[] = Tools::displayError('Name is too long'); } if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid description'); } } if (!$is_attachment_name_valid) { $this->_errors[] = Tools::displayError('Attachment Name Required'); } if (empty($this->_errors)) { if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) { if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) { $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb'); } else { do { $uniqid = sha1(microtime()); } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid)); if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) { $this->_errors[] = $this->l('File copy failed'); } @unlink($_FILES['attachment_file']['tmp_name']); } } elseif ((int) $_FILES['attachment_file']['error'] === 1) { $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $upload_mb = min($max_upload, $max_post); $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>'; } if (empty($this->_errors) && isset($uniqid)) { $attachment = new Attachment(); foreach ($languages as $language) { if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) { $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]); } if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) { $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]); } } $attachment->file = $uniqid; $attachment->mime = $_FILES['attachment_file']['type']; $attachment->file_name = pSQL($_FILES['attachment_file']['name']); if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 128) { $this->_errors[] = Tools::displayError('Invalid file extension'); } if (!Validate::isGenericName($attachment->file_name)) { $this->_errors[] = Tools::displayError('Invalid file name'); } if (Tools::strlen($attachment->file_name) > 128) { $this->_errors[] = Tools::displayError('File name too long'); } if (!sizeof($this->_errors)) { $attachment->add(); Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Invalid file'); } } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = (int) Tools::getValue($this->identifier)) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::addProduct($product); Search::indexation(false, $product->id); Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('An error occurred while creating object.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->toggleStatus()) { Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token); } else { $this->_errors[] = Tools::displayError('An error occurred while updating status.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; if ($this->deleted) { $object->deleteImages(); $object->deleted = 1; if ($object->update()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } } elseif ($object->delete()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } $this->_errors[] = Tools::displayError('An error occurred during deletion.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::getValue('submitDel' . $this->table)) { if ($this->tabAccess['delete'] === '1') { if (isset($_POST[$this->table . 'Box'])) { $object = new $this->className(); if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $result = true; if ($this->deleted) { foreach (Tools::getValue($this->table . 'Box') as $id) { $toDelete = new $this->className($id); $toDelete->deleted = 1; $result = $result and $toDelete->update(); } } else { $result = $object->deleteSelection(Tools::getValue($this->table . 'Box')); } if ($result) { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url); } $this->_errors[] = Tools::displayError('An error occurred while deleting selection.'); } } else { $this->_errors[] = Tools::displayError('You must select at least one element to delete.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { /* PrestaShop demo mode */ if (_PS_MODE_DEMO_) { $this->_errors[] = Tools::displayError('This functionnality has been disabled.'); return; } /* PrestaShop demo mode*/ if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $image->id_product); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . (int) $first_img['id_image']); } @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(false); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm(); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Cannot change the product cover'); } else { $productId = (int) Tools::getValue('id_product'); @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection')); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('Attribute price required.'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('You must add at least one attribute.'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) { $reason = new StockMvtReason((int) $id_reason); $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign; if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) { $this->_errors[] = Tools::displayError('An error occurred while updating qty.'); } } Hook::updateProductAttribute((int) $id_product_attribute); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } } } elseif (Tools::isSubmit('deleteProductAttribute')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute')); $product->checkDefaultAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if (!$product->hasAttributes()) { $product->cache_default_attribute = 0; $product->update(); } else { Product::updateDefaultAttribute($id_product); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('deleteAllProductAttributes')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteProductAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if ($product->cache_default_attribute) { $product->cache_default_attribute = 0; $product->update(); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attributes'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('defaultProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $product->deleteDefaultAttributes(); $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute')); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot make default attribute'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(false); foreach ($_POST as $key => $val) { if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding features.'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (Tools::isSubmit('submitPricesModification')) { $_POST['tabs'] = 5; if ($this->tabAccess['edit'] === '1') { $id_specific_prices = Tools::getValue('spm_id_specific_price'); $id_shops = Tools::getValue('spm_id_shop'); $id_currencies = Tools::getValue('spm_id_currency'); $id_countries = Tools::getValue('spm_id_country'); $id_groups = Tools::getValue('spm_id_group'); $prices = Tools::getValue('spm_price'); $from_quantities = Tools::getValue('spm_from_quantity'); $reductions = Tools::getValue('spm_reduction'); $reduction_types = Tools::getValue('spm_reduction_type'); $froms = Tools::getValue('spm_from'); $tos = Tools::getValue('spm_to'); foreach ($id_specific_prices as $key => $id_specific_price) { if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) { $specificPrice = new SpecificPrice((int) $id_specific_price); $specificPrice->id_shop = (int) $id_shops[$key]; $specificPrice->id_currency = (int) $id_currencies[$key]; $specificPrice->id_country = (int) $id_countries[$key]; $specificPrice->id_group = (int) $id_groups[$key]; $specificPrice->price = (double) $prices[$key]; $specificPrice->from_quantity = (int) $from_quantities[$key]; $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]); $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key]; $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key]; $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key]; if (!$specificPrice->update()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitPriceAddition')) { if ($this->tabAccess['add'] === '1') { $id_product = (int) Tools::getValue('id_product'); $id_shop = Tools::getValue('sp_id_shop'); $id_currency = Tools::getValue('sp_id_currency'); $id_country = Tools::getValue('sp_id_country'); $id_group = Tools::getValue('sp_id_group'); $price = Tools::getValue('sp_price'); $from_quantity = Tools::getValue('sp_from_quantity'); $reduction = (double) Tools::getValue('sp_reduction'); $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type'); $from = Tools::getValue('sp_from'); $to = Tools::getValue('sp_to'); if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) { $specificPrice = new SpecificPrice(); $specificPrice->id_product = $id_product; $specificPrice->id_shop = (int) $id_shop; $specificPrice->id_currency = (int) $id_currency; $specificPrice->id_country = (int) $id_country; $specificPrice->id_group = (int) $id_group; $specificPrice->price = (double) $price; $specificPrice->from_quantity = (int) $from_quantity; $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction); $specificPrice->reduction_type = $reduction_type; $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from; $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to; if (!$specificPrice->add()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('deleteSpecificPrice')) { if ($this->tabAccess['delete'] === '1') { if (!($obj = $this->loadObject())) { return; } if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) { $this->_errors[] = Tools::displayError('Invalid specific price ID'); } else { $specificPrice = new SpecificPrice((int) $id_specific_price); if (!$specificPrice->delete()) { $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitSpecificPricePriorities')) { if (!($obj = $this->loadObject())) { return; } if (!($priorities = Tools::getValue('specificPricePriority'))) { $this->_errors[] = Tools::displayError('Please specify priorities'); } elseif (Tools::isSubmit('specificPricePriorityToAll')) { if (!SpecificPrice::setPriorities($priorities)) { $this->_errors[] = Tools::displayError('An error occurred while updating priorities.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) { $this->_errors[] = Tools::displayError('An error occurred while setting priorities.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) { $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } $product->uploadable_files = (int) $_POST['uploadable_files']; $product->text_fields = (int) $_POST['text_fields']; $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('Label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['position'])) { if ($this->tabAccess['edit'] !== '1') { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (!Validate::isLoadedObject($object = $this->loadObject())) { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) { $this->_errors[] = Tools::displayError('Failed to update the position.'); } else { Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog')); } } else { parent::postProcess(true); } }
public static function getGroupReducedPrice($id_product, $id_group, $price) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if ($reduction_from_category !== false) { $price -= $price * (double) $reduction_from_category; } else { $price *= (100 - Group::getReductionByIdGroup($id_group)) / 100; } return $price; }
public function delete() { if ((int) $this->id === 0 || (int) $this->id === (int) Configuration::get('PS_ROOT_CATEGORY')) { return false; } $this->clearCache(); $deleted_children = $all_cat = $this->getAllChildren(); $all_cat[] = $this; foreach ($all_cat as $cat) { /** @var Category $cat */ $cat->deleteLite(); if (!$this->hasMultishopEntries()) { $cat->deleteImage(); $cat->cleanGroups(); $cat->cleanAssoProducts(); // Delete associated restrictions on cart rules CartRule::cleanProductRuleIntegrity('categories', array($cat->id)); Category::cleanPositions($cat->id_parent); /* Delete Categories in GroupReduction */ if (GroupReduction::getGroupsReductionByCategoryId((int) $cat->id)) { GroupReduction::deleteCategory($cat->id); } } } /* Rebuild the nested tree */ if (!$this->hasMultishopEntries() && (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)) { Category::regenerateEntireNtree(); } Hook::exec('actionCategoryDelete', array('category' => $this, 'deleted_children' => $deleted_children)); return true; }
public static function setProductReduction($id_product, $id_group = null, $id_category = null, $reduction = null) { $res = true; GroupReduction::deleteProductReduction((int) $id_product); $categories = Product::getProductCategories((int) $id_product); if ($categories) { foreach ($categories as $category) { $reductions = GroupReduction::getGroupsByCategoryId((int) $category); if ($reductions) { foreach ($reductions as $reduction) { $current_group_reduction = new GroupReduction((int) $reduction['id_group_reduction']); $res &= $current_group_reduction->_setCache(); } } } } return $res; }
/** * Set Group reduction if needed */ public function setGroupReduction() { $row = GroupReduction::getGroupByCategoryId((int) $this->id_category_default); if (!$row) { if (!GroupReduction::deleteProductReduction((int) $this->id)) { return false; } } else { if (!GroupReduction::setProductReduction((int) $this->id, $row['id_group'], (int) $this->id_category_default, (double) $row['reduction'])) { return false; } } return true; }
/** * Price calculation / Get product price * * @param integer $id_shop Shop id * @param integer $id_product Product id * @param integer $id_product_attribute Product attribute id * @param integer $id_country Country id * @param integer $id_state State id * @param integer $id_currency Currency id * @param integer $id_group Group id * @param integer $quantity Quantity Required for Specific prices : quantity discount application * @param boolean $use_tax with (1) or without (0) tax * @param integer $decimals Number of decimals returned * @param boolean $only_reduc Returns only the reduction amount * @param boolean $use_reduc Set if the returned amount will include reduction * @param boolean $with_ecotax insert ecotax in price output. * @param variable_reference $specific_price_output * If a specific price applies regarding the previous parameters, this variable is filled with the corresponding SpecificPrice object * @return float Product price **/ public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0) { static $address = null; static $context = null; if ($address === null) $address = new Address(); if ($context == null) $context = Context::getContext()->cloneContext(); if ($id_shop !== null && $context->shop->id != (int)$id_shop) $context->shop = new Shop((int)$id_shop); if (!$use_customer_price) $id_customer = 0; if ($id_product_attribute === null) $id_product_attribute = Product::getDefaultAttribute($id_product); $cache_id = $id_product.'-'.$id_shop.'-'.$id_currency.'-'.$id_country.'-'.$id_state.'-'.$zipcode.'-'.$id_group. '-'.$quantity.'-'.$id_product_attribute.'-'.($use_tax?'1':'0').'-'.$decimals.'-'.($only_reduc?'1':'0'). '-'.($use_reduc?'1':'0').'-'.$with_ecotax.'-'.$id_customer.'-'.(int)$use_group_reduction.'-'.(int)$id_cart.'-'.(int)$real_quantity; // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice( (int)$id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity ); if (isset(self::$_prices[$cache_id])) return self::$_prices[$cache_id]; // fetch price & attribute price $cache_id_2 = $id_product.'-'.$id_shop; if (!isset(self::$_pricesLevel2[$cache_id_2])) { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = '.(int)$id_shop.')'); $sql->where('p.`id_product` = '.(int)$id_product); if (Combination::isFeatureActive()) { $sql->select('product_attribute_shop.id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on'); $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product` = p.`id_product`'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product_attribute = pa.id_product_attribute AND product_attribute_shop.id_shop = '.(int)$id_shop.')'); } else $sql->select('0 as id_product_attribute'); $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); foreach ($res as $row) { $array_tmp = array( 'price' => $row['price'], 'ecotax' => $row['ecotax'], 'attribute_price' => (isset($row['attribute_price']) ? $row['attribute_price'] : null) ); self::$_pricesLevel2[$cache_id_2][(int)$row['id_product_attribute']] = $array_tmp; if (isset($row['default_on']) && $row['default_on'] == 1) self::$_pricesLevel2[$cache_id_2][0] = $array_tmp; } } if (!isset(self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute])) return; $result = self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute]; if (!$specific_price || $specific_price['price'] < 0) $price = (float)$result['price']; else $price = (float)$specific_price['price']; // convert only if the specific price is in the default currency (id_currency = 0) if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) $price = Tools::convertPrice($price, $id_currency); // Attribute price if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) { $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (float)$result['attribute_price'] : 0, $id_currency); // If you want the default combination, please use NULL value instead if ($id_product_attribute !== false) $price += $attribute_price; } // Tax $address->id_country = $id_country; $address->id_state = $id_state; $address->postcode = $zipcode; $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int)$id_product, $context)); $product_tax_calculator = $tax_manager->getTaxCalculator(); // Add Tax if ($use_tax) $price = $product_tax_calculator->addTaxes($price); // Reduction $specific_price_reduction = 0; if (($only_reduc || $use_reduc) && $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); $specific_price_reduction = !$use_tax ? $product_tax_calculator->removeTaxes($reduction_amount) : $reduction_amount; } else $specific_price_reduction = $price * $specific_price['reduction']; } if ($use_reduc) $price -= $specific_price_reduction; // Group reduction if ($use_group_reduction) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if($context->customer->id){ $id_group = array(); $customer_groups = Db::getInstance()->executeS("SELECT id_group FROM ps_customer_group WHERE id_customer={$context->customer->id}"); foreach ($customer_groups as $row_group) $id_group[] = $row_group['id_group']; }else $id_group = array($id_group); if ($reduction_from_category !== false) $group_reduction = $price * (float)$reduction_from_category; else // apply group reduction if there is no group reduction for this category $group_reduction = (($reduc = Group::getReductionByIdGroup($id_group)) != 0) ? ($price * $reduc / 100) : 0; } else $group_reduction = 0; if ($only_reduc) return Tools::ps_round($group_reduction + $specific_price_reduction, $decimals); if ($use_reduc) $price -= $group_reduction; // Eco Tax if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) $ecotax = $result['attribute_ecotax']; if ($id_currency) $ecotax = Tools::convertPrice($ecotax, $id_currency); if ($use_tax) { // reinit the tax manager for ecotax handling $tax_manager = TaxManagerFactory::getManager( $address, (int)Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID') ); $ecotax_tax_calculator = $tax_manager->getTaxCalculator(); $price += $ecotax_tax_calculator->addTaxes($ecotax); } else $price += $ecotax; } $price = Tools::ps_round($price, $decimals); if ($price < 0) $price = 0; self::$_prices[$cache_id] = $price; return self::$_prices[$cache_id]; }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false) { global $cart; $cart = new Cart((int) $id_cart); // Does order already exists ? if (!$this->active) { die(Tools::displayError()); } if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $cart->secure_key) { die(Tools::displayError()); } // Copying data from cart $order = new Order(); $order->id_carrier = (int) $cart->id_carrier; $order->id_customer = (int) $cart->id_customer; $order->id_address_invoice = (int) $cart->id_address_invoice; $order->id_address_delivery = (int) $cart->id_address_delivery; $vat_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency; $order->id_lang = (int) $cart->id_lang; $order->id_cart = (int) $cart->id; $customer = new Customer((int) $order->id_customer); $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key); $order->payment = $paymentMethod; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = (int) $cart->gift; $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_shipping = (double) $cart->getOrderShippingCost(); $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } // Creating order if ($cart->OrderExists() == false) { $result = $order->add(); } else { $errorMessage = Tools::displayError('An order has already been placed using this cart.'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart)); die($errorMessage); } // Next ! if ($result and isset($order->id)) { if (!$secure_key) { $message .= $this->l('Warning : the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; $store_all_taxes = array(); foreach ($products as $key => $product) { $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL); $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity']; if ($id_order_state != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('PS_OS_ERROR')) { if (Product::updateQuantity($product, (int) $order->id)) { $product['stock_quantity'] -= $product['cart_quantity']; } if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) { $outOfStock = true; } Product::updateDefaultAttribute($product['id_product']); } $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); /* Store tax info */ $id_country = (int) Country::getDefaultCountryId(); $id_state = 0; $id_county = 0; $rate = 0; $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $address_infos = Address::getCountryAndState($id_address); if ($address_infos['id_country']) { $id_country = (int) $address_infos['id_country']; $id_state = (int) $address_infos['id_state']; $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']); } $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county); // If its a freeOrder, there will be no calculation if ($order->total_products > 0) { // remove order discount quotepart on product price in order to obtain the real tax $ratio = $price / $order->total_products; $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio; $tmp_price = $price - $order_reduction_amount; foreach ($allTaxes as $res) { if (!isset($store_all_taxes[$res->id])) { $store_all_taxes[$res->id] = array(); $store_all_taxes[$res->id]['amount'] = 0; } $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang]; $store_all_taxes[$res->id]['rate'] = $res->rate; $unit_tax_amount = $tmp_price * ($res->rate * 0.01); $tmp_price = $tmp_price + $unit_tax_amount; $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity']; } } /* End */ // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = null; if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) { $productDownload = new ProductDownload((int) $id_product_download); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (!_PS_TAX_) { $product['tax'] = 0; $product['rate'] = 0; $tax_rate = 0; } else { $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $ecotaxTaxRate = 0; if (!empty($product['ecotax'])) { $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $product_price = (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, false, false); $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100; if (!$group_reduction) { $group_reduction = (double) Group::getReduction((int) $order->id_customer); } $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']); $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $query .= '(' . (int) $order->id . ', ' . (int) $product['id_product'] . ', ' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . (int) $product['cart_quantity'] . ', ' . $quantityInStock . ', ' . $product_price . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ', ' . $group_reduction . ', ' . $quantityDiscountValue . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\', ' . (double) $tax_rate . ', ' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ', ' . (double) $ecotaxTaxRate . ', ' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\'),'; $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= count($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />'; } $customizationText .= '---<br />'; } $customizationText = rtrim($customizationText, '---<br />'); $customizationQuantity = (int) $product['customizationQuantityTotal']; $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); /* Add carrier tax */ $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false); $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county); $nTax = 0; foreach ($allTaxes as $tax) { if (!isset($tax->id)) { continue; } if (!isset($store_all_taxes[$tax->id])) { $store_all_taxes[$tax->id] = array(); } if (!isset($store_all_taxes[$tax->id]['amount'])) { $store_all_taxes[$tax->id]['amount'] = 0; } $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang]; $store_all_taxes[$tax->id]['rate'] = $tax->rate; if (!$nTax++) { $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl; } else { $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01); } } /* Store taxes */ foreach ($store_all_taxes as $tax) { Db::getInstance()->Execute(' INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`) VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')'); } // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; $total_discount_value = 0; $shrunk = false; foreach ($discounts as $discount) { $objDiscount = new Discount((int) $discount['id_discount']); $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 and $objDiscount->behavior_not_exhausted == 2) { $voucher = new Discount(); foreach ($objDiscount as $key => $discountValue) { $voucher->{$key} = $discountValue; } $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->value = (double) $value - $amount_to_add; $voucher->add(); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; $params['{firstname}'] = $customer->firstname; $params['{lastname}'] = $customer->lastname; $params['{id_order}'] = $order->id; $params['{order_name}'] = sprintf("#%06d", (int) $order->id); @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $order->id), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $amount_to_add = $value; } $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add); $total_discount_value += $amount_to_add; if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED')) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId((int) $cart->id); if ($oldMessage) { $message = new Message((int) $oldMessage['id_message']); $message->id_order = (int) $order->id; $message->update(); } // Hook new order $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } } if (isset($outOfStock) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id); $new_history->addWithemail(true, $extraVars); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) { $invoice = new Address((int) $order->id_address_invoice); $delivery = new Address((int) $order->id_address_delivery); $carrier = new Carrier((int) $order->id_carrier, $order->id_lang); $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false; $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = null; } if (Validate::isEmail($customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } $this->currentOrder = (int) $order->id; return true; } else { $errorMessage = Tools::displayError('Order creation failed'); Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart)); die($errorMessage); } } else { $errorMessage = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }
public function postProcess() { global $currentIndex; $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token; if (Tools::isSubmit('deleteGroupReduction')) { if ($this->tabAccess['delete'] === '1') { if (!($id_group_reduction = Tools::getValue('id_group_reduction'))) { $this->_errors[] = Tools::displayError('Invalid group reduction ID'); } else { $groupReduction = new GroupReduction((int) $id_group_reduction); if (!$groupReduction->delete()) { $this->_errors[] = Tools::displayError('An error occurred while deleting the group reduction'); } else { Tools::redirectAdmin($currentIndex . '&update' . $this->table . '&id_group=' . (int) Tools::getValue('id_group') . '&conf=1&token=' . $token); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } if (Tools::isSubmit('submitAddGroupReduction')) { if ($this->tabAccess['add'] === '1') { if (!($obj = $this->loadObject())) { return; } $groupReduction = new GroupReduction(); if (!($id_category = Tools::getValue('id_category')) or !Validate::isUnsignedId($id_category)) { $this->_errors[] = Tools::displayError('Wrong category ID'); } elseif (!($reduction = Tools::getValue('reductionByCategory')) or !Validate::isPrice($reduction)) { $this->_errors[] = Tools::displayError('Invalid reduction (must be a percentage)'); } elseif (Tools::getValue('reductionByCategory') > 100 or Tools::getValue('reductionByCategory') < 0) { $this->_errors[] = Tools::displayError('Reduction value is incorrect'); } elseif (GroupReduction::doesExist((int) $obj->id, $id_category)) { $this->_errors[] = Tools::displayError('A reduction already exists for this category.'); } else { $groupReduction->id_category = (int) $id_category; $groupReduction->id_group = (int) $obj->id; $groupReduction->reduction = (double) $reduction / 100; if (!$groupReduction->add()) { $this->_errors[] = Tools::displayError('An error occurred while adding a category group reduction.'); } else { Tools::redirectAdmin($currentIndex . '&update' . $this->table . '&id_group=' . (int) Tools::getValue('id_group') . '&conf=3&token=' . $this->token); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } if (Tools::isSubmit('submitAddgroup')) { if ($this->tabAccess['add'] === '1') { if (Tools::getValue('reduction') > 100 or Tools::getValue('reduction') < 0) { $this->_errors[] = Tools::displayError('Reduction value is incorrect'); } else { $id_group_reductions = Tools::getValue('gr_id_group_reduction'); $reductions = Tools::getValue('gr_reduction'); if ($id_group_reductions) { foreach ($id_group_reductions as $key => $id_group_reduction) { if (!Validate::isUnsignedId($id_group_reductions[$key]) or !Validate::isPrice($reductions[$key])) { $this->_errors[] = Tools::displayError('Invalid reduction (must be a percentage)'); } elseif ($reductions[$key] > 100 or $reductions[$key] < 0) { $this->_errors[] = Tools::displayError('Reduction value is incorrect'); } else { $groupReduction = new GroupReduction((int) $id_group_reductions[$key]); $groupReduction->reduction = $reductions[$key] / 100; if (!$groupReduction->update()) { $this->_errors[] = Tools::displayError('Cannot update group reductions'); } } } } if (!sizeof($this->_errors)) { parent::postProcess(); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->id == 1) { $this->_errors[] = Tools::displayError('You cannot delete default group.'); } else { if ($object->delete()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . $token); } $this->_errors[] = Tools::displayError('An error occurred during deletion.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } else { parent::postProcess(); } }
public function process() { global $cart, $currency; parent::process(); if (!Validate::isLoadedObject($this->product)) { $this->errors[] = Tools::displayError('Product not found'); } else { if (!$this->product->active and Tools::getValue('adtoken') != Tools::encrypt('PreviewProduct' . $this->product->id) || !file_exists(dirname(__FILE__) . '/../' . Tools::getValue('ad') . '/ajax.php')) { header('HTTP/1.1 404 page not found'); $this->errors[] = Tools::displayError('Product is no longer available.'); } elseif (!$this->product->checkAccess((int) self::$cookie->id_customer)) { $this->errors[] = Tools::displayError('You do not have access to this product.'); } else { self::$smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id)); if (!$this->product->active) { self::$smarty->assign('adminActionDisplay', true); } /* Product pictures management */ require_once 'images.inc.php'; if ($this->product->customizable) { self::$smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI']))); if (Tools::isSubmit('submitCustomizedDatas')) { $this->pictureUpload($this->product, $cart); $this->textRecord($this->product, $cart); $this->formTargetFormat(); } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct((int) $this->product->id, (int) Tools::getValue('deletePicture'))) { $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture'); } $files = self::$cookie->getFamily('pictures_' . (int) $this->product->id); $textFields = self::$cookie->getFamily('textFields_' . (int) $this->product->id); foreach ($textFields as $key => $textField) { $textFields[$key] = str_replace('<br />', "\n", $textField); } self::$smarty->assign(array('pictures' => $files, 'textFields' => $textFields)); } /* Features / Values */ $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang); $attachments = $this->product->cache_has_attachments ? $this->product->getAttachments((int) self::$cookie->id_lang) : array(); /* Category */ $category = false; if (isset($_SERVER['HTTP_REFERER']) and preg_match('!^(.*)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) and !strstr($_SERVER['HTTP_REFERER'], '.html')) { if (isset($regs[2]) and is_numeric($regs[2])) { if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[2])))) { $category = new Category((int) $regs[2], (int) self::$cookie->id_lang); } } elseif (isset($regs[5]) and is_numeric($regs[5])) { if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[5])))) { $category = new Category((int) $regs[5], (int) self::$cookie->id_lang); } } } if (!$category) { $category = new Category($this->product->id_category_default, (int) self::$cookie->id_lang); } if (isset($category) and Validate::isLoadedObject($category)) { self::$smarty->assign(array('path' => Tools::getPath((int) $category->id, $this->product->name, true), 'category' => $category, 'subCategories' => $category->getSubCategories((int) self::$cookie->id_lang, true), 'id_category_current' => (int) $category->id, 'id_category_parent' => (int) $category->id_parent, 'return_category_name' => Tools::safeOutput($category->name))); } else { self::$smarty->assign('path', Tools::getPath((int) $this->product->id_category_default, $this->product->name)); } self::$smarty->assign('return_link', (isset($category->id) and $category->id) ? Tools::safeOutput(self::$link->getCategoryLink($category)) : 'javascript: history.back();'); if (Pack::isPack((int) $this->product->id) and !Pack::isInStock((int) $this->product->id)) { $this->product->quantity = 0; } $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0; $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_; $id_country = (int) ($id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT')); $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group); if ($group_reduction == 0) { $group_reduction = Group::getReduction((int) self::$cookie->id_customer) / 100; } // Tax $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); self::$smarty->assign('tax_rate', $tax); $productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6); if (Product::$_taxCalculationMethod == PS_TAX_INC) { $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2); } $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax); $ecotax_rate = (double) Tax::getProductEcotaxRate($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $ecotaxTaxAmount = Tools::ps_round($this->product->ecotax, 2); if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) { $ecotaxTaxAmount = Tools::ps_round($ecotaxTaxAmount * (1 + $ecotax_rate / 100), 2); } self::$smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts(SpecificPrice::getQuantityDiscounts((int) $this->product->id, (int) Shop::getCurrentShop(), (int) self::$cookie->id_currency, $id_country, $id_group), $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false), (double) $tax), 'product' => $this->product, 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, self::$cookie->id_lang), 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => (double) $productPriceWithoutEcoTax, 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'group_reduction' => 1 - $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_)); self::$smarty->assign(array('HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($this->product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($this->product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent'))); $images = $this->product->getImages((int) self::$cookie->id_lang); $productImages = array(); foreach ($images as $k => $image) { if ($image['cover']) { self::$smarty->assign('mainImage', $images[0]); $cover = $image; $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image']; $cover['id_image_only'] = (int) $image['id_image']; } $productImages[(int) $image['id_image']] = $image; } if (!isset($cover)) { $cover = array('id_image' => Language::getIsoById(self::$cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture'); } $size = Image::getSize('large'); self::$smarty->assign(array('cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize('medium'), 'largeSize' => Image::getSize('large'), 'accessories' => $this->product->getAccessories((int) self::$cookie->id_lang))); if (count($productImages)) { self::$smarty->assign('images', $productImages); } /* Attributes / Groups & colors */ $colors = array(); $attributesGroups = $this->product->getAttributesGroups((int) self::$cookie->id_lang); // @todo (RM) should only get groups and not all declination ? if (is_array($attributesGroups) and $attributesGroups) { $groups = array(); $combinationImages = $this->product->getCombinationImages((int) self::$cookie->id_lang); foreach ($attributesGroups as $k => $row) { /* Color management */ if ((isset($row['attribute_color']) and $row['attribute_color'] or file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) and $row['id_attribute_group'] == $this->product->id_color_default) { $colors[$row['id_attribute']]['value'] = $row['attribute_color']; $colors[$row['id_attribute']]['name'] = $row['attribute_name']; if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) { $colors[$row['id_attribute']]['attributes_quantity'] = 0; } $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity']; } if (!isset($groups[$row['id_attribute_group']])) { $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'is_color_group' => $row['is_color_group'], 'default' => -1); } $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name']; if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) { $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute']; } if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) { $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0; } $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity']; $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name']; $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute']; $combinations[$row['id_product_attribute']]['price'] = (double) $row['price']; $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax']; $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight']; $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity']; $combinations[$row['id_product_attribute']]['reference'] = $row['reference']; $combinations[$row['id_product_attribute']]['ean13'] = $row['ean13']; $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact']; $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity']; $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1; } //wash attributes list (if some attributes are unavailables and if allowed to wash it) if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) { foreach ($groups as &$group) { foreach ($group['attributes_quantity'] as $key => &$quantity) { if (!$quantity) { unset($group['attributes'][$key]); } } } foreach ($colors as $key => $color) { if (!$color['attributes_quantity']) { unset($colors[$key]); } } } foreach ($groups as &$group) { natcasesort($group['attributes']); } foreach ($combinations as $id_product_attribute => $comb) { $attributeList = ''; foreach ($comb['attributes'] as $id_attribute) { $attributeList .= '\'' . (int) $id_attribute . '\','; } $attributeList = rtrim($attributeList, ','); $combinations[$id_product_attribute]['list'] = $attributeList; } self::$smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $this->product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages)); } self::$smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields((int) self::$cookie->id_lang) : false)); // Pack management self::$smarty->assign('packItems', $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, (int) self::$cookie->id_lang, true) : array()); self::$smarty->assign('packs', Pack::getPacksTable($this->product->id, (int) self::$cookie->id_lang, true, 1)); } } self::$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'categories' => Category::getHomeCategories((int) self::$cookie->id_lang), 'have_image' => isset($cover) ? (int) $cover['id_image'] : false, 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'ecotax' => !sizeof($this->errors) and $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'), 'ipa_customization' => Tools::getIsset('ipa_customization') ? Tools::getValue('ipa_customization') : '', 'ipa_default' => Product::getDefaultAttribute($this->product->id))); }
public function getTemplateVarProduct() { $productSettings = $this->getProductPresentationSettings(); $product = $this->objectPresenter->present($this->product); $product['id_product'] = (int) $this->product->id; $product['out_of_stock'] = (int) $this->product->out_of_stock; $product['new'] = (int) $this->product->new; $product['id_product_attribute'] = (int) Tools::getValue('id_product_attribute'); $product['minimal_quantity'] = $this->getProductMinimalQuantity($product); $product['quantity_wanted'] = $this->getRequiredQuantity($product); $product_full = Product::getProductProperties($this->context->language->id, $product, $this->context); $product_full = $this->addProductCustomizationData($product_full); $product_full['show_quantities'] = (bool) (Configuration::get('PS_DISPLAY_QTIES') && Configuration::get('PS_STOCK_MANAGEMENT') && $this->product->quantity > 0 && $this->product->available_for_order && !Configuration::isCatalogMode()); $product_full['quantity_label'] = $this->product->quantity > 1 ? $this->trans('Items', array(), 'Shop.Theme.Catalog') : $this->trans('Item', array(), 'Shop.Theme.Catalog'); $product_full['quantity_discounts'] = $this->quantity_discounts; if ($product_full['unit_price_ratio'] > 0) { $unitPrice = $productSettings->include_taxes ? $product_full['price'] : $product_full['price_tax_exc']; $product_full['unit_price'] = $unitPrice / $product_full['unit_price_ratio']; } $group_reduction = GroupReduction::getValueForProduct($this->product->id, (int) Group::getCurrent()->id); if ($group_reduction === false) { $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100; } $product_full['customer_group_discount'] = $group_reduction; $presenter = $this->getProductPresenter(); return $presenter->present($productSettings, $product_full, $this->context->language); }
public function initContent() { if (!$this->ajax) { parent::initContent(); } // parent::initContent(); $this->setTemplate(_PS_THEME_DIR_ . 'category.tpl'); if (!$this->customer_access) { return; } if (isset($this->context->cookie->id_compare)) { $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) $this->context->cookie->id_compare)); } $this->productSort(); // Product sort must be called before assignProductList() $this->assignScenes(); $this->assignSubcategories(); $this->assignProductList(); $products = isset($this->cat_products) && $this->cat_products ? $this->cat_products : null; $combinations = array(); if ($products !== NULL) { foreach ($products as &$pro) { $product_obj = new Product($pro['id_product'], $this->context->language->id); $pro['groups'] = $product_obj->getProductCombinationsGroups($pro['id_product']); $combinations[$pro['id_product']] = $product_obj->getProductAttributeCombinations($pro['id_product']); $id_group = (int) Group::getCurrent()->id; $group_reduction = GroupReduction::getValueForProduct($pro['id_product'], $id_group); if ($group_reduction === false) { $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100; } $pro['group_reduction'] = $group_reduction; $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $pro['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address); $pro['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group); $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $pro['tax_rate'] = $tax; $pro['unit_price_ratio'] = $product_obj->unit_price_ratio; $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $pro['ecotaxTax_rate'] = $ecotax_rate; } } $this->context->smarty->assign(array('category' => $this->category, 'description_short' => Tools::truncateString($this->category->description, 350), 'products' => $products, 'id_category' => (int) $this->category->id, 'id_category_parent' => (int) $this->category->id_parent, 'return_category_name' => Tools::safeOutput($this->category->name), 'path' => Tools::getPath($this->category->id), 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize(ImageType::getFormatedName('category')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'thumbSceneSize' => Image::getSize(ImageType::getFormatedName('m_scene')), 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers(), 'body_classes' => array($this->php_self . '-' . $this->category->id, $this->php_self . '-' . $this->category->link_rewrite), 'combinations' => $combinations)); }
public function delete() { if ((int) $this->id === 0 or (int) $this->id === 1) { return false; } $this->clearCache(); /* Get childs categories */ $toDelete = array((int) $this->id); $this->recursiveDelete($toDelete, (int) $this->id); $toDelete = array_unique($toDelete); /* Delete category and its child from database */ $list = sizeof($toDelete) > 1 ? implode(',', array_map('intval', $toDelete)) : (int) $this->id; Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'category` WHERE `id_category` IN (' . $list . ')'); Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'category_lang` WHERE `id_category` IN (' . $list . ')'); Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_category` IN (' . $list . ')'); Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'category_group` WHERE `id_category` IN (' . $list . ')'); self::cleanPositions($this->id_parent); /* Delete category images and its children images */ $tmpCategory = new Category(); foreach ($toDelete as $id_category) { $tmpCategory->id = (int) $id_category; $tmpCategory->deleteImage(); } /* Delete products which were not in others categories */ $result = Db::getInstance()->ExecuteS(' SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` NOT IN (SELECT `id_product` FROM `' . _DB_PREFIX_ . 'category_product`)'); foreach ($result as $p) { $product = new Product((int) $p['id_product']); if (Validate::isLoadedObject($product)) { $product->delete(); } } /* Set category default to 1 where categorie no more exists */ $result = Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'product` SET `id_category_default` = 1 WHERE `id_category_default` NOT IN (SELECT `id_category` FROM `' . _DB_PREFIX_ . 'category`)'); /* Rebuild the nested tree */ if (!isset($this->doNotRegenerateNTree) or !$this->doNotRegenerateNTree) { self::regenerateEntireNtree(); } Module::hookExec('categoryDeletion', array('category' => $this)); /* Delete Categories in GroupReduction */ foreach ($toDelete as $category) { if (GroupReduction::getGroupReductionByCategoryId((int) $category)) { GroupReduction::deleteCategory($category); } } return true; }
public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0, $service_date = null, $service_time_from = null, $service_time_to = null) { require_once dirname(__FILE__) . '/../../modules/aphrodinet/classes/AphCustomPrice.php'; static $address = null; static $context = null; if ($address === null) { $address = new Address(); } if ($context == null) { $context = Context::getContext()->cloneContext(); } if ($id_shop !== null && $context->shop->id != (int) $id_shop) { $context->shop = new Shop((int) $id_shop); } if (!$use_customer_price) { $id_customer = 0; } if ($id_product_attribute === null) { $id_product_attribute = Product::getDefaultAttribute($id_product); } if (!empty($id_cart)) { $res = Db::getInstance()->executeS('SELECT `delivery_date`, `delivery_time_from`, `delivery_time_to` ' . 'FROM ' . _DB_PREFIX_ . 'cart_product ' . 'WHERE `id_cart` = ' . (int) $id_cart . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute . ' ' . 'LIMIT 1'); if (!empty($res) && empty($service_date)) { $res = $res[0]; if (!empty($res)) { $service_date = $res['delivery_date']; $service_time_from = $res['delivery_time_from']; $service_time_to = $res['delivery_time_to']; } } } if (!empty($service_time_from) && strlen($service_time_from) == 5) { $service_time_from .= ':00'; } if (!empty($service_time_to) && strlen($service_time_to) == 5) { $service_time_to .= ':00'; } $cache_id = (int) $id_product . '-' . (int) $id_shop . '-' . (int) $id_currency . '-' . (int) $id_country . '-' . $id_state . '-' . $zipcode . '-' . (int) $id_group . '-' . (int) $quantity . '-' . (int) $id_product_attribute . '-' . (int) $with_ecotax . '-' . (int) $id_customer . '-' . (int) $use_group_reduction . '-' . (int) $id_cart . '-' . (int) $real_quantity . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . ($use_tax ? '1' : '0') . '-' . (int) $decimals . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : ''); // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity); if (isset(self::$_prices[$cache_id])) { if (isset($specific_price['price']) && $specific_price['price'] > 0) { $specific_price['price'] = self::$_prices[$cache_id]; } return self::$_prices[$cache_id]; } $cache_id_2 = $id_product . '-' . $id_shop . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : ''); if (!isset(self::$_pricesLevel2[$cache_id_2])) { $base_price_wt = 0; $service_date_ts = strtotime($service_date); $service_date_week_day = date('w', $service_date_ts); if (!empty($service_date) && $service_date != '0000-00-00') { // cerco il prezzo del giorno $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, NULL, 1); if (!empty($custom_prices)) { $base_price_wt = $custom_prices[0]['price_wt']; } } if (!empty($service_date) && $service_date != '0000-00-00') { $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, 0, 1); } if (!empty($service_date) && $service_date != '0000-00-00') { $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, 0, 1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1); } if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from); } if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) { $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from); } if (!empty($offer_prices)) { $res = $offer_prices; } elseif (!empty($custom_prices)) { $res = $custom_prices; } else { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = ' . (int) $id_shop . ')'); $sql->where('p.`id_product` = ' . (int) $id_product); if (Combination::isFeatureActive()) { $sql->select('IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product = p.id_product AND product_attribute_shop.id_shop = ' . (int) $id_shop . ')'); } else { $sql->select('0 as id_product_attribute'); } $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); } if (is_array($res) && count($res)) { foreach ($res as $row) { if ($row['price'] < 0) { if ($row['reduction_type'] == 'amount') { $row['price'] = 0; //$base_price_wt - $row['reduction']; } else { $row['price'] = 0; //$base_price_wt - (($row['reduction'] * $base_price_wt) / 100); } } else { $row['price'] = 0; //$row['price_wt']; } $array_tmp = array('price' => $row['price'], 'ecotax' => !empty($row['ecotax']), 'attribute_price' => isset($row['attribute_price']) ? $row['attribute_price'] : null); self::$_pricesLevel2[$cache_id_2][(int) $row['id_product_attribute']] = $array_tmp; if (isset($row['default_on']) && $row['default_on'] == 1) { self::$_pricesLevel2[$cache_id_2][0] = $array_tmp; } } } } if (!isset(self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute])) { return; } $result = self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute]; if (!$specific_price || $specific_price['price'] < 0) { $price = (double) $result['price']; } else { $price = (double) $specific_price['price']; } if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) { $price = Tools::convertPrice($price, $id_currency); if (isset($specific_price['price'])) { $specific_price['price'] = $price; } } if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) { $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (double) $result['attribute_price'] : 0, $id_currency); if ($id_product_attribute !== false) { $price += $attribute_price; } } $address->id_country = $id_country; $address->id_state = $id_state; $address->postcode = $zipcode; $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $id_product, $context)); $product_tax_calculator = $tax_manager->getTaxCalculator(); if ($use_tax) { $price = $product_tax_calculator->addTaxes($price); } if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) { $ecotax = $result['attribute_ecotax']; } if ($id_currency) { $ecotax = Tools::convertPrice($ecotax, $id_currency); } if ($use_tax) { $tax_manager = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID')); $ecotax_tax_calculator = $tax_manager->getTaxCalculator(); $price += $ecotax_tax_calculator->addTaxes($ecotax); } else { $price += $ecotax; } } $specific_price_reduction = 0; if (($only_reduc || $use_reduc) && $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) { $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); } $specific_price_reduction = $reduction_amount; if (!$use_tax && $specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->removeTaxes($specific_price_reduction); } if ($use_tax && !$specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->addTaxes($specific_price_reduction); } } else { $specific_price_reduction = $price * $specific_price['reduction']; } } if ($use_reduc) { $price -= $specific_price_reduction; } if ($use_group_reduction) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if ($reduction_from_category !== false) { $group_reduction = $price * (double) $reduction_from_category; } else { // apply group reduction if there is no group reduction for this category $group_reduction = ($reduc = Group::getReductionByIdGroup($id_group)) != 0 ? $price * $reduc / 100 : 0; } $price -= $group_reduction; } if ($only_reduc) { return Tools::ps_round($specific_price_reduction, $decimals); } $price = Tools::ps_round($price, $decimals); if ($price < 0) { $price = 0; } self::$_prices[$cache_id] = $price; return self::$_prices[$cache_id]; }
foreach ($shops as $shop) { if ($product->isAssociatedToShop($shop['id_shop'])) { $product_price = new Product($id_product_old, false, null, $shop['id_shop']); $product->price = $product_price->price; } } } if (Validate::isLoadedObject($product)) { $id_product_old = $product->id; for ($i = 1; $i <= $quantity; $i++) { echo $i; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) { echo 'An error occurred while copying images.'; } else { Hook::exec('actionProductAdd', array('product' => $product)); if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) { Search::indexation(false, $product->id); } echo ' Duplication, ProductAddHook and re-index done. '; } } else { echo 'An error occurred while duplicating some object properties.'; }
break; } $counter++; } } // Get price changes $more_attributes_price = 0; if (count($more_attributes)) { $more_attributes_price = get_moreAttributesPrice($more_attributes, $request_product); } // Get the group reduction $group_reduction = 1; $group_id = 0; if (isset($cookie->id_customer)) { $group_id = Customer::getDefaultGroupId($cookie->id_customer); $groupReduction = GroupReduction::getValueForProduct($request_product, $group_id); if (!$groupReduction) { $group_reduction -= floatval(Group::getReduction($cookie->id_customer)) / 100; } else { $group_reduction -= floatval($groupReduction); } } $more_attributes_price *= $group_reduction; // If other return only the attributes price if ($request_others && ($request_attr_2 == '' && $request_attr_3 == '-1' || $request_attr_2 != '' && $request_attr_3 == '' || $request_value == '')) { die('Price->' . $more_attributes_price); } $group = str_replace('group_', '', $request_group); $result = DB::getInstance()->ExecuteS('SELECT attribute.id_attribute FROM ' . _DB_PREFIX_ . 'attribute AS attribute, ' . _DB_PREFIX_ . 'attribute_lang AS lang WHERE attribute.id_attribute_group = ' . $group . ' AND lang.name = "' . $param1 . '" AND lang.id_lang = ' . (int) $cookie->id_lang . ' AND attribute.id_attribute = lang.id_attribute'); // Value creation if needed if (!isset($result[0])) {
public function getProducts($selected_filters, &$products, &$nb_products, &$p, &$n, &$pages_nb, &$start, &$stop, &$range, &$combinations) { global $cookie; $products = $this->getProductByFilters($selected_filters); $products = Product::getProductsProperties((int) $cookie->id_lang, $products); $nb_products = $this->nbr_products; $range = 2; /* how many pages around page selected */ $n = (int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')); if ($n <= 0) { $n = 1; } $p = $this->page; if ($p < 0) { $p = 0; } if ($p > $nb_products / $n) { $p = ceil($nb_products / $n); } $pages_nb = ceil($nb_products / (int) $n); $start = (int) ($p - $range); if ($start < 1) { $start = 1; } $stop = (int) ($p + $range); if ($stop > $pages_nb) { $stop = (int) $pages_nb; } foreach ($products as &$product) { if ($product['id_product_attribute'] && isset($product['product_attribute_minimal_quantity'])) { $product['minimal_quantity'] = $product['product_attribute_minimal_quantity']; } $product_obj = new Product((int) $product['id_product'], $this->context->language->id); $product['groups'] = $product_obj->getProductCombinationsGroups((int) $product['id_product']); $product['obj'] = $product_obj; $combinations[$product['id_product']] = $product_obj->getProductAttributeCombinations($product['id_product']); $id_group = (int) Group::getCurrent()->id; $group_reduction = GroupReduction::getValueForProduct($product['id_product'], $id_group); if ($group_reduction === false) { $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100; } $product['group_reduction'] = $group_reduction; $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $product['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address); $product['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group); $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $product['tax_rate'] = $tax; $product['unit_price_ratio'] = $product_obj->unit_price_ratio; $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $product['ecotaxTax_rate'] = $ecotax_rate; } }
/** * Set Group reduction if needed */ public function setGroupReduction() { return GroupReduction::setProductReduction($this->id, null, $this->id_category_default); }
public function processDuplicate() { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; if (empty($product->price) && Shop::getContext() == Shop::CONTEXT_GROUP) { $shops = ShopGroup::getShopsFromGroup(Shop::getContextShopGroupID()); foreach ($shops as $shop) { if ($product->isAssociatedToShop($shop['id_shop'])) { $product_price = new Product($id_product_old, false, null, $shop['id_shop']); $product->price = $product_price->price; } } } unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) { $this->errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::exec('actionProductAdd', array('product' => $product)); if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) { Search::indexation(false, $product->id); } $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=19&token=' . $this->token; } } else { $this->errors[] = Tools::displayError('An error occurred while creating an object.'); } } }
/** * Set Group reduction if needed */ public function setGroupReduction() { return GroupReduction::setProductReduction($this->id); }
protected function updateCategoryReduction() { $category_reduction = Tools::getValue('category_reduction'); Db::getInstance()->execute(' DELETE FROM `' . _DB_PREFIX_ . 'group_reduction` WHERE `id_group` = ' . (int) Tools::getValue('id_group')); Db::getInstance()->execute(' DELETE FROM `' . _DB_PREFIX_ . 'product_group_reduction_cache` WHERE `id_group` = ' . (int) Tools::getValue('id_group')); if (is_array($category_reduction) && count($category_reduction)) { if (!Configuration::getGlobalValue('PS_GROUP_FEATURE_ACTIVE')) { Configuration::updateGlobalValue('PS_GROUP_FEATURE_ACTIVE', 1); } foreach ($category_reduction as $cat => $reduction) { if (!Validate::isUnsignedId($cat) || !$this->validateDiscount($reduction)) { $this->errors[] = Tools::displayError('The discount value is incorrect.'); } else { $category = new Category((int) $cat); $category->addGroupsIfNoExist((int) Tools::getValue('id_group')); $group_reduction = new GroupReduction(); $group_reduction->id_group = (int) Tools::getValue('id_group'); $group_reduction->reduction = (double) ($reduction / 100); $group_reduction->id_category = (int) $cat; if (!$group_reduction->save()) { $this->errors[] = Tools::displayError('You cannot save group reductions.'); } } } } }
if (Configuration::get('AIMD_FIRST_DIMENSION_ACTIVE') == 1) { $dimensions[] = Configuration::get('AIMD_FIRST_DIMENSION_ID'); $scales[Configuration::get('AIMD_FIRST_DIMENSION_ID')] = Configuration::get('AIMD_FIRST_DIMENSION_SCALE'); } if (Configuration::get('AIMD_SECOND_DIMENSION_ACTIVE') == 1) { $dimensions[] = Configuration::get('AIMD_SECOND_DIMENSION_ID'); $scales[Configuration::get('AIMD_SECOND_DIMENSION_ID')] = Configuration::get('AIMD_SECOND_DIMENSION_SCALE'); } if (Configuration::get('AIMD_THIRD_DIMENSION_ACTIVE') == 1) { $dimensions[] = Configuration::get('AIMD_THIRD_DIMENSION_ID'); $scales[Configuration::get('AIMD_THIRD_DIMENSION_ID')] = Configuration::get('AIMD_THIRD_DIMENSION_SCALE'); } // Get the group reduction $groupReduction = 1; if (isset($cookie->id_customer)) { $productGroupReduction = GroupReduction::getValueForProduct($idProduct, $groupId); if (!$productGroupReduction) { $groupReduction -= floatval(Group::getReduction((int) $cookie->id_customer)) / 100; } else { $groupReduction -= floatval($productGroupReduction); } } // Get the product price with attributes but the multidimensionnals attributes (including taxes) $more_tmp = array(); $more_attributes_price = 0; $more_attributes = DB::getInstance()->ExecuteS('SELECT pac.id_attribute FROM ' . _DB_PREFIX_ . 'attribute_lang AS lang LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute_combination AS pac ON lang.id_attribute = pac.id_attribute' . ' LEFT JOIN ' . _DB_PREFIX_ . 'attribute AS attribute ON lang.id_attribute = attribute.id_attribute LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute AS pa ON pac.id_product_attribute = pa.id_product_attribute' . ' WHERE pa.id_product = ' . $idProduct . ' AND pa.id_product_attribute = ' . $idProductAttribute . ' AND lang.id_lang = ' . (int) $cookie->id_lang . ' AND attribute.id_attribute_group NOT IN (' . implode(', ', $dimensions) . ')'); if (count($more_attributes)) { foreach ($more_attributes as $more_attribute) { $more_tmp[] = $more_attribute['id_attribute']; } $more_attributes_price = get_moreAttributesPrice($more_tmp, $idProduct);