public function generateFlux() { if (Tools::getValue('token') == '' || Tools::getValue('token') != Configuration::get('SHOPPING_FLUX_TOKEN')) { die('Invalid Token'); } $titles = array(0 => 'id_produit', 1 => 'nom_produit', 2 => 'url_produit', 3 => 'url_image', 4 => 'description', 5 => 'description_courte', 6 => 'prix', 7 => 'prix_barre', 8 => 'frais_de_port', 9 => 'delaiLiv', 10 => 'marque', 11 => 'rayon', 12 => 'stock', 13 => 'qte_stock', 14 => 'EAN', 15 => 'poids', 16 => 'ecotaxe', 17 => 'TVA', 18 => 'Reference constructeur', 19 => 'Reference fournisseur'); echo implode("|", $titles) . "\r\n"; //For Shipping $configuration = Configuration::getMultiple(array('PS_TAX_ADDRESS_TYPE', 'PS_CARRIER_DEFAULT', 'PS_COUNTRY_DEFAULT', 'PS_LANG_DEFAULT', 'PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT')); $products = Product::getSimpleProducts($configuration['PS_LANG_DEFAULT']); $defaultCountry = new Country($configuration['PS_COUNTRY_DEFAULT'], Configuration::get('PS_LANG_DEFAULT')); $id_zone = (int) $defaultCountry->id_zone; $carrier = new Carrier((int) $configuration['PS_CARRIER_DEFAULT']); $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{$configuration['PS_TAX_ADDRESS_TYPE']}); foreach ($products as $key => $produit) { $product = new Product((int) $produit['id_product'], true, $configuration['PS_LANG_DEFAULT']); //For links $link = new Link(); //For images $cover = $product->getCover($product->id); $ids = $product->id . '-' . $cover['id_image']; //For shipping if ($product->getPrice(true, NULL, 2, NULL, false, true, 1) >= (double) $configuration['PS_SHIPPING_FREE_PRICE'] and (double) $configuration['PS_SHIPPING_FREE_PRICE'] > 0) { $shipping = 0; } elseif (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $product->weight >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] and (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) { $shipping = 0; } else { if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) { $shipping = (double) $configuration['PS_SHIPPING_HANDLING']; } if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping += $carrier->getDeliveryPriceByWeight($product->weight, $id_zone); } else { $shipping += $carrier->getDeliveryPriceByPrice($product->getPrice(true, NULL, 2, NULL, false, true, 1), $id_zone); } $shipping *= 1 + $carrierTax / 100; $shipping = (double) Tools::ps_round((double) $shipping, 2); } $data = array(); $data[0] = $product->id; $data[1] = $product->name; $data[2] = $link->getProductLink($product); $data[3] = $link->getImageLink($product->link_rewrite, $ids, 'large'); $data[4] = $product->description; $data[5] = $product->description_short; $data[6] = $product->getPrice(true, NULL, 2, NULL, false, true, 1); $data[7] = $product->getPrice(true, NULL, 2, NULL, false, false, 1); $data[8] = $shipping; $data[9] = $carrier->delay[2]; $data[10] = $product->manufacturer_name; $data[11] = $product->category; $data[12] = $product->quantity > 0 ? 'oui' : 'non'; $data[13] = $product->quantity; $data[14] = $product->ean13; $data[15] = $product->weight; $data[16] = $product->ecotax; $data[17] = $product->tax_rate; $data[18] = $product->reference; $data[19] = $product->supplier_reference; foreach ($data as $key => $value) { $data[$key] = $this->clean($value); } echo implode("|", $data) . "\r\n"; } }
public function getOrderShippingCostPerSellerCarrier($id_seller, $use_tax, $id_zone, $id_carrier, $carrier_amount, $carrier_weight) { $shipping_cost = 0; $carrier = new Carrier($id_carrier, $this->id_lang); if ($carrier->is_free == 1) { return 0; } if ($use_tax and !Tax::excludeTaxeOption()) { $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_FREE_WEIGHT')); $free_fees_price = 0; if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) { $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency)); } $free_fees_weight = 0; if (isset($configuration['PS_SHIPPING_FREE_WEIGHT'])) { $free_fees_weight = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_WEIGHT'], Currency::getCurrencyInstance((int) $this->id_currency)); } $shipping_method = $carrier->getShippingMethod(); if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE and $carrier_amount >= (double) $free_fees_price and (double) $free_fees_price > 0) { } else { if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT and $carrier_weight >= (double) $free_fees_weight and (double) $free_fees_weight > 0) { } else { if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT) { $seller_shipping = $carrier->getDeliveryPriceByWeight($carrier_weight, $id_zone); $shipping_cost += $seller_shipping; } else { $seller_shipping = $carrier->getDeliveryPriceByPrice($carrier_amount, $id_zone, (int) $this->id_currency); $shipping_cost += $seller_shipping; } } } $shipping_cost += $this->getAdditionalShippingCostOfSeller($id_carrier); if ($carrier->shipping_handling) { $shipping_cost += (double) Configuration::get('PS_SHIPPING_HANDLING'); } if (isset($carrierTax)) { $shipping_cost *= 1 + $carrierTax / 100; } $shipping_cost = Tools::convertPrice($shipping_cost); return $shipping_cost; }
private static function _getShippingPriceForProduct($product, $zone, $carrier_id) { $carrier = new Carrier($carrier_id); if ($carrier->shipping_method == 0) { // Default if (Configuration::get('PS_SHIPPING_METHOD') == 1) { // Shipping by weight $price = $carrier->getDeliveryPriceByWeight($product->weight, $zone); } else { // Shipping by price $price = $carrier->getDeliveryPriceByPrice($product->price, $zone); } } else { if ($carrier->shipping_method == 1) { // Shipping by weight $price = $carrier->getDeliveryPriceByWeight($product->weight, $zone); } else { if ($carrier->shipping_method == 2) { // Shipping by price $price = $carrier->getDeliveryPriceByPrice($product->price, $zone); } else { // return 0 if is an other shipping method return 0; } } } if ($carrier->shipping_handling) { //Add shipping handling fee $price += Configuration::get('PS_SHIPPING_HANDLING'); } $price += $price * Tax::getCarrierTaxRate($carrier_id) / 100; return $price; }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false) { global $cart; $cart = new Cart((int) $id_cart); // Does order already exists ? if (!$this->active) { die(Tools::displayError()); } if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $cart->secure_key) { die(Tools::displayError()); } // Copying data from cart $order = new Order(); $order->id_carrier = (int) $cart->id_carrier; $order->id_customer = (int) $cart->id_customer; $order->id_address_invoice = (int) $cart->id_address_invoice; $order->id_address_delivery = (int) $cart->id_address_delivery; $vat_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency; $order->id_lang = (int) $cart->id_lang; $order->id_cart = (int) $cart->id; $customer = new Customer((int) $order->id_customer); $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key); $order->payment = $paymentMethod; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = (int) $cart->gift; $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_shipping = (double) $cart->getOrderShippingCost(); $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } // Creating order if ($cart->OrderExists() == false) { $result = $order->add(); } else { $errorMessage = Tools::displayError('An order has already been placed using this cart.'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart)); die($errorMessage); } // Next ! if ($result and isset($order->id)) { if (!$secure_key) { $message .= $this->l('Warning : the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; $store_all_taxes = array(); foreach ($products as $key => $product) { $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL); $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity']; if ($id_order_state != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('PS_OS_ERROR')) { if (Product::updateQuantity($product, (int) $order->id)) { $product['stock_quantity'] -= $product['cart_quantity']; } if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) { $outOfStock = true; } Product::updateDefaultAttribute($product['id_product']); } $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); /* Store tax info */ $id_country = (int) Country::getDefaultCountryId(); $id_state = 0; $id_county = 0; $rate = 0; $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $address_infos = Address::getCountryAndState($id_address); if ($address_infos['id_country']) { $id_country = (int) $address_infos['id_country']; $id_state = (int) $address_infos['id_state']; $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']); } $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county); // If its a freeOrder, there will be no calculation if ($order->total_products > 0) { // remove order discount quotepart on product price in order to obtain the real tax $ratio = $price / $order->total_products; $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio; $tmp_price = $price - $order_reduction_amount; foreach ($allTaxes as $res) { if (!isset($store_all_taxes[$res->id])) { $store_all_taxes[$res->id] = array(); $store_all_taxes[$res->id]['amount'] = 0; } $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang]; $store_all_taxes[$res->id]['rate'] = $res->rate; $unit_tax_amount = $tmp_price * ($res->rate * 0.01); $tmp_price = $tmp_price + $unit_tax_amount; $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity']; } } /* End */ // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = null; if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) { $productDownload = new ProductDownload((int) $id_product_download); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (!_PS_TAX_) { $product['tax'] = 0; $product['rate'] = 0; $tax_rate = 0; } else { $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $ecotaxTaxRate = 0; if (!empty($product['ecotax'])) { $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $product_price = (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, false, false); $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100; if (!$group_reduction) { $group_reduction = (double) Group::getReduction((int) $order->id_customer); } $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']); $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $query .= '(' . (int) $order->id . ', ' . (int) $product['id_product'] . ', ' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . (int) $product['cart_quantity'] . ', ' . $quantityInStock . ', ' . $product_price . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ', ' . $group_reduction . ', ' . $quantityDiscountValue . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\', ' . (double) $tax_rate . ', ' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ', ' . (double) $ecotaxTaxRate . ', ' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\'),'; $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= count($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />'; } $customizationText .= '---<br />'; } $customizationText = rtrim($customizationText, '---<br />'); $customizationQuantity = (int) $product['customizationQuantityTotal']; $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); /* Add carrier tax */ $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false); $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county); $nTax = 0; foreach ($allTaxes as $tax) { if (!isset($tax->id)) { continue; } if (!isset($store_all_taxes[$tax->id])) { $store_all_taxes[$tax->id] = array(); } if (!isset($store_all_taxes[$tax->id]['amount'])) { $store_all_taxes[$tax->id]['amount'] = 0; } $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang]; $store_all_taxes[$tax->id]['rate'] = $tax->rate; if (!$nTax++) { $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl; } else { $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01); } } /* Store taxes */ foreach ($store_all_taxes as $tax) { Db::getInstance()->Execute(' INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`) VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')'); } // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; $total_discount_value = 0; $shrunk = false; foreach ($discounts as $discount) { $objDiscount = new Discount((int) $discount['id_discount']); $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 and $objDiscount->behavior_not_exhausted == 2) { $voucher = new Discount(); foreach ($objDiscount as $key => $discountValue) { $voucher->{$key} = $discountValue; } $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->value = (double) $value - $amount_to_add; $voucher->add(); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; $params['{firstname}'] = $customer->firstname; $params['{lastname}'] = $customer->lastname; $params['{id_order}'] = $order->id; $params['{order_name}'] = sprintf("#%06d", (int) $order->id); @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $order->id), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $amount_to_add = $value; } $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add); $total_discount_value += $amount_to_add; if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED')) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId((int) $cart->id); if ($oldMessage) { $message = new Message((int) $oldMessage['id_message']); $message->id_order = (int) $order->id; $message->update(); } // Hook new order $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } } if (isset($outOfStock) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id); $new_history->addWithemail(true, $extraVars); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) { $invoice = new Address((int) $order->id_address_invoice); $delivery = new Address((int) $order->id_address_delivery); $carrier = new Carrier((int) $order->id_carrier, $order->id_lang); $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false; $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = null; } if (Validate::isEmail($customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } $this->currentOrder = (int) $order->id; return true; } else { $errorMessage = Tools::displayError('Order creation failed'); Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart)); die($errorMessage); } } else { $errorMessage = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }
public function getRoyalMailRates($id_zone, $is_cart, $cart, $product_weight, $dest_zip, $dest_state, $dest_country, $currency, $product, $id_product_attribute, $qty, $dest_city) { $rates = array(); if (file_exists(dirname(__FILE__) . '/../../royalmail/classes/RateAvailableServices.php')) { include_once dirname(__FILE__) . '/../../royalmail/royalmail.php'; include_once dirname(__FILE__) . '/../../royalmail/classes/RateAvailableServices.php'; $rm = new RoyalMail(); if ($rm->active) { $handling = Configuration::get('PS_SHIPPING_HANDLING'); $carriers = $rm->getCarriers($id_zone, $cart, $is_cart, $product); foreach ($carriers as $carrier) { if (get_parent_class($rm) == 'PrestoChangeoCarrierModule') { $rm_rate = new RoyalMailRate(); $amount = $rm_rate->getRate($carrier['id_carrier'], $carrier['id_zone'], $is_cart != '' ? $cart->getTotalWeight() : max($product_weight, 0.001), $dest_zip, $dest_state, $dest_country, "", $is_cart != '' ? 0 : $product->getPrice(true, $id_product_attribute, 6, NULL, false, true, $qty), $is_cart != '' ? 0 : $product->id, $is_cart != '' ? 0 : $id_product_attribute, $qty); } else { $amount = getRoyalMailRate($carrier['id_carrier'], $carrier['id_zone'], $is_cart != '' ? $cart->getTotalWeight() : max($product_weight, 0.001), $dest_zip, $dest_country, $is_cart != '' ? 0 : $product->getPrice(true, $id_product_attribute, 6, NULL, false, true, $qty), $is_cart != '' ? 0 : $product->id); } // Add product spercific cost + handling fee if ($amount > 0) { $amount += $this->getExtraShippingCost($carrier, $handling, $is_cart != '' ? $cart->getProducts() : array(), $product, $qty); } // Apply shipping tax if needed if (!Tax::excludeTaxeOption()) { $carrierTax = Tax::getCarrierTaxRate($carrier['id_carrier']); } if (isset($carrierTax) && $amount !== false) { $amount *= 1 + $carrierTax / 100; } $amount = $amount === false ? -1 : Tools::convertPrice($amount, $currency); if ($amount > 0) { $rates[$carrier['name']] = array(Tools::displayPrice($amount, $currency, false), $carrier['id_carrier']); } elseif ($amount !== false && $amount == 0) { $rates[$carrier['name']] = array($ap->l('Free!'), $carrier['id_carrier']); } } } } return $rates; }
private function _getShipping($product, $configuration, $carrier, $attribute_id = null, $attribute_weight = null) { $default_country = new Country($configuration['PS_COUNTRY_DEFAULT'], $configuration['PS_LANG_DEFAULT']); $id_zone = (int) $default_country->id_zone; $this->id_address_delivery = 0; $carrier_tax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{$configuration['PS_TAX_ADDRESS_TYPE']}); $shipping = 0; $product_price = $product->getPrice(true, $attribute_id, 2, null, false, true, 1); $shipping_free_price = $configuration['PS_SHIPPING_FREE_PRICE']; $shipping_free_weight = isset($configuration['PS_SHIPPING_FREE_WEIGHT']) ? $configuration['PS_SHIPPING_FREE_WEIGHT'] : 0; if (!((double) $shipping_free_price > 0 && $product_price >= (double) $shipping_free_price) && !((double) $shipping_free_weight > 0 && $product->weight + $attribute_weight >= (double) $shipping_free_weight)) { if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) { $shipping = (double) $configuration['PS_SHIPPING_HANDLING']; } if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping += $carrier->getDeliveryPriceByWeight($product->weight, $id_zone); } else { $shipping += $carrier->getDeliveryPriceByPrice($product_price, $id_zone); } $shipping *= 1 + $carrier_tax / 100; $shipping = (double) Tools::ps_round((double) $shipping, 2); } return (double) $shipping + (double) $product->additional_shipping_cost; }
public function addTax($cena) { if (Configuration::get('PS_TAX')) { if ($this->tax_rate === false) { $this->taxrate = Tax::getCarrierTaxRate(Configuration::get($this->uppername . '_CARRIER_ID')); } $cena = $cena / 100 * (100 + $this->taxrate); } return $cena; }
private function getShippingPriceForProduct($product, $zone, $carrierid) { $carrier = new Carrier($carrierid); if (Configuration::get('PS_SHIPPING_METHOD') == 1) { //Shipping by weight $price = $carrier->getDeliveryPriceByWeight($product->weight, $zone); } else { //Shipping by price $price = $carrier->getDeliveryPriceByPrice($product->price, $zone); } if ($carrier->shipping_handling) { //Add shipping handling fee (frais de manutention) $price += Configuration::get('PS_SHIPPING_HANDLING'); } $taxrate = Tax::getCarrierTaxRate($carrierid); $price += $price * $taxrate / 100; return $price; }
public function hookProductFooter($params) { global $cookie, $smarty; $pr = new Product($params['product']->id); $carriers = Carrier::getCarriers($cookie->id_lang); $c = array(); foreach ($carriers as $carrier) { $a = new Carrier($carrier['id_carrier']); if (!Tax::excludeTaxeOption()) { $carrierTax = Tax::getCarrierTaxRate((int) $a->id); } $price = $a->getDeliveryPriceByPrice($pr->getPrice(true, null), 1) * (1 + $carrierTax / 100); $c[] = array('name' => $a->name, 'price' => $price); } $smarty->assign('carriers', $c); $smarty->assign('free', (int) Configuration::get('PS_SHIPPING_FREE_PRICE')); $smarty->assign(array('delivery' => $this->doruceni())); return $this->display(__FILE__, 'blank_deliverytime.tpl'); }
public function initReservation($klarna, $cart, $customer, $house = null, $ext = null) { $address_invoice = new Address((int) $cart->id_address_invoice); $carrier = new Carrier((int) $cart->id_carrier); $country = new Country((int) $address_invoice->id_country); $id_currency = (int) Validate::isLoadedObject($this->context->currency) ? (int) $this->context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT'); $order_id = Order::getOrderByCartId((int) $cart->id); if ($order_id) { $order = new Order((int) $order_id); foreach ($order->getProducts() as $article) { $price_wt = (double) $article['product_price_wt']; $price = (double) $article['product_price']; if (empty($article['tax_rate'])) { $rate = round(($price_wt / $price - 1.0) * 100); } else { $rate = $article['tax_rate']; } $klarna->addArticle((int) $article['product_quantity'], $this->klarnaEncode($article['product_id']), $this->klarnaEncode($article['product_name']), $price_wt, $rate, 0, KlarnaFlags::INC_VAT | (substr($article['product_name'], 0, 10) == 'invoiceFee' ? KlarnaFlags::IS_HANDLING : 0)); } } else { foreach ($cart->getProducts() as $article) { $price_wt = (double) $article['price_wt']; $price = (double) $article['price']; if (empty($article['rate'])) { $rate = round(($price_wt / $price - 1.0) * 100); } else { $rate = $article['rate']; } $klarna->addArticle((int) $article['cart_quantity'], $this->klarnaEncode((int) $article['id_product']), $this->klarnaEncode($article['name'] . (isset($article['attributes']) ? $article['attributes'] : '')), $price_wt, $rate, 0, KlarnaFlags::INC_VAT | (substr($article['name'], 0, 10) == 'invoiceFee' ? KlarnaFlags::IS_HANDLING : 0)); } } // Add discounts if (_PS_VERSION_ >= 1.5) { $discounts = $cart->getCartRules(); } else { $discounts = $cart->getDiscounts(); } foreach ($discounts as $discount) { $rate = 0; $incvat = 0; // Free shipping has a real value of '!'. if ($discount['value_real'] !== '!') { $incvat = $discount['value_real']; $extvat = $discount['value_tax_exc']; $rate = round(($incvat / $extvat - 1.0) * 100); } $klarna->addArticle(1, '', $this->klarnaEncode($discount['description']), $incvat * -1, $rate, 0, KlarnaFlags::INC_VAT); } $carrier = new Carrier((int) $cart->id_carrier); if ($carrier->active) { $taxrate = Tax::getCarrierTaxRate((int) $carrier->id, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); // Next we might want to add a shipment fee for the product if ($order_id) { $order = new Order((int) $order_id); $shippingPrice = $order->total_shipping_tax_incl; } else { $shippingPrice = $cart->getTotalShippingCost(); } $klarna->addArticle(1, $this->klarnaEncode((int) $cart->id_carrier), $this->klarnaEncode($carrier->name), $shippingPrice, $taxrate, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT); } if ($cart->gift == 1) { $rate = 0; $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); if ($wrapping_fees_tax->rate !== null) { $rate = $wrapping_fees_tax->rate; } $klarna->addArticle(1, '', $this->klarnaEncode($this->l('Gift wrapping fee')), $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), $rate, 0, KlarnaFlags::INC_VAT); } // Create the address object and specify the values. $address_delivery = new Address((int) $cart->id_address_delivery); // Next we tell the Klarna instance to use the address in the next order. $address = str_replace($house, '', $address_invoice->address1); $address = str_replace($ext, '', $address); $address2 = str_replace($house, '', $address_invoice->address2); $address2 = str_replace($ext, '', $address2); $klarna->setAddress(KlarnaFlags::IS_BILLING, new KlarnaAddr($this->klarnaEncode($customer->email), $this->klarnaEncode($address_invoice->phone), $this->klarnaEncode($address_invoice->phone_mobile), $this->klarnaEncode($address_invoice->firstname), $this->klarnaEncode($address_invoice->lastname), $this->klarnaEncode($address_invoice->company), $this->klarnaEncode(trim($address) . ($address2 != '' ? ' ' . trim($address2) : '')), $this->klarnaEncode($address_invoice->postcode), $this->klarnaEncode($address_invoice->city), $this->klarnaEncode($this->countries[$country->iso_code]['code']), trim($house), trim($ext))); // Billing / invoice address $address = str_replace($house, '', $address_delivery->address1); $address = str_replace($ext, '', $address); $address2 = str_replace($house, '', $address_delivery->address2); $address2 = str_replace($ext, '', $address2); $klarna->setAddress(KlarnaFlags::IS_SHIPPING, new KlarnaAddr($this->klarnaEncode($customer->email), $this->klarnaEncode($address_delivery->phone), $this->klarnaEncode($address_delivery->phone_mobile), $this->klarnaEncode($address_delivery->firstname), $this->klarnaEncode($address_delivery->lastname), $this->klarnaEncode($address_delivery->company), $this->klarnaEncode(trim($address) . ($address2 != '' ? ' ' . trim($address2) : '')), $this->klarnaEncode($address_delivery->postcode), $this->klarnaEncode($address_delivery->city), $this->klarnaEncode($this->countries[$country->iso_code]['code']), trim($house), trim($ext))); // Billing / invoice address }
public function updatePrice() { $total_price_tax_excl = 0; $total_shipping_tax_incl = 0; $total_shipping_tax_excl = 0; $id_carrier = (int) EbayShipping::getPsCarrierByEbayCarrier($this->shippingService); if (version_compare(_PS_VERSION_, '1.4.0.5', '<')) { $carrier_tax_rate = (double) $this->_getTaxByCarrier((int) $id_carrier); } else { $carrier_tax_rate = (double) Tax::getCarrierTaxRate((int) $id_carrier); } foreach ($this->product_list as $product) { if (version_compare(_PS_VERSION_, '1.4.0.5', '<')) { $tax_rate = (double) $this->_getTaxByProduct((int) $product['id_product']); } else { $tax_rate = (double) Tax::getProductTaxRate((int) $product['id_product']); } $coef_rate = 1 + $tax_rate / 100; $detail_data = array('product_price' => (double) ($product['price'] / $coef_rate), 'unit_price_tax_incl' => (double) $product['price'], 'unit_price_tax_excl' => (double) ($product['price'] / $coef_rate), 'total_price_tax_incl' => (double) ($product['price'] * $product['quantity']), 'total_price_tax_excl' => (double) ($product['price'] / $coef_rate * $product['quantity']), 'reduction_percent' => 0, 'reduction_amount' => 0); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', $detail_data, 'UPDATE', '`id_order` = ' . (int) $this->id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']); if (version_compare(_PS_VERSION_, '1.5', '>')) { $detail_tax_data = array('unit_amount' => (double) ($product['price'] - $product['price'] / $coef_rate), 'total_amount' => (double) ($product['price'] - $product['price'] / $coef_rate) * $product['quantity']); DB::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail_tax', $detail_tax_data, 'UPDATE', '`id_order_detail` = (SELECT `id_order_detail` FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $this->id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute'] . ') '); } $total_price_tax_excl += (double) ($product['price'] / $coef_rate * $product['quantity']); // ebay get one shipping cost by product $total_shipping_tax_incl += $this->shippingServiceCost; $total_shipping_tax_excl += $this->shippingServiceCost / (1 + $carrier_tax_rate / 100); } $data = array('total_paid' => (double) $this->amount, 'total_paid_real' => (double) $this->amount, 'total_products' => (double) $total_price_tax_excl, 'total_products_wt' => (double) ($this->amount - $this->shippingServiceCost), 'total_shipping' => (double) $total_shipping_tax_incl, 'total_shipping_tax_incl' => (double) $total_shipping_tax_incl, 'total_shipping_tax_excl' => (double) $total_shipping_tax_excl); if ((double) $this->shippingServiceCost == 0) { $data = array_merge($data, array('total_shipping_tax_excl' => 0, 'total_shipping_tax_incl' => 0)); } if (version_compare(_PS_VERSION_, '1.5', '>')) { $order = new Order((int) $this->id_order); $data_old = $data; $data = array_merge($data, array('total_paid_tax_incl' => (double) $this->amount, 'total_paid_tax_excl' => (double) ($total_price_tax_excl + $order->total_shipping_tax_excl))); // Update Incoice $invoice_data = $data; unset($invoice_data['total_paid'], $invoice_data['total_paid_real'], $invoice_data['total_shipping']); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_invoice', $invoice_data, 'UPDATE', '`id_order` = ' . (int) $this->id_order); // Update payment $payment_data = array('amount' => (double) $this->amount); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_payment', $payment_data, 'UPDATE', '`order_reference` = "' . pSQL($order->reference) . '" '); } return Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $data, 'UPDATE', '`id_order` = ' . (int) $this->id_order); }
private function cartToOrder($items, $foreignKey) { $this->alterTable('order'); foreach ($items as $item) { $order = new Order(); $order->id_carrier = (int) $item['id_carrier']; $order->id_customer = (int) $foreignKey['id_customer'][$item['id_customer']]; $order->id_address_invoice = (int) $foreignKey['id_address_invoice'][$item['id_address_invoice']]; $order->id_address_delivery = (int) $foreignKey['id_address_delivery'][$item['id_address_delivery']]; $vat_address = new Address((int) $foreignKey['id_address_delivery'][$item['id_address_delivery']]); $id_zone = Address::getZoneById((int) $vat_address->id); $order->id_currency = (int) $item['id_currency']; $order->id_lang = (int) $item['id_lang']; $order->id_cart = (int) $foreignKey['id_cart'][$item['id_cart']]; $customer = new Customer((int) $order->id_customer); $order->secure_key = pSQL($customer->secure_key); $order->payment = Tools::substr($item['payment'], 0, 32); if (isset($this->name)) { $order->module = $this->name; } $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $order->total_products = (double) $item['total_products']; $order->total_products_wt = (double) $item['total_products_wt']; $order->total_discounts = (double) $item['total_discounts']; $order->total_shipping = (double) $item['total_shipping']; $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate((int) $item['id_carrier'], (int) $item[Configuration::get('PS_TAX_ADDRESS_TYPE')]); $order->total_wrapping = (double) $item['total_wrapping']; $order->total_paid = (double) $item['total_paid']; $order->total_paid_real = (double) $item['total_paid_real']; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; $order->add(); $this->saveMatchId('order', (int) $order->id, (int) $item['id_cart']); } }
public function hookExtraCarrier($params) { $carrier_so = new Carrier((int) Configuration::get('SOCOLISSIMO_CARRIER_ID')); if (!isset($carrier_so) || !$carrier_so->active) { return ''; } $country = new Country((int) $params['address']->id_country); $carriers = Carrier::getCarriers($this->context->language->id, true, false, false, null, defined('ALL_CARRIERS') ? ALL_CARRIERS : Carrier::ALL_CARRIERS); // Backward compatibility 1.5 $id_carrier = $carrier_so->id; // bug fix for cart rule with restriction if (!version_compare(_PS_VERSION_, '1.5', '<')) { CartRule::autoAddToCart($this->context); } // For now works only with single shipping ! if (method_exists($params['cart'], 'carrierIsSelected')) { if ($params['cart']->carrierIsSelected((int) $carrier_so->id, $params['address']->id)) { $id_carrier = (int) $carrier_so->id; } } $customer = new Customer($params['address']->id_customer); $gender = array('1' => 'MR', '2' => 'MME', '3' => 'MLE'); if (in_array((int) $customer->id_gender, array(1, 2))) { $cecivility = $gender[(int) $customer->id_gender]; } else { $cecivility = 'MR'; } $tax_rate = Tax::getCarrierTaxRate($id_carrier, isset($params['cart']->id_address_delivery) ? $params['cart']->id_address_delivery : null); $tax_rate_seller = Tax::getCarrierTaxRate(Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER'), isset($params['cart']->id_address_delivery) ? $params['cart']->id_address_delivery : null); if ($tax_rate) { $std_cost_with_taxes = number_format((double) $this->initial_cost * (1 + $tax_rate / 100), 2, ',', ' '); } else { $std_cost_with_taxes = number_format((double) $this->initial_cost, 2, ',', ' '); } $seller_cost_with_taxes = 0; if ($this->seller_cost) { if ($tax_rate_seller) { $seller_cost_with_taxes = number_format((double) $this->seller_cost * (1 + $tax_rate_seller / 100), 2, ',', ' '); } else { $seller_cost_with_taxes = number_format((double) $this->seller_cost, 2, ',', ' '); } } $free_shipping = false; if (version_compare(_PS_VERSION_, '1.5', '<')) { $rules = $params['cart']->getDiscounts(); if (!empty($rules)) { foreach ($rules as $rule) { if ($rule['id_discount_type'] == 3) { $free_shipping = true; break; } } } } else { $rules = $params['cart']->getCartRules(); if (!empty($rules)) { foreach ($rules as $rule) { if ($rule['free_shipping'] && !$rule['carrier_restriction']) { $free_shipping = true; break; } } if (!$free_shipping) { $key_search = $id_carrier . ','; $deliveries_list = $params['cart']->getDeliveryOptionList(); foreach ($deliveries_list as $deliveries) { foreach ($deliveries as $key => $elt) { if ($key == $key_search) { $free_shipping = $elt['is_free']; } } } } } else { // for cart rule with restriction $key_search = $id_carrier . ','; $deliveries_list = $params['cart']->getDeliveryOptionList(); foreach ($deliveries_list as $deliveries) { foreach ($deliveries as $key => $elt) { if ($key == $key_search) { $free_shipping = $elt['is_free']; } } } } } if ($free_shipping) { $std_cost_with_taxes = 0; $seller_cost_with_taxes = 0; } // Keep this fields order (see doc.) $inputs = array('pudoFOId' => Configuration::get('SOCOLISSIMO_ID'), 'ceName' => $this->replaceAccentedChars(Tools::substr($params['address']->lastname, 0, 34)), 'dyPreparationTime' => (int) Configuration::Get('SOCOLISSIMO_PREPARATION_TIME'), 'dyForwardingCharges' => $std_cost_with_taxes, 'dyForwardingChargesCMT' => $seller_cost_with_taxes, 'trClientNumber' => (int) $params['address']->id_customer, 'orderId' => $this->formatOrderId((int) $params['address']->id), 'numVersion' => $this->getNumVersion(), 'ceCivility' => $cecivility, 'ceFirstName' => $this->replaceAccentedChars(Tools::substr($params['address']->firstname, 0, 29)), 'ceCompanyName' => $this->replaceAccentedChars(Tools::substr($params['address']->company, 0, 38)), 'ceAdress3' => $this->replaceAccentedChars(Tools::substr($params['address']->address1, 0, 38)), 'ceAdress4' => $this->replaceAccentedChars(Tools::substr($params['address']->address2, 0, 38)), 'ceZipCode' => $this->replaceAccentedChars($params['address']->postcode), 'ceTown' => $this->replaceAccentedChars(Tools::substr($params['address']->city, 0, 32)), 'ceEmail' => $this->replaceAccentedChars($params['cookie']->email), 'cePhoneNumber' => $this->replaceAccentedChars(str_replace(array(' ', '.', '-', ',', ';', '/', '\\', '(', ')'), '', $params['address']->phone_mobile)), 'dyWeight' => (double) $params['cart']->getTotalWeight() * 1000, 'trParamPlus' => $carrier_so->id, 'trReturnUrlKo' => htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'trReturnUrlOk' => htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'CHARSET' => 'UTF-8', 'cePays' => $country->iso_code, 'trInter' => Configuration::get('SOCOLISSIMO_EXP_BEL'), 'ceLang' => 'FR'); if (!$inputs['dyForwardingChargesCMT'] && !Configuration::get('SOCOLISSIMO_COST_SELLER')) { unset($inputs['dyForwardingChargesCMT']); } // set params for Api 3.0 if needed $inputs = $this->setInputParams($inputs); // generate key for API $inputs['signature'] = $this->generateKey($inputs); // calculate lowest cost $from_cost = $std_cost_with_taxes; if ($seller_cost_with_taxes || Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER') && Configuration::get('SOCOLISSIMO_COST_SELLER')) { if ((double) str_replace(',', '.', $seller_cost_with_taxes) < (double) str_replace(',', '.', $std_cost_with_taxes)) { $from_cost = $seller_cost_with_taxes; } } $rewrite_active = true; if (!Configuration::get('PS_REWRITING_SETTINGS')) { $rewrite_active = false; } // module link for prestashop 1.5 to get proper url $link = new Link(); $module_link = ''; if (!version_compare(_PS_VERSION_, '1.5', '<')) { $module_link = $link->getModuleLink('socolissimo', 'redirect', array(), true); } $module_link_mobile = ''; if (!version_compare(_PS_VERSION_, '1.5', '<')) { $module_link_mobile = $link->getModuleLink('socolissimo', 'redirectmobile', array(), true); } // automatic settings api protocol for ssl $protocol = 'http://'; if (Configuration::get('PS_SSL_ENABLED')) { $protocol = 'https://'; } $this->context->smarty->assign(array('select_label' => $this->l('Select delivery mode'), 'edit_label' => $this->l('Edit delivery mode'), 'token' => sha1('socolissimo' . _COOKIE_KEY_ . Context::getContext()->cookie->id_cart), 'urlSo' => $protocol . Configuration::get('SOCOLISSIMO_URL') . '?trReturnUrlKo=' . htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'urlSoMobile' => $protocol . Configuration::get('SOCOLISSIMO_URL_MOBILE') . '?trReturnUrlKo=' . htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'id_carrier' => $id_carrier, 'id_carrier_seller' => Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER'), 'SOBWD_C' => version_compare(_PS_VERSION_, '1.5', '<') ? false : true, 'inputs' => $inputs, 'initialCost_label' => $this->l('From'), 'initialCost' => $from_cost . $this->l(' €'), 'taxMention' => $this->l(' TTC'), 'finishProcess' => $this->l('To choose SoColissimo, click on a delivery method'), 'rewrite_active' => $rewrite_active, 'link_socolissimo' => $module_link, 'link_socolissimo_mobile' => $module_link_mobile)); $ids = array(); foreach ($carriers as $carrier) { $ids[] = $carrier['id_carrier']; } if ($params['cart']->id_carrier == Configuration::Get('SOCOLISSIMO_CARRIER_ID') && $this->getDeliveryInfos($this->context->cart->id, $this->context->customer->id)) { $this->context->smarty->assign('already_select_delivery', true); } else { $this->context->smarty->assign('already_select_delivery', false); } if (($country->iso_code == 'FR' || $country->iso_code == 'BE' && Configuration::get('SOCOLISSIMO_EXP_BEL')) && Configuration::Get('SOCOLISSIMO_ID') != null && Configuration::get('SOCOLISSIMO_KEY') != null && $this->checkAvailibility() && $this->checkSoCarrierAvailable((int) Configuration::get('SOCOLISSIMO_CARRIER_ID')) && in_array((int) Configuration::get('SOCOLISSIMO_CARRIER_ID'), $ids)) { // if mobile or iPad if (version_compare(_PS_VERSION_, '1.5', '<')) { // 1.4 if ($this->context->getMobileDevice()) { return $this->fetchTemplate('socolissimo_redirect_mobile.tpl'); } } else { // 1.5 if (Context::getContext()->getMobileDevice() || _THEME_NAME_ == 'prestashop_mobile' || $this->isIpad()) { if (Configuration::get('PS_ORDER_PROCESS_TYPE')) { $tab_id_soco = explode('|', Configuration::get('SOCOLISSIMO_CARRIER_ID_HIST')); $tab_id_soco[] = $id_carrier; $this->context->smarty->assign('ids', $tab_id_soco); return $this->fetchTemplate('socolissimo_error_mobile_opc.tpl'); } else { return $this->fetchTemplate('socolissimo_redirect_mobile.tpl'); } } } // route display mode if (Configuration::get('PS_ORDER_PROCESS_TYPE') || Configuration::get('SOCOLISSIMO_USE_FANCYBOX')) { return $this->fetchTemplate('socolissimo_fancybox.tpl'); } if (Configuration::get('SOCOLISSIMO_USE_IFRAME')) { return $this->fetchTemplate('socolissimo_iframe.tpl'); } return $this->fetchTemplate('socolissimo_redirect.tpl'); } else { $tab_id_soco = explode('|', Configuration::get('SOCOLISSIMO_CARRIER_ID_HIST')); $tab_id_soco[] = $id_carrier; $this->context->smarty->assign('ids', $tab_id_soco); return $this->fetchTemplate('socolissimo_error.tpl'); } }
/** * create carriers * * @return mixed */ protected function _getCarriers() { $resultsCarrier = array(); $mobileCarrierUse = unserialize(base64_decode(Configuration::get('SG_MOBILE_CARRIER'))); if ($this->_deliveryAddress) { foreach (Carrier::getCarriersForOrder(Address::getZoneById($this->_deliveryAddress->id), $this->getPlugin()->getContext()->customer->getGroups(), $this->getPlugin()->getContext()->cart) as $carrier) { /** @var CarrierCore $carrierItem */ $carrierItem = new Carrier($carrier['id_carrier'], $this->getPlugin()->getContext()->language->id); $taxRulesGroup = new TaxRulesGroup($carrierItem->id_tax_rules_group); $resultCarrier = new ShopgateShippingMethod(); /** * check is defined as mobile carrier */ $idColumn = version_compare(_PS_VERSION_, '1.5.0.1', '>=') ? 'id_reference' : 'id_carrier'; if (is_array($mobileCarrierUse) && empty($mobileCarrierUse[$carrier[$idColumn]])) { continue; } $resultCarrier->setId($carrier['id_carrier']); $resultCarrier->setTitle($carrier['name']); $resultCarrier->setDescription($carrier['delay']); $resultCarrier->setSortOrder($carrier['position']); $resultCarrier->setAmount($carrier['price_tax_exc']); $resultCarrier->setAmountWithTax($carrier['price']); $resultCarrier->setTaxClass($taxRulesGroup->name); if (version_compare(_PS_VERSION_, '1.5.0', '<')) { $carrierTax = Tax::getCarrierTaxRate($carrierItem->id, $this->_deliveryAddress->id); } else { $carrierTax = $carrierItem->getTaxesRate($this->_deliveryAddress); } $resultCarrier->setTaxPercent($carrierTax); $resultCarrier->setInternalShippingInfo(serialize(array('carrierId' => $carrier['id_carrier']))); $resultsCarrier[] = $resultCarrier; } } return $resultsCarrier; }
private function cartToOrder($items, $foreignKey) { $this->alterTable('order'); foreach ($items as $item) { $order = new Order(); $order->id_carrier = (int) $item['id_carrier']; $order->id_customer = (int) $foreignKey['id_customer'][$item['id_customer']]; $order->id_address_invoice = (int) $foreignKey['id_address_invoice'][$item['id_address_invoice']]; $order->id_address_delivery = (int) $foreignKey['id_address_delivery'][$item['id_address_delivery']]; $vat_address = new Address((int) $foreignKey['id_address_delivery'][$item['id_address_delivery']]); $id_zone = Address::getZoneById((int) $vat_address->id); $order->id_currency = (int) $item['id_currency']; $order->id_lang = (int) $item['id_lang']; $order->id_cart = (int) $foreignKey['id_cart'][$item['id_cart']]; $customer = new Customer((int) $order->id_customer); $order->secure_key = pSQL($customer->secure_key); if (!strlen(trim($item['payment']))) { $order->payment = 'payment' . Tools::getValue('moduleName'); } else { $order->payment = utf8_encode(html_entity_decode(strip_tags(Tools::substr($item['payment'], 0, 32)))); } if (isset($this->name)) { $order->module = $this->name; } $currency = new Currency($order->id_currency); $order->conversion_rate = !empty($currency->conversion_rate) ? $currency->conversion_rate : 1; $order->total_products = (double) $item['total_products']; $order->total_products_wt = (double) $item['total_products_wt']; $order->total_discounts = (double) $item['total_discounts']; $order->total_shipping = (double) $item['total_shipping']; $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate((int) $item['id_carrier'], (int) $item[Configuration::get('PS_TAX_ADDRESS_TYPE')]); $order->total_wrapping = (double) $item['total_wrapping']; $order->total_paid = (double) $item['total_paid']; $order->total_paid_real = (double) $item['total_paid_real']; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; if (array_key_exists('date_add', $item)) { $order->date_add = $item['date_add']; } if (array_key_exists('date_upd', $item)) { $order->date_upd = $item['date_upd']; } //test valid paid if ($item['total_paid'] == $item['total_paid_real']) { $order->valid = 1; } else { $order->valid = 0; } $order->save(false, false); $this->saveMatchId('order', (int) $order->id, (int) $item['id_cart']); } }
/** * Creating of the PrestaShop order * @param $neteven_order * @param $neteven_orders * @return int */ private function createOrder($neteven_order, $neteven_orders) { if (constant('_PS_VERSION_') >= 1.5) { include_once dirname(__FILE__) . '/OrderInvoiceOverride.php'; } /* Treatment of customer */ $id_customer = $this->addCustomerInBDD($neteven_order); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Customer') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } /* Treatment of addresses of the customer */ $id_address_billing = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->BillingAddress, 'facturation', $id_customer); $id_address_shipping = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->ShippingAddress, 'livraison', $id_customer); if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Address') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } /* Get secure key of customer */ $secure_key_default = md5(uniqid(rand(), true)); if ($secure_key = Db::getInstance()->getValue('SELECT `secure_key` FROM `' . _DB_PREFIX_ . 'customer` WHERE `id_customer` = ' . (int) $id_customer)) { $secure_key_default = $secure_key; } else { Toolbox::addLogLine(self::getL('Problem with a secure key recovery for the customer / NetEven Order Id') . ' ' . $neteven_order->OrderID); } /* Treatment of order informations */ $total_wt = 0; $total_product = 0; $total_product_wt = 0; $total_taxe = 0; foreach ($neteven_orders as $neteven_order_temp) { if ($neteven_order_temp->OrderID == $neteven_order->OrderID) { if (in_array($neteven_order_temp->Status, $this->getValue('t_list_order_status'))) { continue; } $total_product += (double) $neteven_order_temp->Price->_ - (double) $neteven_order_temp->VAT->_; $total_product_wt += (double) $neteven_order_temp->Price->_; $total_taxe += $neteven_order_temp->VAT->_; } } $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_; $date_now = date('Y-m-d H:i:s'); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order total') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } /* Creating and add order in PrestaShop */ if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = 0'))) { /* Creating cart */ $cart = new Cart(); $cart->id_address_delivery = (int) $id_address_shipping; $cart->id_address_invoice = (int) $id_address_billing; $cart->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); $cart->id_customer = (int) $id_customer; $cart->id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $cart->id_carrier = Gateway::getConfig('CARRIER_NETEVEN'); $cart->recyclable = 1; $cart->gift = 0; $cart->gift_message = ''; $cart->date_add = $date_now; $cart->secure_key = $secure_key_default; $cart->date_upd = $date_now; if (!$cart->add()) { Toolbox::addLogLine(self::getL('Failed for cart creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Cart') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } /* Creating order */ $id_order_temp = 0; $order = new Order(); $order->id_carrier = Gateway::getConfig('CARRIER_NETEVEN'); $order->id_lang = Configuration::get('PS_LANG_DEFAULT'); $order->id_customer = $id_customer; $order->id_cart = $cart->id; $order->id_currency = Configuration::get('PS_CURRENCY_DEFAULT'); $order->id_address_delivery = $id_address_shipping; $order->id_address_invoice = $id_address_billing; $order->secure_key = $secure_key_default; $order->payment = $neteven_order->PaymentMethod; $order->conversion_rate = 1; $order->module = 'nqgatewayneteven'; $order->recyclable = 0; $order->gift = 0; $order->gift_message = ' '; $order->shipping_number = ''; /* generate reference order */ $nbr_order_neteven = Configuration::get('NUMBER_ORDER_NETEVEN'); if (false === $nbr_order_neteven) { $nbr_order_neteven = 1; } else { $nbr_order_neteven = (int) str_replace('N', '', $nbr_order_neteven); $nbr_order_neteven++; } $next_ref_gen_order_neteven = 'N' . sprintf('%07s', $nbr_order_neteven); Configuration::updateValue('NUMBER_ORDER_NETEVEN', $next_ref_gen_order_neteven); $order->reference = $next_ref_gen_order_neteven; /* ----- */ $carrier = new Carrier((int) $order->id_carrier); if (method_exists($carrier, 'getTaxesRate')) { $carrier_tax_rate = $carrier->getTaxesRate(new Address($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } elseif (method_exists('Tax', 'getCarrierTaxRate')) { $carrier_tax_rate = (double) Tax::getCarrierTaxRate($order->id_carrier, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } else { $carrier_tax_rate = 100; } $total_shipping_tax_excl = $carrier_tax_rate ? $neteven_order->OrderShippingCost->_ / ($carrier_tax_rate / 100) : $neteven_order->OrderShippingCost->_; $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_; $total = $total_product + $total_shipping_tax_excl; $order->total_discounts_tax_excl = 0; $order->total_discounts_tax_incl = 0; $order->total_discounts = 0; $order->total_wrapping_tax_excl = 0; $order->total_wrapping_tax_incl = 0; $order->total_wrapping = 0; $order->total_products = (double) number_format($total_product, 2, '.', ''); $order->total_products_wt = (double) number_format($total_product_wt, 2, '.', ''); $order->total_shipping_tax_excl = (double) number_format($total_shipping_tax_excl, 2, '.', ''); $order->total_shipping_tax_incl = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', ''); $order->total_shipping = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', ''); $order->total_paid_tax_excl = (double) number_format($total_wt - $total_taxe, 2, '.', ''); $order->total_paid_tax_incl = (double) number_format($total_wt, 2, '.', ''); $order->total_paid_real = (double) number_format($total_wt, 2, '.', ''); $order->total_paid = (double) number_format($total_wt, 2, '.', ''); $order->carrier_tax_rate = 0; $order->total_wrapping = 0; $order->invoice_number = 0; $order->delivery_number = 0; $order->invoice_date = $date_now; $order->delivery_date = $date_now; $order->valid = 1; $order->date_add = $date_now; $order->date_upd = $date_now; if (Configuration::get('PS_SHOP_ENABLE')) { $order->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT'); } if (!$order->add()) { Toolbox::addLogLine(self::getL('Failed for order creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } else { $id_order_temp = $order->id; Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_carrier` (`id_order`, `id_carrier`, `id_order_invoice`, `weight`, `shipping_cost_tax_excl`, `shipping_cost_tax_incl`, `tracking_number`, `date_add`) VALUES (' . (int) $id_order_temp . ', ' . (int) Gateway::getConfig('CARRIER_NETEVEN') . ', 0, 0, 0, 0, 0,"' . pSQL(date('Y-m-d H:i:s')) . '")'); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "Place de marché ' . $neteven_order->MarketPlaceName . '", "' . pSQL(date('Y-m-d H:i:s')) . '")'); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "ID order NetEven ' . $neteven_order->MarketPlaceOrderId . '", "' . pSQL(date('Y-m-d H:i:s')) . '")'); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } Toolbox::addLogLine(self::getL('Add order Id') . ' ' . (int) $id_order_temp . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('History') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } /* Insert order in orders_gateway table */ if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order_temp . ', 0, "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) { Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID); } else { Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID); } } } else { $id_order_temp = $res['id_order']; Toolbox::addLogLine(self::getL('Get already exported order Id') . ' ' . $res['id_order'] . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } return $id_order_temp; }
/** * Return shipping total * * @param integer $id_carrier Carrier ID (default : current carrier) * @return float Shipping total */ function getOrderShippingCost($id_carrier = NULL, $useTax = true) { global $defaultCountry; if ($this->isVirtualCart()) { return 0; } // Checking discounts in cart $products = $this->getProducts(); $discounts = $this->getDiscounts(true); if ($discounts) { foreach ($discounts as $id_discount) { if ($id_discount['id_discount_type'] == 3) { if ($id_discount['minimal'] > 0) { $total_cart = 0; $categories = Discount::getCategories((int) $id_discount['id_discount']); if (sizeof($categories)) { foreach ($products as $product) { if (Product::idIsOnCategoryId((int) $product['id_product'], $categories)) { $total_cart += $product['total_wt']; } } } if ($total_cart >= $id_discount['minimal']) { return 0; } } else { return 0; } } } } // Order total in default currency without fees $order_total = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING); // Start with shipping cost at 0 $shipping_cost = 0; // If no product added, return 0 if ($order_total <= 0 and !(int) self::getNbProducts($this->id)) { return $shipping_cost; } // Get id zone if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) { $id_zone = Address::getZoneById((int) $this->id_address_delivery); } else { // This method can be called from the backend, and $defaultCountry won't be defined if (!Validate::isLoadedObject($defaultCountry)) { $defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT')); } $id_zone = (int) $defaultCountry->id_zone; } // If no carrier, select default one if (!$id_carrier) { $id_carrier = $this->id_carrier; } if ($id_carrier && !$this->isCarrierInRange($id_carrier, $id_zone)) { $id_carrier = ''; } if (empty($id_carrier) && $this->isCarrierInRange(Configuration::get('PS_CARRIER_DEFAULT'), $id_zone)) { $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT'); } if (empty($id_carrier)) { if ((int) $this->id_customer) { $customer = new Customer((int) $this->id_customer); $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups()); unset($customer); } else { $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone); } foreach ($result as $k => $row) { if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) { continue; } if (!isset(self::$_carriers[$row['id_carrier']])) { self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']); } $carrier = self::$_carriers[$row['id_carrier']]; // Get only carriers that are compliant with shipping method if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and $carrier->getMaxDeliveryPriceByWeight($id_zone) === false or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and $carrier->getMaxDeliveryPriceByPrice($id_zone) === false) { unset($result[$k]); continue; } // If out-of-range behavior carrier is set on "Desactivate carrier" if ($row['range_behavior']) { // Get only carriers that have a range compatible with cart if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) { unset($result[$k]); continue; } } if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone); } else { $shipping = $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency); } if (!isset($minShippingPrice)) { $minShippingPrice = $shipping; } if ($shipping <= $minShippingPrice) { $id_carrier = (int) $row['id_carrier']; $minShippingPrice = $shipping; } } } if (empty($id_carrier)) { $id_carrier = Configuration::get('PS_CARRIER_DEFAULT'); } if (!isset(self::$_carriers[$id_carrier])) { self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT')); } $carrier = self::$_carriers[$id_carrier]; if (!Validate::isLoadedObject($carrier)) { die(Tools::displayError('Fatal error: "no default carrier"')); } if (!$carrier->active) { return $shipping_cost; } // Free fees if free carrier if ($carrier->is_free == 1) { return 0; } // Select carrier tax if ($useTax and !Tax::excludeTaxeOption()) { $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT')); // Free fees $free_fees_price = 0; if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) { $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency)); } $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING); if ($orderTotalwithDiscounts >= (double) $free_fees_price and (double) $free_fees_price > 0) { return $shipping_cost; } if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] and (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) { return $shipping_cost; } // Get shipping cost using correct method if ($carrier->range_behavior) { // Get id zone if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) { $id_zone = Address::getZoneById((int) $this->id_address_delivery); } else { $id_zone = (int) $defaultCountry->id_zone; } if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) { $shipping_cost += 0; } else { if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone); } else { // by price $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency); } } } else { if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone); } else { $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency); } } // Adding handling charges if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) { $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING']; } // Additional Shipping Cost per product foreach ($products as $product) { $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity']; } $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency)); //get external shipping cost from module if ($carrier->shipping_external) { $moduleName = $carrier->external_module_name; $module = Module::getInstanceByName($moduleName); if (Validate::isLoadedObject($module)) { if (array_key_exists('id_carrier', $module)) { $module->id_carrier = $carrier->id; } if ($carrier->need_range) { $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost); } else { $shipping_cost = $module->getOrderShippingCostExternal($this); } // Check if carrier is available if ($shipping_cost === false) { return false; } } else { return false; } } // Apply tax if (isset($carrierTax)) { $shipping_cost *= 1 + $carrierTax / 100; } return (double) Tools::ps_round((double) $shipping_cost, 2); }
/** * @return InvoicePosition */ protected function _createInvoicePositionShippingCost() { $invoicePosition = new InvoicePosition(); if (_PS_VERSION_ < 1.5) { $carrier = new \Carrier($this->_order->id); $shipping = $this->_shipping; $tax = \Tax::getCarrierTaxRate($carrier->id, $this->_order->id_address_delivery); $invoicePosition->{InvoicePosition::KEY_JEDNOSTKA} = self::DEFAULT_SHIPPING_UNIT_NAME; $invoicePosition->{InvoicePosition::KEY_STAWKA_VAT} = (string) ($tax / 100); $invoicePosition->{InvoicePosition::KEY_ILOSC} = 1; $invoicePosition->{InvoicePosition::KEY_CENA_JEDNOSTKOWA} = $this->_roundPrice($shipping); $invoicePosition->{InvoicePosition::KEY_NAZWA_PELNA} = self::SHIPPING_NAME_PREFIX . $carrier->name; $invoicePosition->{InvoicePosition::KEY_TYP_STAWKI_VAT} = InvoicePosition::DEFAULT_VALUE_TYP_STAWKI_VAT; } else { $shipping = $this->_shipping[0]; $tax = \Tax::getCarrierTaxRate($shipping['id_carrier'], $this->_order->id_address_delivery); $invoicePosition->{InvoicePosition::KEY_JEDNOSTKA} = self::DEFAULT_SHIPPING_UNIT_NAME; $invoicePosition->{InvoicePosition::KEY_STAWKA_VAT} = (string) ($tax / 100); $invoicePosition->{InvoicePosition::KEY_ILOSC} = 1; $invoicePosition->{InvoicePosition::KEY_CENA_JEDNOSTKOWA} = $this->_roundPrice($shipping['shipping_cost_tax_incl']); $invoicePosition->{InvoicePosition::KEY_NAZWA_PELNA} = self::SHIPPING_NAME_PREFIX . $shipping['state_name']; $invoicePosition->{InvoicePosition::KEY_TYP_STAWKI_VAT} = InvoicePosition::DEFAULT_VALUE_TYP_STAWKI_VAT; } return $invoicePosition; }
/** * Récupération du prix de shipping pour un produit id * @param $shipping * @return float */ public function getShippingPrice($product_id, $attribute_id, $id_carrier = 0, $id_zone = 0) { $product = new Product($product_id); $shipping = 0; $carrier = new Carrier((int) $id_carrier); if ($id_zone == 0) { $defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT')); $id_zone = (int) $defaultCountry->id_zone; } $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id); $free_weight = Configuration::get('PS_SHIPPING_FREE_WEIGHT'); $shipping_handling = Configuration::get('PS_SHIPPING_HANDLING'); if ($product->getPrice(true, $attribute_id, 2, NULL, false, true, 1) >= (double) $free_weight and (double) $free_weight > 0) { $shipping = 0; } elseif (isset($free_weight) and $product->weight >= (double) $free_weight and (double) $free_weight > 0) { $shipping = 0; } else { if (isset($shipping_handling) and $carrier->shipping_handling) { $shipping = (double) $shipping_handling; } if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) { $shipping += $carrier->getDeliveryPriceByWeight($product->weight, $id_zone); } else { $shipping += $carrier->getDeliveryPriceByPrice($product->getPrice(true, $attribute_id, 2, NULL, false, true, 1), $id_zone); } $shipping *= 1 + $carrierTax / 100; $shipping = (double) Tools::ps_round((double) $shipping, 2); } unset($product); return $shipping; }
/** * 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, $link, $cookie; $id_payment_state = _PS_PS_NOT_PAID_; $cart = new Cart((int) $id_cart); // Does order already exists ? if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) { if ($secure_key !== false and $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->id_address_delivery); $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_customization = $cart->getCartCustomizationCost(); $order->total_donation = round($cookie->donation_amount); unset($cookie->donation_amount); if (strpos($order->payment, 'COD') === false) { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true)); } else { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false)); $order->total_cod = COD_CHARGE; } $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->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; $shippingdate = $cart->getExpectedShippingDate(); $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); // 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(round($order->total_paid)) != number_format(round($order->total_paid_real))) { $id_order_state = _PS_OS_ERROR_; $id_payment_state = _PS_PS_NOT_PAID_; } else { if (strpos($order->payment, 'COD') === false) { $id_payment_state = _PS_PS_PAID_; } } //update payment status // Creating order if ($cart->OrderExists() == false) { $cart_value = $cart->getOrderTotal(); if ($cart_value >= 1000) { //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL)) //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE); } $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`, `customization`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; 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 != _PS_OS_CANCELED_ and $id_order_state != _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; } if ($product['stock_quantity'] < 1) { SolrSearch::updateProduct((int) $product['id_product']); } 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')}); // 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 (Tax::excludeTaxeOption()) { $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')}); } $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; $specificPrice = 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 . ', ' . (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) . ', ' . (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) . ', ' . (double) Group::getReduction((int) $order->id_customer) . ', ' . $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) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),'; $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) { if ($text['index'] == 8) { $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 1) { $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 2) { $customizationText .= 'Stitched to measure blouse.' . '<br />'; } else { if ($text['index'] == 3) { $customizationText .= 'Stitched to measure in-skirt.' . '<br />'; } else { if ($text['index'] == 4) { $customizationText .= 'Stitched to measure kurta.' . '<br />'; } else { if ($text['index'] == 5) { $customizationText .= 'Stitched to measure salwar.' . '<br />'; } } } } } } } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= sizeof($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;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $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 * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $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;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $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) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> </tr>'; } //if giftcard, create voucher and send the mails now. $categories = Product::getProductCategories($product['id_product']); if (in_array(CAT_GIFTCARD, $categories)) { $friendsName = ''; $friendsEmail = ''; $giftMessage = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { if ($text['index'] == 21) { $friendsName = $text['value']; } else { if ($text['index'] == 22) { $friendsEmail = $text['value']; } else { if ($text['index'] == 23) { $giftMessage = $text['value']; } else { if ($text['index'] == 25) { $couponCode = $text['value']; } } } } } } } //$couponCode = "GC" . Tools::rand_string(8); // create discount $languages = Language::getLanguages($order); $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = $product['name']; } $voucher->value = (double) $unitPrice; $voucher->name = $couponCode; $voucher->id_currency = 2; //USD $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = 0; $voucher->active = 1; $voucher->cart_display = 0; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365); /* 365 days */ $voucher->add(); $productObj = new Product($product['id_product'], true, 1); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $params = array(); $params['{voucher_code}'] = $voucher->name; $params['{freinds_name}'] = $friendsName; $params['{gift_message}'] = $giftMessage; $params['{product_name}'] = $product['name']; $params['{voucher_value}'] = $voucher->value; $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location; $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname; $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card'; @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); // 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'], $order->id_lang); $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 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; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $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 != _PS_OS_ERROR_ and $id_order_state != _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) and $outOfStock) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(_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); //Payment status $paymentHistory = new OrderPaymentHistory(); $paymentHistory->id_order = (int) $order->id; $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id); $paymentHistory->addState(); // Order is reloaded because the status just changed $order = new Order($order->id); //Update tracking code for quantium if ($order->id_carrier == QUANTIUM) { if (strpos($order->payment, 'COD') === false) { $order->shipping_number = 'VBN' . $order->id; } else { $order->shipping_number = 'VBC' . $order->id; } $order->update(); } else { if ($order->id_carrier == SABEXPRESS) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } else { if ($order->id_carrier == AFL) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } } } // Send an e-mail to customer if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) { //deduct reward points $points_redeemed = $cart->getPoints(); if ($points_redeemed) { VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add); } /* if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0) { VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add); } */ $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; $shippingdate = new DateTime($order->expected_shipping_date); $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{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}' => date("F j, Y, g:i a"), '{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_cod - $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_cod}' => Tools::displayPrice($order->total_cod, $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'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = NULL; } if (Validate::isEmail($customer->email)) { if ($id_order_state == _PS_OS_BANKWIRE_) { Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } else { $data['payment'] = 'Online Payment'; Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } //Send SMS //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com'; //Tools::sendSMS($delivery->phone_mobile, $smsText); } $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 can\'t be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }