// Merging multishipping branche on 1.5

This commit is contained in:
mDeflotte
2011-11-18 11:13:31 +00:00
parent bc06976a52
commit 0df1a7e2eb
41 changed files with 2870 additions and 889 deletions
+95 -2
View File
@@ -92,13 +92,29 @@ class CarrierCore extends ObjectModel
/** @var int Position */
public $position;
/** @var int maximum package width managed by the transporter */
public $max_width;
/** @var int maximum package height managed by the transporter */
public $max_height;
/** @var int maximum package deep managed by the transporter */
public $max_depth;
/** @var int maximum package weight managed by the transporter */
public $max_weight;
/** @var int grade of the shipping delay (0 for longest, 9 for shortest) */
public $grade;
protected $langMultiShop = true;
protected $fieldsRequired = array('name', 'active');
protected $fieldsSize = array('name' => 64);
protected $fieldsSize = array('name' => 64, 'grade' => 1);
protected $fieldsValidate = array('id_tax_rules_group' => 'isInt', 'name' => 'isCarrierName', 'active' => 'isBool',
'is_free' => 'isBool', 'url' => 'isAbsoluteUrl', 'shipping_handling' => 'isBool', 'range_behavior' => 'isBool',
'shipping_method' => 'isUnsignedInt');
'shipping_method' => 'isUnsignedInt', 'max_width' => 'isUnsignedInt', 'max_height' => 'isUnsignedInt',
'max_deep' => 'isUnsignedInt', 'max_weight' => 'isUnsignedInt', 'grade' => 'isUnsignedInt');
protected $fieldsRequiredLang = array('delay');
protected $fieldsSizeLang = array('delay' => 128);
protected $fieldsValidateLang = array('delay' => 'isGenericName');
@@ -138,6 +154,11 @@ class CarrierCore extends ObjectModel
$fields['external_module_name'] = $this->external_module_name;
$fields['need_range'] = $this->need_range;
$fields['position'] = (int)$this->position;
$fields['max_width'] = (int)$this->max_width;
$fields['max_height'] = (int)$this->max_height;
$fields['max_depth'] = (int)$this->max_depth;
$fields['max_weight'] = (int)$this->max_weight;
$fields['grade'] = (int)$this->grade;
return $fields;
}
@@ -553,6 +574,7 @@ class CarrierCore extends ObjectModel
}
// if we have to sort carriers by price
$prices = array();
if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE)
{
foreach ($results_array as $r)
@@ -993,5 +1015,76 @@ class CarrierCore extends ObjectModel
$position = DB::getInstance()->getValue($sql);
return ($position !== false) ? $position : -1;
}
/**
* For a given {product, warehouse}, gets the carrier available
*
* @param $product integer The id of the product, or an array with at least the package size and weight
*/
public static function getAvailableCarrierList($product, $id_warehouse, $id_shop = null)
{
if(is_numeric($product))
$product = new Product((int)$product);
else if (is_array($product))
{
$product['id'] = $product['id_product'];
$product = (object)$product;
}
if (is_null($id_shop))
$id_shop = Context::getContext()->shop->getID(true);
// Does the product is linked with carriers?
$query = new DbQuery();
$query->select('id_carrier');
$query->from('product_carrier pc');
$query->innerJoin('carrier c ON (c.id_reference = pc.id_carrier_reference AND c.deleted = 0)');
$query->where('id_product = '.(int)($product->id));
$query->where('id_shop = '.(int)$id_shop);
$carriers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
if (!empty($carriers))
{
$carrier_list = array();
foreach ($carriers as $carrier)
$carrier_list[] = $carrier['id_carrier'];
return $carrier_list;
}
$carrier_list = array();
// The product is not dirrectly linked with a carrier
// Get all the carriers linked to a warehouse
if ($id_warehouse)
{
$warehouse = new Warehouse($id_warehouse);
$carrier_list = $warehouse->getCarriers();
}
if (empty($carrier_list)) // No carriers defined, get all available carriers
{
$carrier_list = array();
$id_address = ((isset($product->id_address_delivery) && $product->id_address_delivery != 0) ? $product->id_address_delivery : Context::getContext()->cart->id_address_delivery);
$address = new Address($id_address);
$id_zone = Address::getZoneById($address->id);
$carriers = Carrier::getCarriersForOrder($id_zone, Context::getContext()->customer->getGroups());
foreach ($carriers as $carrier)
$carrier_list[] = $carrier['id_carrier'];
}
if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0)
{
foreach ($carrier_list as $key => $id_carrier)
{
$carrier = new Carrier($id_carrier);
if (($carrier->max_width > 0 && $carrier->max_width < $product->width)
|| ($carrier->max_height > 0 && $carrier->max_height > $product->height)
|| ($carrier->max_depth > 0 && $carrier->max_depth > $product->depth)
|| ($carrier->max_weight > 0 && $carrier->max_weight > $product->weight)
)
unset($carrier_list[$key]);
}
}
return $carrier_list;
}
}
+932 -117
View File
File diff suppressed because it is too large Load Diff
+16 -14
View File
@@ -366,44 +366,46 @@ class HookCore extends ObjectModel
static public function orderConfirmation($id_order)
{
if (Validate::isUnsignedId($id_order))
{
if (Validate::isUnsignedId($id_order))
{
$params = array();
$order = new Order((int)$id_order);
$currency = new Currency((int)$order->id_currency);
if (Validate::isLoadedObject($order))
{
$params['total_to_pay'] = $order->total_paid;
if (Validate::isLoadedObject($order))
{
$cart = new Cart((int)$order->id_cart);
$params['total_to_pay'] = $cart->getOrderTotal();
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Hook::exec('orderConfirmation', $params);
}
}
}
return false;
return false;
}
static public function paymentReturn($id_order, $id_module)
{
if (Validate::isUnsignedId($id_order) AND Validate::isUnsignedId($id_module))
{
if (Validate::isUnsignedId($id_order) AND Validate::isUnsignedId($id_module))
{
$params = array();
$order = new Order((int)($id_order));
$currency = new Currency((int)($order->id_currency));
if (Validate::isLoadedObject($order))
{
$params['total_to_pay'] = $order->total_paid;
if (Validate::isLoadedObject($order))
{
$cart = new Cart((int)$order->id_cart);
$params['total_to_pay'] = $cart->getOrderTotal();
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Hook::exec('paymentReturn', $params, (int)($id_module));
}
}
return false;
}
return false;
}
static public function PDFInvoice($pdf, $id_order)
+141 -102
View File
@@ -21,69 +21,69 @@
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 7331 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class OrderCore extends ObjectModel
{
/** @var integer Delivery address id */
public $id_address_delivery;
public $id_address_delivery;
/** @var integer Invoice address id */
public $id_address_invoice;
public $id_address_invoice;
public $id_group_shop;
public $id_group_shop;
public $id_shop;
public $id_shop;
/** @var integer Cart id */
public $id_cart;
public $id_cart;
/** @var integer Currency id */
public $id_currency;
public $id_currency;
/** @var integer Language id */
public $id_lang;
public $id_lang;
/** @var integer Customer id */
public $id_customer;
public $id_customer;
/** @var integer Carrier id */
public $id_carrier;
public $id_carrier;
/** @var string Secure key */
public $secure_key;
public $secure_key;
/** @var string Payment method */
public $payment;
public $payment;
/** @var string Payment module */
public $module;
public $module;
/** @var float Currency conversion rate */
public $conversion_rate;
public $conversion_rate;
/** @var boolean Customer is ok for a recyclable package */
public $recyclable = 1;
public $recyclable = 1;
/** @var boolean True if the customer wants a gift wrapping */
public $gift = 0;
public $gift = 0;
/** @var string Gift message if specified */
public $gift_message;
public $gift_message;
/** @var string Shipping number */
public $shipping_number;
public $shipping_number;
/** @var float Discounts total */
public $total_discounts;
public $total_discounts;
public $total_discounts_tax_incl;
public $total_discounts_tax_excl;
/** @var float Total to pay */
public $total_paid;
public $total_paid;
/** @var float Total to pay tax included */
public $total_paid_tax_incl;
@@ -92,16 +92,16 @@ class OrderCore extends ObjectModel
public $total_paid_tax_excl;
/** @var float Total really paid */
public $total_paid_real;
public $total_paid_real;
/** @var float Products total */
public $total_products;
public $total_products;
/** @var float Products total tax excluded */
public $total_products_wt;
public $total_products_wt;
/** @var float Shipping total */
public $total_shipping;
public $total_shipping;
/** @var float Shipping total tax included */
public $total_shipping_tax_incl;
@@ -110,10 +110,10 @@ class OrderCore extends ObjectModel
public $total_shipping_tax_excl;
/** @var float Shipping tax rate */
public $carrier_tax_rate;
public $carrier_tax_rate;
/** @var float Wrapping total */
public $total_wrapping;
public $total_wrapping;
/** @var float Wrapping total tax included */
public $total_wrapping_tax_incl;
@@ -122,30 +122,38 @@ class OrderCore extends ObjectModel
public $total_wrapping_tax_excl;
/** @var integer Invoice number */
public $invoice_number;
public $invoice_number;
/** @var integer Delivery number */
public $delivery_number;
public $delivery_number;
/** @var string Invoice creation date */
public $invoice_date;
public $invoice_date;
/** @var string Delivery creation date */
public $delivery_date;
public $delivery_date;
/** @var boolean Order validity (paid and not canceled) */
public $valid;
public $valid;
/** @var string Object creation date */
public $date_add;
public $date_add;
/** @var string Object last modification date */
public $date_upd;
public $date_upd;
/** @var string Order reference
* This reference is not unique, but unique for a payment
*/
public $reference;
/** @var int Id warehouse */
public $id_warehouse;
protected $tables = array ('orders');
protected $fieldsRequired = array('conversion_rate', 'id_address_delivery', 'id_address_invoice', 'id_cart', 'id_currency', 'id_lang', 'id_customer', 'id_carrier', 'payment', 'total_paid', 'total_paid_real', 'total_products', 'total_products_wt');
protected $fieldsValidate = array(
protected $fieldsRequired = array('conversion_rate', 'id_address_delivery', 'id_address_invoice', 'id_cart', 'id_currency', 'id_lang', 'id_customer', 'id_carrier', 'payment', 'total_paid', 'total_paid_real', 'total_products', 'total_products_wt');
protected $fieldsValidate = array(
'id_address_delivery' => 'isUnsignedId',
'id_address_invoice' => 'isUnsignedId',
'id_cart' => 'isUnsignedId',
@@ -155,6 +163,7 @@ class OrderCore extends ObjectModel
'id_lang' => 'isUnsignedId',
'id_customer' => 'isUnsignedId',
'id_carrier' => 'isUnsignedId',
'id_warehouse' => 'isUnsignedId',
'secure_key' => 'isMd5',
'payment' => 'isGenericName',
'recyclable' => 'isBool',
@@ -172,7 +181,7 @@ class OrderCore extends ObjectModel
'conversion_rate' => 'isFloat'
);
protected $webserviceParameters = array(
protected $webserviceParameters = array(
'objectMethods' => array('add' => 'addWs'),
'objectNodeName' => 'order',
'objectsNodeName' => 'orders',
@@ -209,9 +218,9 @@ class OrderCore extends ObjectModel
);
/* MySQL does not allow 'order' for a table name */
protected $table = 'orders';
protected $identifier = 'id_order';
protected $_taxCalculationMethod = PS_TAX_EXC;
protected $table = 'orders';
protected $identifier = 'id_order';
protected $_taxCalculationMethod = PS_TAX_EXC;
protected static $_historyCache = array();
@@ -262,6 +271,8 @@ class OrderCore extends ObjectModel
$fields['valid'] = (int)($this->valid) ? 1 : 0;
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
$fields['reference'] = pSQL($this->reference);
$fields['id_warehouse'] = pSQL($this->id_warehouse);
return $fields;
}
@@ -321,7 +332,7 @@ class OrderCore extends ObjectModel
$productPrice = number_format($quantity * $price, 2, '.', '');
/* Update cart */
$cart = new Cart($this->id_cart);
$cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down'); // customization are deleted in deleteCustomization
$cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 0, 'down'); // customization are deleted in deleteCustomization
$cart->update();
/* Update order */
@@ -335,7 +346,7 @@ class OrderCore extends ObjectModel
if ($this->total_products_wt != 0)
$this->total_products_wt -= $productPrice;
$this->total_shipping = $cart->getOrderShippingCost();
$this->total_shipping = $cart->getTotalShippingCost();
/* It's temporary fix for 1.3 version... */
if ($orderDetail->product_quantity_discount != '0.000000')
@@ -731,16 +742,16 @@ class OrderCore extends ObjectModel
* @return array Customer orders
*/
static public function getCustomerOrders($id_customer, $showHiddenStatus = false, Context $context = null)
{
{
if (!$context)
$context = Context::getContext();
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT o.*, (SELECT SUM(od.`product_quantity`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = o.`id_order`) nb_products
FROM `'._DB_PREFIX_.'orders` o
WHERE o.`id_customer` = '.(int)$id_customer.'
GROUP BY o.`id_order`
ORDER BY o.`date_add` DESC');
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT o.*, (SELECT SUM(od.`product_quantity`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = o.`id_order`) nb_products
FROM `'._DB_PREFIX_.'orders` o
WHERE o.`id_customer` = '.(int)$id_customer.'
GROUP BY o.`id_order`
ORDER BY o.`date_add` DESC');
if (!$res)
return array();
@@ -760,7 +771,7 @@ class OrderCore extends ObjectModel
}
return $res;
}
}
public static function getOrdersIdByDate($date_from, $date_to, $id_customer = NULL, $type = NULL)
{
@@ -839,22 +850,22 @@ class OrderCore extends ObjectModel
return $orders;
}
/**
* Get product total without taxes
*
* @return Product total with taxes
*/
public function getTotalProductsWithoutTaxes($products = false)
/**
* Get product total without taxes
*
* @return Product total with taxes
*/
public function getTotalProductsWithoutTaxes($products = false)
{
return $this->total_products;
}
/**
* Get product total with taxes
*
* @return Product total with taxes
*/
public function getTotalProductsWithTaxes($products = false)
/**
* Get product total with taxes
*
* @return Product total with taxes
*/
public function getTotalProductsWithTaxes($products = false)
{
if ($this->total_products_wt != '0.00' AND !$products)
return $this->total_products_wt;
@@ -895,15 +906,15 @@ class OrderCore extends ObjectModel
* @return array Customer orders number
*/
public static function getCustomerNbOrders($id_customer)
{
$sql = 'SELECT COUNT(`id_order`) AS nb
{
$sql = 'SELECT COUNT(`id_order`) AS nb
FROM `'._DB_PREFIX_.'orders`
WHERE `id_customer` = '.(int)$id_customer
.Context::getContext()->shop->addSqlRestriction();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
.Context::getContext()->shop->addSqlRestriction();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return isset($result['nb']) ? $result['nb'] : 0;
}
}
/**
* Get an order by its cart id
@@ -912,26 +923,26 @@ class OrderCore extends ObjectModel
* @return array Order details
*/
public static function getOrderByCartId($id_cart)
{
$sql = 'SELECT `id_order`
{
$sql = 'SELECT `id_order`
FROM `'._DB_PREFIX_.'orders`
WHERE `id_cart` = '.(int)($id_cart)
.Context::getContext()->shop->addSqlRestriction();
$result = Db::getInstance()->getRow($sql);
.Context::getContext()->shop->addSqlRestriction();
$result = Db::getInstance()->getRow($sql);
return isset($result['id_order']) ? $result['id_order'] : false;
}
}
/**
/**
* @deprecated 1.5.0.1
*/
public function addDiscount($id_cart_rule, $name, $value)
public function addDiscount($id_cart_rule, $name, $value)
{
Tools::displayAsDeprecated();
return Order::addCartRule($id_cart_rule, $name, $value);
}
public function addCartRule($id_cart_rule, $name, $value)
public function addCartRule($id_cart_rule, $name, $value)
{
return Db::getInstance()->AutoExecute(_DB_PREFIX_.'order_cart_rule', array('id_order' => (int)$this->id, 'id_cart_rule' => (int)$id_cart_rule, 'name' => pSQL($name), 'value' => (float)$value), 'INSERT');
}
@@ -961,38 +972,38 @@ class OrderCore extends ObjectModel
}
public static function getLastInvoiceNumber()
{
return (int)Db::getInstance()->getValue('
SELECT MAX(`invoice_number`) AS `invoice_number`
public static function getLastInvoiceNumber()
{
return (int)Db::getInstance()->getValue('
SELECT MAX(`invoice_number`) AS `invoice_number`
FROM `'._DB_PREFIX_.'orders`');
}
}
public function setInvoice()
{
$number = (int)Configuration::get('PS_INVOICE_START_NUMBER');
if ($number)
Configuration::updateValue('PS_INVOICE_START_NUMBER', false);
else
$number = '(SELECT `invoice_number`
FROM (
SELECT MAX(`invoice_number`) + 1 AS `invoice_number`
FROM `'._DB_PREFIX_.'orders`)
tmp )';
// a way to avoid duplicate invoice number
Configuration::updateValue('PS_INVOICE_START_NUMBER', false);
else
$number = '(SELECT `invoice_number`
FROM (
SELECT MAX(`invoice_number`) + 1 AS `invoice_number`
FROM `'._DB_PREFIX_.'orders`)
tmp )';
// a way to avoid duplicate invoice number
Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'orders`
SET `invoice_number` = '.$number.', `invoice_date` = \''.date('Y-m-d H:i:s').'\'
WHERE `id_order` = '.(int)$this->id
);
$res = Db::getInstance()->getRow('
SELECT `invoice_number`, `invoice_date`
FROM `'._DB_PREFIX_.'orders`
$res = Db::getInstance()->getRow('
SELECT `invoice_number`, `invoice_date`
FROM `'._DB_PREFIX_.'orders`
WHERE `id_order` = '.(int)$this->id
);
);
$this->invoice_date = $res['invoice_date'];
$this->invoice_number = $res['invoice_number'];
$this->invoice_date = $res['invoice_date'];
$this->invoice_number = $res['invoice_number'];
}
public function setDelivery()
@@ -1034,10 +1045,10 @@ class OrderCore extends ObjectModel
public static function getByDelivery($id_delivery)
{
$sql = 'SELECT id_order
FROM `'._DB_PREFIX_.'orders`
WHERE `delivery_number` = '.(int)($id_delivery).'
'.Context::getContext()->shop->addSqlRestriction();
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
FROM `'._DB_PREFIX_.'orders`
WHERE `delivery_number` = '.(int)($id_delivery).'
'.Context::getContext()->shop->addSqlRestriction();
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return new Order((int)($res['id_order']));
}
@@ -1108,10 +1119,10 @@ class OrderCore extends ObjectModel
SELECT `invoice_number`, `invoice_date`, `delivery_number`, `delivery_date`
FROM `'._DB_PREFIX_.'orders`
WHERE `id_order` = '.(int)$this->id);
$this->invoice_date = $res['invoice_date'];
$this->invoice_number = $res['invoice_number'];
$this->delivery_date = $res['delivery_date'];
$this->delivery_number = $res['delivery_number'];
$this->invoice_date = $res['invoice_date'];
$this->invoice_number = $res['invoice_number'];
$this->delivery_date = $res['delivery_date'];
$this->delivery_number = $res['delivery_number'];
$history->addWithemail();
}
@@ -1166,6 +1177,35 @@ class OrderCore extends ObjectModel
return OrderDetail::getList($this->id);
}
/**
* Gennerate a unique reference for orders generated with the same cart id
* This references, is usefull for check payment
*
* @return String
*/
public static function generateReference()
{
// To generate a random reference, we first generate a random number
// This number is a rand concated with the current timestamp
$rand = (int)(microtime(true) * 100 % 10000000000).rand(10, 1000);
$reference = '';
do {
$reference .= chr(65 + $rand % 26);
$rand = (int)($rand / 26);
} while ($rand > 26);
// Check if semi-random string generated is not already used
// /!\ Here we CANNOT/MUSTN'T use _PS_USE_SQL_SLAVE_
if (Db::getInstance()->getValue('
SELECT count(*)
FROM '._DB_PREFIX_.'orders
WHERE reference = \''.$reference.'\'') > 0)
return self::generateReference(); // If the reference already exists, generate a new one
return $reference;
}
public function orderContainProduct($id_product)
{
$product_list = $this->getOrderDetailList();
@@ -1174,7 +1214,6 @@ class OrderCore extends ObjectModel
return true;
return false;
}
/**
* This method returns true if at least one order details uses the
* One After Another tax computation method.
+2 -2
View File
@@ -522,13 +522,13 @@ class OrderDetailCore extends ObjectModel
* @param object $cart
* @param int $id_order_status
*/
public function createList(Order $order, Cart $cart, $id_order_state)
public function createList(Order $order, Cart $cart, $id_order_state, $product_list)
{
$this->vat_address = new Address((int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$this->customer = new Customer((int)($order->id_customer));
$this->id_order = $order->id;
$products = $cart->getProducts();
$products = $product_list;
$this->outOfStock = false;
foreach ($products as $product)
+329 -287
View File
@@ -114,309 +114,351 @@ abstract class PaymentModuleCore extends Module
{
if ($secure_key !== false AND $secure_key != $cart->secure_key)
die(Tools::displayError());
// Be carefull, carrier may not exist
$carrier = new Carrier($cart->id_carrier, $cart->id_lang);
// Copying data from cart
$order = new Order();
$order->id_carrier = (int)$carrier->id;
$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);
$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);
$order->id_shop = (int)($shop->getID() ? $shop->getID() : $cart->id_shop);
$order->id_group_shop = (int)($shop->getID() ? $shop->getGroupID() : $cart->id_group_shop);
$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((float)($amountPaid), 2) : $amountPaid;
$order->total_paid_real = $amountPaid;
$order->total_products = (float)$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
$order->total_products_wt = (float)$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
$order->total_discounts = (float)abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
$order->total_discounts_tax_excl = (float)abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
$order->total_discounts_tax_incl = (float)abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
$order->total_shipping = (float)$cart->getOrderShippingCost();
$order->total_shipping_tax_excl = (float)$cart->getOrderShippingCost(NULL, false);
$order->total_shipping_tax_incl = (float)$cart->getOrderShippingCost();
if (Validate::isLoadedObject($carrier))
$order->carrier_tax_rate = $carrier->getTaxesRate(new Address($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$order->total_wrapping = (float)abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
$order->total_wrapping_tax_excl = (float)abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
$order->total_wrapping_tax_incl = (float)abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
$order->total_paid = (float)Tools::ps_round((float)($cart->getOrderTotal(true, Cart::BOTH)), 2);
$order->total_paid_tax_excl = (float)Tools::ps_round((float)($cart->getOrderTotal(false, Cart::BOTH)), 2);
$order->total_paid_tax_incl = (float)Tools::ps_round((float)($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
// For each package, generate an order
$delivery_option_list = $cart->getDeliveryOptionList();
$package_list = $cart->getPackageList();
$cart_delivery_option = unserialize($cart->delivery_option);
foreach ($delivery_option_list as $id_address => $package)
{
if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package))
die('Error: delivery option for some addresses is not defined');
}
$order_list = array();
$order_detail_list = array();
$reference = Order::generateReference();
$this->currentOrderReference = $reference;
$id_currency = $currency_special ? (int)($currency_special) : (int)($cart->id_currency);
$currency = new Currency($id_currency);
$this->context->cart->order_reference = $reference;
$orderCreationFailed = false;
$cart_total_paid = (float)Tools::ps_round((float)($cart->getOrderTotal(true, Cart::BOTH)), 2);
if ($cart->orderExists())
{
$errorMessage = Tools::displayError('An order has already been placed using this cart.');
Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
die($errorMessage);
}
foreach ($cart_delivery_option as $id_address => $key_carriers)
foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data)
foreach ($data['package_list'] as $id_package)
{
$product_list = $package_list[$id_address][$id_package]['product_list'];
$carrier = new Carrier($id_carrier, $cart->id_lang);
$order = new Order();
$order->id_carrier = (int)$carrier->id;
$order->id_customer = (int)($cart->id_customer);
$order->id_address_invoice = (int)($cart->id_address_invoice);
$order->id_address_delivery = (int)$id_address;
$order->id_currency = $id_currency;
$order->id_lang = (int)($cart->id_lang);
$order->id_warehouse = $package_list[$id_address][$id_package]['id_warehouse'];
$order->id_cart = (int)($cart->id);
$order->reference = $reference;
$order->id_shop = (int)($shop->getID() ? $shop->getID() : $cart->id_shop);
$order->id_group_shop = (int)($shop->getID() ? $shop->getGroupID() : $cart->id_group_shop);
$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;
$order->conversion_rate = $currency->conversion_rate;
$amountPaid = !$dont_touch_amount ? Tools::ps_round((float)($amountPaid), 2) : $amountPaid;
$order->total_paid_real = $amountPaid;
$order->total_products = (float)$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $product_list, $id_carrier);
$order->total_products_wt = (float)$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $product_list, $id_carrier);
$order->total_discounts = (float)abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $product_list, $id_carrier));
$order->total_discounts_tax_excl = (float)abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $product_list, $id_carrier));
$order->total_discounts_tax_incl = (float)abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $product_list, $id_carrier));
$order->total_shipping = (float)$cart->getPackageShippingCost((int)$id_carrier, true, null, $product_list, $id_carrier);
$order->total_shipping_tax_excl = (float)$cart->getPackageShippingCost((int)$id_carrier, false, null, $product_list, $id_carrier);
$order->total_shipping_tax_incl = (float)$cart->getPackageShippingCost((int)$id_carrier, true, null, $product_list, $id_carrier);
if (Validate::isLoadedObject($carrier))
$order->carrier_tax_rate = $carrier->getTaxesRate(new Address($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$order->total_wrapping = (float)abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $product_list, $id_carrier));
$order->total_wrapping_tax_excl = (float)abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $product_list, $id_carrier));
$order->total_wrapping_tax_incl = (float)abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $product_list, $id_carrier));
$order->total_paid = (float)Tools::ps_round((float)($cart->getOrderTotal(true, Cart::BOTH, $product_list, $id_carrier)), 2);
$order->total_paid_tax_excl = (float)Tools::ps_round((float)($cart->getOrderTotal(false, Cart::BOTH, $product_list, $id_carrier)), 2);
$order->total_paid_tax_incl = (float)Tools::ps_round((float)($cart->getOrderTotal(true, Cart::BOTH, $product_list, $id_carrier)), 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($cart_total_paid, 2) != number_format($order->total_paid_real, 2))
$id_order_state = Configuration::get('PS_OS_ERROR');
// Creating order
$result = $order->add();
$order_list[] = $order;
// Insert new Order detail list using cart for the current order
$order_detail = new OrderDetail($this->context);
$order_detail->createList($order, $cart, $id_order_state, $product_list);
$order_detail_list[] = $order_detail;
}
$this->addPCC($reference, $id_currency, $amountPaid);
// Next !
if ($result AND isset($order->id))
foreach ($order_detail_list as $key => $order_detail)
{
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))
$order = $order_list[$key];
if (!$orderCreationFailed AND isset($order->id))
{
$msg = new Message();
$message = strip_tags($message, '<br>');
if (Validate::isCleanHtml($message))
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->message = $message;
$msg->id_order = intval($order->id);
$msg->private = 1;
$msg->add();
}
}
// Insert new Order detail list using cart for the current order
$orderDetail = new OrderDetail($this->context);
$orderDetail->createList($order, $cart, $id_order_state);
$this->addPCC($order->id, $order->id_currency, $amountPaid);
// Insert products from cart into order_detail table
$productsList = '';
$products = $cart->getProducts();
foreach ($products AS $key => $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')}));
$customizationQuantity = 0;
if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']]))
{
$customizationText = '';
foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] AS $customization)
$msg = new Message();
$message = strip_tags($message, '<br>');
if (Validate::isCleanHtml($message))
{
if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD]))
foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] AS $text)
$customizationText .= $text['name'].':'.' '.$text['value'].'<br />';
if (isset($customization['datas'][Product::CUSTOMIZE_FILE]))
$customizationText .= sizeof($customization['datas'][Product::CUSTOMIZE_FILE]) .' '. Tools::displayError('image(s)').'<br />';
$customizationText .= '---<br />';
$msg->message = $message;
$msg->id_order = intval($order->id);
$msg->private = 1;
$msg->add();
}
$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']) ? ' - '.$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 ? $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 * (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']) ? ' - '.$product['attributes'] : '').'</strong></td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice(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) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false).'</td>
</tr>';
} // end foreach ($products)
$cartRulesList = '';
$result = $cart->getCartRules();
$cartRules = ObjectModel::hydrateCollection('CartRule', $result, (int)$order->id_lang);
foreach ($cartRules AS $cartRule)
{
$value = $cartRule->getContextualValue(true);
// Todo: repair shrunk
// 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 ($cartRule->id_discount_type == Discount::AMOUNT AND $cartRule->behavior_not_exhausted == 2)
// {
// $voucher = new Discount();
// foreach ($cartRule AS $key => $discountValue)
// $voucher->$key = $discountValue;
// $voucher->name = 'VSRK'.(int)$order->id_customer.'O'.(int)$order->id;
// $voucher->value = (float)$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;
// @Mail::Send((int)$order->id_lang, 'voucher', Mail::l('New voucher regarding your order #').$order->id, $params, $customer->email, $customer->firstname.' '.$customer->lastname);
// }
// }
$order->addCartRule($cartRule->id, $cartRule->name, $value);
if ($id_order_state != Configuration::get('PS_OS_ERROR') AND $id_order_state != Configuration::get('PS_OS_CANCELED'))
$cartRule->quantity = $cartRule->quantity - 1;
$cartRule->update();
$cartRulesList .= '
<tr style="background-color:#EBECEE;">
<td colspan="4" style="padding:0.6em 0.4em;text-align:right">'.$this->l('Voucher name:').' '.$cartRule->name.'</td>
<td style="padding:0.6em 0.4em;text-align:right">'.($value != 0.00 ? '-' : '').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 validate order
$orderStatus = new OrderState((int)$id_order_state, (int)$order->id_lang);
if (Validate::isLoadedObject($orderStatus))
{
Hook::exec('newOrder', array('cart' => $cart, 'order' => $order, 'customer' => $customer, 'currency' => $currency, 'orderStatus' => $orderStatus));
foreach ($cart->getProducts() AS $product)
if ($orderStatus->logable)
ProductSale::addProductSale((int)$product['id_product'], (int)$product['cart_quantity']);
}
if (Configuration::get('PS_STOCK_MANAGEMENT') && $orderDetail->getStockState())
{
$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);
unset($orderDetail, $pcc);
// 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));
$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}' => $cartRulesList,
'{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)
// Insert new Order detail list using cart for the current order
//$orderDetail = new OrderDetail($this->context);
//$orderDetail->createList($order, $cart, $id_order_state);
//$this->addPCC($order->id, $order->id_currency, $amountPaid);
// Construct order detail table for the email
$productsList = '';
$products = $cart->getProducts();
foreach ($products AS $key => $product)
{
$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';
$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')}));
$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'][Product::CUSTOMIZE_TEXTFIELD]))
foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] AS $text)
$customizationText .= $text['name'].':'.' '.$text['value'].'<br />';
if (isset($customization['datas'][Product::CUSTOMIZE_FILE]))
$customizationText .= sizeof($customization['datas'][Product::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']) ? ' - '.$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 ? $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 * (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']) ? ' - '.$product['attributes'] : '').'</strong></td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice(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) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false).'</td>
</tr>';
} // end foreach ($products)
$cartRulesList = '';
$result = $cart->getCartRules();
$cartRules = ObjectModel::hydrateCollection('CartRule', $result, (int)$order->id_lang);
// @todo How to menage cart rules, with multiple shipping?
foreach ($cartRules AS $cartRule)
{
$value = $cartRule->getContextualValue(true);
// Todo: repair shrunk
// 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 ($cartRule->id_discount_type == Discount::AMOUNT AND $cartRule->behavior_not_exhausted == 2)
// {
// $voucher = new Discount();
// foreach ($cartRule AS $key => $discountValue)
// $voucher->$key = $discountValue;
// $voucher->name = 'VSRK'.(int)$order->id_customer.'O'.(int)$order->id;
// $voucher->value = (float)$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;
// @Mail::Send((int)$order->id_lang, 'voucher', Mail::l('New voucher regarding your order #').$order->id, $params, $customer->email, $customer->firstname.' '.$customer->lastname);
// }
// }
$order->addCartRule($cartRule->id, $cartRule->name, $value);
if ($id_order_state != Configuration::get('PS_OS_ERROR') AND $id_order_state != Configuration::get('PS_OS_CANCELED'))
$cartRule->quantity = $cartRule->quantity - 1;
$cartRule->update();
$cartRulesList .= '
<tr style="background-color:#EBECEE;">
<td colspan="4" style="padding:0.6em 0.4em;text-align:right">'.$this->l('Voucher name:').' '.$cartRule->name.'</td>
<td style="padding:0.6em 0.4em;text-align:right">'.($value != 0.00 ? '-' : '').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 validate order
$orderStatus = new OrderState((int)$id_order_state, (int)$order->id_lang);
if (Validate::isLoadedObject($orderStatus))
{
Hook::exec('newOrder', array('cart' => $cart, 'order' => $order, 'customer' => $customer, 'currency' => $currency, 'orderStatus' => $orderStatus));
foreach ($cart->getProducts() AS $product)
if ($orderStatus->logable)
ProductSale::addProductSale((int)$product['id_product'], (int)$product['cart_quantity']);
}
if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState())
{
$history = new OrderHistory();
$history->id_order = (int)$order->id;
$history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int)$order->id);
$history->addWithemail();
}
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);
// 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);
unset($order_detail, $pcc);
// Order is reloaded because the status just changed
$order = new Order($order->id);
// Send an e-mail to customer (one order = one email)
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));
$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}' => $cartRulesList,
'{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);
}
}
else
{
$errorMessage = Tools::displayError('Order creation failed');
Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
die($errorMessage);
}
$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);
}
// Use the last order as currentOrder
$this->currentOrder = (int)$order->id;
return true;
}
else
{
@@ -432,11 +474,11 @@ abstract class PaymentModuleCore extends Module
* @var int id_currency
* @var float amount
*/
private function addPCC($id_order, $id_currency, $amount)
private function addPCC($reference, $id_currency, $amount)
{
// Other information are set by the module
$this->pcc->id_order = (int)$id_order;
$this->pcc->order_reference = (int)$reference;
$this->pcc->id_currency = (int)$id_currency;
$this->pcc->amount = (float)$amount;
$this->pcc->add();
+43 -7
View File
@@ -1696,6 +1696,38 @@ class ProductCore extends ObjectModel
{
return Product::getProductCategories($this->id);
}
/**
* Gets carriers assigned to the product
*/
public function getCarriers()
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.*
FROM `'._DB_PREFIX_.'product_carrier` pc
INNER JOIN `'._DB_PREFIX_.'carrier` c
ON (c.`id_reference` = pc.`id_carrier_reference` AND c.`deleted` = 0)
WHERE pc.`id_product` = '.(int)$this->id.'
AND pc.`id_shop` = '.(int)$this->id_shop);
}
/**
* Sets carriers assigned to the product
*/
public function setCarriers($carrier_list)
{
$data = array();
foreach($carrier_list as $carrier)
{
$data[] = array(
'id_product' => (int)$this->id,
'id_carrier_reference' => (int)$carrier,
'id_shop' => (int)$this->id_shop
);
}
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'product_carrier` WHERE id_product = '.(int)$this->id.' AND id_shop = '.(int)$this->id_shop);
Db::getInstance()->AutoExecute(_DB_PREFIX_.'product_carrier', $data, 'INSERT');
}
/**
* Get product images and legends
@@ -2994,7 +3026,7 @@ class ProductCore extends ObjectModel
$id_lang = Context::getContext()->language->id;
if (!$result = Db::getInstance()->executeS('
SELECT cd.`id_customization`, c.`id_product`, cfl.`id_customization_field`, c.`id_product_attribute`, cd.`type`, cd.`index`, cd.`value`, cfl.`name`
SELECT cd.`id_customization`, c.`id_address_delivery`, c.`id_product`, cfl.`id_customization_field`, c.`id_product_attribute`, cd.`type`, cd.`index`, cd.`value`, cfl.`name`
FROM `'._DB_PREFIX_.'customized_data` cd
NATURAL JOIN `'._DB_PREFIX_.'customization` c
LEFT JOIN `'._DB_PREFIX_.'customization_field_lang` cfl ON (cfl.id_customization_field = cd.`index` AND id_lang = '.(int)($id_lang).')
@@ -3004,21 +3036,24 @@ class ProductCore extends ObjectModel
return false;
$customizedDatas = array();
foreach ($result as $row)
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_customization'])]['datas'][(int)($row['type'])][] = $row;
if (!$result = Db::getInstance()->executeS('SELECT `id_product`, `id_product_attribute`, `id_customization`, `quantity`, `quantity_refunded`, `quantity_returned`
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_address_delivery'])][(int)($row['id_customization'])]['datas'][(int)($row['type'])][] = $row;
if (!$result = Db::getInstance()->executeS('SELECT `id_product`, `id_product_attribute`, `id_customization`, `id_address_delivery`, `quantity`, `quantity_refunded`, `quantity_returned`
FROM `'._DB_PREFIX_.'customization` WHERE `id_cart` = '.(int)($id_cart).($only_in_cart ? ' AND `in_cart` = 1' : '')))
return false;
foreach ($result as $row)
{
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_customization'])]['quantity'] = (int)($row['quantity']);
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_customization'])]['quantity_refunded'] = (int)($row['quantity_refunded']);
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_customization'])]['quantity_returned'] = (int)($row['quantity_returned']);
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_address_delivery'])][(int)($row['id_customization'])]['quantity'] = (int)($row['quantity']);
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_address_delivery'])][(int)($row['id_customization'])]['quantity_refunded'] = (int)($row['quantity_refunded']);
$customizedDatas[(int)($row['id_product'])][(int)($row['id_product_attribute'])][(int)($row['id_address_delivery'])][(int)($row['id_customization'])]['quantity_returned'] = (int)($row['quantity_returned']);
}
return $customizedDatas;
}
public static function addCustomizationPrice(&$products, &$customizedDatas)
{
if(!$customizedDatas)
return;
foreach ($products as &$productUpdate)
{
if (!Customization::isFeatureActive())
@@ -3035,11 +3070,12 @@ class ProductCore extends ObjectModel
/* Compatibility */
$productId = (int)(isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id']);
$productAttributeId = (int)(isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id']);
$id_address_delivery = (int)$productUpdate['id_address_delivery'];
$productQuantity = (int)(isset($productUpdate['cart_quantity']) ? $productUpdate['cart_quantity'] : $productUpdate['product_quantity']);
$price = isset($productUpdate['price']) ? $productUpdate['price'] : $productUpdate['product_price'];
$priceWt = $price * (1 + ((isset($productUpdate['tax_rate']) ? $productUpdate['tax_rate'] : $productUpdate['rate']) * 0.01));
if (isset($customizedDatas[$productId][$productAttributeId]))
foreach ($customizedDatas[$productId][$productAttributeId] as $customization)
foreach ($customizedDatas[$productId][$productAttributeId][$id_address_delivery] as $customization)
{
$customizationQuantity += (int)$customization['quantity'];
$customizationQuantityRefunded += (int)$customization['quantity_refunded'];
+14
View File
@@ -590,6 +590,20 @@ class ToolsCore
return $object;
}
/**
* Display a var dump in firebug console
*
* @param object $object Object to display
*/
public static function fd($object)
{
echo '
<script type="text/javascript">
console.log('.json_encode($object).');
</script>
';
}
/**
* ALIAS OF dieObject() - Display an error with detailed object
*
+23 -3
View File
@@ -250,13 +250,33 @@ class StockAvailableCore extends ObjectModel
/**
* Upgrades total_quantity_available after having saved
* @see ObjectModel::save()
* @see ObjectModel::add()
*/
public function save($null_values = false, $autodate = true)
public function add($autodate = true, $null_values = false)
{
if (!parent::save($null_values, $autodate))
if (!parent::add($autodate, $null_values))
return false;
$this->afterSave();
}
/**
* Upgrades total_quantity_available after having update
* @see ObjectModel::update()
*/
public function update($null_values = false)
{
if (!parent::update($null_values))
return false;
$this->afterSave();
}
/**
* Upgrades total_quantity_available after having saved
* @see StockAvailableCore::update()
* @see StockAvailableCore::add()
*/
public function afterSave()
{
if ($this->id_product_attribute == 0)
return true;
+24
View File
@@ -267,6 +267,30 @@ class WarehouseCore extends ObjectModel
return (Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query));
}
/**
* For a given {product, product attribute} gets warehouse list
*
* @param int $id_product
* @param int $id_product_attribute
* @param int $id_shop
* @return string
*/
public static function getProductWarehouseList($id_product, $id_product_attribute, $id_shop = null)
{
if (is_null($id_shop))
$id_shop = Context::getContext()->shop->getID(true);
$query = new DbQuery();
$query->select('wpl.id_warehouse');
$query->from('warehouse_product_location wpl');
$query->innerJoin('warehouse_shop ws ON (ws.id_warehouse = wpl.id_warehouse AND id_shop = '.(int)$id_shop.')');
$query->where('id_product = '.(int)$id_product);
$query->where('id_product_attribute = '.(int)$id_product_attribute);
$query->groupBy('wpl.id_warehouse');
return (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query));
}
/**
* Gets available warehouses