forked from PrestaShop/ps_emailalerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ps_emailalerts.php
1343 lines (1214 loc) · 59.5 KB
/
ps_emailalerts.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
$autoloadPath = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoloadPath)) {
require_once $autoloadPath;
}
include_once dirname(__FILE__) . '/MailAlert.php';
class Ps_EmailAlerts extends Module
{
/** @var string Page name */
public $page_name;
/**
* @var string Name of the module running on PS 1.6.x. Used for data migration.
*/
const PS_16_EQUIVALENT_MODULE = 'mailalerts';
protected $html = '';
protected $merchant_new_order_emails;
protected $merchant_oos_emails;
protected $merchant_return_slip_emails;
protected $merchant_order;
protected $merchant_oos;
protected $customer_qty;
protected $merchant_coverage;
protected $product_coverage;
protected $order_edited;
protected $return_slip;
const __MA_MAIL_DELIMITER__ = ',';
public function __construct()
{
$this->name = 'ps_emailalerts';
$this->tab = 'administration';
$this->version = '2.4.2';
$this->author = 'PrestaShop';
$this->need_instance = 0;
$this->controllers = ['account'];
$this->bootstrap = true;
parent::__construct();
if ($this->id) {
$this->init();
}
$this->displayName = $this->trans('Mail alerts', [], 'Modules.Emailalerts.Admin');
$this->description = $this->trans('Make your everyday life easier, handle mail alerts about stock and orders, addressed to you as well as your customers.', [], 'Modules.Emailalerts.Admin');
$this->ps_versions_compliancy = [
'min' => '1.7.6.0',
'max' => _PS_VERSION_,
];
}
protected function init()
{
$this->merchant_new_order_emails = (string) Configuration::get('MA_MERCHANT_ORDER_EMAILS');
$this->merchant_oos_emails = (string) Configuration::get('MA_MERCHANT_OOS_EMAILS');
$this->merchant_return_slip_emails = (string) Configuration::get('MA_RETURN_SLIP_EMAILS');
$this->merchant_order = (int) Configuration::get('MA_MERCHANT_ORDER');
$this->merchant_oos = (int) Configuration::get('MA_MERCHANT_OOS');
$this->customer_qty = (int) Configuration::get('MA_CUSTOMER_QTY');
$this->merchant_coverage = (int) Configuration::getGlobalValue('MA_MERCHANT_COVERAGE');
$this->product_coverage = (int) Configuration::getGlobalValue('MA_PRODUCT_COVERAGE');
$this->order_edited = (int) Configuration::getGlobalValue('MA_ORDER_EDIT');
$this->return_slip = (int) Configuration::getGlobalValue('MA_RETURN_SLIP');
}
public function install($delete_params = true)
{
if (!parent::install() ||
!$this->registerHook('actionValidateOrder') ||
!$this->registerHook('actionUpdateQuantity') ||
!$this->registerHook('displayCustomerAccount') ||
!$this->registerHook('displayMyAccountBlock') ||
!$this->registerHook('actionProductDelete') ||
!$this->registerHook('actionProductAttributeDelete') ||
!$this->registerHook('actionProductAttributeUpdate') ||
!$this->registerHook('actionProductCoverage') ||
!$this->registerHook('actionOrderReturn') ||
!$this->registerHook('actionOrderEdited') ||
!$this->registerHook('registerGDPRConsent') ||
!$this->registerHook('actionDeleteGDPRCustomer') ||
!$this->registerHook('actionExportGDPRData') ||
!$this->registerHook('displayProductAdditionalInfo') ||
!$this->registerHook('actionFrontControllerSetMedia') ||
!$this->registerHook('actionAdminControllerSetMedia')) {
return false;
}
if ($delete_params && $this->uninstallPrestaShop16Module()) {
Configuration::updateValue('MA_MERCHANT_ORDER', 1);
Configuration::updateValue('MA_MERCHANT_OOS', 1);
Configuration::updateValue('MA_CUSTOMER_QTY', 1);
Configuration::updateValue('MA_ORDER_EDIT', 1);
Configuration::updateValue('MA_RETURN_SLIP', 1);
Configuration::updateValue('MA_MERCHANT_MAILS', Configuration::get('PS_SHOP_EMAIL'));
Configuration::updateValue('MA_LAST_QTIES', (int) Configuration::get('PS_LAST_QTIES'));
Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', 0);
Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', 0);
$sql = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . MailAlert::$definition['table'] . '`
(
`id_customer` int(10) unsigned NOT NULL,
`customer_email` varchar(128) NOT NULL,
`id_product` int(10) unsigned NOT NULL,
`id_product_attribute` int(10) unsigned NOT NULL,
`id_shop` int(10) unsigned NOT NULL,
`id_lang` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_customer`,`customer_email`,`id_product`,`id_product_attribute`,`id_shop`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
if (!Db::getInstance()->execute($sql)) {
return false;
}
}
return true;
}
public function uninstall($delete_params = true)
{
if ($delete_params) {
Configuration::deleteByName('MA_MERCHANT_ORDER');
Configuration::deleteByName('MA_MERCHANT_OOS');
Configuration::deleteByName('MA_CUSTOMER_QTY');
Configuration::deleteByName('MA_MERCHANT_MAILS');
Configuration::deleteByName('MA_LAST_QTIES');
Configuration::deleteByName('MA_MERCHANT_COVERAGE');
Configuration::deleteByName('MA_PRODUCT_COVERAGE');
Configuration::deleteByName('MA_ORDER_EDIT');
Configuration::deleteByName('MA_RETURN_SLIP');
if (!Db::getInstance()->execute('DROP TABLE IF EXISTS ' . _DB_PREFIX_ . MailAlert::$definition['table'])) {
return false;
}
}
return parent::uninstall();
}
/**
* Migrate data from 1.6 equivalent module (if applicable), then uninstall
*/
public function uninstallPrestaShop16Module()
{
if (!Module::isInstalled(self::PS_16_EQUIVALENT_MODULE)) {
return true;
}
$oldModule = Module::getInstanceByName(self::PS_16_EQUIVALENT_MODULE);
if ($oldModule) {
// This closure calls the parent class to prevent data to be erased
// It allows the new module to be configured without migration
$parentUninstallClosure = function () {
return parent::uninstall();
};
$parentUninstallClosure = $parentUninstallClosure->bindTo($oldModule, get_class($oldModule));
$parentUninstallClosure();
}
return true;
}
public function reset()
{
if (!$this->uninstall(false)) {
return false;
}
if (!$this->install(false)) {
return false;
}
return true;
}
public function getContent()
{
$this->context->controller->addJqueryUi('ui.widget');
$this->context->controller->addJqueryPlugin('tagify');
$this->html = '';
$this->postProcess();
$this->html .= $this->renderForm();
return $this->html;
}
protected function postProcess()
{
$errors = [];
if (Tools::isSubmit('submitMailAlert')) {
if (!Configuration::updateValue('MA_CUSTOMER_QTY', (int) Tools::getValue('MA_CUSTOMER_QTY'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateGlobalValue('MA_ORDER_EDIT', (int) Tools::getValue('MA_ORDER_EDIT'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
}
} elseif (Tools::isSubmit('submitMAMerchant')) {
$new_order_flag = (int) Tools::getValue('MA_MERCHANT_ORDER');
$new_order_emails = (string) Tools::getValue('MA_MERCHANT_ORDER_EMAILS');
$outofstock_flag = (int) Tools::getValue('MA_MERCHANT_OOS');
$outofstock_emails = (string) Tools::getValue('MA_MERCHANT_OOS_EMAILS');
$return_slip_flag = (int) Tools::getValue('MA_RETURN_SLIP');
$return_slip_emails = (string) Tools::getValue('MA_RETURN_SLIP_EMAILS');
// Check new order e-mails (if setting is active)
if ($new_order_flag && empty($new_order_emails)) {
$errors[] = $this->trans('Please enter one (or more) email address for the new order notification.', [], 'Modules.Emailalerts.Admin');
} else {
$new_order_emails = explode(self::__MA_MAIL_DELIMITER__, $new_order_emails);
foreach ($new_order_emails as $k => $email) {
$email = trim($email);
if (!empty($email) && !Validate::isEmail($email)) {
// Add error message and remove it
$errors[] = $this->trans('Invalid email:', [], 'Modules.Emailalerts.Admin') . ' ' . Tools::safeOutput($email);
unset($new_order_emails[$k]);
} elseif (!empty($email)) {
$new_order_emails[$k] = $email;
} else {
unset($new_order_emails[$k]);
}
}
$new_order_emails = implode(self::__MA_MAIL_DELIMITER__, $new_order_emails);
if (!Configuration::updateValue('MA_MERCHANT_ORDER_EMAILS', (string) $new_order_emails)) {
$errors[] = $this->trans('Cannot update new order emails.', [], 'Modules.Emailalerts.Admin');
}
}
// Check out of stock e-mails (if setting is active)
if ($outofstock_flag && empty($outofstock_emails)) {
$errors[] = $this->trans('Please enter one (or more) email address for "out of stock" notifications.', [], 'Modules.Emailalerts.Admin');
} else {
$outofstock_emails = explode(self::__MA_MAIL_DELIMITER__, $outofstock_emails);
foreach ($outofstock_emails as $k => $email) {
$email = trim($email);
if (!empty($email) && !Validate::isEmail($email)) {
// Add error message and remove it
$errors[] = $this->trans('Invalid email:', [], 'Modules.Emailalerts.Admin') . ' ' . Tools::safeOutput($email);
unset($outofstock_emails[$k]);
} elseif (!empty($email)) {
$outofstock_emails[$k] = $email;
} else {
unset($outofstock_emails[$k]);
}
}
$outofstock_emails = implode(self::__MA_MAIL_DELIMITER__, $outofstock_emails);
if (!Configuration::updateValue('MA_MERCHANT_OOS_EMAILS', (string) $outofstock_emails)) {
$errors[] = $this->trans('Cannot update email for "out of stock" notifications.', [], 'Modules.Emailalerts.Admin');
}
}
// Check return slip e-mails (if setting is active)
if ($return_slip_flag && empty($return_slip_emails)) {
$errors[] = $this->trans('Please enter one (or more) email address for "return slip" notifications.', [], 'Modules.Emailalerts.Admin');
} else {
$return_slip_emails = explode(self::__MA_MAIL_DELIMITER__, $return_slip_emails);
foreach ($return_slip_emails as $k => $email) {
$email = trim($email);
if (!empty($email) && !Validate::isEmail($email)) {
// Add error message and remove it
$errors[] = $this->trans('Invalid email:', [], 'Modules.Emailalerts.Admin') . ' ' . Tools::safeOutput($email);
unset($return_slip_emails[$k]);
} elseif (!empty($email)) {
$return_slip_emails[$k] = $email;
} else {
unset($return_slip_emails[$k]);
}
}
$return_slip_emails = implode(self::__MA_MAIL_DELIMITER__, $return_slip_emails);
if (!Configuration::updateValue('MA_RETURN_SLIP_EMAILS', (string) $return_slip_emails)) {
$errors[] = $this->trans('Cannot update "return slip" emails.', [], 'Modules.Emailalerts.Admin');
}
}
if (!Configuration::updateValue('MA_MERCHANT_ORDER', (int) Tools::getValue('MA_MERCHANT_ORDER'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateValue('MA_MERCHANT_OOS', (int) Tools::getValue('MA_MERCHANT_OOS'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateValue('MA_LAST_QTIES', (int) Tools::getValue('MA_LAST_QTIES'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', (int) Tools::getValue('MA_MERCHANT_COVERAGE'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', (int) Tools::getValue('MA_PRODUCT_COVERAGE'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
} elseif (!Configuration::updateGlobalValue('MA_RETURN_SLIP', (int) Tools::getValue('MA_RETURN_SLIP'))) {
$errors[] = $this->trans('Cannot update settings', [], 'Modules.Emailalerts.Admin');
}
}
if (count($errors) > 0) {
$this->html .= $this->displayError(implode('<br />', $errors));
} elseif (Tools::isSubmit('submitMailAlert') || Tools::isSubmit('submitMAMerchant')) {
$this->html .= $this->displayConfirmation($this->trans('Settings updated successfully', [], 'Modules.Emailalerts.Admin'));
}
$this->init();
}
public function getAllMessages($id)
{
$messages = Db::getInstance()->executeS('
SELECT `message`
FROM `' . _DB_PREFIX_ . 'message`
WHERE `id_order` = ' . (int) $id . '
ORDER BY `id_message` ASC');
$result = [];
foreach ($messages as $message) {
$result[] = $message['message'];
}
return implode('<br/>', $result);
}
/**
* Return current locale
*
* @param Context $context
*
* @return \PrestaShop\PrestaShop\Core\Localization\Locale|null
*
* @throws Exception
*/
public static function getContextLocale(Context $context)
{
$locale = $context->getCurrentLocale();
if (null !== $locale) {
return $locale;
}
$containerFinder = new \PrestaShop\PrestaShop\Adapter\ContainerFinder($context);
$container = $containerFinder->getContainer();
if (null === $context->container) {
// @phpstan-ignore-next-line
$context->container = $container;
}
/** @var \PrestaShop\PrestaShop\Core\Localization\CLDR\LocaleRepository $localeRepository */
$localeRepository = $container->get(Controller::SERVICE_LOCALE_REPOSITORY);
$locale = $localeRepository->getLocale(
$context->language->getLocale()
);
// @phpstan-ignore-next-line
return $locale;
}
public function hookActionValidateOrder($params)
{
if (!$this->merchant_order || empty($this->merchant_new_order_emails)) {
return;
}
// Getting differents vars
$context = Context::getContext();
$id_lang = (int) $context->language->id;
$locale = $context->language->getLocale();
// We use use static method from current class to prevent retro compatibility issues with PrestaShop < 1.7.7
$contextLocale = static::getContextLocale($context);
$id_shop = (int) $context->shop->id;
$currency = $params['currency'];
$order = $params['order'];
$customer = $params['customer'];
$configuration = Configuration::getMultiple(
[
'PS_SHOP_EMAIL',
'PS_MAIL_METHOD',
'PS_MAIL_SERVER',
'PS_MAIL_USER',
'PS_MAIL_PASSWD',
'PS_SHOP_NAME',
'PS_MAIL_COLOR',
], $id_lang, null, $id_shop
);
$delivery = new Address((int) $order->id_address_delivery);
$invoice = new Address((int) $order->id_address_invoice);
$order_date_text = Tools::displayDate($order->date_add);
$carrier = new Carrier((int) $order->id_carrier);
$message = $this->getAllMessages($order->id);
if (!$message || empty($message)) {
$message = $this->trans('No message', [], 'Modules.Emailalerts.Admin');
}
$items_table = '';
$products = $params['order']->getProducts();
$customized_datas = Product::getAllCustomizedDatas((int) $params['cart']->id);
Product::addCustomizationPrice($products, $customized_datas);
foreach ($products as $key => $product) {
$unit_price = Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'];
$customization_text = '';
if (isset($customized_datas[$product['product_id']][$product['product_attribute_id']][$order->id_address_delivery][$product['id_customization']])) {
foreach ($customized_datas[$product['product_id']][$product['product_attribute_id']][$order->id_address_delivery][$product['id_customization']] as $customization) {
if (isset($customization[Product::CUSTOMIZE_TEXTFIELD])) {
foreach ($customization[Product::CUSTOMIZE_TEXTFIELD] as $text) {
$customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
}
$customization_text .= '---<br />';
}
if (isset($customization[Product::CUSTOMIZE_FILE])) {
$customization_text .= count($customization[Product::CUSTOMIZE_FILE]) . ' ' . $this->trans('image(s)', [], 'Modules.Emailalerts.Admin') . '<br />';
$customization_text .= '---<br />';
}
}
if (method_exists('Tools', 'rtrimString')) {
$customization_text = Tools::rtrimString($customization_text, '---<br />');
} else {
$customization_text = preg_replace('/---<br \/>$/', '', $customization_text);
}
}
$url = $context->link->getProductLink($product['product_id']);
$items_table .=
'<tr style="background-color:' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
<td style="padding:0.6em 0.4em;">' . $product['product_reference'] . '</td>
<td style="padding:0.6em 0.4em;">
<strong><a href="' . $url . '">' . $product['product_name'] . '</a>'
. (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '')
. (!empty($customization_text) ? '<br />' . $customization_text : '')
. '</strong>
</td>
<td style="padding:0.6em 0.4em; text-align:right;">' . $contextLocale->formatPrice($unit_price, $currency->iso_code) . '</td>
<td style="padding:0.6em 0.4em; text-align:center;">' . (int) $product['product_quantity'] . '</td>
<td style="padding:0.6em 0.4em; text-align:right;">'
. $contextLocale->formatPrice(($unit_price * $product['product_quantity']), $currency->iso_code)
. '</td>
</tr>';
}
foreach ($params['order']->getCartRules() as $discount) {
$items_table .=
'<tr style="background-color:#EBECEE;">
<td colspan="4" style="padding:0.6em 0.4em; text-align:right;">' . $this->trans('Voucher code:', [], 'Modules.Emailalerts.Admin') . ' ' . $discount['name'] . '</td>
<td style="padding:0.6em 0.4em; text-align:right;">-' . $contextLocale->formatPrice($discount['value'], $currency->iso_code) . '</td>
</tr>';
}
if ($delivery->id_state) {
$delivery_state = new State((int) $delivery->id_state);
}
if ($invoice->id_state) {
$invoice_state = new State((int) $invoice->id_state);
}
if (Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC) {
$total_products = $order->getTotalProductsWithoutTaxes();
} else {
$total_products = $order->getTotalProductsWithTaxes();
}
$order_state = $params['orderStatus'];
// Filling-in vars for email
$template_vars = [
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"),
'{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"),
'{delivery_block_html}' => MailAlert::getFormatedAddress(
$delivery, '<br />', [
'firstname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
]
),
'{invoice_block_html}' => MailAlert::getFormatedAddress(
$invoice, '<br />', [
'firstname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
]
),
'{delivery_company}' => $delivery->company,
'{delivery_firstname}' => $delivery->firstname,
'{delivery_lastname}' => $delivery->lastname,
'{delivery_address1}' => $delivery->address1,
'{delivery_address2}' => $delivery->address2,
'{delivery_city}' => $delivery->city,
'{delivery_postal_code}' => $delivery->postcode,
'{delivery_country}' => $delivery->country,
'{delivery_state}' => isset($delivery_state->name) ? $delivery_state->name : '',
'{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile,
'{delivery_other}' => $delivery->other,
'{invoice_company}' => $invoice->company,
'{invoice_firstname}' => $invoice->firstname,
'{invoice_lastname}' => $invoice->lastname,
'{invoice_address2}' => $invoice->address2,
'{invoice_address1}' => $invoice->address1,
'{invoice_city}' => $invoice->city,
'{invoice_postal_code}' => $invoice->postcode,
'{invoice_country}' => $invoice->country,
'{invoice_state}' => isset($invoice_state->name) ? $invoice_state->name : '',
'{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile,
'{invoice_other}' => $invoice->other,
'{order_name}' => $order->reference,
'{order_status}' => $order_state->name,
'{shop_name}' => $configuration['PS_SHOP_NAME'],
'{date}' => $order_date_text,
'{carrier}' => (($carrier->name == '0') ? $configuration['PS_SHOP_NAME'] : $carrier->name),
'{payment}' => Tools::substr($order->payment, 0, 32),
'{items}' => $items_table,
'{total_paid}' => $contextLocale->formatPrice($order->total_paid, $currency->iso_code),
'{total_products}' => $contextLocale->formatPrice($total_products, $currency->iso_code),
'{total_discounts}' => $contextLocale->formatPrice($order->total_discounts, $currency->iso_code),
'{total_shipping}' => $contextLocale->formatPrice($order->total_shipping, $currency->iso_code),
'{total_shipping_tax_excl}' => $contextLocale->formatPrice($order->total_shipping_tax_excl, $currency->iso_code),
'{total_shipping_tax_incl}' => $contextLocale->formatPrice($order->total_shipping_tax_incl, $currency->iso_code),
'{total_tax_paid}' => $contextLocale->formatPrice(
$order->total_paid_tax_incl - $order->total_paid_tax_excl,
$currency->iso_code
),
'{total_wrapping}' => $contextLocale->formatPrice($order->total_wrapping, $currency->iso_code),
'{currency}' => $currency->sign,
'{gift}' => (bool) $order->gift,
'{gift_message}' => $order->gift_message,
'{message}' => $message,
];
// Shop iso
$iso = Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT'));
// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
$merchant_new_order_emails = explode(self::__MA_MAIL_DELIMITER__, $this->merchant_new_order_emails);
foreach ($merchant_new_order_emails as $merchant_mail) {
// Default language
$mail_id_lang = $id_lang;
$mail_iso = $iso;
// Use the merchant lang if he exists as an employee
$results = Db::getInstance()->executeS('
SELECT `id_lang` FROM `' . _DB_PREFIX_ . 'employee`
WHERE `email` = \'' . pSQL($merchant_mail) . '\'
');
if ($results) {
$user_iso = Language::getIsoById((int) $results[0]['id_lang']);
if ($user_iso) {
$mail_id_lang = (int) $results[0]['id_lang'];
$mail_iso = $user_iso;
}
}
$dir_mail = false;
if (file_exists(dirname(__FILE__) . '/mails/' . $mail_iso . '/new_order.txt') &&
file_exists(dirname(__FILE__) . '/mails/' . $mail_iso . '/new_order.html')) {
$dir_mail = dirname(__FILE__) . '/mails/';
}
if (file_exists(_PS_MAIL_DIR_ . $mail_iso . '/new_order.txt') &&
file_exists(_PS_MAIL_DIR_ . $mail_iso . '/new_order.html')) {
$dir_mail = _PS_MAIL_DIR_;
}
if ($dir_mail) {
Mail::send(
$mail_id_lang,
'new_order',
$this->trans(
'New order : #%d - %s',
[
$order->id,
$order->reference,
],
'Emails.Subject',
$locale),
$template_vars,
$merchant_mail,
null,
$configuration['PS_SHOP_EMAIL'],
$configuration['PS_SHOP_NAME'],
null,
null,
$dir_mail,
false,
$id_shop
);
}
}
}
public function hookDisplayProductAdditionalInfo($params)
{
if ($params['product']['minimal_quantity'] <= $params['product']['quantity'] ||
!$this->customer_qty ||
!Configuration::get('PS_STOCK_MANAGEMENT') ||
Product::isAvailableWhenOutOfStock($params['product']['out_of_stock'])) {
return;
}
$context = Context::getContext();
$id_product = (int) $params['product']['id'];
$id_product_attribute = $params['product']['id_product_attribute'];
$id_customer = (int) $context->customer->id;
if ((int) $context->customer->id <= 0) {
$this->context->smarty->assign('email', 1);
} elseif (MailAlert::customerHasNotification($id_customer, $id_product, $id_product_attribute, (int) $context->shop->id)) {
$this->context->smarty->assign('has_notification', 1);
}
$this->context->smarty->assign(
[
'id_product' => $id_product,
'id_product_attribute' => $id_product_attribute,
'id_module' => $this->id,
]
);
return $this->display(__FILE__, 'product.tpl');
}
public function hookActionUpdateQuantity($params)
{
// Do not send email if stock did not change
if (isset($params['delta_quantity']) && (int) $params['delta_quantity'] === 0) {
return;
}
$id_product = (int) $params['id_product'];
$id_product_attribute = (int) $params['id_product_attribute'];
$context = Context::getContext();
$id_shop = (int) $context->shop->id;
$id_lang = (int) $context->language->id;
$locale = $context->language->getLocale();
$product = new Product($id_product, false, $id_lang, $id_shop, $context);
if (!Validate::isLoadedObject($product) || $product->active != 1) {
return;
}
$quantity = (int) $params['quantity'];
$product_has_attributes = $product->hasAttributes();
$configuration = Configuration::getMultiple(
[
'MA_LAST_QTIES',
'PS_STOCK_MANAGEMENT',
'PS_SHOP_EMAIL',
'PS_SHOP_NAME',
], null, null, $id_shop
);
$ma_last_qties = (int) $configuration['MA_LAST_QTIES'];
$check_oos = ($product_has_attributes && $id_product_attribute) || (!$product_has_attributes && !$id_product_attribute);
if ($check_oos &&
(int) $quantity <= $ma_last_qties &&
!(!$this->merchant_oos || empty($this->merchant_oos_emails)) &&
$configuration['PS_STOCK_MANAGEMENT']) {
$iso = Language::getIsoById($id_lang);
$product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang);
$template_vars = [
'{qty}' => $quantity,
'{last_qty}' => $ma_last_qties,
'{product}' => $product_name,
];
// Do not send mail if multiples product are created / imported.
if (!defined('PS_MASS_PRODUCT_CREATION') &&
file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productoutofstock.txt') &&
file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productoutofstock.html')) {
// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
$merchant_oos_emails = explode(self::__MA_MAIL_DELIMITER__, $this->merchant_oos_emails);
foreach ($merchant_oos_emails as $merchant_mail) {
Mail::Send(
$id_lang,
'productoutofstock',
$this->trans('Product out of stock', [], 'Emails.Subject', $locale),
$template_vars,
$merchant_mail,
null,
(string) $configuration['PS_SHOP_EMAIL'],
(string) $configuration['PS_SHOP_NAME'],
null,
null,
dirname(__FILE__) . '/mails/',
false,
$id_shop
);
}
}
}
if ($product_has_attributes) {
$sql = 'SELECT `minimal_quantity`, `id_product_attribute`
FROM ' . _DB_PREFIX_ . 'product_attribute
WHERE id_product_attribute = ' . (int) $id_product_attribute;
$result = Db::getInstance()->getRow($sql);
if ($result && $this->customer_qty && $quantity >= $result['minimal_quantity']) {
MailAlert::sendCustomerAlert((int) $product->id, (int) $params['id_product_attribute']);
}
} else {
if ($this->customer_qty && $quantity >= $product->minimal_quantity) {
MailAlert::sendCustomerAlert((int) $product->id, (int) $params['id_product_attribute']);
}
}
}
public function hookActionProductAttributeUpdate($params)
{
$sql = 'SELECT sa.`id_product`, sa.`quantity`, pa.`minimal_quantity`
FROM `' . _DB_PREFIX_ . 'stock_available` sa
LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON sa.id_product_attribute = pa.id_product_attribute
WHERE sa.`id_product_attribute` = ' . (int) $params['id_product_attribute'];
$result = Db::getInstance()->getRow($sql);
if ($result && $this->customer_qty && $result['quantity'] >= $result['minimal_quantity']) {
MailAlert::sendCustomerAlert((int) $result['id_product'], (int) $params['id_product_attribute']);
}
}
public function hookDisplayCustomerAccount($params)
{
return $this->customer_qty ? $this->display(__FILE__, 'my-account.tpl') : null;
}
public function hookDisplayMyAccountBlock($params)
{
return $this->customer_qty ? $this->display(__FILE__, 'my-account-footer.tpl') : null;
}
public function hookActionProductDelete($params)
{
$sql = '
DELETE FROM `' . _DB_PREFIX_ . MailAlert::$definition['table'] . '`
WHERE `id_product` = ' . (int) $params['product']->id;
Db::getInstance()->execute($sql);
}
public function hookActionProductAttributeDelete($params)
{
if ($params['deleteAllAttributes']) {
$sql = '
DELETE FROM `' . _DB_PREFIX_ . MailAlert::$definition['table'] . '`
WHERE `id_product` = ' . (int) $params['id_product'];
} else {
$sql = '
DELETE FROM `' . _DB_PREFIX_ . MailAlert::$definition['table'] . '`
WHERE `id_product_attribute` = ' . (int) $params['id_product_attribute'] . '
AND `id_product` = ' . (int) $params['id_product'];
}
Db::getInstance()->execute($sql);
}
public function hookActionProductCoverage($params)
{
// if not advanced stock management, nothing to do
if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
return;
}
// retrieves informations
$id_product = (int) $params['id_product'];
$id_product_attribute = (int) $params['id_product_attribute'];
$warehouse = $params['warehouse'];
$product = new Product($id_product);
if (!Validate::isLoadedObject($product)) {
return;
}
if (!$product->advanced_stock_management) {
return;
}
// sets warehouse id to get the coverage
if (!Validate::isLoadedObject($warehouse)) {
$id_warehouse = 0;
} else {
$id_warehouse = (int) $warehouse->id;
}
// coverage of the product
$warning_coverage = (int) Configuration::getGlobalValue('MA_PRODUCT_COVERAGE');
$coverage = StockManagerFactory::getManager()->getProductCoverage($id_product, $id_product_attribute, $warning_coverage, $id_warehouse);
// if we need to send a notification
if ($product->active == 1 &&
($coverage < $warning_coverage) && !empty($this->merchant_mails) &&
Configuration::getGlobalValue('MA_MERCHANT_COVERAGE')) {
$context = Context::getContext();
$id_lang = (int) $context->language->id;
$locale = $context->language->getLocale();
$id_shop = (int) $context->shop->id;
$iso = Language::getIsoById($id_lang);
$product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang);
$template_vars = [
'{current_coverage}' => $coverage,
'{warning_coverage}' => $warning_coverage,
'{product}' => pSQL($product_name),
];
if (file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productcoverage.txt') &&
file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productcoverage.html')) {
// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
$merchant_oos_emails = explode(self::__MA_MAIL_DELIMITER__, $this->merchant_oos);
foreach ($merchant_oos_emails as $merchant_mail) {
Mail::send(
$id_lang,
'productcoverage',
$this->trans('Stock coverage', [], 'Emails.Subject', $locale),
$template_vars,
$merchant_mail,
null,
(string) Configuration::get('PS_SHOP_EMAIL'),
(string) Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__) . '/mails/',
false,
$id_shop
);
}
}
}
}
public function hookActionFrontControllerSetMedia()
{
$this->context->controller->registerJavascript(
'mailalerts-js',
'modules/' . $this->name . '/js/mailalerts.js'
);
$this->context->controller->registerStylesheet(
'mailalerts-css',
'modules/' . $this->name . '/css/mailalerts.css'
);
}
public function hookActionAdminControllerSetMedia()
{
$this->context->controller->addJS($this->_path . 'js/admin/' . $this->name . '.js');
}
/**
* Send a mail when a customer return an order.
*
* @param array $params Hook params
*/
public function hookActionOrderReturn($params)
{
if (!$this->return_slip || empty($this->merchant_return_slip_emails)) {
return;
}
$context = Context::getContext();
$id_lang = (int) $context->language->id;
$locale = $context->language->getLocale();
$id_shop = (int) $context->shop->id;
$configuration = Configuration::getMultiple(
[
'PS_SHOP_EMAIL',
'PS_MAIL_METHOD',
'PS_MAIL_SERVER',
'PS_MAIL_USER',
'PS_MAIL_PASSWD',
'PS_SHOP_NAME',
'PS_MAIL_COLOR',
], $id_lang, null, $id_shop
);
// Shop iso
$iso = Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT'));
$order = new Order((int) $params['orderReturn']->id_order);
$customer = new Customer((int) $params['orderReturn']->id_customer);
$delivery = new Address((int) $order->id_address_delivery);
$invoice = new Address((int) $order->id_address_invoice);
$order_date_text = Tools::displayDate($order->date_add);
if ($delivery->id_state) {
$delivery_state = new State((int) $delivery->id_state);
}
if ($invoice->id_state) {
$invoice_state = new State((int) $invoice->id_state);
}
$order_return_products = OrderReturn::getOrdersReturnProducts($params['orderReturn']->id, $order);
$items_table = '';
foreach ($order_return_products as $key => $product) {
$url = $context->link->getProductLink($product['product_id']);
$items_table .=
'<tr style="background-color:' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
<td style="padding:0.6em 0.4em;">' . $product['product_reference'] . '</td>
<td style="padding:0.6em 0.4em;">
<strong><a href="' . $url . '">' . $product['product_name'] . '</a>
</strong>
</td>
<td style="padding:0.6em 0.4em; text-align:center;">' . (int) $product['product_quantity'] . '</td>
</tr>';
}
$template_vars = [
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"),
'{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"),
'{delivery_block_html}' => MailAlert::getFormatedAddress(
$delivery, '<br />', [
'firstname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
]
),
'{invoice_block_html}' => MailAlert::getFormatedAddress(
$invoice, '<br />', [
'firstname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:' . $configuration['PS_MAIL_COLOR'] . '; font-weight:bold;">%s</span>',
]
),
'{delivery_company}' => $delivery->company,
'{delivery_firstname}' => $delivery->firstname,
'{delivery_lastname}' => $delivery->lastname,
'{delivery_address1}' => $delivery->address1,
'{delivery_address2}' => $delivery->address2,
'{delivery_city}' => $delivery->city,
'{delivery_postal_code}' => $delivery->postcode,
'{delivery_country}' => $delivery->country,
'{delivery_state}' => isset($delivery_state->name) ? $delivery_state->name : '',
'{delivery_phone}' => isset($delivery->phone) ? $delivery->phone : $delivery->phone_mobile,
'{delivery_other}' => $delivery->other,
'{invoice_company}' => $invoice->company,
'{invoice_firstname}' => $invoice->firstname,
'{invoice_lastname}' => $invoice->lastname,
'{invoice_address2}' => $invoice->address2,
'{invoice_address1}' => $invoice->address1,
'{invoice_city}' => $invoice->city,
'{invoice_postal_code}' => $invoice->postcode,
'{invoice_country}' => $invoice->country,
'{invoice_state}' => isset($invoice_state->name) ? $invoice_state->name : '',
'{invoice_phone}' => isset($invoice->phone) ? $invoice->phone : $invoice->phone_mobile,
'{invoice_other}' => $invoice->other,
'{order_name}' => $order->reference,
'{shop_name}' => $configuration['PS_SHOP_NAME'],
'{date}' => $order_date_text,
'{items}' => $items_table,
'{message}' => Tools::purifyHTML($params['orderReturn']->question),
];
// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
$merchant_return_slip_emails = explode(self::__MA_MAIL_DELIMITER__, $this->merchant_return_slip_emails);
foreach ($merchant_return_slip_emails as $merchant_mail) {
// Default language
$mail_id_lang = $id_lang;
$mail_iso = $iso;
$mail_locale = $locale;
// Use the merchant lang if he exists as an employee
$results = Db::getInstance()->executeS('
SELECT `id_lang` FROM `' . _DB_PREFIX_ . 'employee`
WHERE `email` = \'' . pSQL($merchant_mail) . '\'
');
if ($results) {
$user_iso = Language::getIsoById((int) $results[0]['id_lang']);
if ($user_iso) {
$mail_id_lang = (int) $results[0]['id_lang'];
$mail_iso = $user_iso;
$mail_locale = Language::getLocaleByIso($user_iso);
}
}
$dir_mail = false;
if (file_exists(dirname(__FILE__) . '/mails/' . $mail_iso . '/return_slip.txt') &&
file_exists(dirname(__FILE__) . '/mails/' . $mail_iso . '/return_slip.html')) {
$dir_mail = dirname(__FILE__) . '/mails/';
}