· 7 years ago · Jan 08, 2019, 01:00 PM
1<?php
2public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown',
3 $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false,
4 $secure_key = false, Shop $shop = null)
5{
6 if (self::DEBUG_MODE) {
7 PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int)$id_cart, true);
8 }
9
10 if (!isset($this->context)) {
11 $this->context = Context::getContext();
12 }
13 $this->context->cart = new Cart((int)$id_cart);
14 $this->context->customer = new Customer((int)$this->context->cart->id_customer);
15 // The tax cart is loaded before the customer so re-cache the tax calculation method
16 $this->context->cart->setTaxCalculationMethod();
17
18 $this->context->language = new Language((int)$this->context->cart->id_lang);
19 $this->context->shop = ($shop ? $shop : new Shop((int)$this->context->cart->id_shop));
20 ShopUrl::resetMainDomainCache();
21 $id_currency = $currency_special ? (int)$currency_special : (int)$this->context->cart->id_currency;
22 $this->context->currency = new Currency((int)$id_currency, null, (int)$this->context->shop->id);
23 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
24 $context_country = $this->context->country;
25 }
26
27 $order_status = new OrderState((int)$id_order_state, (int)$this->context->language->id);
28 if (!Validate::isLoadedObject($order_status)) {
29 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int)$id_cart, true);
30 throw new PrestaShopException('Can\'t load Order status');
31 }
32
33 if (!$this->active) {
34 PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int)$id_cart, true);
35 die(Tools::displayError());
36 }
37
38 // Does order already exists ?
39 if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
40 if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
41 PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int)$id_cart, true);
42 die(Tools::displayError());
43 }
44
45 // For each package, generate an order
46 $delivery_option_list = $this->context->cart->getDeliveryOptionList();
47 $package_list = $this->context->cart->getPackageList();
48 $cart_delivery_option = $this->context->cart->getDeliveryOption();
49
50 // If some delivery options are not defined, or not valid, use the first valid option
51 foreach ($delivery_option_list as $id_address => $package) {
52 if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
53 foreach ($package as $key => $val) {
54 $cart_delivery_option[$id_address] = $key;
55 break;
56 }
57 }
58 }
59
60 $order_list = array();
61 $order_detail_list = array();
62
63 do {
64 $reference = Order::generateReference();
65 } while (Order::getByReference($reference)->count());
66
67 $this->currentOrderReference = $reference;
68
69 $order_creation_failed = false;
70 $cart_total_paid = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
71
72 foreach ($cart_delivery_option as $id_address => $key_carriers) {
73 foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
74 foreach ($data['package_list'] as $id_package) {
75 // Rewrite the id_warehouse
76 $package_list[$id_address][$id_package]['id_warehouse'] = (int)$this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int)$id_carrier);
77 $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
78 }
79 }
80 }
81 // Make sure CartRule caches are empty
82 CartRule::cleanCache();
83 $cart_rules = $this->context->cart->getCartRules();
84 foreach ($cart_rules as $cart_rule) {
85 if (($rule = new CartRule((int)$cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
86 if ($error = $rule->checkValidity($this->context, true, true)) {
87 $this->context->cart->removeCartRule((int)$rule->id);
88 if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
89 if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
90 Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name='.urlencode($rule->code));
91 }
92 Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name='.urlencode($rule->code));
93 } else {
94 $rule_name = isset($rule->name[(int)$this->context->cart->id_lang]) ? $rule->name[(int)$this->context->cart->id_lang] : $rule->code;
95 $error = sprintf(Tools::displayError('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart'), (int)$rule->id, $rule_name);
96 PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int)$this->context->cart->id);
97 }
98 }
99 }
100 }
101
102 foreach ($package_list as $id_address => $packageByAddress) {
103 foreach ($packageByAddress as $id_package => $package) {
104 /** @var Order $order */
105 $order = new Order();
106 $order->product_list = $package['product_list'];
107
108 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
109 $address = new Address((int)$id_address);
110 $this->context->country = new Country((int)$address->id_country, (int)$this->context->cart->id_lang);
111 if (!$this->context->country->active) {
112 throw new PrestaShopException('The delivery address country is not active.');
113 }
114 }
115
116 $carrier = null;
117 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
118 $carrier = new Carrier((int)$package['id_carrier'], (int)$this->context->cart->id_lang);
119 $order->id_carrier = (int)$carrier->id;
120 $id_carrier = (int)$carrier->id;
121 } else {
122 $order->id_carrier = 0;
123 $id_carrier = 0;
124 }
125
126 $order->id_customer = (int)$this->context->cart->id_customer;
127 $order->id_address_invoice = (int)$this->context->cart->id_address_invoice;
128 $order->id_address_delivery = (int)$id_address;
129 $order->id_currency = $this->context->currency->id;
130 $order->id_lang = (int)$this->context->cart->id_lang;
131 $order->id_cart = (int)$this->context->cart->id;
132 $order->reference = $reference;
133 $order->id_shop = (int)$this->context->shop->id;
134 $order->id_shop_group = (int)$this->context->shop->id_shop_group;
135
136 $order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key));
137 $order->payment = $payment_method;
138 if (isset($this->name)) {
139 $order->module = $this->name;
140 }
141 $order->recyclable = $this->context->cart->recyclable;
142 $order->gift = (int)$this->context->cart->gift;
143 $order->gift_message = $this->context->cart->gift_message;
144 $order->mobile_theme = $this->context->cart->mobile_theme;
145 $order->conversion_rate = $this->context->currency->conversion_rate;
146 $amount_paid = !$dont_touch_amount ? Tools::ps_round((float)$amount_paid, 2) : $amount_paid;
147 $order->total_paid_real = 0;
148
149 $order->total_products = (float)$this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
150 $order->total_products_wt = (float)$this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
151 $order->total_discounts_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
152 $order->total_discounts_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
153 $order->total_discounts = $order->total_discounts_tax_incl;
154
155 $order->total_shipping_tax_excl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, false, null, $order->product_list);
156 $order->total_shipping_tax_incl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, true, null, $order->product_list);
157 $order->total_shipping = $order->total_shipping_tax_incl;
158
159 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
160 $order->carrier_tax_rate = $carrier->getTaxesRate(new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
161 }
162
163 $order->total_wrapping_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
164 $order->total_wrapping_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
165 $order->total_wrapping = $order->total_wrapping_tax_incl;
166
167 $order->total_paid_tax_excl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
168 $order->total_paid_tax_incl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
169 $order->total_paid = $order->total_paid_tax_incl;
170 $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
171 $order->round_type = Configuration::get('PS_ROUND_TYPE');
172
173 $order->invoice_date = '0000-00-00 00:00:00';
174 $order->delivery_date = '0000-00-00 00:00:00';
175
176 if (self::DEBUG_MODE) {
177 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int)$id_cart, true);
178 }
179
180 // Creating order
181 $result = $order->add();
182
183 if (!$result) {
184 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int)$id_cart, true);
185 throw new PrestaShopException('Can\'t save Order');
186 }
187
188 // Amount paid by customer is not the right one -> Status = payment error
189 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
190 // if ($order->total_paid != $order->total_paid_real)
191 // We use number_format in order to compare two string
192 if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
193 $id_order_state = Configuration::get('PS_OS_ERROR');
194 }
195
196 $order_list[] = $order;
197
198 if (self::DEBUG_MODE) {
199 PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int)$id_cart, true);
200 }
201
202 // Insert new Order detail list using cart for the current order
203 $order_detail = new OrderDetail(null, null, $this->context);
204 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
205 $order_detail_list[] = $order_detail;
206
207 if (self::DEBUG_MODE) {
208 PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int)$id_cart, true);
209 }
210
211 // Adding an entry in order_carrier table
212 if (!is_null($carrier)) {
213 $order_carrier = new OrderCarrier();
214 $order_carrier->id_order = (int)$order->id;
215 $order_carrier->id_carrier = (int)$id_carrier;
216 $order_carrier->weight = (float)$order->getTotalWeight();
217 $order_carrier->shipping_cost_tax_excl = (float)$order->total_shipping_tax_excl;
218 $order_carrier->shipping_cost_tax_incl = (float)$order->total_shipping_tax_incl;
219 $order_carrier->add();
220 }
221 }
222 }
223
224 // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
225 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
226 $this->context->country = $context_country;
227 }
228
229 if (!$this->context->country->active) {
230 PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int)$id_cart, true);
231 throw new PrestaShopException('The order address country is not active.');
232 }
233
234 if (self::DEBUG_MODE) {
235 PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int)$id_cart, true);
236 }
237
238 // Register Payment only if the order status validate the order
239 if ($order_status->logable) {
240 // $order is the last order loop in the foreach
241 // The method addOrderPayment of the class Order make a create a paymentOrder
242 // linked to the order reference and not to the order id
243 if (isset($extra_vars['transaction_id'])) {
244 $transaction_id = $extra_vars['transaction_id'];
245 } else {
246 $transaction_id = null;
247 }
248
249 if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
250 PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int)$id_cart, true);
251 throw new PrestaShopException('Can\'t save Order Payment');
252 }
253 }
254
255 // Next !
256 $only_one_gift = false;
257 $cart_rule_used = array();
258 $products = $this->context->cart->getProducts();
259
260 // Make sure CartRule caches are empty
261 CartRule::cleanCache();
262 foreach ($order_detail_list as $key => $order_detail) {
263 /** @var OrderDetail $order_detail */
264
265 $order = $order_list[$key];
266 if (!$order_creation_failed && isset($order->id)) {
267 if (!$secure_key) {
268 $message .= '<br />'.Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
269 }
270 // Optional message to attach to this order
271 if (isset($message) & !empty($message)) {
272 $msg = new Message();
273 $message = strip_tags($message, '<br>');
274 if (Validate::isCleanHtml($message)) {
275 if (self::DEBUG_MODE) {
276 PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int)$id_cart, true);
277 }
278 $msg->message = $message;
279 $msg->id_cart = (int)$id_cart;
280 $msg->id_customer = (int)($order->id_customer);
281 $msg->id_order = (int)$order->id;
282 $msg->private = 1;
283 $msg->add();
284 }
285 }
286
287 // Insert new Order detail list using cart for the current order
288 //$orderDetail = new OrderDetail(null, null, $this->context);
289 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
290
291 // Construct order detail table for the email
292 $products_list = '';
293 $virtual_product = true;
294
295 $product_var_tpl_list = array();
296 foreach ($order->product_list as $product) {
297 $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')});
298 $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')});
299
300 $product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;
301
302 $product_var_tpl = array(
303 'reference' => $product['reference'],
304 'name' => $product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : ''),
305 'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false),
306 'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),
307 'quantity' => $product['quantity'],
308 'customization' => array()
309 );
310
311 $customized_datas = Product::getAllCustomizedDatas((int)$order->id_cart);
312 if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
313 $product_var_tpl['customization'] = array();
314 foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
315 $customization_text = '';
316 if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
317 foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
318 $customization_text .= $text['name'].': '.$text['value'].'<br />';
319 }
320 }
321
322 if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
323 $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])).'<br />';
324 }
325
326 $customization_quantity = (int)$product['customization_quantity'];
327
328 $product_var_tpl['customization'][] = array(
329 'customization_text' => $customization_text,
330 'customization_quantity' => $customization_quantity,
331 'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)
332 );
333 }
334 }
335
336 $product_var_tpl_list[] = $product_var_tpl;
337 // Check if is not a virutal product for the displaying of shipping
338 if (!$product['is_virtual']) {
339 $virtual_product &= false;
340 }
341 } // end foreach ($products)
342
343 $product_list_txt = '';
344 $product_list_html = '';
345 if (count($product_var_tpl_list) > 0) {
346 $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
347 $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
348 }
349
350 $cart_rules_list = array();
351 $total_reduction_value_ti = 0;
352 $total_reduction_value_tex = 0;
353 foreach ($cart_rules as $cart_rule) {
354 $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
355 $values = array(
356 'tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package),
357 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)
358 );
359
360 // If the reduction is not applicable to this order, then continue with the next one
361 if (!$values['tax_excl']) {
362 continue;
363 }
364
365 // IF
366 // This is not multi-shipping
367 // The value of the voucher is greater than the total of the order
368 // Partial use is allowed
369 // This is an "amount" reduction, not a reduction in % or a gift
370 // THEN
371 // The voucher is cloned with a new value corresponding to the remainder
372 if (count($order_list) == 1 && $values['tax_incl'] > ($order->total_products_wt - $total_reduction_value_ti) && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
373 // Create a new voucher from the original
374 $voucher = new CartRule((int)$cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it
375 unset($voucher->id);
376
377 // Set a new voucher code
378 $voucher->code = empty($voucher->code) ? substr(md5($order->id.'-'.$order->id_customer.'-'.$cart_rule['obj']->id), 0, 16) : $voucher->code.'-2';
379 if (preg_match('/\-([0-9]{1,2})\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
380 $voucher->code = preg_replace('/'.$matches[0].'$/', '-'.(intval($matches[1]) + 1), $voucher->code);
381 }
382
383 // Set the new voucher value
384 if ($voucher->reduction_tax) {
385 $voucher->reduction_amount = ($total_reduction_value_ti + $values['tax_incl']) - $order->total_products_wt;
386
387 // Add total shipping amout only if reduction amount > total shipping
388 if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
389 $voucher->reduction_amount -= $order->total_shipping_tax_incl;
390 }
391 } else {
392 $voucher->reduction_amount = ($total_reduction_value_tex + $values['tax_excl']) - $order->total_products;
393
394 // Add total shipping amout only if reduction amount > total shipping
395 if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
396 $voucher->reduction_amount -= $order->total_shipping_tax_excl;
397 }
398 }
399 if ($voucher->reduction_amount <= 0) {
400 continue;
401 }
402
403 if ($this->context->customer->isGuest()) {
404 $voucher->id_customer = 0;
405 } else {
406 $voucher->id_customer = $order->id_customer;
407 }
408
409 $voucher->quantity = 1;
410 $voucher->reduction_currency = $order->id_currency;
411 $voucher->quantity_per_user = 1;
412 $voucher->free_shipping = 0;
413 if ($voucher->add()) {
414 // If the voucher has conditions, they are now copied to the new voucher
415 CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
416
417 $params = array(
418 '{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false),
419 '{voucher_num}' => $voucher->code,
420 '{firstname}' => $this->context->customer->firstname,
421 '{lastname}' => $this->context->customer->lastname,
422 '{id_order}' => $order->reference,
423 '{order_name}' => $order->getUniqReference()
424 );
425 Mail::Send(
426 (int)$order->id_lang,
427 'voucher',
428 sprintf(Mail::l('New voucher for your order %s', (int)$order->id_lang), $order->reference),
429 $params,
430 $this->context->customer->email,
431 $this->context->customer->firstname.' '.$this->context->customer->lastname,
432 null, null, null, null, _PS_MAIL_DIR_, false, (int)$order->id_shop
433 );
434 }
435
436 $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
437 $values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
438 }
439 $total_reduction_value_ti += $values['tax_incl'];
440 $total_reduction_value_tex += $values['tax_excl'];
441
442 $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
443
444 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
445 $cart_rule_used[] = $cart_rule['obj']->id;
446
447 // Create a new instance of Cart Rule without id_lang, in order to update its quantity
448 $cart_rule_to_update = new CartRule((int)$cart_rule['obj']->id);
449 $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
450 $cart_rule_to_update->update();
451 }
452
453 $cart_rules_list[] = array(
454 'voucher_name' => $cart_rule['obj']->name,
455 'voucher_reduction' => ($values['tax_incl'] != 0.00 ? '-' : '').Tools::displayPrice($values['tax_incl'], $this->context->currency, false)
456 );
457 }
458
459 $cart_rules_list_txt = '';
460 $cart_rules_list_html = '';
461 if (count($cart_rules_list) > 0) {
462 $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
463 $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
464 }
465
466 // Specify order id for message
467 $old_message = Message::getMessageByCartId((int)$this->context->cart->id);
468 if ($old_message && !$old_message['private']) {
469 $update_message = new Message((int)$old_message['id_message']);
470 $update_message->id_order = (int)$order->id;
471 $update_message->update();
472
473 // Add this message in the customer thread
474 $customer_thread = new CustomerThread();
475 $customer_thread->id_contact = 0;
476 $customer_thread->id_customer = (int)$order->id_customer;
477 $customer_thread->id_shop = (int)$this->context->shop->id;
478 $customer_thread->id_order = (int)$order->id;
479 $customer_thread->id_lang = (int)$this->context->language->id;
480 $customer_thread->email = $this->context->customer->email;
481 $customer_thread->status = 'open';
482 $customer_thread->token = Tools::passwdGen(12);
483 $customer_thread->add();
484
485 $customer_message = new CustomerMessage();
486 $customer_message->id_customer_thread = $customer_thread->id;
487 $customer_message->id_employee = 0;
488 $customer_message->message = $update_message->message;
489 $customer_message->private = 0;
490
491 if (!$customer_message->add()) {
492 $this->errors[] = Tools::displayError('An error occurred while saving message');
493 }
494 }
495
496 if (self::DEBUG_MODE) {
497 PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int)$id_cart, true);
498 }
499
500 // Hook validate order
501 Hook::exec('actionValidateOrder', array(
502 'cart' => $this->context->cart,
503 'order' => $order,
504 'customer' => $this->context->customer,
505 'currency' => $this->context->currency,
506 'orderStatus' => $order_status
507 ));
508
509 foreach ($this->context->cart->getProducts() as $product) {
510 if ($order_status->logable) {
511 ProductSale::addProductSale((int)$product['id_product'], (int)$product['cart_quantity']);
512 }
513 }
514
515 if (self::DEBUG_MODE) {
516 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int)$id_cart, true);
517 }
518
519 // Set the order status
520 $new_history = new OrderHistory();
521 $new_history->id_order = (int)$order->id;
522 $new_history->changeIdOrderState((int)$id_order_state, $order, true);
523 $new_history->addWithemail(true, $extra_vars);
524
525 // Switch to back order if needed
526 if (Configuration::get('PS_STOCK_MANAGEMENT') && ($order_detail->getStockState() || $order_detail->product_quantity_in_stock <= 0)) {
527 $history = new OrderHistory();
528 $history->id_order = (int)$order->id;
529 $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
530 $history->addWithemail();
531 }
532
533 unset($order_detail);
534
535 // Order is reloaded because the status just changed
536 $order = new Order((int)$order->id);
537
538 // Send an e-mail to customer (one order = one email)
539 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
540 $invoice = new Address((int)$order->id_address_invoice);
541 $delivery = new Address((int)$order->id_address_delivery);
542 $delivery_state = $delivery->id_state ? new State((int)$delivery->id_state) : false;
543 $invoice_state = $invoice->id_state ? new State((int)$invoice->id_state) : false;
544
545 $data = array(
546 '{firstname}' => $this->context->customer->firstname,
547 '{lastname}' => $this->context->customer->lastname,
548 '{email}' => $this->context->customer->email,
549 '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"),
550 '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"),
551 '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array(
552 'firstname' => '<span style="font-weight:bold;">%s</span>',
553 'lastname' => '<span style="font-weight:bold;">%s</span>'
554 )),
555 '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array(
556 'firstname' => '<span style="font-weight:bold;">%s</span>',
557 'lastname' => '<span style="font-weight:bold;">%s</span>'
558 )),
559 '{delivery_company}' => $delivery->company,
560 '{delivery_firstname}' => $delivery->firstname,
561 '{delivery_lastname}' => $delivery->lastname,
562 '{delivery_address1}' => $delivery->address1,
563 '{delivery_address2}' => $delivery->address2,
564 '{delivery_city}' => $delivery->city,
565 '{delivery_postal_code}' => $delivery->postcode,
566 '{delivery_country}' => $delivery->country,
567 '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
568 '{delivery_phone}' => ($delivery->phone) ? $delivery->phone : $delivery->phone_mobile,
569 '{delivery_other}' => $delivery->other,
570 '{invoice_company}' => $invoice->company,
571 '{invoice_vat_number}' => $invoice->vat_number,
572 '{invoice_firstname}' => $invoice->firstname,
573 '{invoice_lastname}' => $invoice->lastname,
574 '{invoice_address2}' => $invoice->address2,
575 '{invoice_address1}' => $invoice->address1,
576 '{invoice_city}' => $invoice->city,
577 '{invoice_postal_code}' => $invoice->postcode,
578 '{invoice_country}' => $invoice->country,
579 '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
580 '{invoice_phone}' => ($invoice->phone) ? $invoice->phone : $invoice->phone_mobile,
581 '{invoice_other}' => $invoice->other,
582 '{order_name}' => $order->getUniqReference(),
583 '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
584 '{carrier}' => ($virtual_product || !isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
585 '{payment}' => Tools::substr($order->payment, 0, 32),
586 '{products}' => $product_list_html,
587 '{products_txt}' => $product_list_txt,
588 '{discounts}' => $cart_rules_list_html,
589 '{discounts_txt}' => $cart_rules_list_txt,
590 '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
591 '{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
592 '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
593 '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
594 '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
595 '{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false));
596
597 if (is_array($extra_vars)) {
598 $data = array_merge($data, $extra_vars);
599 }
600
601 // Join PDF invoice
602 if ((int)Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
603 $order_invoice_list = $order->getInvoicesCollection();
604 Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $order_invoice_list));
605 $pdf = new PDF($order_invoice_list, PDF::TEMPLATE_INVOICE, $this->context->smarty);
606 $file_attachement['content'] = $pdf->render(false);
607 $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
608 $file_attachement['mime'] = 'application/pdf';
609 } else {
610 $file_attachement = null;
611 }
612
613 if (self::DEBUG_MODE) {
614 PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int)$id_cart, true);
615 }
616
617 if (Validate::isEmail($this->context->customer->email)) {
618 Mail::Send(
619 (int)$order->id_lang,
620 'order_conf',
621 Mail::l('Order confirmation', (int)$order->id_lang),
622 $data,
623 $this->context->customer->email,
624 $this->context->customer->firstname.' '.$this->context->customer->lastname,
625 null,
626 null,
627 $file_attachement,
628 null, _PS_MAIL_DIR_, false, (int)$order->id_shop
629 );
630 }
631 }
632
633 // updates stock in shops
634 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
635 $product_list = $order->getProducts();
636 foreach ($product_list as $product) {
637 // if the available quantities depends on the physical stock
638 if (StockAvailable::dependsOnStock($product['product_id'])) {
639 // synchronizes
640 StockAvailable::synchronize($product['product_id'], $order->id_shop);
641 }
642 }
643 }
644
645 $order->updateOrderDetailTax();
646 } else {
647 $error = Tools::displayError('Order creation failed');
648 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart));
649 die($error);
650 }
651 } // End foreach $order_detail_list
652
653 // Use the last order as currentOrder
654 if (isset($order) && $order->id) {
655 $this->currentOrder = (int)$order->id;
656 }
657
658 if (self::DEBUG_MODE) {
659 PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int)$id_cart, true);
660 }
661
662 return true;
663 } else {
664 $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
665 PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id));
666 die($error);
667 }
668}