/** * 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 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; } }
/** * 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, $use_groupReduction) { // 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; // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity); 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) { return $reduc; } if ($use_reduc) { $price -= $reduc; } // Group reduction if ($use_groupReduction) { 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['attribute_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]; }
/** * 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; if ($address === null) { $address = new Address(); } if (!$use_customer_price) { $id_customer = 0; } $cache_id = $id_product . '-' . $id_shop . '-' . $id_currency . '-' . $id_country . '-' . $id_state . '-' . $zipcode . '-' . $id_group . '-' . $quantity . '-' . (int) $id_product_attribute . '-' . ($use_tax ? '1' : '0') . '-' . $decimals . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . $with_ecotax . '-' . $id_customer; // 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; if (!isset(self::$_pricesLevel2[$cache_id_2])) { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->join(Shop::addSqlAssociation('product', 'p')); $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->join(Shop::addSqlAssociation('product_attribute', 'pa', false, '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 = (double) $result['price']; } else { $price = (double) $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 ? (double) $result['attribute_price'] : 0, $id_currency); if ($id_product_attribute !== false && !is_null($id_product_attribute)) { // If you want the default combination, please use NULL value instead $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)); $product_tax_calculator = $tax_manager->getTaxCalculator(); // Add Tax if ($use_tax) { $price = $product_tax_calculator->addTaxes($price); } $price = Tools::ps_round($price, $decimals); // Reduction $reduc = 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); } $reduc = Tools::ps_round(!$use_tax ? $product_tax_calculator->removeTaxes($reduction_amount) : $reduction_amount, $decimals); } else { $reduc = Tools::ps_round($price * $specific_price['reduction'], $decimals); } } if ($only_reduc) { return $reduc; } if ($use_reduc) { $price -= $reduc; } // Group reduction if ($use_group_reduction) { if ($reduction_from_category = (double) GroupReduction::getValueForProduct($id_product, $id_group)) { $price -= $price * $reduction_from_category; } 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'] || 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]; }
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 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]; }
/** * 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 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 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; }
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);