/**
  * Returns the carrier tax rate
  *
  * @param id_address
  * @return float $tax_rate
  */
 public static function getCarrierTaxRate($id_carrier, $id_address = null)
 {
     $address = Address::initialize($id_address);
     $id_tax_rules = (int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $id_carrier);
     $tax_manager = TaxManagerFactory::getManager($address, $id_tax_rules);
     $tax_calculator = $tax_manager->getTaxCalculator();
     return $tax_calculator->getTotalRate();
 }
Exemple #2
0
 /**
  * Get TaxRulesGroup ID for this Carrier
  *
  * @param Context|null $context Context
  *
  * @return false|null|string TaxrulesGroup ID
  *                           false if not found
  */
 public function getIdTaxRulesGroup(Context $context = null)
 {
     return Carrier::getIdTaxRulesGroupByIdCarrier((int) $this->id, $context);
 }
 public function getStepThreeFieldsValues($carrier)
 {
     $id_tax_rules_group = is_object($this->object) && !$this->object->id ? Carrier::getIdTaxRulesGroupMostUsed() : Carrier::getIdTaxRulesGroupByIdCarrier($this->object->id);
     $shipping_handling = is_object($this->object) && !$this->object->id ? 0 : $this->getFieldValue($carrier, 'shipping_handling');
     return array('is_free' => $this->getFieldValue($carrier, 'is_free'), 'id_tax_rules_group' => (int) $id_tax_rules_group, 'shipping_handling' => $shipping_handling, 'shipping_method' => $this->getFieldValue($carrier, 'shipping_method'), 'range_behavior' => $this->getFieldValue($carrier, 'range_behavior'), 'zones' => $this->getFieldValue($carrier, 'zones'));
 }
Exemple #4
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);
     }
 }
Exemple #5
0
 public static function getCarrierTaxRate($id_carrier, $id_address = null)
 {
     global $cookie, $defaultCountry;
     $id_country = (int) Country::getDefaultCountryId();
     if ($id_country == _PS_COUNTRY_DEFAULT_ && isset($cookie->id_country) && $cookie->id_country != (int) _PS_COUNTRY_DEFAULT_) {
         $country = new Country((int) $cookie->id_country, $cookie->id_lang);
         if (ValidaTe::isLoadedObject($country) && $country->active) {
             $id_country = (int) $country->id;
             $defaultCountry = $country;
         }
     }
     $id_state = 0;
     $id_county = 0;
     if (!empty($id_address)) {
         $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']);
         }
         if (!empty($address_infos['vat_number']) && $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) {
             return 0;
         }
     }
     return TaxRulesGroup::getTaxesRate((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $id_carrier), (int) $id_country, (int) $id_state, (int) $id_county);
 }
    /**
     * 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);
        }
    }
Exemple #7
0
 public static function getCarrierTaxRate($id_carrier, $id_address = NULL)
 {
     $id_country = (int) Country::getDefaultCountryId();
     $id_state = 0;
     $id_county = 0;
     if (!empty($id_address)) {
         $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']);
         }
         if (!empty($address_infos['vat_number']) and $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') and Configuration::get('VATNUMBER_MANAGEMENT')) {
             return 0;
         }
     }
     return TaxRulesGroup::getTaxesRate((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $id_carrier), (int) $id_country, (int) $id_state, (int) $id_county);
 }