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