Example #1
0
 public function updateTaxAmount($order, $tax_calculator = false)
 {
     $this->setContext((int) $this->id_shop);
     $address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $tax_manager = TaxManagerFactory::getManager($address, (int) Product::getIdTaxRulesGroupByIdProduct((int) $this->product_id, $this->context));
     $this->tax_calculator = $tax_manager->getTaxCalculator();
     return $tax_calculator ? $this->tax_calculator : $this->saveTaxCalculator($order, true);
 }
 /**
  * Returns the product tax
  *
  * @param integer $id_product
  * @param integer $id_country
  * @return Tax
  */
 public static function getProductTaxRate($id_product, $id_address = null, Context $context = null)
 {
     if ($context == null) {
         $context = Context::getContext();
     }
     $address = Address::initialize($id_address);
     $id_tax_rules = (int) Product::getIdTaxRulesGroupByIdProduct($id_product, $context);
     $tax_manager = TaxManagerFactory::getManager($address, $id_tax_rules);
     $tax_calculator = $tax_manager->getTaxCalculator();
     return $tax_calculator->getTotalRate();
 }
Example #3
0
 /**
  * This function returns the total cart amount
  *
  * Possible values for $type:
  * Cart::ONLY_PRODUCTS
  * Cart::ONLY_DISCOUNTS
  * Cart::BOTH
  * Cart::BOTH_WITHOUT_SHIPPING
  * Cart::ONLY_SHIPPING
  * Cart::ONLY_WRAPPING
  * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  *
  * @param boolean $withTaxes With or without taxes
  * @param integer $type Total type
  * @param boolean $use_cache Allow using cache of the method CartRule::getContextualValue
  * @return float Order total
  */
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     static $address = null;
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
         if (is_null($products) && is_null($id_carrier)) {
             $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
         } else {
             $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool) $with_taxes, null, $products);
         }
     } else {
         $shipping_fees = 0;
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     $products_total = array();
     $ecotax_total = 0;
     foreach ($products as $product) {
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
             $id_address = (int) $this->id_address_invoice;
         } else {
             $id_address = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!Address::addressExists($id_address)) {
             $id_address = null;
         }
         $price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 6, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $id_address, $null, false, true, $virtual_context);
         if (Configuration::get('PS_USE_ECOTAX')) {
             $ecotax = $product['ecotax'];
             if (isset($product['attribute_ecotax']) && $product['attribute_ecotax'] > 0) {
                 $ecotax = $product['attribute_ecotax'];
             }
         } else {
             $ecotax = 0;
         }
         $address = Address::initialize($id_address, true);
         if ($with_taxes) {
             $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
             $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
             if ($ecotax) {
                 $ecotax_tax_calculator = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'))->getTaxCalculator();
             }
         } else {
             $id_tax_rules_group = 0;
         }
         if (in_array(Configuration::get('PS_ROUND_TYPE'), array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($products_total[$id_tax_rules_group])) {
                 $products_total[$id_tax_rules_group] = 0;
             }
         } else {
             if (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
                 $products_total[$id_tax_rules_group . '_' . $id_address] = 0;
             }
         }
         switch (Configuration::get('PS_ROUND_TYPE')) {
             case Order::ROUND_TOTAL:
                 $products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_total += $ecotax * (int) $product['cart_quantity'];
                 }
                 break;
             case Order::ROUND_LINE:
                 $product_price = $price * $product['cart_quantity'];
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_);
                 if ($with_taxes) {
                     $products_total[$id_tax_rules_group] += Tools::ps_round($tax_calculator->getTaxesTotalAmount($product_price), _PS_PRICE_COMPUTE_PRECISION_);
                 }
                 if ($ecotax) {
                     $ecotax_price = $ecotax * (int) $product['cart_quantity'];
                     $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_);
                     if ($with_taxes) {
                         $ecotax_total += Tools::ps_round($ecotax_tax_calculator->getTaxesTotalAmount($ecotax_price), _PS_PRICE_COMPUTE_PRECISION_);
                     }
                 }
                 break;
             case Order::ROUND_ITEM:
             default:
                 $product_price = $with_taxes ? $tax_calculator->addTaxes($price) : $price;
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_price = $with_taxes ? $ecotax_tax_calculator->addTaxes($ecotax) : $ecotax;
                     $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 }
                 break;
         }
     }
     foreach ($products_total as $key => $price) {
         if ($with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
             $tmp = explode('_', $key);
             $address = Address::initialize((int) $tmp[1], true);
             $tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
             $order_total += Tools::ps_round($price, _PS_PRICE_COMPUTE_PRECISION_) + Tools::ps_round($tax_calculator->getTaxesTotalAmount($price), _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             $order_total += $price;
         }
     }
     if ($ecotax_total && $with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
         $ecotax_total = Tools::ps_round($ecotax_total, _PS_PRICE_COMPUTE_PRECISION_) + Tools::ps_round($ecotax_tax_calculator->getTaxesTotalAmount($ecotax_total), _PS_PRICE_COMPUTE_PRECISION_);
     }
     $order_total += $ecotax_total;
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     if ($this->gift) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), _PS_PRICE_COMPUTE_PRECISION_), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), $wrapping_fees + $order_total_products + $shipping_fees);
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, _PS_PRICE_COMPUTE_PRECISION_);
 }
Example #4
0
 /**
  * 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];
 }
Example #5
0
 public static function getTaxesInformations($row, Context $context = null)
 {
     static $address = null;
     if ($context === null) {
         $context = Context::getContext();
     }
     if ($address === null) {
         $address = new Address();
     }
     $address->id_country = (int) $context->country->id;
     $address->id_state = 0;
     $address->postcode = 0;
     $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $context));
     $row['rate'] = $tax_manager->getTaxCalculator()->getTotalRate();
     $row['tax_name'] = $tax_manager->getTaxCalculator()->getTaxesName();
     return $row;
 }
Example #6
0
 /**
  * Set specific price of the product
  * @param object $order
  */
 protected function setSpecificPrice(Order $order)
 {
     $this->reduction_amount = 0.0;
     $this->reduction_percent = 0.0;
     $this->reduction_amount_tax_incl = 0.0;
     $this->reduction_amount_tax_excl = 0.0;
     if ($this->specificPrice) {
         switch ($this->specificPrice['reduction_type']) {
             case 'percentage':
                 $this->reduction_percent = (double) $this->specificPrice['reduction'] * 100;
                 break;
             case 'amount':
                 $price = Tools::convertPrice($this->specificPrice['reduction'], $order->id_currency);
                 $this->reduction_amount = (double) (!$this->specificPrice['id_currency'] ? $price : $this->specificPrice['reduction']);
                 $id_tax_rules = (int) Product::getIdTaxRulesGroupByIdProduct((int) $this->specificPrice['id_product']);
                 $tax_manager = TaxManagerFactory::getManager($this->vat_address, $id_tax_rules);
                 $this->tax_calculator = $tax_manager->getTaxCalculator();
                 $this->reduction_amount_tax_incl = $this->reduction_amount;
                 $this->reduction_amount_tax_excl = Tools::ps_round($this->tax_calculator->removeTaxes($this->reduction_amount_tax_incl), 2);
                 break;
         }
     }
 }
Example #7
0
 /**
  * Set specific price of the product
  * @param object $order
  */
 protected function setSpecificPrice($id_specific_price, $id_product, $id_currency)
 {
     $specificPrice = new AphSpecificPrice($id_specific_price);
     $reduction_amount = 0.0;
     $reduction_percent = 0.0;
     $reduction_amount_tax_incl = 0.0;
     $reduction_amount_tax_excl = 0.0;
     if ($specificPrice) {
         switch ($specificPrice['reduction_type']) {
             case 'percentage':
                 $reduction_percent = (double) $specificPrice['reduction'] * 100;
                 break;
             case 'amount':
                 $price = Tools::convertPrice($specificPrice['reduction'], $id_currency);
                 $reduction_amount = !$specificPrice['id_currency'] ? (double) $price : (double) $specificPrice['reduction'];
                 $id_tax_rules = (int) Product::getIdTaxRulesGroupByIdProduct((int) $specificPrice['id_product'], $context);
                 $tax_manager = TaxManagerFactory::getManager($vat_address, $id_tax_rules);
                 $tax_calculator = $tax_manager->getTaxCalculator();
                 if ($specificPrice['reduction_tax']) {
                     $reduction_amount_tax_incl = $reduction_amount;
                     $reduction_amount_tax_excl = Tools::ps_round($tax_calculator->removeTaxes($reduction_amount), _PS_PRICE_COMPUTE_PRECISION_);
                 } else {
                     $reduction_amount_tax_incl = Tools::ps_round($tax_calculator->addTaxes($reduction_amount), _PS_PRICE_COMPUTE_PRECISION_);
                     $reduction_amount_tax_excl = $reduction_amount;
                 }
                 break;
         }
     }
 }
Example #8
0
 /**
  * Set specific price of the product
  * @param object $order
  */
 protected function setSpecificPrice(Order $order, $product = null)
 {
     $this->reduction_amount = 0.0;
     $this->reduction_percent = 0.0;
     $this->reduction_amount_tax_incl = 0.0;
     $this->reduction_amount_tax_excl = 0.0;
     if ($this->specificPrice) {
         switch ($this->specificPrice['reduction_type']) {
             case 'percentage':
                 $this->reduction_percent = (double) $this->specificPrice['reduction'] * 100;
                 break;
             case 'amount':
                 $price = Tools::convertPrice($this->specificPrice['reduction'], $order->id_currency);
                 $this->reduction_amount = !$this->specificPrice['id_currency'] ? (double) $price : (double) $this->specificPrice['reduction'];
                 if ($product !== null) {
                     $this->setContext((int) $product['id_shop']);
                 }
                 $id_tax_rules = (int) Product::getIdTaxRulesGroupByIdProduct((int) $this->specificPrice['id_product'], $this->context);
                 $tax_manager = TaxManagerFactory::getManager($this->vat_address, $id_tax_rules);
                 $this->tax_calculator = $tax_manager->getTaxCalculator();
                 if ($this->reduction_tax) {
                     $this->reduction_amount_tax_incl = $this->reduction_amount;
                     $this->reduction_amount_tax_excl = Tools::ps_round($this->tax_calculator->removeTaxes($this->reduction_amount), _PS_PRICE_COMPUTE_PRECISION_);
                 } else {
                     $this->reduction_amount_tax_incl = Tools::ps_round($this->tax_calculator->addTaxes($this->reduction_amount), _PS_PRICE_COMPUTE_PRECISION_);
                     $this->reduction_amount_tax_excl = $this->reduction_amount;
                 }
                 break;
         }
     }
 }
Example #9
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];
 }
Example #10
0
	/**
	* 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];
	}
Example #11
0
    /**
     * 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'] : '&nbsp;') . '</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'] : '&nbsp;') . '</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);
        }
    }
Example #12
0
    /**
     * Return cart products
     *
     * @result array Products
     */
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`,
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        $sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`');
        // AND 'sp.`id_shop` = cp.`id_shop`
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity,
				IF(product_attribute_shop.wholesale_price > 0,  product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            $address = Address::initialize($address_id, true);
            $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context);
            $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, false, true, $cart_shop_context);
            switch (Configuration::get('PS_ROUND_TYPE')) {
                case Order::ROUND_TOTAL:
                case Order::ROUND_LINE:
                    $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    break;
                case Order::ROUND_ITEM:
                default:
                    $row['total'] = Tools::ps_round($row['price'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']), _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    break;
            }
            $row['price_wt'] = $tax_calculator->addTaxes($row['price']);
            $row['description_short'] = Tools::nl2br($row['description_short']);
            /**
             * ABU: correction bug
             * https://github.com/PrestaShop/PrestaShop/commit/bbc5591495b12021aa95421af1a0d27acd7a378e?diff=split
             */
            /*if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0)
            		{
            			$cache_id = 'Cart::getProducts_'.'-pai_id_image-'.(int)$row['id_product'].'-'.(int)$this->id_lang.'-'.(int)$row['id_shop'];
            			if (!Cache::isStored($cache_id))
            			{
            				$row2 = Db::getInstance()->getRow('
            					SELECT image_shop.`id_image` id_image, il.`legend`
            					FROM `'._DB_PREFIX_.'image` i
            					JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop='.(int)$row['id_shop'].')
            					LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$this->id_lang.')
            					WHERE i.`id_product` = '.(int)$row['id_product'].' AND image_shop.`cover` = 1'
            				);
            				Cache::store($cache_id, $row2);
            			}
            			$row2 = Cache::retrieve($cache_id);
            			if (!$row2)
            				$row2 = array('id_image' => false, 'legend' => false);
            			else
            				$row = array_merge($row, $row2);
            		}
            		else
            		{
            			$row['id_image'] = $row['pai_id_image'];
            			$row['legend'] = $row['pai_legend'];
            		}*/
            $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $row['id_product_attribute'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
            if (!Cache::isStored($cache_id)) {
                $flag = (int) $row['id_product_attribute'] && (int) $row['pai_id_image'];
                $row2 = Db::getInstance()->getRow('
					SELECT image_shop.`id_image` id_image, il.`legend`
					FROM `' . _DB_PREFIX_ . 'image` i
					INNER JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop
						ON (i.id_image = image_shop.id_image' . (!$flag ? ' AND image_shop.cover = 1' : '') . ' AND image_shop.id_shop = ' . (int) $row['id_shop'] . ')' . ($flag ? '
					INNER JOIN `' . _DB_PREFIX_ . 'product_attribute_image` pai
						ON (pai.`id_image` = i.`id_image` AND pai.`id_product_attribute` = ' . (int) $row['id_product_attribute'] . ')' : '') . '
					LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il
						ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
					WHERE i.`id_product` = ' . (int) $row['id_product'] . ($flag ? '
					ORDER BY i.`position` ASC' : ''));
                Cache::store($cache_id, $row2);
            }
            $row2 = Cache::retrieve($cache_id);
            if (!$row2) {
                $row2 = array('id_image' => false, 'legend' => false);
            }
            $row = array_merge($row, $row2);
            /**
             * /end bug correction
             */
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
Example #13
0
    public static function create(Order $order, $product_list, $shipping_cost = false, $amount = 0, $amount_choosen = false, $add_tax = true)
    {
        $currency = new Currency((int) $order->id_currency);
        $order_slip = new OrderSlip();
        $order_slip->id_customer = (int) $order->id_customer;
        $order_slip->id_order = (int) $order->id;
        $order_slip->conversion_rate = $currency->conversion_rate;
        if ($add_tax) {
            $add_or_remove = 'add';
            $inc_or_ex_1 = 'excl';
            $inc_or_ex_2 = 'incl';
        } else {
            $add_or_remove = 'remove';
            $inc_or_ex_1 = 'incl';
            $inc_or_ex_2 = 'excl';
        }
        $order_slip->{'total_shipping_tax_' . $inc_or_ex_1} = 0;
        $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = 0;
        $order_slip->partial = 0;
        if ($shipping_cost !== false) {
            $order_slip->shipping_cost = true;
            $carrier = new Carrier((int) $order->id_carrier);
            $address = Address::initialize($order->id_address_delivery, false);
            $tax_calculator = $carrier->getTaxCalculator($address);
            $order_slip->{'total_shipping_tax_' . $inc_or_ex_1} = $shipping_cost === null ? $order->{'total_shipping_tax_' . $inc_or_ex_1} : (double) $shipping_cost;
            if ($tax_calculator instanceof TaxCalculator) {
                $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($order_slip->{'total_shipping_tax_' . $inc_or_ex_1}), _PS_PRICE_COMPUTE_PRECISION_);
            } else {
                $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = $order_slip->{'total_shipping_tax_' . $inc_or_ex_1};
            }
        } else {
            $order_slip->shipping_cost = false;
        }
        $order_slip->amount = 0;
        $order_slip->{'total_products_tax_' . $inc_or_ex_1} = 0;
        $order_slip->{'total_products_tax_' . $inc_or_ex_2} = 0;
        foreach ($product_list as &$product) {
            $order_detail = new OrderDetail((int) $product['id_order_detail']);
            $price = (double) $product['unit_price'];
            $quantity = (int) $product['quantity'];
            $order_slip_resume = OrderSlip::getProductSlipResume((int) $order_detail->id);
            if ($quantity + $order_slip_resume['product_quantity'] > $order_detail->product_quantity) {
                $quantity = $order_detail->product_quantity - $order_slip_resume['product_quantity'];
            }
            if ($quantity == 0) {
                continue;
            }
            $order_detail->product_quantity_refunded += $quantity;
            $order_detail->save();
            $address = Address::initialize($order->id_address_invoice, false);
            $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $order_detail->product_id);
            $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
            $order_slip->{'total_products_tax_' . $inc_or_ex_1} += $price * $quantity;
            if (in_array(Configuration::get('PS_ROUND_TYPE'), array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
                if (!isset($total_products[$id_tax_rules_group])) {
                    $total_products[$id_tax_rules_group] = 0;
                } else {
                    if (!isset($total_products[$id_tax_rules_group . '_' . $id_address])) {
                        $total_products[$id_tax_rules_group . '_' . $id_address] = 0;
                    }
                }
            }
            $product_tax_incl_line = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price) * $quantity, _PS_PRICE_COMPUTE_PRECISION_);
            switch (Configuration::get('PS_ROUND_TYPE')) {
                case Order::ROUND_ITEM:
                    $product_tax_incl = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_) * $quantity;
                    $total_products[$id_tax_rules_group] += $product_tax_incl;
                    break;
                case Order::ROUND_LINE:
                    $product_tax_incl = $product_tax_incl_line;
                    $total_products[$id_tax_rules_group] += $product_tax_incl;
                    break;
                case Order::ROUND_TOTAL:
                    $product_tax_incl = $product_tax_incl_line;
                    $total_products[$id_tax_rules_group . '_' . $id_address] += $price * $quantity;
                    break;
            }
            $product['unit_price_tax_' . $inc_or_ex_1] = $price;
            $product['unit_price_tax_' . $inc_or_ex_2] = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_);
            $product['total_price_tax_' . $inc_or_ex_1] = Tools::ps_round($price * $quantity, _PS_PRICE_COMPUTE_PRECISION_);
            $product['total_price_tax_' . $inc_or_ex_2] = Tools::ps_round($product_tax_incl, _PS_PRICE_COMPUTE_PRECISION_);
            $product['product_id'] = $order_detail->product_id;
        }
        unset($product);
        foreach ($total_products as $key => $price) {
            if (Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
                $tmp = explode('_', $key);
                $address = Address::initialize((int) $tmp[1], true);
                $tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
                $order_slip->{'total_products_tax_' . $inc_or_ex_2} += Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_);
            } else {
                $order_slip->{'total_products_tax_' . $inc_or_ex_2} += $price;
            }
        }
        $order_slip->{'total_products_tax_' . $inc_or_ex_2} -= (double) $amount && !$amount_choosen ? (double) $amount : 0;
        $order_slip->amount = $amount_choosen ? (double) $amount : $order_slip->{'total_products_tax_' . $inc_or_ex_1};
        $order_slip->shipping_cost_amount = $order_slip->{'total_shipping_tax_' . $inc_or_ex_1};
        if ((double) $amount && !$amount_choosen) {
            $order_slip->order_slip_type = 1;
        }
        if ((double) $amount && $amount_choosen || $order_slip->shipping_cost_amount > 0) {
            $order_slip->order_slip_type = 2;
        }
        if (!$order_slip->add()) {
            return false;
        }
        $res = true;
        $param = array();
        $param['MerchantOrderID'] = $order->id;
        $prefix = _DB_PREFIX_;
        $i = 0;
        foreach ($product_list as $product) {
            $res &= $order_slip->addProductOrderSlip($product);
            $order_item_detail = new OrderDetail((int) $product['id_order_detail']);
            $sql = 'UPDATE `' . $prefix . 'stock_available` set
					`quantity` = `quantity` + ' . $product['quantity'] . '
					where `id_product` = ' . $product['product_id'] . ' and
					`id_product_attribute` = 0
					';
            //Db::getInstance()->Execute($sql);
            if ($order_item_detail->product_attribute_id > 0) {
                $sql = 'UPDATE `' . $prefix . 'stock_available` set
						`quantity` = `quantity` + ' . $product['quantity'] . '
						where `id_product` = ' . $product['product_id'] . ' and
						`id_product_attribute` = ' . $order_item_detail->product_attribute_id . '
						';
                //Db::getInstance()->Execute($sql);
            }
            $date = date('Y-m-d');
            $sql = 'UPDATE `' . $prefix . 'product_sale` set
					`quantity` = `quantity` - ' . $product['quantity'] . ',
					`sale_nbr` = `sale_nbr` - ' . $product['quantity'] . ',
					`date_upd` = ' . $date . '
					where `id_product` = ' . $product['product_id'] . '
					';
            //Db::getInstance()->Execute($sql);
            $param['items'][$i]['MerchantOrderItemID'] = $product['product_id'];
            $param['items'][$i]['Principal'] = $product['total_price_tax_incl'];
            $param['items'][$i]['Shipping'] = 0;
            $param['items'][$i]['Tax'] = 0;
            $param['items'][$i]['ShippingTax'] = 0;
            $param['items'][$i]['quantity'] = $product['quantity'];
            $i++;
        }
        $refund = new Pwapresta();
        $refund->pwa_refund_feed($param);
        return $res;
    }
Example #14
0
 /**
  * @return string
  */
 public function prepareTaxClass()
 {
     $taxRulesGroups = TaxRulesGroupCore::getTaxRulesGroups(true);
     $idTaxRulesGroup = (int) Product::getIdTaxRulesGroupByIdProduct($this->currentProduct->id, null);
     foreach ($taxRulesGroups as $taxRulesGroup) {
         if ($taxRulesGroup['id_tax_rules_group'] == $idTaxRulesGroup) {
             $tax = ShopgateSettings::getTaxItemByTaxRuleGroupId($idTaxRulesGroup);
             $taxClassName = '';
             if (is_array($tax->name) && !empty($tax->name[$this->getPlugin()->getLanguageId()])) {
                 $taxClassName = $tax->name[$this->getPlugin()->getLanguageId()];
             } else {
                 if (is_array($tax->name)) {
                     // fallback: just in case for older Prestashop versions
                     $taxClassName = reset($tax->name);
                 }
             }
             return $taxClassName;
         }
     }
     return '';
 }
Example #15
0
 public static function create(Order $order, $product_list, $shipping_cost = false, $amount = 0, $amount_choosen = false, $add_tax = true)
 {
     $currency = new Currency((int) $order->id_currency);
     $order_slip = new OrderSlip();
     $order_slip->id_customer = (int) $order->id_customer;
     $order_slip->id_order = (int) $order->id;
     $order_slip->conversion_rate = $currency->conversion_rate;
     if ($add_tax) {
         $add_or_remove = 'add';
         $inc_or_ex_1 = 'excl';
         $inc_or_ex_2 = 'incl';
     } else {
         $add_or_remove = 'remove';
         $inc_or_ex_1 = 'incl';
         $inc_or_ex_2 = 'excl';
     }
     $order_slip->{'total_shipping_tax_' . $inc_or_ex_1} = 0;
     $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = 0;
     $order_slip->partial = 0;
     if ($shipping_cost !== false) {
         $order_slip->shipping_cost = true;
         $carrier = new Carrier((int) $order->id_carrier);
         $address = Address::initialize($order->id_address_delivery, false);
         $tax_calculator = $carrier->getTaxCalculator($address);
         $order_slip->{'total_shipping_tax_' . $inc_or_ex_1} = $shipping_cost === null ? $order->{'total_shipping_tax_' . $inc_or_ex_1} : (double) $shipping_cost;
         if ($tax_calculator instanceof TaxCalculator) {
             $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($order_slip->{'total_shipping_tax_' . $inc_or_ex_1}), _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             $order_slip->{'total_shipping_tax_' . $inc_or_ex_2} = $order_slip->{'total_shipping_tax_' . $inc_or_ex_1};
         }
     } else {
         $order_slip->shipping_cost = false;
     }
     $order_slip->amount = 0;
     $order_slip->{'total_products_tax_' . $inc_or_ex_1} = 0;
     $order_slip->{'total_products_tax_' . $inc_or_ex_2} = 0;
     foreach ($product_list as &$product) {
         $order_detail = new OrderDetail((int) $product['id_order_detail']);
         $price = (double) $product['unit_price'];
         $quantity = (int) $product['quantity'];
         $order_slip_resume = OrderSlip::getProductSlipResume((int) $order_detail->id);
         if ($quantity + $order_slip_resume['product_quantity'] > $order_detail->product_quantity) {
             $quantity = $order_detail->product_quantity - $order_slip_resume['product_quantity'];
         }
         if ($quantity == 0) {
             continue;
         }
         if (!Tools::isSubmit('cancelProduct') && $order->hasBeenPaid()) {
             $order_detail->product_quantity_refunded += $quantity;
         }
         $order_detail->save();
         $address = Address::initialize($order->id_address_invoice, false);
         $id_address = (int) $address->id;
         $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $order_detail->product_id);
         $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
         $order_slip->{'total_products_tax_' . $inc_or_ex_1} += $price * $quantity;
         if (in_array(Configuration::get('PS_ROUND_TYPE'), array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($total_products[$id_tax_rules_group])) {
                 $total_products[$id_tax_rules_group] = 0;
             }
         } else {
             if (!isset($total_products[$id_tax_rules_group . '_' . $id_address])) {
                 $total_products[$id_tax_rules_group . '_' . $id_address] = 0;
             }
         }
         $product_tax_incl_line = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price) * $quantity, _PS_PRICE_COMPUTE_PRECISION_);
         switch (Configuration::get('PS_ROUND_TYPE')) {
             case Order::ROUND_ITEM:
                 $product_tax_incl = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_) * $quantity;
                 $total_products[$id_tax_rules_group] += $product_tax_incl;
                 break;
             case Order::ROUND_LINE:
                 $product_tax_incl = $product_tax_incl_line;
                 $total_products[$id_tax_rules_group] += $product_tax_incl;
                 break;
             case Order::ROUND_TOTAL:
                 $product_tax_incl = $product_tax_incl_line;
                 $total_products[$id_tax_rules_group . '_' . $id_address] += $price * $quantity;
                 break;
         }
         $product['unit_price_tax_' . $inc_or_ex_1] = $price;
         $product['unit_price_tax_' . $inc_or_ex_2] = Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_);
         $product['total_price_tax_' . $inc_or_ex_1] = Tools::ps_round($price * $quantity, _PS_PRICE_COMPUTE_PRECISION_);
         $product['total_price_tax_' . $inc_or_ex_2] = Tools::ps_round($product_tax_incl, _PS_PRICE_COMPUTE_PRECISION_);
     }
     unset($product);
     foreach ($total_products as $key => $price) {
         if (Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
             $tmp = explode('_', $key);
             $address = Address::initialize((int) $tmp[1], true);
             $tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
             $order_slip->{'total_products_tax_' . $inc_or_ex_2} += Tools::ps_round($tax_calculator->{$add_or_remove . 'Taxes'}($price), _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             $order_slip->{'total_products_tax_' . $inc_or_ex_2} += $price;
         }
     }
     $order_slip->{'total_products_tax_' . $inc_or_ex_2} -= (double) $amount && !$amount_choosen ? (double) $amount : 0;
     $order_slip->amount = $amount_choosen ? (double) $amount : $order_slip->{'total_products_tax_' . $inc_or_ex_1};
     $order_slip->shipping_cost_amount = $order_slip->{'total_shipping_tax_' . $inc_or_ex_1};
     if ((double) $amount && !$amount_choosen) {
         $order_slip->order_slip_type = 1;
     }
     if ((double) $amount && $amount_choosen || $order_slip->shipping_cost_amount > 0) {
         $order_slip->order_slip_type = 2;
     }
     if (!$order_slip->add()) {
         return false;
     }
     $res = true;
     foreach ($product_list as $product) {
         $res &= $order_slip->addProductOrderSlip($product);
     }
     return $res;
 }
Example #16
0
 /**
  * Return the product tax rate using the tax rules system
  *
  * @param integer $id_product
  * @param integer $id_country
  * @return Tax
  */
 public static function getProductTaxRateViaRules($id_product, $id_country, $id_state, $id_county)
 {
     if (!isset(self::$_product_tax_via_rules[$id_product . '-' . $id_country . '-' . $id_state . '-' . $id_county])) {
         self::$_product_tax_via_rules[$id_product . '-' . $id_country . '-' . $id_county] = TaxRulesGroup::getTaxesRate((int) Product::getIdTaxRulesGroupByIdProduct((int) $id_product), (int) $id_country, (int) $id_state, (int) $id_county);
     }
     return self::$_product_tax_via_rules[$id_product . '-' . $id_country . '-' . $id_county];
 }
Example #17
0
 /**
  * This function returns the total cart amount
  *
  * Possible values for $type:
  * Cart::ONLY_PRODUCTS
  * Cart::ONLY_DISCOUNTS
  * Cart::BOTH
  * Cart::BOTH_WITHOUT_SHIPPING
  * Cart::ONLY_SHIPPING
  * Cart::ONLY_WRAPPING
  * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  *
  * @param bool $withTaxes With or without taxes
  * @param int $type Total type
  * @param bool $use_cache Allow using cache of the method CartRule::getContextualValue
  * @return float Order total
  */
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     // Dependencies
     $address_factory = Adapter_ServiceLocator::get('Adapter_AddressFactory');
     $price_calculator = Adapter_ServiceLocator::get('Adapter_ProductPriceCalculator');
     $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface');
     $ps_tax_address_type = $configuration->get('PS_TAX_ADDRESS_TYPE');
     $ps_use_ecotax = $configuration->get('PS_USE_ECOTAX');
     $ps_round_type = $configuration->get('PS_ROUND_TYPE');
     $ps_ecotax_tax_rules_group_id = $configuration->get('PS_ECOTAX_TAX_RULES_GROUP_ID');
     $compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_');
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
         if (is_null($products) && is_null($id_carrier)) {
             $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
         } else {
             $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool) $with_taxes, null, $products);
         }
     } else {
         $shipping_fees = 0;
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     $products_total = array();
     $ecotax_total = 0;
     foreach ($products as $product) {
         // products refer to the cart details
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if ($ps_tax_address_type == 'id_address_invoice') {
             $id_address = (int) $this->id_address_invoice;
         } else {
             $id_address = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!$address_factory->addressExists($id_address)) {
             $id_address = null;
         }
         // The $null variable below is not used,
         // but it is necessary to pass it to getProductPrice because
         // it expects a reference.
         $null = null;
         $price = $price_calculator->getProductPrice((int) $product['id_product'], $with_taxes, (int) $product['id_product_attribute'], 6, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $id_address, $null, $ps_use_ecotax, true, $virtual_context);
         if ($product['price_more']) {
             $price += $product['price_more'];
         }
         $address = $address_factory->findOrCreate($id_address, true);
         if ($with_taxes) {
             $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
             $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
         } else {
             $id_tax_rules_group = 0;
         }
         if (in_array($ps_round_type, array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($products_total[$id_tax_rules_group])) {
                 $products_total[$id_tax_rules_group] = 0;
             }
         } elseif (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
             $products_total[$id_tax_rules_group . '_' . $id_address] = 0;
         }
         switch ($ps_round_type) {
             case Order::ROUND_TOTAL:
                 $products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
                 break;
             case Order::ROUND_LINE:
                 $product_price = $price * $product['cart_quantity'];
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision);
                 break;
             case Order::ROUND_ITEM:
             default:
                 $product_price = $price;
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision) * (int) $product['cart_quantity'];
                 break;
         }
     }
     foreach ($products_total as $key => $price) {
         $order_total += $price;
     }
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     // With PS_ATCP_SHIPWRAP on the gift wrapping cost computation calls getOrderTotal with $type === Cart::ONLY_PRODUCTS, so the flag below prevents an infinite recursion.
     $include_gift_wrapping = !$configuration->get('PS_ATCP_SHIPWRAP') || $type !== Cart::ONLY_PRODUCTS;
     if ($this->gift && $include_gift_wrapping) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), $compute_precision), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     $order_shipping_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         $flag = false;
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping && !$flag) {
                 $order_shipping_discount = (double) Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), $compute_precision);
                 $flag = true;
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), $compute_precision);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), (double) $order_total_products) + (double) $order_shipping_discount;
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, $compute_precision);
 }
Example #18
0
 /**
  * Main
  *
  * @param object $order Order
  * @param string $mode Download or display (optional)
  */
 public static function invoice($order, $mode = 'D', $multiple = false, &$pdf = null, $slip = false, $delivery = false)
 {
     global $cookie;
     if (!Validate::isLoadedObject($order) or !$cookie->id_employee and (!OrderState::invoiceAvailable($order->getCurrentState()) and !$order->invoice_number)) {
         die('Invalid order or invalid order state');
     }
     self::$order = $order;
     self::$orderSlip = $slip;
     self::$delivery = $delivery;
     self::$_iso = strtoupper(Language::getIsoById((int) self::$order->id_lang));
     if (!isset(self::$_pdfparams[self::$_iso])) {
         self::$_iso = strtoupper(Language::getIsoById((int) _PS_LANG_DEFAULT_));
     }
     if ((self::$_priceDisplayMethod = $order->getTaxCalculationMethod()) === false) {
         die(self::l('No price display method defined for the customer group'));
     }
     if (!$multiple) {
         $pdf = new PDF('P', 'mm', 'A4');
     }
     $pdf->SetAutoPageBreak(true, 35);
     $pdf->StartPageGroup();
     self::$currency = Currency::getCurrencyInstance((int) self::$order->id_currency);
     $pdf->AliasNbPages();
     $pdf->AddPage();
     $width = 100;
     $pdf->SetX(10);
     $pdf->SetY(25);
     $pdf->SetFont(self::fontname(), '', 12);
     $pdf->Cell($width, 10, self::l('Delivery'), 0, 'L');
     $pdf->Cell($width, 10, self::l('Invoicing'), 0, 'L');
     $pdf->Ln(5);
     $pdf->SetFont(self::fontname(), '', 9);
     $addressType = array('delivery' => array(), 'invoice' => array());
     $patternRules = array('optional' => array('address2', 'company'), 'avoid' => array('State:iso_code'));
     $addressType = self::generateHeaderAddresses($pdf, $order, $addressType, $patternRules, $width);
     if (Configuration::get('VATNUMBER_MANAGEMENT') and !empty($addressType['invoice']['addressObject']->vat_number)) {
         $vat_delivery = '';
         if ($addressType['invoice']['addressObject']->id != $addressType['delivery']['addressObject']->id) {
             $vat_delivery = $addressType['delivery']['addressObject']->vat_number;
         }
         $pdf->Cell($width, 10, Tools::iconv('utf-8', self::encoding(), $vat_delivery), 0, 'L');
         $pdf->Cell($width, 10, Tools::iconv('utf-8', self::encoding(), $addressType['invoice']['addressObject']->vat_number), 0, 'L');
         $pdf->Ln(5);
     }
     if ($addressType['invoice']['addressObject']->dni != null) {
         $pdf->Cell($width, 10, self::l('Tax ID number:') . ' ' . Tools::iconv('utf-8', self::encoding(), $addressType['invoice']['addressObject']->dni), 0, 'L');
     }
     /*
      * display order information
      */
     $carrier = new Carrier(self::$order->id_carrier);
     if ($carrier->name == '0') {
         $carrier->name = Configuration::get('PS_SHOP_NAME');
     }
     $history = self::$order->getHistory(self::$order->id_lang);
     foreach ($history as $h) {
         if ($h['id_order_state'] == Configuration::get('PS_OS_SHIPPING')) {
             $shipping_date = $h['date_add'];
         }
     }
     $pdf->Ln(12);
     $pdf->SetFillColor(240, 240, 240);
     $pdf->SetTextColor(0, 0, 0);
     $pdf->SetFont(self::fontname(), '', 9);
     if (self::$orderSlip) {
         $pdf->Cell(0, 6, self::l('SLIP #') . ' ' . sprintf('%06d', self::$orderSlip->id) . ' ' . self::l('from') . ' ' . Tools::displayDate(self::$orderSlip->date_upd, self::$order->id_lang), 1, 2, 'L', 1);
     } elseif (self::$delivery) {
         $pdf->Cell(0, 6, self::l('DELIVERY SLIP #') . Tools::iconv('utf-8', self::encoding(), Configuration::get('PS_DELIVERY_PREFIX', (int) $cookie->id_lang)) . sprintf('%06d', self::$delivery) . ' ' . self::l('from') . ' ' . Tools::displayDate(self::$order->delivery_date, self::$order->id_lang), 1, 2, 'L', 1);
     } elseif ((int) self::$order->invoice_date) {
         $pdf->Cell(0, 6, self::l('INVOICE #') . ' ' . Tools::iconv('utf-8', self::encoding(), Configuration::get('PS_INVOICE_PREFIX', (int) $cookie->id_lang)) . sprintf('%06d', self::$order->invoice_number) . ' ' . self::l('from') . ' ' . Tools::displayDate(self::$order->invoice_date, self::$order->id_lang), 1, 2, 'L', 1);
     } else {
         $pdf->Cell(0, 6, self::l('Invoice draft'), 1, 2, 'L', 1);
     }
     $pdf->Cell(55, 6, self::l('Order #') . ' ' . sprintf('%06d', self::$order->id), 'L', 0);
     $pdf->Cell(70, 6, self::l('Carrier:') . ($order->gift ? ' ' . Tools::iconv('utf-8', self::encoding(), $carrier->name) : ''), 'L');
     $pdf->Cell(0, 6, self::l('Payment method:'), 'LR');
     $pdf->Ln(5);
     $pdf->Cell(55, 6, isset($shipping_date) ? self::l('Shipping date:') . ' ' . Tools::displayDate($shipping_date, self::$order->id_lang) : ' ', 'LB', 0);
     $pdf->Cell(70, 6, $order->gift ? self::l('Gift-wrapped order') : Tools::iconv('utf-8', self::encoding(), $carrier->name), 'LRB');
     $pdf->Cell(0, 6, Tools::iconv('utf-8', self::encoding(), $order->payment), 'LRB');
     $pdf->Ln(15);
     $pdf->ProdTab(self::$delivery ? true : '');
     if (!self::$delivery) {
         $priceBreakDown = array();
         $pdf->priceBreakDownCalculation($priceBreakDown);
     }
     /* Canada */
     $taxable_address = new Address((int) self::$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     if (!self::$delivery && strtoupper(Country::getIsoById((int) $taxable_address->id_country)) == 'CA') {
         $pdf->Ln(15);
         if (self::$orderSlip) {
             $id_country = (int) $taxable_address->id_country;
             $id_state = (int) $taxable_address->id_state;
             $id_county = 0;
             // fetch taxes for product
             $products = self::$orderSlip->getOrdersSlipProducts(self::$orderSlip->id, self::$order);
             foreach ($products as $product) {
                 $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['product_id']), $id_country, $id_state, $id_county);
                 foreach ($allTaxes as $tax) {
                     if (!isset($store_all_taxes[$tax->id])) {
                         $store_all_taxes[$tax->id] = array();
                         $store_all_taxes[$tax->id]['amount'] = 0;
                     }
                     $store_all_taxes[$tax->id]['name'] = $tax->name[(int) self::$order->id_lang];
                     $store_all_taxes[$tax->id]['rate'] = $tax->rate;
                     $unit_tax_amount = $product['product_price'] * ($tax->rate * 0.01);
                     $store_all_taxes[$tax->id]['amount'] += $unit_tax_amount * $product['product_quantity'];
                 }
             }
             if (self::$orderSlip->shipping_cost) {
                 // fetch taxes for carrier
                 $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) self::$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) self::$order->id_lang];
                     $store_all_taxes[$tax->id]['rate'] = $tax->rate;
                     if (!$nTax++) {
                         $store_all_taxes[$tax->id]['amount'] += $priceBreakDown['shippingCostWithoutTax'] * (1 + $tax->rate * 0.01) - $priceBreakDown['shippingCostWithoutTax'];
                     } else {
                         $store_all_taxes[$tax->id]['amount'] += self::$order->total_shipping - self::$order->total_shipping / (1 + $tax->rate * 0.01);
                     }
                 }
             }
             foreach ($store_all_taxes as $tax) {
                 $pdf->Cell(0, 6, utf8_decode($tax['name']) . ' (' . number_format($tax['rate'], 2, '.', '') . '%)      ' . self::convertSign(Tools::displayPrice($tax['amount'], self::$currency, true)), 0, 0, 'R');
                 $pdf->Ln(5);
             }
         } else {
             $taxes = Db::getInstance()->ExecuteS('SELECT * FROM ' . _DB_PREFIX_ . 'order_tax WHERE id_order = ' . (int) self::$order->id);
             foreach ($taxes as $tax) {
                 $pdf->Cell(0, 6, utf8_decode($tax['tax_name']) . ' (' . number_format($tax['tax_rate'], 2, '.', '') . '%)      ' . self::convertSign(Tools::displayPrice($tax['amount'], self::$currency, true)), 0, 0, 'R');
                 $pdf->Ln(5);
             }
         }
     }
     /* End */
     /* Exit if delivery */
     if (!self::$delivery) {
         if (!self::$orderSlip) {
             $pdf->DiscTab();
         }
         if (!self::$orderSlip or self::$orderSlip and self::$orderSlip->shipping_cost) {
             $priceBreakDown['totalWithoutTax'] += Tools::ps_round($priceBreakDown['shippingCostWithoutTax'], 2) + Tools::ps_round($priceBreakDown['wrappingCostWithoutTax'], 2);
             $priceBreakDown['totalWithTax'] += self::$order->total_shipping + self::$order->total_wrapping;
         }
         if (!self::$orderSlip) {
             $taxDiscount = self::$order->getTaxesAverageUsed();
             if ($taxDiscount != 0) {
                 $priceBreakDown['totalWithoutTax'] -= Tools::ps_round(self::$order->total_discounts / (1 + self::$order->getTaxesAverageUsed() * 0.01), 2);
             } else {
                 $priceBreakDown['totalWithoutTax'] -= self::$order->total_discounts;
             }
             // The discount is already applied in Tax Incl mode
             if (self::$_priceDisplayMethod == PS_TAX_EXC) {
                 $priceBreakDown['totalWithTax'] -= self::$order->total_discounts;
             }
         }
         /*
          * Display price summation
          */
         if (Configuration::get('PS_TAX') or $order->total_products_wt != $order->total_products) {
             $pdf->Ln(5);
             $pdf->SetFont(self::fontname(), 'B', 8);
             $width = 165;
             $pdf->Cell($width, 0, self::l('Total products (tax excl.)') . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice($priceBreakDown['totalProductsWithoutTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
             $pdf->SetFont(self::fontname(), 'B', 8);
             $width = 165;
             $pdf->Cell($width, 0, self::l('Total products (tax incl.)') . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice($priceBreakDown['totalProductsWithTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
         } else {
             $pdf->Ln(5);
             $pdf->SetFont(self::fontname(), 'B', 8);
             $width = 165;
             $pdf->Cell($width, 0, self::l('Total products ') . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice($priceBreakDown['totalProductsWithoutTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
         }
         if (!self::$orderSlip and self::$order->total_discounts != '0.00') {
             $pdf->Cell($width, 0, self::l('Total discounts (tax incl.)') . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (!self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(self::$order->total_discounts, self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
         }
         if (isset(self::$order->total_wrapping) and (double) self::$order->total_wrapping > 0) {
             $pdf->Cell($width, 0, self::l('Total gift-wrapping') . ' : ', 0, 0, 'R');
             if (self::$_priceDisplayMethod == PS_TAX_EXC) {
                 $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice($priceBreakDown['wrappingCostWithoutTax'], self::$currency, true)), 0, 0, 'R');
             } else {
                 $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(self::$order->total_wrapping, self::$currency, true)), 0, 0, 'R');
             }
             $pdf->Ln(4);
         }
         if (self::$order->total_shipping != '0.00' and (!self::$orderSlip or self::$orderSlip and self::$orderSlip->shipping_cost)) {
             if (self::$_priceDisplayMethod == PS_TAX_EXC) {
                 $pdf->Cell($width, 0, self::l('Total shipping (tax excl.)') . ' : ', 0, 0, 'R');
                 $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(Tools::ps_round($priceBreakDown['shippingCostWithoutTax'], 2), self::$currency, true)), 0, 0, 'R');
             } else {
                 $pdf->Cell($width, 0, self::l('Total shipping (tax incl.)') . ' : ', 0, 0, 'R');
                 $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(self::$order->total_shipping, self::$currency, true)), 0, 0, 'R');
             }
             $pdf->Ln(4);
         }
         if (Configuration::get('PS_TAX') or $order->total_products_wt != $order->total_products) {
             $pdf->Cell($width, 0, self::l('Total') . ' ' . (self::$_priceDisplayMethod == PS_TAX_EXC ? self::l(' (tax incl.)') : self::l(' (tax excl.)')) . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(self::$_priceDisplayMethod == PS_TAX_EXC ? $priceBreakDown['totalWithTax'] : $priceBreakDown['totalWithoutTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
             $pdf->Cell($width, 0, self::l('Total') . ' ' . (self::$_priceDisplayMethod == PS_TAX_EXC ? self::l(' (tax excl.)') : self::l(' (tax incl.)')) . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice(self::$_priceDisplayMethod == PS_TAX_EXC ? $priceBreakDown['totalWithoutTax'] : $priceBreakDown['totalWithTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
         } else {
             $pdf->Cell($width, 0, self::l('Total') . ' : ', 0, 0, 'R');
             $pdf->Cell(0, 0, (self::$orderSlip ? '-' : '') . self::convertSign(Tools::displayPrice($priceBreakDown['totalWithoutTax'], self::$currency, true)), 0, 0, 'R');
             $pdf->Ln(4);
         }
         $pdf->TaxTab($priceBreakDown);
     }
     Hook::PDFInvoice($pdf, self::$order->id);
     if (!$multiple) {
         return $pdf->Output(sprintf('%06d', self::$order->id) . '.pdf', $mode);
     }
 }
Example #19
0
 public function getTaxDetails($products = false)
 {
     if (!is_array($products) || !count($products)) {
         $products = $this->getProducts();
     }
     $context = Context::getContext();
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
         $address = Address::initialize((int) $this->id_address_invoice);
     } else {
         $address = Address::initialize((int) $this->id_address_delivery);
     }
     if (!count($products)) {
         return false;
     }
     $prepared_taxes = array();
     $total_products_price = 0;
     foreach ($products as $product) {
         $id_tax_rules = (int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $context);
         $tax_manager = TaxManagerFactory::getManager($address, $id_tax_rules);
         $tax_calculator = $tax_manager->getTaxCalculator();
         $product_taxes = $tax_calculator->getTaxData($product['price']);
         $total_products_price += (double) $product['total_wt'];
         foreach ($product_taxes as $tax_id => $tax_data) {
             if (!array_key_exists($tax_id, $prepared_taxes)) {
                 $prepared_taxes[$tax_id] = $tax_data + array('total' => (double) $product['total_wt'] - (double) $product['total'], 'total_net' => (double) $product['total'], 'total_vat' => (double) $product['total_wt'], 'percentage' => 0);
             } else {
                 $prepared_taxes[$tax_id]['total'] += (double) $product['total_wt'] - (double) $product['total'];
                 $prepared_taxes[$tax_id]['total_net'] += (double) $product['total'];
                 $prepared_taxes[$tax_id]['total_vat'] += (double) $product['total_wt'];
             }
         }
     }
     foreach ($prepared_taxes as &$tax) {
         if ($total_products_price > 0 && $tax['total_vat'] > 0) {
             $tax['percentage'] = 100 / ($total_products_price / $tax['total_vat']);
         }
     }
     return count($prepared_taxes) ? $prepared_taxes : false;
 }
Example #20
0
 public static function getTaxesInformations($row, JeproshopContext $context = null)
 {
     static $address = null;
     if ($context === null) {
         $context = Context::getContext();
     }
     if ($address === null) {
         $address = new JeproshopAddressModelAddress();
     }
     $address->country_id = (int) $context->country->country_id;
     $address->state_id = 0;
     $address->postcode = 0;
     $tax_manager = JeproshopTaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $row->product_id, $context));
     $row->rate = $tax_manager->getTaxCalculator()->getTotalRate();
     $row->tax_name = $tax_manager->getTaxCalculator()->getTaxesName();
     return $row;
 }