Advertisement
Guest User

Untitled

a guest
Nov 6th, 2012
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 59.41 KB | None | 0 0
  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @version Release: $Revision: 7331 $
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. * International Registered Trademark & Property of PrestaShop SA
  26. */
  27.  
  28. class OrderCore extends ObjectModel
  29. {
  30. /** @var integer Delivery address id */
  31. public $id_address_delivery;
  32.  
  33. /** @var integer Invoice address id */
  34. public $id_address_invoice;
  35.  
  36. public $id_shop_group;
  37.  
  38. public $id_shop;
  39.  
  40. /** @var integer Cart id */
  41. public $id_cart;
  42.  
  43. /** @var integer Currency id */
  44. public $id_currency;
  45.  
  46. /** @var integer Language id */
  47. public $id_lang;
  48.  
  49. /** @var integer Customer id */
  50. public $id_customer;
  51.  
  52. /** @var integer Carrier id */
  53. public $id_carrier;
  54.  
  55. /** @var integer Order State id */
  56. public $current_state;
  57.  
  58. /** @var string Secure key */
  59. public $secure_key;
  60.  
  61. /** @var string Payment method */
  62. public $payment;
  63.  
  64. /** @var string Payment module */
  65. public $module;
  66.  
  67. /** @var float Currency conversion rate */
  68. public $conversion_rate;
  69.  
  70. /** @var boolean Customer is ok for a recyclable package */
  71. public $recyclable = 1;
  72.  
  73. /** @var boolean True if the customer wants a gift wrapping */
  74. public $gift = 0;
  75.  
  76. /** @var string Gift message if specified */
  77. public $gift_message;
  78.  
  79. /**
  80. * @var string Shipping number
  81. * @deprecated 1.5.0.4
  82. * @see OrderCarrier->tracking_number
  83. */
  84. public $shipping_number;
  85.  
  86. /** @var float Discounts total */
  87. public $total_discounts;
  88.  
  89. public $total_discounts_tax_incl;
  90. public $total_discounts_tax_excl;
  91.  
  92. /** @var float Total to pay */
  93. public $total_paid;
  94.  
  95. /** @var float Total to pay tax included */
  96. public $total_paid_tax_incl;
  97.  
  98. /** @var float Total to pay tax excluded */
  99. public $total_paid_tax_excl;
  100.  
  101. /** @var float Total really paid @deprecated 1.5.0.1 */
  102. public $total_paid_real;
  103.  
  104. /** @var float Products total */
  105. public $total_products;
  106.  
  107. /** @var float Products total tax included */
  108. public $total_products_wt;
  109.  
  110. /** @var float Shipping total */
  111. public $total_shipping;
  112.  
  113. /** @var float Shipping total tax included */
  114. public $total_shipping_tax_incl;
  115.  
  116. /** @var float Shipping total tax excluded */
  117. public $total_shipping_tax_excl;
  118.  
  119. /** @var float Shipping tax rate */
  120. public $carrier_tax_rate;
  121.  
  122. /** @var float Wrapping total */
  123. public $total_wrapping;
  124.  
  125. /** @var float Wrapping total tax included */
  126. public $total_wrapping_tax_incl;
  127.  
  128. /** @var float Wrapping total tax excluded */
  129. public $total_wrapping_tax_excl;
  130.  
  131. /** @var integer Invoice number */
  132. public $invoice_number;
  133.  
  134. /** @var integer Delivery number */
  135. public $delivery_number;
  136.  
  137. /** @var string Invoice creation date */
  138. public $invoice_date;
  139.  
  140. /** @var string Delivery creation date */
  141. public $delivery_date;
  142.  
  143. /** @var boolean Order validity (paid and not canceled) */
  144. public $valid;
  145.  
  146. /** @var string Object creation date */
  147. public $date_add;
  148.  
  149. /** @var string Object last modification date */
  150. public $date_upd;
  151.  
  152. /**
  153. * @var string Order reference, this reference is not unique, but unique for a payment
  154. */
  155. public $reference;
  156.  
  157. /**
  158. * @see ObjectModel::$definition
  159. */
  160. public static $definition = array(
  161. 'table' => 'orders',
  162. 'primary' => 'id_order',
  163. 'fields' => array(
  164. 'id_address_delivery' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  165. 'id_address_invoice' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  166. 'id_cart' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  167. 'id_currency' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  168. 'id_shop_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  169. 'id_shop' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  170. 'id_lang' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  171. 'id_customer' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  172. 'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  173. 'current_state' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  174. 'secure_key' => array('type' => self::TYPE_STRING, 'validate' => 'isMd5'),
  175. 'payment' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true),
  176. 'module' => array('type' => self::TYPE_STRING),
  177. 'recyclable' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  178. 'gift' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  179. 'gift_message' => array('type' => self::TYPE_STRING, 'validate' => 'isMessage'),
  180. 'total_discounts' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  181. 'total_discounts_tax_incl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  182. 'total_discounts_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  183. 'total_paid' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true),
  184. 'total_paid_tax_incl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  185. 'total_paid_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  186. 'total_paid_real' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true),
  187. 'total_products' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true),
  188. 'total_products_wt' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true),
  189. 'total_shipping' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  190. 'total_shipping_tax_incl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  191. 'total_shipping_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  192. 'carrier_tax_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
  193. 'total_wrapping' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  194. 'total_wrapping_tax_incl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  195. 'total_wrapping_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
  196. 'shipping_number' => array('type' => self::TYPE_STRING, 'validate' => 'isTrackingNumber'),
  197. 'conversion_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat', 'required' => true),
  198. 'invoice_number' => array('type' => self::TYPE_INT),
  199. 'delivery_number' => array('type' => self::TYPE_INT),
  200. 'invoice_date' => array('type' => self::TYPE_DATE),
  201. 'delivery_date' => array('type' => self::TYPE_DATE),
  202. 'valid' => array('type' => self::TYPE_BOOL),
  203. 'reference' => array('type' => self::TYPE_STRING),
  204. 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  205. 'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  206. ),
  207. );
  208.  
  209. protected $webserviceParameters = array(
  210. 'objectMethods' => array('add' => 'addWs'),
  211. 'objectNodeName' => 'order',
  212. 'objectsNodeName' => 'orders',
  213. 'fields' => array(
  214. 'id_address_delivery' => array('xlink_resource'=> 'addresses'),
  215. 'id_address_invoice' => array('xlink_resource'=> 'addresses'),
  216. 'id_cart' => array('xlink_resource'=> 'carts'),
  217. 'id_currency' => array('xlink_resource'=> 'currencies'),
  218. 'id_lang' => array('xlink_resource'=> 'languages'),
  219. 'id_customer' => array('xlink_resource'=> 'customers'),
  220. 'id_carrier' => array('xlink_resource'=> 'carriers'),
  221. 'current_state' => array('xlink_resource'=> 'order_states'),
  222. 'module' => array('required' => true),
  223. 'invoice_number' => array(),
  224. 'invoice_date' => array(),
  225. 'delivery_number' => array(),
  226. 'delivery_date' => array(),
  227. 'valid' => array(),
  228. 'date_add' => array(),
  229. 'date_upd' => array(),
  230. ),
  231. 'associations' => array(
  232. 'order_rows' => array('resource' => 'order_row', 'setter' => false, 'virtual_entity' => true,
  233. 'fields' => array(
  234. 'id' => array(),
  235. 'product_id' => array('required' => true),
  236. 'product_attribute_id' => array('required' => true),
  237. 'product_quantity' => array('required' => true),
  238. 'product_name' => array('setter' => false),
  239. 'product_price' => array('setter' => false),
  240. )),
  241. ),
  242.  
  243. );
  244.  
  245. protected $_taxCalculationMethod = PS_TAX_EXC;
  246.  
  247. protected static $_historyCache = array();
  248.  
  249. public function __construct($id = null, $id_lang = null)
  250. {
  251. parent::__construct($id, $id_lang);
  252. if ($this->id_customer)
  253. {
  254. $customer = new Customer((int)($this->id_customer));
  255. $this->_taxCalculationMethod = Group::getPriceDisplayMethod((int)($customer->id_default_group));
  256. }
  257. else
  258. $this->_taxCalculationMethod = Group::getDefaultPriceDisplayMethod();
  259. }
  260.  
  261. /**
  262. * @see ObjectModel::getFields()
  263. * @return array
  264. */
  265. public function getFields()
  266. {
  267. if (!$this->id_lang)
  268. $this->id_lang = Configuration::get('PS_LANG_DEFAULT');
  269.  
  270. return parent::getFields();
  271. }
  272.  
  273. public function add($autodate = true, $null_values = true)
  274. {
  275. if (parent::add($autodate, $null_values))
  276. return SpecificPrice::deleteByIdCart($this->id_cart);
  277. return false;
  278. }
  279.  
  280. public function getTaxCalculationMethod()
  281. {
  282. return (int)($this->_taxCalculationMethod);
  283. }
  284.  
  285. /* Does NOT delete a product but "cancel" it (which means return/refund/delete it depending of the case) */
  286. public function deleteProduct($order, $orderDetail, $quantity)
  287. {
  288. if (!(int)($this->getCurrentState()))
  289. return false;
  290.  
  291. if ($this->hasBeenDelivered())
  292. {
  293. if (!Configuration::get('PS_ORDER_RETURN'))
  294. throw new PrestaShopException('PS_ORDER_RETURN is not defined in table configuration');
  295. $orderDetail->product_quantity_return += (int)($quantity);
  296. return $orderDetail->update();
  297. }
  298. elseif ($this->hasBeenPaid())
  299. {
  300. $orderDetail->product_quantity_refunded += (int)($quantity);
  301. return $orderDetail->update();
  302. }
  303. return $this->_deleteProduct($orderDetail, (int)$quantity);
  304. }
  305.  
  306. /**
  307. * This function return products of the orders
  308. * It's similar to Order::getProducts but witrh similar outputs of Cart::getProducts
  309. *
  310. * @return array
  311. */
  312. public function getCartProducts()
  313. {
  314. $product_id_list = array();
  315. foreach ($this->getProducts() as $product)
  316. $product_id_list[] = $this->id_address_delivery.'_'
  317. .$product['product_id'].'_'
  318. .$product['product_attribute_id'].'_'
  319. .(isset($product['id_customization']) ? $product['id_customization'] : '0');
  320.  
  321. $product_list = array();
  322. foreach ($this->getProducts() as $product)
  323. {
  324. $key = $this->id_address_delivery.'_'
  325. .$product['id_product'].'_'
  326. .(isset($product['id_product_attribute']) ? $product['id_product_attribute'] : '0').'_'
  327. .(isset($product['id_customization']) ? $product['id_customization'] : '0');
  328.  
  329. if (in_array($key, $product_id_list))
  330. $product_list[] = $product;
  331. }
  332. return $product_list;
  333. }
  334.  
  335. /* DOES delete the product */
  336. protected function _deleteProduct($orderDetail, $quantity)
  337. {
  338. $product_price_tax_excl = $orderDetail->unit_price_tax_excl * $quantity;
  339. $product_price_tax_incl = $orderDetail->unit_price_tax_incl * $quantity;
  340.  
  341. /* Update cart */
  342. $cart = new Cart($this->id_cart);
  343. $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down'); // customization are deleted in deleteCustomization
  344. $cart->update();
  345.  
  346. /* Update order */
  347. $shipping_diff_tax_incl = $this->total_shipping_tax_incl - $cart->getPackageShippingCost($this->id_carrier, true, null, $this->getCartProducts());
  348. $shipping_diff_tax_excl = $this->total_shipping_tax_excl - $cart->getPackageShippingCost($this->id_carrier, false, null, $this->getCartProducts());
  349. $this->total_shipping -= $shipping_diff_tax_incl;
  350. $this->total_shipping_tax_excl -= $shipping_diff_tax_excl;
  351. $this->total_shipping_tax_incl -= $shipping_diff_tax_incl;
  352. $this->total_products -= $product_price_tax_excl;
  353. $this->total_products_wt -= $product_price_tax_incl;
  354. $this->total_paid -= $product_price_tax_incl + $shipping_diff_tax_incl;
  355. $this->total_paid_tax_incl -= $product_price_tax_incl + $shipping_diff_tax_incl;
  356. $this->total_paid_tax_excl -= $product_price_tax_excl + $shipping_diff_tax_excl;
  357. $this->total_paid_real -= $product_price_tax_incl + $shipping_diff_tax_incl;
  358.  
  359. $fields = array(
  360. 'total_shipping',
  361. 'total_shipping_tax_excl',
  362. 'total_shipping_tax_incl',
  363. 'total_products',
  364. 'total_products_wt',
  365. 'total_paid',
  366. 'total_paid_tax_incl',
  367. 'total_paid_tax_excl',
  368. 'total_paid_real'
  369. );
  370.  
  371. /* Prevent from floating precision issues (total_products has only 2 decimals) */
  372. foreach ($fields as $field)
  373. if ($this->{$field} < 0)
  374. $this->{$field} = 0;
  375.  
  376. /* Prevent from floating precision issues */
  377. foreach ($fields as $field)
  378. $this->{$field} = number_format($this->{$field}, 2, '.', '');
  379.  
  380. /* Update order detail */
  381. $orderDetail->product_quantity -= (int)$quantity;
  382. if ($orderDetail->product_quantity == 0)
  383. {
  384. if (!$orderDetail->delete())
  385. return false;
  386. if (count($this->getProductsDetail()) == 0)
  387. {
  388. $history = new OrderHistory();
  389. $history->id_order = (int)($this->id);
  390. $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), $this);
  391. if (!$history->addWithemail())
  392. return false;
  393. }
  394. return $this->update();
  395. }
  396. else
  397. {
  398. $orderDetail->total_price_tax_incl -= $product_price_tax_incl;
  399. $orderDetail->total_price_tax_excl -= $product_price_tax_excl;
  400. $orderDetail->total_shipping_price_tax_incl -= $shipping_diff_tax_incl;
  401. $orderDetail->total_shipping_price_tax_excl -= $shipping_diff_tax_excl;
  402. }
  403. return $orderDetail->update() && $this->update();
  404. }
  405.  
  406. public function deleteCustomization($id_customization, $quantity, $orderDetail)
  407. {
  408. if (!(int)($this->getCurrentState()))
  409. return false;
  410.  
  411. if ($this->hasBeenDelivered())
  412. return Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity_returned` = `quantity_returned` + '.(int)($quantity).' WHERE `id_customization` = '.(int)($id_customization).' AND `id_cart` = '.(int)($this->id_cart).' AND `id_product` = '.(int)($orderDetail->product_id));
  413. elseif ($this->hasBeenPaid())
  414. return Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity_refunded` = `quantity_refunded` + '.(int)($quantity).' WHERE `id_customization` = '.(int)($id_customization).' AND `id_cart` = '.(int)($this->id_cart).' AND `id_product` = '.(int)($orderDetail->product_id));
  415. if (!Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity` = `quantity` - '.(int)($quantity).' WHERE `id_customization` = '.(int)($id_customization).' AND `id_cart` = '.(int)($this->id_cart).' AND `id_product` = '.(int)($orderDetail->product_id)))
  416. return false;
  417. if (!Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'customization` WHERE `quantity` = 0'))
  418. return false;
  419. return $this->_deleteProduct($orderDetail, (int)$quantity);
  420. }
  421.  
  422. /**
  423. * Get order history
  424. *
  425. * @param integer $id_lang Language id
  426. * @param integer $id_order_state Filter a specific order state
  427. * @param integer $no_hidden Filter no hidden status
  428. * @param integer $filters Flag to use specific field filter
  429. *
  430. * @return array History entries ordered by date DESC
  431. */
  432. public function getHistory($id_lang, $id_order_state = false, $no_hidden = false, $filters = 0)
  433. {
  434. if (!$id_order_state)
  435. $id_order_state = 0;
  436.  
  437. $logable = false;
  438. $delivery = false;
  439. $paid = false;
  440. $shipped = false;
  441. if ($filters > 0)
  442. {
  443. if ($filters & OrderState::FLAG_NO_HIDDEN)
  444. $no_hidden = true;
  445. if ($filters & OrderState::FLAG_DELIVERY)
  446. $delivery = true;
  447. if ($filters & OrderState::FLAG_LOGABLE)
  448. $logable = true;
  449. if ($filters & OrderState::FLAG_PAID)
  450. $paid = true;
  451. if ($filters & OrderState::FLAG_SHIPPED)
  452. $shipped = true;
  453. }
  454.  
  455. if (!isset(self::$_historyCache[$this->id.'_'.$id_order_state.'_'.$filters]) || $no_hidden)
  456. {
  457. $id_lang = $id_lang ? (int)($id_lang) : 'o.`id_lang`';
  458. $result = Db::getInstance()->executeS('
  459. SELECT oh.*, e.`firstname` AS employee_firstname, e.`lastname` AS employee_lastname, osl.`name` AS ostate_name
  460. FROM `'._DB_PREFIX_.'orders` o
  461. LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON o.`id_order` = oh.`id_order`
  462. LEFT JOIN `'._DB_PREFIX_.'order_state` os ON os.`id_order_state` = oh.`id_order_state`
  463. LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)($id_lang).')
  464. LEFT JOIN `'._DB_PREFIX_.'employee` e ON e.`id_employee` = oh.`id_employee`
  465. WHERE oh.id_order = '.(int)($this->id).'
  466. '.($no_hidden ? ' AND os.hidden = 0' : '').'
  467. '.($logable ? ' AND os.logable = 1' : '').'
  468. '.($delivery ? ' AND os.delivery = 1' : '').'
  469. '.($paid ? ' AND os.paid = 1' : '').'
  470. '.($shipped ? ' AND os.shipped = 1' : '').'
  471. '.((int)($id_order_state) ? ' AND oh.`id_order_state` = '.(int)($id_order_state) : '').'
  472. ORDER BY oh.date_add DESC, oh.id_order_history DESC');
  473. if ($no_hidden)
  474. return $result;
  475. self::$_historyCache[$this->id.'_'.$id_order_state.'_'.$filters] = $result;
  476. }
  477. return self::$_historyCache[$this->id.'_'.$id_order_state.'_'.$filters];
  478. }
  479.  
  480. public function getProductsDetail()
  481. {
  482. return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  483. SELECT *
  484. FROM `'._DB_PREFIX_.'order_detail` od
  485. LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = od.product_id)
  486. LEFT JOIN `'._DB_PREFIX_.'product_shop` ps ON (ps.id_product = p.id_product AND ps.id_shop = od.id_shop)
  487. WHERE od.`id_order` = '.(int)($this->id));
  488. }
  489.  
  490. public function getFirstMessage()
  491. {
  492. return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
  493. SELECT `message`
  494. FROM `'._DB_PREFIX_.'message`
  495. WHERE `id_order` = '.(int)$this->id.'
  496. ORDER BY `id_message`
  497. ');
  498. }
  499.  
  500. /**
  501. * Marked as deprecated but should not throw any "deprecated" message
  502. * This function is used in order to keep front office backward compatibility 14 -> 1.5
  503. * (Order History)
  504. *
  505. * @deprecated
  506. */
  507. public function setProductPrices(&$row)
  508. {
  509. $tax_calculator = OrderDetail::getTaxCalculatorStatic((int)$row['id_order_detail']);
  510. $row['tax_calculator'] = $tax_calculator;
  511. $row['tax_rate'] = $tax_calculator->getTotalRate();
  512.  
  513. $row['product_price'] = Tools::ps_round($row['unit_price_tax_excl'], 2);
  514. $row['product_price_wt'] = Tools::ps_round($row['unit_price_tax_incl'], 2);
  515.  
  516. $group_reduction = 1;
  517. if ($row['group_reduction'] > 0)
  518. $group_reduction = 1 - $row['group_reduction'] / 100;
  519.  
  520. $row['product_price_wt_but_ecotax'] = $row['product_price_wt'] - $row['ecotax'];
  521.  
  522. $row['total_wt'] = $row['total_price_tax_incl'];
  523. $row['total_price'] = $row['total_price_tax_excl'];
  524. }
  525.  
  526.  
  527. /**
  528. * Get order products
  529. *
  530. * @return array Products with price, quantity (with taxe and without)
  531. */
  532. public function getProducts($products = false, $selectedProducts = false, $selectedQty = false)
  533. {
  534. if (!$products)
  535. $products = $this->getProductsDetail();
  536.  
  537. $customized_datas = Product::getAllCustomizedDatas($this->id_cart);
  538.  
  539. $resultArray = array();
  540. foreach ($products as $row)
  541. {
  542. // Change qty if selected
  543. if ($selectedQty)
  544. {
  545. $row['product_quantity'] = 0;
  546. foreach ($selectedProducts as $key => $id_product)
  547. if ($row['id_order_detail'] == $id_product)
  548. $row['product_quantity'] = (int)($selectedQty[$key]);
  549. if (!$row['product_quantity'])
  550. continue;
  551. }
  552.  
  553. $this->setProductImageInformations($row);
  554. $this->setProductCurrentStock($row);
  555.  
  556. // Backward compatibility 1.4 -> 1.5
  557. $this->setProductPrices($row);
  558.  
  559. $this->setProductCustomizedDatas($row, $customized_datas);
  560.  
  561. // Add information for virtual product
  562. if ($row['download_hash'] && !empty($row['download_hash']))
  563. {
  564. $row['filename'] = ProductDownload::getFilenameFromIdProduct((int)$row['product_id']);
  565. // Get the display filename
  566. $row['display_filename'] = ProductDownload::getFilenameFromFilename($row['filename']);
  567. }
  568.  
  569. $row['id_address_delivery'] = $this->id_address_delivery;
  570.  
  571. /* Stock product */
  572. $resultArray[(int)$row['id_order_detail']] = $row;
  573. }
  574.  
  575. if ($customized_datas)
  576. Product::addCustomizationPrice($resultArray, $customized_datas);
  577.  
  578. return $resultArray;
  579. }
  580.  
  581. public static function getIdOrderProduct($id_customer, $id_product)
  582. {
  583. return (int)Db::getInstance()->getValue('
  584. SELECT o.id_order
  585. FROM '._DB_PREFIX_.'orders o
  586. LEFT JOIN '._DB_PREFIX_.'order_detail od
  587. ON o.id_order = od.id_order
  588. WHERE o.id_customer = '.(int)$id_customer.'
  589. AND od.product_id = '.(int)$id_product.'
  590. ORDER BY o.date_add DESC
  591. ');
  592. }
  593.  
  594. protected function setProductCustomizedDatas(&$product, $customized_datas)
  595. {
  596. $product['customizedDatas'] = null;
  597. if (isset($customized_datas[$product['product_id']][$product['product_attribute_id']]))
  598. $product['customizedDatas'] = $customized_datas[$product['product_id']][$product['product_attribute_id']];
  599. else
  600. $product['customizationQuantityTotal'] = 0;
  601. }
  602.  
  603. /**
  604. *
  605. * This method allow to add stock information on a product detail
  606. *
  607. * If advanced stock management is active, get physical stock of this product in the warehouse associated to the ptoduct for the current order
  608. * Else get the available quantity of the product in fucntion of the shop associated to the order
  609. *
  610. * @param array &$product
  611. */
  612. protected function setProductCurrentStock(&$product)
  613. {
  614. if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')
  615. && (int)$product['advanced_stock_management'] == 1
  616. && (int)$product['id_warehouse'] > 0)
  617. $product['current_stock'] = StockManagerFactory::getManager()->getProductPhysicalQuantities($product['product_id'], $product['product_attribute_id'], (int)$product['id_warehouse'], true);
  618. else
  619. $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], (int)$this->id_shop);
  620. }
  621.  
  622. /**
  623. *
  624. * This method allow to add image information on a product detail
  625. * @param array &$product
  626. */
  627. protected function setProductImageInformations(&$product)
  628. {
  629. if (isset($product['product_attribute_id']) && $product['product_attribute_id'])
  630. $id_image = Db::getInstance()->getValue('
  631. SELECT image_shop.id_image
  632. FROM '._DB_PREFIX_.'product_attribute_image pai'.
  633. Shop::addSqlAssociation('image', 'pai', true).'
  634. WHERE id_product_attribute = '.(int)$product['product_attribute_id']);
  635.  
  636. if (!isset($id_image) || !$id_image)
  637. $id_image = Db::getInstance()->getValue('
  638. SELECT image_shop.id_image
  639. FROM '._DB_PREFIX_.'image i'.
  640. Shop::addSqlAssociation('image', 'i', true, 'image_shop.cover=1').'
  641. WHERE id_product = '.(int)($product['product_id'])
  642. );
  643.  
  644. $product['image'] = null;
  645. $product['image_size'] = null;
  646.  
  647. if ($id_image)
  648. $product['image'] = new Image($id_image);
  649. }
  650.  
  651. public function getTaxesAverageUsed()
  652. {
  653. return Cart::getTaxesAverageUsed((int)($this->id_cart));
  654. }
  655.  
  656. /**
  657. * Count virtual products in order
  658. *
  659. * @return int number of virtual products
  660. */
  661. public function getVirtualProducts()
  662. {
  663. $sql = '
  664. SELECT `product_id`, `product_attribute_id`, `download_hash`, `download_deadline`
  665. FROM `'._DB_PREFIX_.'order_detail` od
  666. WHERE od.`id_order` = '.(int)($this->id).'
  667. AND `download_hash` <> \'\'';
  668. return Db::getInstance()->executeS($sql);
  669. }
  670.  
  671. /**
  672. * Check if order contains (only) virtual products
  673. *
  674. * @param boolean $strict If false return true if there are at least one product virtual
  675. * @return boolean true if is a virtual order or false
  676. *
  677. */
  678. public function isVirtual($strict = true)
  679. {
  680. $products = $this->getProducts();
  681. if (count($products) < 1)
  682. return false;
  683. $virtual = true;
  684. foreach ($products as $product)
  685. {
  686. $pd = ProductDownload::getIdFromIdProduct((int)($product['product_id']));
  687. if ($pd && Validate::isUnsignedInt($pd) && $product['download_hash'] && $product['display_filename'] != '')
  688. {
  689. if ($strict === false)
  690. return true;
  691. }
  692. else
  693. $virtual &= false;
  694. }
  695. return $virtual;
  696. }
  697.  
  698. /**
  699. * @deprecated 1.5.0.1
  700. */
  701. public function getDiscounts($details = false)
  702. {
  703. Tools::displayAsDeprecated();
  704. return Order::getCartRules();
  705. }
  706.  
  707. public function getCartRules()
  708. {
  709. return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  710. SELECT *
  711. FROM `'._DB_PREFIX_.'order_cart_rule` ocr
  712. LEFT JOIN `'._DB_PREFIX_.'cart_rule` cr ON cr.`id_cart_rule` = ocr.`id_cart_rule`
  713. WHERE ocr.`id_order` = '.(int)$this->id);
  714. }
  715.  
  716. public static function getDiscountsCustomer($id_customer, $id_cart_rule)
  717. {
  718. return Db::getInstance()->getValue('
  719. SELECT COUNT(*) FROM `'._DB_PREFIX_.'orders` o
  720. LEFT JOIN '._DB_PREFIX_.'order_cart_rule ocr ON (ocr.id_order = o.id_order)
  721. WHERE o.id_customer = '.(int)$id_customer.'
  722. AND ocr.id_cart_rule = '.(int)$id_cart_rule);
  723. }
  724.  
  725. /**
  726. * Get current order state (eg. Awaiting payment, Delivered...)
  727. *
  728. * @return int Order state id
  729. */
  730. public function getCurrentState()
  731. {
  732. return $this->current_state;
  733. }
  734.  
  735. /**
  736. * Get current order state name (eg. Awaiting payment, Delivered...)
  737. *
  738. * @return array Order state details
  739. */
  740. public function getCurrentStateFull($id_lang)
  741. {
  742. return Db::getInstance()->getRow('
  743. SELECT os.`id_order_state`, osl.`name`, os.`logable`, os.`shipped`
  744. FROM `'._DB_PREFIX_.'order_state` os
  745. LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (osl.`id_order_state` = os.`id_order_state`)
  746. WHERE osl.`id_lang` = '.(int)$id_lang.' AND os.`id_order_state` = '.(int)$this->current_state);
  747. }
  748.  
  749. public function hasBeenDelivered()
  750. {
  751. return count($this->getHistory((int)($this->id_lang), false, false, OrderState::FLAG_DELIVERY));
  752. }
  753.  
  754. /**
  755. * Has products returned by the merchant or by the customer?
  756. */
  757. public function hasProductReturned()
  758. {
  759. return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
  760. SELECT IFNULL(SUM(ord.product_quantity), SUM(product_quantity_return))
  761. FROM `'._DB_PREFIX_.'orders` o
  762. INNER JOIN `'._DB_PREFIX_.'order_detail` od
  763. ON od.id_order = o.id_order
  764. LEFT JOIN `'._DB_PREFIX_.'order_return_detail` ord
  765. ON ord.id_order_detail = od.id_order_detail
  766. WHERE o.id_order = '.(int)$this->id);
  767. }
  768.  
  769. public function hasBeenPaid()
  770. {
  771. return count($this->getHistory((int)($this->id_lang), false, false, OrderState::FLAG_PAID));
  772. }
  773.  
  774. public function hasBeenShipped()
  775. {
  776. return count($this->getHistory((int)($this->id_lang), false, false, OrderState::FLAG_SHIPPED));
  777. }
  778.  
  779. public function isInPreparation()
  780. {
  781. return count($this->getHistory((int)($this->id_lang), Configuration::get('PS_OS_PREPARATION')));
  782. }
  783.  
  784. /**
  785. * Checks if the current order state is paid and shipped
  786. *
  787. * @return bool
  788. */
  789. public function isPaidAndShipped()
  790. {
  791. $order_state = $this->getCurrentOrderState();
  792. if ($order_state && $order_state->paid && $order_state->shipped)
  793. return true;
  794. return false;
  795. }
  796.  
  797. /**
  798. * Get customer orders
  799. *
  800. * @param integer $id_customer Customer id
  801. * @param boolean $showHiddenStatus Display or not hidden order statuses
  802. * @return array Customer orders
  803. */
  804. public static function getCustomerOrders($id_customer, $showHiddenStatus = false, Context $context = null)
  805. {
  806. if (!$context)
  807. $context = Context::getContext();
  808.  
  809. $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  810. SELECT o.*, (SELECT SUM(od.`product_quantity`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = o.`id_order`) nb_products
  811. FROM `'._DB_PREFIX_.'orders` o
  812. WHERE o.`id_customer` = '.(int)$id_customer.'
  813. GROUP BY o.`id_order`
  814. ORDER BY o.`date_add` DESC');
  815. if (!$res)
  816. return array();
  817.  
  818. foreach ($res as $key => $val)
  819. {
  820. $res2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  821. SELECT os.`id_order_state`, osl.`name` AS order_state, os.`invoice`
  822. FROM `'._DB_PREFIX_.'order_history` oh
  823. LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`)
  824. INNER JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)$context->language->id.')
  825. WHERE oh.`id_order` = '.(int)($val['id_order']).(!$showHiddenStatus ? ' AND os.`hidden` != 1' : '').'
  826. ORDER BY oh.`date_add` DESC, oh.`id_order_history` DESC
  827. LIMIT 1');
  828.  
  829. if ($res2)
  830. $res[$key] = array_merge($res[$key], $res2[0]);
  831.  
  832. }
  833. return $res;
  834. }
  835.  
  836. public static function getOrdersIdByDate($date_from, $date_to, $id_customer = null, $type = null)
  837. {
  838. $sql = 'SELECT `id_order`
  839. FROM `'._DB_PREFIX_.'orders`
  840. WHERE DATE_ADD(date_upd, INTERVAL -1 DAY) <= \''.pSQL($date_to).'\' AND date_upd >= \''.pSQL($date_from).'\'
  841. '.Shop::addSqlRestriction()
  842. .($type ? ' AND '.pSQL(strval($type)).'_number != 0' : '')
  843. .($id_customer ? ' AND id_customer = '.(int)($id_customer) : '');
  844. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
  845.  
  846. $orders = array();
  847. foreach ($result as $order)
  848. $orders[] = (int)($order['id_order']);
  849. return $orders;
  850. }
  851.  
  852. public static function getOrdersWithInformations($limit = null, Context $context = null)
  853. {
  854. if (!$context)
  855. $context = Context::getContext();
  856.  
  857. $sql = 'SELECT *, (
  858. SELECT osl.`name`
  859. FROM `'._DB_PREFIX_.'order_state_lang` osl
  860. WHERE osl.`id_order_state` = o.`current_state`
  861. AND osl.`id_lang` = '.(int)$context->language->id.'
  862. LIMIT 1
  863. ) AS `state_name`
  864. FROM `'._DB_PREFIX_.'orders` o
  865. LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = o.`id_customer`)
  866. WHERE 1
  867. '.Shop::addSqlRestriction(false, 'o').'
  868. ORDER BY o.`date_add` DESC
  869. '.((int)$limit ? 'LIMIT 0, '.(int)$limit : '');
  870. return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
  871. }
  872.  
  873. /**
  874. * @deprecated since 1.5.0.2
  875. *
  876. * @static
  877. * @param $date_from
  878. * @param $date_to
  879. * @param $id_customer
  880. * @param $type
  881. *
  882. * @return array
  883. */
  884. public static function getOrdersIdInvoiceByDate($date_from, $date_to, $id_customer = null, $type = null)
  885. {
  886. Tools::displayAsDeprecated();
  887. $sql = 'SELECT `id_order`
  888. FROM `'._DB_PREFIX_.'orders`
  889. WHERE DATE_ADD(invoice_date, INTERVAL -1 DAY) <= \''.pSQL($date_to).'\' AND invoice_date >= \''.pSQL($date_from).'\'
  890. '.Shop::addSqlRestriction()
  891. .($type ? ' AND '.pSQL(strval($type)).'_number != 0' : '')
  892. .($id_customer ? ' AND id_customer = '.(int)($id_customer) : '').
  893. ' ORDER BY invoice_date ASC';
  894. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
  895.  
  896. $orders = array();
  897. foreach ($result as $order)
  898. $orders[] = (int)$order['id_order'];
  899. return $orders;
  900. }
  901.  
  902. /**
  903. * @deprecated 1.5.0.3
  904. *
  905. * @static
  906. * @param $id_order_state
  907. * @return array
  908. */
  909. public static function getOrderIdsByStatus($id_order_state)
  910. {
  911. Tools::displayAsDeprecated();
  912. $sql = 'SELECT id_order
  913. FROM '._DB_PREFIX_.'orders o
  914. WHERE o.`current_state` = '.(int)$id_order_state.'
  915. '.Shop::addSqlRestriction(false, 'o').'
  916. ORDER BY invoice_date ASC';
  917. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
  918.  
  919. $orders = array();
  920. foreach ($result as $order)
  921. $orders[] = (int)($order['id_order']);
  922. return $orders;
  923. }
  924.  
  925. /**
  926. * Get product total without taxes
  927. *
  928. * @return Product total with taxes
  929. */
  930. public function getTotalProductsWithoutTaxes($products = false)
  931. {
  932. return $this->total_products;
  933. }
  934.  
  935. /**
  936. * Get product total with taxes
  937. *
  938. * @return Product total with taxes
  939. */
  940. public function getTotalProductsWithTaxes($products = false)
  941. {
  942. if ($this->total_products_wt != '0.00' && !$products)
  943. return $this->total_products_wt;
  944. /* Retro-compatibility (now set directly on the validateOrder() method) */
  945.  
  946. if (!$products)
  947. $products = $this->getProductsDetail();
  948.  
  949. $return = 0;
  950. foreach ($products as $row)
  951. $return += $row['total_price_tax_incl'];
  952.  
  953. if (!$products)
  954. {
  955. $this->total_products_wt = $return;
  956. $this->update();
  957. }
  958. return $return;
  959. }
  960.  
  961. /**
  962. * Get order customer
  963. *
  964. * @return Customer $customer
  965. */
  966. public function getCustomer()
  967. {
  968. static $customer = null;
  969. if (is_null($customer))
  970. $customer = new Customer((int)$this->id_customer);
  971.  
  972. return $customer;
  973. }
  974.  
  975. /**
  976. * Get customer orders number
  977. *
  978. * @param integer $id_customer Customer id
  979. * @return array Customer orders number
  980. */
  981. public static function getCustomerNbOrders($id_customer)
  982. {
  983. $sql = 'SELECT COUNT(`id_order`) AS nb
  984. FROM `'._DB_PREFIX_.'orders`
  985. WHERE `id_customer` = '.(int)$id_customer
  986. .Shop::addSqlRestriction();
  987. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
  988.  
  989. return isset($result['nb']) ? $result['nb'] : 0;
  990. }
  991.  
  992. /**
  993. * Get an order by its cart id
  994. *
  995. * @param integer $id_cart Cart id
  996. * @return array Order details
  997. */
  998. public static function getOrderByCartId($id_cart)
  999. {
  1000. $sql = 'SELECT `id_order`
  1001. FROM `'._DB_PREFIX_.'orders`
  1002. WHERE `id_cart` = '.(int)($id_cart)
  1003. .Shop::addSqlRestriction();
  1004. $result = Db::getInstance()->getRow($sql);
  1005.  
  1006. return isset($result['id_order']) ? $result['id_order'] : false;
  1007. }
  1008.  
  1009. /**
  1010. * @deprecated 1.5.0.1
  1011. * @see Order::addCartRule()
  1012. * @param int $id_cart_rule
  1013. * @param string $name
  1014. * @param float $value
  1015. * @return bool
  1016. */
  1017. public function addDiscount($id_cart_rule, $name, $value)
  1018. {
  1019. Tools::displayAsDeprecated();
  1020. return Order::addCartRule($id_cart_rule, $name, array('tax_incl' => $value, 'tax_excl' => '0.00'));
  1021. }
  1022.  
  1023. /**
  1024. * @since 1.5.0.1
  1025. * @param int $id_cart_rule
  1026. * @param string $name
  1027. * @param array $values
  1028. * @param int $id_order_invoice
  1029. * @return bool
  1030. */
  1031. public function addCartRule($id_cart_rule, $name, $values, $id_order_invoice = 0)
  1032. {
  1033. $order_cart_rule = new OrderCartRule();
  1034. $order_cart_rule->id_order = $this->id;
  1035. $order_cart_rule->id_cart_rule = $id_cart_rule;
  1036. $order_cart_rule->id_order_invoice = $id_order_invoice;
  1037. $order_cart_rule->name = $name;
  1038. $order_cart_rule->value = $values['tax_incl'];
  1039. $order_cart_rule->value_tax_excl = $values['tax_excl'];
  1040. $order_cart_rule->add();
  1041. }
  1042.  
  1043. public function getNumberOfDays()
  1044. {
  1045. $nbReturnDays = (int)(Configuration::get('PS_ORDER_RETURN_NB_DAYS'));
  1046. if (!$nbReturnDays)
  1047. return true;
  1048. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
  1049. SELECT TO_DAYS(NOW()) - TO_DAYS(`delivery_date`) AS days FROM `'._DB_PREFIX_.'orders`
  1050. WHERE `id_order` = '.(int)($this->id));
  1051. if ($result['days'] <= $nbReturnDays)
  1052. return true;
  1053. return false;
  1054. }
  1055.  
  1056. /**
  1057. * Can this order be returned by the client?
  1058. *
  1059. * @return bool
  1060. */
  1061. public function isReturnable()
  1062. {
  1063. if (Configuration::get('PS_ORDER_RETURN') && $this->isPaidAndShipped())
  1064. return $this->getNumberOfDays();
  1065.  
  1066. return false;
  1067. }
  1068.  
  1069. public static function getLastInvoiceNumber()
  1070. {
  1071. return Db::getInstance()->getValue('
  1072. SELECT MAX(`number`)
  1073. FROM `'._DB_PREFIX_.'order_invoice`
  1074. ');
  1075. }
  1076.  
  1077. /**
  1078. * This method allows to generate first invoice of the current order
  1079. */
  1080. public function setInvoice($use_existing_payment = false)
  1081. {
  1082. if (!$this->hasInvoice())
  1083. {
  1084. $order_invoice = new OrderInvoice();
  1085. $order_invoice->id_order = $this->id;
  1086. $order_invoice->number = Configuration::get('PS_INVOICE_START_NUMBER');
  1087. // If invoice start number has been set, you clean the value of this configuration
  1088. if ($order_invoice->number)
  1089. Configuration::updateValue('PS_INVOICE_START_NUMBER', false );
  1090. else
  1091. $order_invoice->number = Order::getLastInvoiceNumber() + 1;
  1092.  
  1093. $invoice_address = new Address((int)$this->id_address_invoice);
  1094. $carrier = new Carrier((int)$this->id_carrier);
  1095. $tax_calculator = $carrier->getTaxCalculator($invoice_address);
  1096.  
  1097. $order_invoice->total_discount_tax_excl = $this->total_discounts_tax_excl;
  1098. $order_invoice->total_discount_tax_incl = $this->total_discounts_tax_incl;
  1099. $order_invoice->total_paid_tax_excl = $this->total_paid_tax_excl;
  1100. $order_invoice->total_paid_tax_incl = $this->total_paid_tax_incl;
  1101. $order_invoice->total_products = $this->total_products;
  1102. $order_invoice->total_products_wt = $this->total_products_wt;
  1103. $order_invoice->total_shipping_tax_excl = $this->total_shipping_tax_excl;
  1104. $order_invoice->total_shipping_tax_incl = $this->total_shipping_tax_incl;
  1105. $order_invoice->shipping_tax_computation_method = $tax_calculator->computation_method;
  1106. $order_invoice->total_wrapping_tax_excl = $this->total_wrapping_tax_excl;
  1107. $order_invoice->total_wrapping_tax_incl = $this->total_wrapping_tax_incl;
  1108.  
  1109. // Save Order invoice
  1110. $order_invoice->add();
  1111.  
  1112. $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
  1113.  
  1114. // Update order_carrier
  1115. $id_order_carrier = Db::getInstance()->getValue('
  1116. SELECT `id_order_carrier`
  1117. FROM `'._DB_PREFIX_.'order_carrier`
  1118. WHERE `id_order` = '.(int)$order_invoice->id_order.'
  1119. AND (`id_order_invoice` IS NULL OR `id_order_invoice` = 0)');
  1120.  
  1121. if ($id_order_carrier)
  1122. {
  1123. $order_carrier = new OrderCarrier($id_order_carrier);
  1124. $order_carrier->id_order_invoice = (int)$order_invoice->id;
  1125. $order_carrier->update();
  1126. }
  1127.  
  1128. // Update order detail
  1129. Db::getInstance()->execute('
  1130. UPDATE `'._DB_PREFIX_.'order_detail`
  1131. SET `id_order_invoice` = '.(int)$order_invoice->id.'
  1132. WHERE `id_order` = '.(int)$order_invoice->id_order);
  1133.  
  1134. // Update order payment
  1135. if ($use_existing_payment)
  1136. {
  1137. $id_order_payments = Db::getInstance()->executeS('
  1138. SELECT op.id_order_payment
  1139. FROM `'._DB_PREFIX_.'order_payment` op
  1140. INNER JOIN `'._DB_PREFIX_.'orders` o ON (o.reference = op.order_reference)
  1141. LEFT JOIN `'._DB_PREFIX_.'order_invoice_payment` oip ON (oip.id_order_payment = op.id_order_payment)
  1142. WHERE oip.id_order_payment IS NULL AND o.id_order = '.(int)$order_invoice->id_order);
  1143.  
  1144. if (count($id_order_payments))
  1145. foreach ($id_order_payments as $order_payment)
  1146. Db::getInstance()->execute('
  1147. INSERT INTO `'._DB_PREFIX_.'order_invoice_payment`
  1148. SET
  1149. `id_order_invoice` = '.(int)$order_invoice->id.',
  1150. `id_order_payment` = '.(int)$order_payment['id_order_payment'].',
  1151. `id_order` = '.(int)$order_invoice->id_order);
  1152. }
  1153.  
  1154. // Update order cart rule
  1155. Db::getInstance()->execute('
  1156. UPDATE `'._DB_PREFIX_.'order_cart_rule`
  1157. SET `id_order_invoice` = '.(int)$order_invoice->id.'
  1158. WHERE `id_order` = '.(int)$order_invoice->id_order);
  1159.  
  1160. // Keep it for backward compatibility, to remove on 1.6 version
  1161. $this->invoice_date = $order_invoice->date_add;
  1162. $this->invoice_number = $order_invoice->number;
  1163. $this->update();
  1164. }
  1165. }
  1166.  
  1167. public function setDelivery()
  1168. {
  1169. // Get all invoice
  1170. $order_invoice_collection = $this->getInvoicesCollection();
  1171. foreach ($order_invoice_collection as $order_invoice)
  1172. {
  1173. $number = (int)Configuration::get('PS_DELIVERY_NUMBER');
  1174. if (!$number)
  1175. {
  1176. //if delivery number is not set or wrong, we set a default one.
  1177. Configuration::updateValue('PS_DELIVERY_NUMBER', 1);
  1178. $number = 1;
  1179. }
  1180.  
  1181. // Set delivery number on invoice
  1182. $order_invoice->delivery_number = $number;
  1183. $order_invoice->delivery_date = date('Y-m-d H:i:s');
  1184. // Update Order Invoice
  1185. $order_invoice->update();
  1186.  
  1187. // Keep for backward compatibility
  1188. $this->delivery_number = $number;
  1189. Configuration::updateValue('PS_DELIVERY_NUMBER', $number + 1);
  1190. }
  1191.  
  1192. // Keep it for backward compatibility, to remove on 1.6 version
  1193. // Set delivery date
  1194. $this->delivery_date = date('Y-m-d H:i:s');
  1195. // Update object
  1196. $this->update();
  1197. }
  1198.  
  1199. public static function getByDelivery($id_delivery)
  1200. {
  1201. $sql = 'SELECT id_order
  1202. FROM `'._DB_PREFIX_.'orders`
  1203. WHERE `delivery_number` = '.(int)($id_delivery).'
  1204. '.Shop::addSqlRestriction();
  1205. $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
  1206. return new Order((int)($res['id_order']));
  1207. }
  1208.  
  1209. /**
  1210. * Get a collection of orders using reference
  1211. *
  1212. * @since 1.5.0.14
  1213. *
  1214. * @param string $reference
  1215. * @return Collection of Order
  1216. */
  1217. public static function getByReference($reference)
  1218. {
  1219. $orders = new Collection('Order');
  1220. $orders->where('reference', '=', $reference);
  1221. return $orders;
  1222. }
  1223.  
  1224. public function getTotalWeight()
  1225. {
  1226. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
  1227. SELECT SUM(product_weight * product_quantity) weight
  1228. FROM '._DB_PREFIX_.'order_detail
  1229. WHERE id_order = '.(int)($this->id));
  1230.  
  1231. return (float)($result['weight']);
  1232. }
  1233.  
  1234. /**
  1235. *
  1236. * @param int $id_invoice
  1237. * @deprecated 1.5.0.1
  1238. */
  1239. public static function getInvoice($id_invoice)
  1240. {
  1241. Tools::displayAsDeprecated();
  1242. return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
  1243. SELECT `invoice_number`, `id_order`
  1244. FROM `'._DB_PREFIX_.'orders`
  1245. WHERE invoice_number = '.(int)($id_invoice));
  1246. }
  1247.  
  1248. public function isAssociatedAtGuest($email)
  1249. {
  1250. if (!$email)
  1251. return false;
  1252. $sql = 'SELECT COUNT(*)
  1253. FROM `'._DB_PREFIX_.'orders` o
  1254. LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = o.`id_customer`)
  1255. WHERE o.`id_order` = '.(int)$this->id.'
  1256. AND c.`email` = \''.pSQL($email).'\'
  1257. AND c.`is_guest` = 1
  1258. '.Shop::addSqlRestriction(false, 'c');
  1259. return (bool)Db::getInstance()->getValue($sql);
  1260. }
  1261.  
  1262. /**
  1263. * @param int $id_order
  1264. * @param int $id_customer optionnal
  1265. * @return int id_cart
  1266. */
  1267. public static function getCartIdStatic($id_order, $id_customer = 0)
  1268. {
  1269. return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
  1270. SELECT `id_cart`
  1271. FROM `'._DB_PREFIX_.'orders`
  1272. WHERE `id_order` = '.(int)$id_order.'
  1273. '.($id_customer ? 'AND `id_customer` = '.(int)$id_customer : ''));
  1274. }
  1275.  
  1276. public function getWsOrderRows()
  1277. {
  1278. $query = 'SELECT id_order_detail as `id`, `product_id`, `product_price`, `id_order`, `product_attribute_id`, `product_quantity`, `product_name`
  1279. FROM `'._DB_PREFIX_.'order_detail`
  1280. WHERE id_order = '.(int)$this->id;
  1281. $result = Db::getInstance()->executeS($query);
  1282. return $result;
  1283. }
  1284.  
  1285. /** Set current order state
  1286. * @param int $id_order_state
  1287. * @param int $id_employee (/!\ not optional except for Webservice.
  1288. */
  1289. public function setCurrentState($id_order_state, $id_employee = 0)
  1290. {
  1291. if (empty($id_order_state))
  1292. return false;
  1293. $history = new OrderHistory();
  1294. $history->id_order = (int)$this->id;
  1295. $history->id_employee = (int)$id_employee;
  1296. $history->changeIdOrderState((int)$id_order_state, $this);
  1297. $res = Db::getInstance()->getRow('
  1298. SELECT `invoice_number`, `invoice_date`, `delivery_number`, `delivery_date`
  1299. FROM `'._DB_PREFIX_.'orders`
  1300. WHERE `id_order` = '.(int)$this->id);
  1301. $this->invoice_date = $res['invoice_date'];
  1302. $this->invoice_number = $res['invoice_number'];
  1303. $this->delivery_date = $res['delivery_date'];
  1304. $this->delivery_number = $res['delivery_number'];
  1305. $this->update();
  1306.  
  1307. $history->addWithemail();
  1308. }
  1309.  
  1310. public function addWs($autodate = true, $nullValues = false)
  1311. {
  1312. $paymentModule = Module::getInstanceByName($this->module);
  1313. $customer = new Customer($this->id_customer);
  1314. $paymentModule->validateOrder($this->id_cart, Configuration::get('PS_OS_WS_PAYMENT'), $this->total_paid, $this->payment, null, array(), null, false, $customer->secure_key);
  1315. $this->id = $paymentModule->currentOrder;
  1316. return true;
  1317. }
  1318.  
  1319. public function deleteAssociations()
  1320. {
  1321. return (Db::getInstance()->execute('
  1322. DELETE FROM `'._DB_PREFIX_.'order_detail`
  1323. WHERE `id_order` = '.(int)($this->id)) !== false);
  1324. }
  1325.  
  1326. /**
  1327. * This method return the ID of the previous order
  1328. * @since 1.5.0.1
  1329. * @return int
  1330. */
  1331. public function getPreviousOrderId()
  1332. {
  1333. return Db::getInstance()->getValue('
  1334. SELECT id_order
  1335. FROM '._DB_PREFIX_.'orders
  1336. WHERE id_order < '.(int)$this->id.'
  1337. ORDER BY id_order DESC');
  1338. }
  1339.  
  1340. /**
  1341. * This method return the ID of the next order
  1342. * @since 1.5.0.1
  1343. * @return int
  1344. */
  1345. public function getNextOrderId()
  1346. {
  1347. return Db::getInstance()->getValue('
  1348. SELECT id_order
  1349. FROM '._DB_PREFIX_.'orders
  1350. WHERE id_order > '.(int)$this->id.'
  1351. ORDER BY id_order ASC');
  1352. }
  1353.  
  1354. /**
  1355. * Get the an order detail list of the current order
  1356. * @return array
  1357. */
  1358. public function getOrderDetailList()
  1359. {
  1360. return OrderDetail::getList($this->id);
  1361. }
  1362.  
  1363. /**
  1364. * Gennerate a unique reference for orders generated with the same cart id
  1365. * This references, is usefull for check payment
  1366. *
  1367. * @return String
  1368. */
  1369. public static function generateReference()
  1370. {
  1371. return strtoupper(Tools::passwdGen(9, 'NO_NUMERIC'));
  1372. }
  1373.  
  1374. public function orderContainProduct($id_product)
  1375. {
  1376. $product_list = $this->getOrderDetailList();
  1377. foreach ($product_list as $product)
  1378. if ($product['product_id'] == (int)$id_product)
  1379. return true;
  1380. return false;
  1381. }
  1382. /**
  1383. * This method returns true if at least one order details uses the
  1384. * One After Another tax computation method.
  1385. *
  1386. * @since 1.5.0.1
  1387. * @return boolean
  1388. */
  1389. public function useOneAfterAnotherTaxComputationMethod()
  1390. {
  1391. // if one of the order details use the tax computation method the display will be different
  1392. return Db::getInstance()->getValue('
  1393. SELECT od.`tax_computation_method`
  1394. FROM `'._DB_PREFIX_.'order_detail_tax` odt
  1395. LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
  1396. WHERE od.`id_order` = '.(int)$this->id.'
  1397. AND od.`tax_computation_method` = '.(int)TaxCalculator::ONE_AFTER_ANOTHER_METHOD
  1398. );
  1399. }
  1400.  
  1401. /**
  1402. * This method allows to get all Order Payment for the current order
  1403. * @since 1.5.0.1
  1404. * @return Collection of Order Payment
  1405. */
  1406. public function getOrderPaymentCollection()
  1407. {
  1408. $order_payments = new Collection('OrderPayment');
  1409. $order_payments->where('order_reference', '=', $this->reference);
  1410. return $order_payments;
  1411. }
  1412.  
  1413. /**
  1414. *
  1415. * This method allows to add a payment to the current order
  1416. * @since 1.5.0.1
  1417. * @param float $amount_paid
  1418. * @param string $payment_method
  1419. * @param string $payment_transaction_id
  1420. * @param Currency $currency
  1421. * @param string $date
  1422. * @param OrderInvoice $order_invoice
  1423. * @return bool
  1424. */
  1425. public function addOrderPayment($amount_paid, $payment_method = null, $payment_transaction_id = null, $currency = null, $date = null, $order_invoice = null)
  1426. {
  1427. $order_payment = new OrderPayment();
  1428. $order_payment->order_reference = $this->reference;
  1429. $order_payment->id_currency = ($currency ? $currency->id : $this->id_currency);
  1430. // we kept the currency rate for historization reasons
  1431. $order_payment->conversion_rate = ($currency ? $currency->conversion_rate : 1);
  1432. // if payment_method is define, we used this
  1433. $order_payment->payment_method = ($payment_method ? $payment_method : $this->payment);
  1434. $order_payment->transaction_id = $payment_transaction_id;
  1435. $order_payment->amount = $amount_paid;
  1436. $order_payment->date_add = ($date ? $date : null);
  1437.  
  1438. // Update total_paid_real value for backward compatibility reasons
  1439. if ($order_payment->id_currency == $this->id_currency)
  1440. $this->total_paid_real += $order_payment->amount;
  1441. else
  1442. $this->total_paid_real += Tools::ps_round(Tools::convertPrice($order_payment->amount, $order_payment->id_currency, false), 2);
  1443.  
  1444. // We put autodate parameter of add method to true if date_add field is null
  1445. $res = $order_payment->add(is_null($order_payment->date_add)) && $this->update();
  1446.  
  1447. if (!$res)
  1448. return false;
  1449.  
  1450. if (!is_null($order_invoice))
  1451. {
  1452. $res = Db::getInstance()->execute('
  1453. INSERT INTO `'._DB_PREFIX_.'order_invoice_payment`
  1454. VALUES('.(int)$order_invoice->id.', '.(int)$order_payment->id.', '.(int)$this->id.')');
  1455. }
  1456.  
  1457. return $res;
  1458. }
  1459.  
  1460. /**
  1461. * Returns the correct product taxes breakdown.
  1462. *
  1463. * Get all documents linked to the current order
  1464. *
  1465. * @since 1.5.0.1
  1466. * @return array
  1467. */
  1468. public function getDocuments()
  1469. {
  1470. $invoices = $this->getInvoicesCollection()->getResults();
  1471. $delivery_slips = $this->getDeliverySlipsCollection()->getResults();
  1472. // @TODO review
  1473. foreach ($delivery_slips as $delivery)
  1474. {
  1475. $delivery->is_delivery = true;
  1476. $delivery->date_add = $delivery->delivery_date;
  1477. }
  1478. $order_slips = $this->getOrderSlipsCollection()->getResults();
  1479.  
  1480. // @TODO review
  1481. function sortDocuments($a, $b)
  1482. {
  1483. if ($a->date_add == $b->date_add)
  1484. return 0;
  1485. return ($a->date_add < $b->date_add) ? -1 : 1;
  1486. }
  1487.  
  1488. $documents = array_merge($invoices, $order_slips, $delivery_slips);
  1489. usort($documents, 'sortDocuments');
  1490.  
  1491. return $documents;
  1492. }
  1493.  
  1494. public function getReturn()
  1495. {
  1496. return OrderReturn::getOrdersReturn($this->id_customer, $this->id);
  1497. }
  1498.  
  1499. /**
  1500. * @return array return all shipping method for the current order
  1501. */
  1502. public function getShipping()
  1503. {
  1504. return Db::getInstance()->executeS('
  1505. SELECT DISTINCT oc.`id_order_invoice`, oc.`weight`, oc.`shipping_cost_tax_excl`, oc.`shipping_cost_tax_incl`, c.`url`, oc.`id_carrier`, c.`name` as `state_name`, oc.`date_add`, "Delivery" as `type`, "true" as `can_edit`, oc.`tracking_number`, oc.`id_order_carrier`
  1506. FROM `'._DB_PREFIX_.'orders` o
  1507. LEFT JOIN `'._DB_PREFIX_.'order_history` oh
  1508. ON (o.`id_order` = oh.`id_order`)
  1509. LEFT JOIN `'._DB_PREFIX_.'order_carrier` oc
  1510. ON (o.`id_order` = oc.`id_order`)
  1511. LEFT JOIN `'._DB_PREFIX_.'carrier` c
  1512. ON (oc.`id_carrier` = c.`id_carrier`)
  1513. LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl
  1514. ON (oh.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)Context::getContext()->language->id.')
  1515. WHERE oc.`id_order` = '.(int)$this->id);
  1516. }
  1517.  
  1518.  
  1519. /**
  1520. *
  1521. * Get all order_slips for the current order
  1522. * @since 1.5.0.2
  1523. * @return Collection of Order slip
  1524. */
  1525. public function getOrderSlipsCollection()
  1526. {
  1527. $order_slips = new Collection('OrderSlip');
  1528. $order_slips->where('id_order', '=', $this->id);
  1529. return $order_slips;
  1530. }
  1531.  
  1532. /**
  1533. *
  1534. * Get all invoices for the current order
  1535. * @since 1.5.0.1
  1536. * @return Collection of Order invoice
  1537. */
  1538. public function getInvoicesCollection()
  1539. {
  1540. $order_invoices = new Collection('OrderInvoice');
  1541. $order_invoices->where('id_order', '=', $this->id);
  1542. return $order_invoices;
  1543. }
  1544.  
  1545. /**
  1546. *
  1547. * Get all delivery slips for the current order
  1548. * @since 1.5.0.2
  1549. * @return Collection of Order invoice
  1550. */
  1551. public function getDeliverySlipsCollection()
  1552. {
  1553. $order_invoices = new Collection('OrderInvoice');
  1554. $order_invoices->where('id_order', '=', $this->id);
  1555. $order_invoices->where('delivery_number', '!=', '0');
  1556. return $order_invoices;
  1557. }
  1558.  
  1559. /**
  1560. * Get all not paid invoices for the current order
  1561. * @since 1.5.0.2
  1562. * @return Collection of Order invoice not paid
  1563. */
  1564. public function getNotPaidInvoicesCollection()
  1565. {
  1566. $invoices = $this->getInvoicesCollection();
  1567. foreach ($invoices as $key => $invoice)
  1568. if ($invoice->isPaid())
  1569. unset($invoices[$key]);
  1570. return $invoices;
  1571. }
  1572.  
  1573. /**
  1574. * Get total paid
  1575. *
  1576. * @since 1.5.0.1
  1577. * @param Currency $currency currency used for the total paid of the current order
  1578. * @return float amount in the $currency
  1579. */
  1580. public function getTotalPaid($currency = null)
  1581. {
  1582. if (!$currency)
  1583. $currency = new Currency($this->id_currency);
  1584.  
  1585. $total = 0;
  1586. // Retrieve all payments
  1587. $payments = $this->getOrderPaymentCollection();
  1588. foreach ($payments as $payment)
  1589. {
  1590. if ($payment->id_currency == $currency->id)
  1591. $total += $payment->amount;
  1592. else
  1593. {
  1594. $amount = Tools::convertPrice($payment->amount, $payment->id_currency, false);
  1595. if ($currency->id == Configuration::get('PS_DEFAULT_CURRENCY'))
  1596. $total += $amount;
  1597. else
  1598. $total += Tools::convertPrice($amount, $currency->id, true);
  1599. }
  1600. }
  1601.  
  1602. return Tools::ps_round($total, 2);
  1603. }
  1604.  
  1605. /**
  1606. * Get the sum of total_paid_tax_incl of the orders with similar reference
  1607. *
  1608. * @since 1.5.0.1
  1609. * @return float
  1610. */
  1611. public function getOrdersTotalPaid()
  1612. {
  1613. return Db::getInstance()->getValue('
  1614. SELECT SUM(total_paid_tax_incl)
  1615. FROM `'._DB_PREFIX_.'orders`
  1616. WHERE `reference` = '.(int)$this->reference.'
  1617. AND `id_cart` = '.(int)$this->id_cart
  1618. );
  1619. }
  1620.  
  1621. /**
  1622. *
  1623. * This method allows to change the shipping cost of the current order
  1624. * @since 1.5.0.1
  1625. * @param float $amount
  1626. * @return bool
  1627. */
  1628. public function updateShippingCost($amount)
  1629. {
  1630. $difference = $amount - $this->total_shipping;
  1631. // if the current amount is same as the new, we return true
  1632. if ($difference == 0)
  1633. return true;
  1634.  
  1635. // update the total_shipping value
  1636. $this->total_shipping = $amount;
  1637. // update the total of this order
  1638. $this->total_paid += $difference;
  1639.  
  1640. // update database
  1641. return $this->update();
  1642. }
  1643.  
  1644. /**
  1645. * Returns the correct product taxes breakdown.
  1646. *
  1647. * @since 1.5.0.1
  1648. * @return array
  1649. */
  1650. public function getProductTaxesBreakdown()
  1651. {
  1652. $tmp_tax_infos = array();
  1653. if ($this->useOneAfterAnotherTaxComputationMethod())
  1654. {
  1655. // sum by taxes
  1656. $taxes_by_tax = Db::getInstance()->executeS('
  1657. SELECT odt.`id_order_detail`, t.`name`, t.`rate`, SUM(`total_amount`) AS `total_amount`
  1658. FROM `'._DB_PREFIX_.'order_detail_tax` odt
  1659. LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
  1660. LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
  1661. WHERE od.`id_order` = '.(int)$this->id.'
  1662. GROUP BY odt.`id_tax`
  1663. ');
  1664.  
  1665. // format response
  1666. $tmp_tax_infos = array();
  1667. foreach ($taxes_infos as $tax_infos)
  1668. {
  1669. $tmp_tax_infos[$tax_infos['rate']]['total_amount'] = $tax_infos['tax_amount'];
  1670. $tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
  1671. }
  1672. }
  1673. else
  1674. {
  1675. // sum by order details in order to retrieve real taxes rate
  1676. $taxes_infos = Db::getInstance()->executeS('
  1677. SELECT odt.`id_order_detail`, t.`rate` AS `name`, SUM(od.`total_price_tax_excl`) AS total_price_tax_excl, SUM(t.`rate`) AS rate, SUM(`total_amount`) AS `total_amount`
  1678. FROM `'._DB_PREFIX_.'order_detail_tax` odt
  1679. LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
  1680. LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
  1681. WHERE od.`id_order` = '.(int)$this->id.'
  1682. GROUP BY odt.`id_order_detail`
  1683. ');
  1684.  
  1685. // sum by taxes
  1686. $tmp_tax_infos = array();
  1687. foreach ($taxes_infos as $tax_infos)
  1688. {
  1689. if (!isset($tmp_tax_infos[$tax_infos['rate']]))
  1690. $tmp_tax_infos[$tax_infos['rate']] = array('total_amount' => 0,
  1691. 'name' => 0,
  1692. 'total_price_tax_excl' => 0);
  1693.  
  1694. $tmp_tax_infos[$tax_infos['rate']]['total_amount'] += $tax_infos['total_amount'];
  1695. $tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
  1696. $tmp_tax_infos[$tax_infos['rate']]['total_price_tax_excl'] += $tax_infos['total_price_tax_excl'];
  1697. }
  1698. }
  1699.  
  1700. return $tmp_tax_infos;
  1701. }
  1702.  
  1703. /**
  1704. * Returns the shipping taxes breakdown
  1705. *
  1706. * @since 1.5.0.1
  1707. * @return array
  1708. */
  1709. public function getShippingTaxesBreakdown()
  1710. {
  1711. $taxes_breakdown = array();
  1712.  
  1713. $shipping_tax_amount = $this->total_shipping_tax_incl - $this->total_shipping_tax_excl;
  1714.  
  1715. if ($shipping_tax_amount > 0)
  1716. $taxes_breakdown[] = array(
  1717. 'rate' => $this->carrier_tax_rate,
  1718. 'total_amount' => $shipping_tax_amount
  1719. );
  1720.  
  1721. return $taxes_breakdown;
  1722. }
  1723.  
  1724. /**
  1725. * Returns the wrapping taxes breakdown
  1726. * @todo
  1727.  
  1728. * @since 1.5.0.1
  1729. * @return array
  1730. */
  1731. public function getWrappingTaxesBreakdown()
  1732. {
  1733. $taxes_breakdown = array();
  1734. return $taxes_breakdown;
  1735. }
  1736.  
  1737. /**
  1738. * Returns the ecotax taxes breakdown
  1739. *
  1740. * @since 1.5.0.1
  1741. * @return array
  1742. */
  1743. public function getEcoTaxTaxesBreakdown()
  1744. {
  1745. return Db::getInstance()->executeS('
  1746. SELECT `ecotax_tax_rate`, SUM(`ecotax`) as `ecotax_tax_excl`, SUM(`ecotax`) as `ecotax_tax_incl`
  1747. FROM `'._DB_PREFIX_.'order_detail`
  1748. WHERE `id_order` = '.(int)$this->id
  1749. );
  1750. }
  1751.  
  1752. /**
  1753. *
  1754. * Has invoice return true if this order has already an invoice
  1755. * @return bool
  1756. */
  1757. public function hasInvoice()
  1758. {
  1759. if (Db::getInstance()->getRow('
  1760. SELECT *
  1761. FROM `'._DB_PREFIX_.'order_invoice`
  1762. WHERE `id_order` = '.(int)$this->id))
  1763. return true;
  1764. return false;
  1765. }
  1766.  
  1767. /**
  1768. * Get warehouse associated to the order
  1769. *
  1770. * return array List of warehouse
  1771. */
  1772. public function getWarehouseList()
  1773. {
  1774. $results = Db::getInstance()->executeS('
  1775. SELECT id_warehouse
  1776. FROM `'._DB_PREFIX_.'order_detail`
  1777. WHERE `id_order` = '.(int)$this->id.'
  1778. GROUP BY id_warehouse');
  1779. if (!$results)
  1780. return array();
  1781.  
  1782. $warehouse_list = array();
  1783. foreach ($results as $row)
  1784. $warehouse_list[] = $row['id_warehouse'];
  1785.  
  1786. return $warehouse_list;
  1787. }
  1788.  
  1789. /**
  1790. * @since 1.5.0.4
  1791. * @return OrderState or null if Order haven't a state
  1792. */
  1793. public function getCurrentOrderState()
  1794. {
  1795. if ($this->current_state)
  1796. return new OrderState($this->current_state);
  1797. return null;
  1798. }
  1799.  
  1800. /**
  1801. * @see ObjectModel::getWebserviceObjectList()
  1802. */
  1803. public function getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit)
  1804. {
  1805. $sql_filter .= Shop::addSqlRestriction(Shop::SHARE_ORDER, 'main');
  1806. return parent::getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit);
  1807. }
  1808.  
  1809. /**
  1810. * Get all other orders with the same reference
  1811. *
  1812. * @since 1.5.0.13
  1813. */
  1814. public function getBrother()
  1815. {
  1816. $collection = new Collection('order');
  1817. $collection->where('reference', '=', $this->reference);
  1818. $collection->where('id_order', '<>', $this->id);
  1819. return $collection;
  1820. }
  1821.  
  1822. /**
  1823. * Get a collection of order payments
  1824. *
  1825. * @since 1.5.0.13
  1826. */
  1827. public function getOrderPayments()
  1828. {
  1829. return OrderPayment::getByOrderReference($this->reference);
  1830. }
  1831.  
  1832. /**
  1833. * Return a unique reference like : GWJTHMZUN#2
  1834. *
  1835. * With multishipping, order reference are the same for all orders made with the same cart
  1836. * in this case this method suffix the order reference by a # and the order number
  1837. *
  1838. * @since 1.5.0.14
  1839. */
  1840. public function getUniqReference()
  1841. {
  1842. $query = new DbQuery();
  1843. $query->select('MIN(id_order) as min, MAX(id_order) as max');
  1844. $query->from('orders');
  1845. $query->where('id_cart = '.(int)$this->id_cart);
  1846. $query->orderBy('id_order');
  1847.  
  1848. $order = Db::getInstance()->getRow($query);
  1849.  
  1850. if ($order['min'] == $order['max'])
  1851. return $this->reference;
  1852. else
  1853. return $this->reference.'#'.($this->id + 1 - $order['min']);
  1854. }
  1855.  
  1856. /**
  1857. * Return a unique reference like : GWJTHMZUN#2
  1858. *
  1859. * With multishipping, order reference are the same for all orders made with the same cart
  1860. * in this case this method suffix the order reference by a # and the order number
  1861. *
  1862. * @since 1.5.0.14
  1863. */
  1864. public static function getUniqReferenceOf($id_order)
  1865. {
  1866. $order = new Order($id_order);
  1867. return $order->getUniqReference();
  1868. }
  1869. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement