-
Notifications
You must be signed in to change notification settings - Fork 1
/
vg_postnord.php
1736 lines (1545 loc) · 68.4 KB
/
vg_postnord.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
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use PrestaShop\PrestaShop\Adapter\SymfonyContainer;
use PrestaShop\PrestaShop\Core\Grid\Definition\GridDefinition;
use PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton;
use PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButtonsCollection;
use Psr\Log\AbstractLogger;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Vilkas\Postnord\Client\PostnordClient;
use Vilkas\Postnord\Entity\VgPostnordBooking;
use Vilkas\Postnord\Entity\VgPostnordCartData;
use Vilkas\Postnord\Grid\Action\VgPostnordJavascriptAction;
use Vilkas\Postnord\Validator\VgPostnordPartyIdValidator;
if (!defined('_PS_VERSION_')) {
exit;
}
class Vg_postnord extends CarrierModule
{
const MODULE_NAME = 'vg_postnord';
protected $config_form = false;
/** @var AbstractLogger */
private $logger;
public function __construct()
{
$this->name = self::MODULE_NAME;
$this->tab = 'shipping_logistics';
$this->version = '1.1.3';
$this->author = 'Vilkas Group Oy';
$this->need_instance = 0;
/*
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->trans('Postnord', [], 'Modules.Vgpostnord.Admin');
$this->description = $this->trans('Postnord shipping for your Prestashop', [], 'Modules.Vgpostnord.Admin');
$this->ps_versions_compliancy = ['min' => '1.7.7', 'max' => _PS_VERSION_];
$this->tabs = [
[
'name' => $this->trans('Postnord Shipments', [], 'Modules.Vgpostnord.Admin'),
'parent_class_name' => 'AdminParentOrders',
'route_name' => 'admin_vg_postnord_list_action',
'class_name' => 'VgPostnordBookingController',
'visible' => true,
]
];
$this->logger = static::getLogger();
}
public function isUsingNewTranslationSystem(): bool
{
return true;
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install(): bool
{
Configuration::updateValue('VG_POSTNORD_DEBUG_MODE', false);
Configuration::updateValue('VG_POSTNORD_FETCH_BOTH', false);
Configuration::updateValue('VG_POSTNORD_DIFFERENT_RETURN_ADDRESS', false);
Configuration::updateValue('VG_POSTNORD_HOST', '');
Configuration::updateValue('VG_POSTNORD_APIKEY', '');
Configuration::updateValue('VG_POSTNORD_ISSUER_COUNTRY', '');
Configuration::updateValue('VG_POSTNORD_PARTY_ID', '');
Configuration::updateValue('VG_POSTNORD_EORI_NUMBER', '');
Configuration::updateValue('VG_POSTNORD_DEFAULT_TARIFF_NUMBER', '');
Configuration::updateValue('VG_POSTNORD_LABEL_PAPER_SIZE', 'A5');
Configuration::updateValue('VG_POSTNORD_CARRIER_SETTINGS', '[]');
Configuration::updateValue('VG_POSTNORD_SHOP_ADDRESS', '[]');
Configuration::updateValue('VG_POSTNORD_RETURN_ADDRESS', '[]');
return parent::install()
&& $this->installSQL()
&& $this->registerHook('displayHeader')
&& $this->registerHook('actionAdminControllerSetMedia')
&& $this->registerHook('displayCarrierExtraContent')
&& $this->registerHook('displayAdminOrderMain')
&& $this->registerHook('actionValidateOrder')
&& $this->registerHook('displayAdminEndContent')
// show possible selected pickup location in SF my account old order view
&& $this->registerHook('displayOrderDetail')
// show possible selected pickup location in order confirmation page
&& $this->registerHook('displayOrderConfirmation1')
// add "fetch label" button to order preview
&& $this->registerHook('displayOrderPreview')
// add "fetch label" button to order buttons
&& $this->registerHook('actionGetAdminOrderButtons')
// add "fetch label" button to order bulk actions
&& $this->registerHook('actionOrderGridDefinitionModifier')
// add service point information to order confirmation template variables
&& $this->registerHook('actionGetExtraMailTemplateVars')
// update booking when changing order carrier
&& $this->registerHook('actionObjectOrderUpdateBefore')
;
}
public function uninstall(): bool
{
Configuration::deleteByName('VG_POSTNORD_DEBUG_MODE');
Configuration::deleteByName('VG_POSTNORD_FETCH_BOTH');
Configuration::deleteByName('VG_POSTNORD_DIFFERENT_RETURN_ADDRESS');
Configuration::deleteByName('VG_POSTNORD_HOST');
Configuration::deleteByName('VG_POSTNORD_APIKEY');
Configuration::deleteByName('VG_POSTNORD_ISSUER_COUNTRY');
Configuration::deleteByName('VG_POSTNORD_PARTY_ID');
Configuration::deleteByName('VG_POSTNORD_EORI_NUMBER');
Configuration::deleteByName('VG_POSTNORD_DEFAULT_TARIFF_NUMBER');
Configuration::deleteByName('VG_POSTNORD_LABEL_PAPER_SIZE');
Configuration::deleteByName('VG_POSTNORD_CARRIER_SETTINGS');
Configuration::deleteByName('VG_POSTNORD_SHOP_ADDRESS');
Configuration::deleteByName('VG_POSTNORD_RETURN_ADDRESS');
return parent::uninstall()
&& $this->uninstallSQL();
}
/**
* Create SQL Tables for module.
*
* @return bool `true` if every entity gets created correctly
*/
private function installSQL(): bool
{
$queries = include dirname(__FILE__) . '/sql/install.php';
if (is_array($queries)) {
return $this->performInstallQueries($queries);
} else {
return false;
}
}
/**
* Drops module SQL tables.
*
* @return bool `true` if removed correctly
*/
private function uninstallSQL(): bool
{
$queries = include dirname(__FILE__) . '/sql/uninstall.php';
if (is_array($queries)) {
return $this->performInstallQueries($queries);
} else {
return false;
}
}
/**
* Execute a collection of SQL queries of the installation/uninstallation procedures.
*
* @param array $queries list of raw SQL queries to execute
*
* @return bool `true` if all queries were executed successfully
*/
private function performInstallQueries(array $queries): bool
{
foreach ($queries as $query) {
if (!Db::getInstance()->execute($query)) {
return false;
}
}
return true;
}
public static function getLogger(): Logger
{
$logger = new Logger('vg_postnord');
$logger->pushHandler(new StreamHandler(_PS_ROOT_DIR_ . '/var/logs/postnord.log'));
return $logger;
}
/**
* Load the configuration form
*/
public function getContent(): string
{
/*
* If values have been submitted in the form, process.
*/
$message = '';
if ((Tools::isSubmit('submitVg_postnordModule')) == true) {
if ($this->postProcess()) {
$message = $this->displayConfirmation(
$this->trans('Settings saved successfully.', [], 'Modules.Vgpostnord.Admin')
);
} else {
$message = $this->displayError(
$this->trans('Could not save settings.', [], 'Modules.Vgpostnord.Admin')
);
}
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
$footer = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure_footer.tpl');
return $message . $output . $this->renderForm() . $footer;
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm(): string
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitVg_postnordModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = [
'fields_value' => $this->getAllFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
return $helper->generateForm($this->getConfigForms());
}
protected function getConfigForms(): array
{
$form = [
'general' => $this->getConfigForm(),
'carriers' => $this->getCarrierConfigForm(),
'address' => $this->getAddressConfigForm(),
];
if (Configuration::get('VG_POSTNORD_DIFFERENT_RETURN_ADDRESS')) {
$form['return'] = $this->getReturnAddressConfigForm();
}
return $form;
}
protected function getAllFormValues(): array
{
return array_merge(
$this->getConfigFormValues(),
$this->getCarrierConfigFormValues(),
$this->getAddressConfigFormValues(),
Configuration::get('VG_POSTNORD_DIFFERENT_RETURN_ADDRESS') ? $this->getReturnAddressConfigFormValues() : []
);
}
/**
* Create the structure of your form.
*/
protected function getConfigForm(): array
{
return [
'form' => [
'legend' => [
'title' => $this->trans('Settings', [], 'Modules.Vgpostnord.Admin'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'switch',
'name' => 'VG_POSTNORD_DEBUG_MODE',
'label' => $this->trans('Debug mode', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Write more debug logs', [], 'Modules.Vgpostnord.Admin'),
'is_bool' => true,
'values' => [
[
'id' => 'active_on',
'value' => true,
'label' => $this->trans('Enabled', [], 'Modules.Vgpostnord.Admin'),
],
[
'id' => 'active_off',
'value' => false,
'label' => $this->trans('Disabled', [], 'Modules.Vgpostnord.Admin'),
],
],
],
[
'type' => 'switch',
'name' => 'VG_POSTNORD_FETCH_BOTH',
'label' => $this->trans('Fetch both labels', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Fetch shipping label and return label at the same time', [], 'Modules.Vgpostnord.Admin'),
'is_bool' => true,
'values' => [
[
'id' => 'active_on',
'value' => true,
'label' => $this->trans('Enabled', [], 'Modules.Vgpostnord.Admin'),
],
[
'id' => 'active_off',
'value' => false,
'label' => $this->trans('Disabled', [], 'Modules.Vgpostnord.Admin'),
],
],
],
[
'type' => 'switch',
'name' => 'VG_POSTNORD_DIFFERENT_RETURN_ADDRESS',
'label' => $this->trans('Different return address', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Enable if the return address is different than shop address', [], 'Modules.Vgpostnord.Admin'),
'is_bool' => true,
'values' => [
[
'id' => 'active_on',
'value' => true,
'label' => $this->trans('Enabled', [], 'Modules.Vgpostnord.Admin'),
],
[
'id' => 'active_off',
'value' => false,
'label' => $this->trans('Disabled', [], 'Modules.Vgpostnord.Admin'),
],
],
],
[
'type' => 'select',
'name' => 'VG_POSTNORD_ISSUER_COUNTRY',
'label' => $this->trans('Postnord issuer country', [], 'Modules.Vgpostnord.Admin'),
'options' => [
'query' => [
['id' => 'FI', 'name' => 'FI'],
['id' => 'AX', 'name' => 'AX'],
['id' => 'SE', 'name' => 'SE'],
['id' => 'DK', 'name' => 'DK'],
['id' => 'NO', 'name' => 'NO'],
],
'id' => 'id',
'name' => 'name',
'default' => null,
],
'desc' => $this->trans('Get this information from Postnord.', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'VG_POSTNORD_HOST',
'label' => $this->trans('Postnord hostname', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Get this information from Postnord. Usually something like: atapi2.postnord.com', [], 'Modules.Vgpostnord.Admin'),
'required' => true
],
[
'type' => 'text',
'name' => 'VG_POSTNORD_APIKEY',
'label' => $this->trans('Postnord apikey', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Get this information from Postnord. Something like abc123123123123abc123', [], 'Modules.Vgpostnord.Admin'),
'required' => true
],
[
'type' => 'text',
'name' => 'VG_POSTNORD_PARTY_ID',
'label' => $this->trans('Party ID', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('10 digits long customer number (Party ID). Get this information from Postnord', [], 'Modules.Vgpostnord.Admin'),
'required' => true
],
[
'type' => 'text',
'name' => 'VG_POSTNORD_EORI_NUMBER',
'label' => $this->trans('EORI number', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Required for all customs declarations', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'VG_POSTNORD_DEFAULT_TARIFF_NUMBER',
'label' => $this->trans('Default tariff number', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Default HS tariff number (see: tulltaxan.tullverket.se). Used to prefill tariff number for customs declarations.', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'select',
'name' => 'VG_POSTNORD_LABEL_PAPER_SIZE',
'label' => $this->trans('Label paper size', [], 'Modules.Vgpostnord.Admin'),
'options' => [
'query' => [
['id' => 'A4', 'name' => 'A4'],
['id' => 'A5', 'name' => 'A5'],
['id' => 'LABEL', 'name' => 'LABEL'],
],
'id' => 'id',
'name' => 'name',
'default' => null,
],
'desc' => $this->trans('Paper size for labels.', [], 'Modules.Vgpostnord.Admin'),
],
],
'submit' => [
'title' => $this->trans('Save', [], 'Modules.Vgpostnord.Admin'),
],
],
];
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues(): array
{
return [
'VG_POSTNORD_DEBUG_MODE' => Configuration::get('VG_POSTNORD_DEBUG_MODE'),
'VG_POSTNORD_FETCH_BOTH' => Configuration::get('VG_POSTNORD_FETCH_BOTH'),
'VG_POSTNORD_DIFFERENT_RETURN_ADDRESS' => Configuration::get('VG_POSTNORD_DIFFERENT_RETURN_ADDRESS'),
'VG_POSTNORD_HOST' => Configuration::get('VG_POSTNORD_HOST'),
'VG_POSTNORD_APIKEY' => Configuration::get('VG_POSTNORD_APIKEY'),
'VG_POSTNORD_ISSUER_COUNTRY' => Configuration::get('VG_POSTNORD_ISSUER_COUNTRY'),
'VG_POSTNORD_PARTY_ID' => Configuration::get('VG_POSTNORD_PARTY_ID'),
'VG_POSTNORD_EORI_NUMBER' => Configuration::get('VG_POSTNORD_EORI_NUMBER'),
'VG_POSTNORD_DEFAULT_TARIFF_NUMBER' => Configuration::get('VG_POSTNORD_DEFAULT_TARIFF_NUMBER'),
'VG_POSTNORD_LABEL_PAPER_SIZE' => Configuration::get('VG_POSTNORD_LABEL_PAPER_SIZE'),
];
}
/**
* Create a form to store shop address
* address will be stored in VG_POSTNORD_SHOP_ADDRESS as json
*/
protected function getAddressConfigForm(): array
{
return [
'form' => [
'legend' => [
'title' => $this->trans('Shop Address Setting', [], 'Modules.Vgpostnord.Admin'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'text',
'name' => 'shop_name',
'label' => $this->trans('Shop name', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender name', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'shop_street',
'label' => $this->trans('Shop street address', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender street address', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'shop_postcode',
'label' => $this->trans('Shop postal code', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender postal code', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'shop_city',
'label' => $this->trans('Shop city', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender city', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'select',
'name' => 'shop_country',
'label' => $this->trans('Shop country', [], 'Modules.Vgpostnord.Admin'),
'options' => [
'query' => [
['id' => 'FI', 'name' => 'Finland'],
['id' => 'AX', 'name' => 'Åland'],
['id' => 'SE', 'name' => 'Sweden'],
['id' => 'DK', 'name' => 'Denmark'],
['id' => 'NO', 'name' => 'Norway'],
],
'id' => 'id',
'name' => 'name',
'default' => null,
],
'desc' => $this->trans('Sender country', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'shop_phone',
'label' => $this->trans('Shop phone', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender phone', [], 'Modules.Vgpostnord.Admin'),
],
],
'submit' => [
'title' => $this->trans('Save', [], 'Modules.Vgpostnord.Admin'),
],
],
];
}
/**
* parse VG_POSTNORD_SHOP_ADDRESS to config form values
*/
public function getAddressConfigFormValues(): array
{
$address = json_decode(Configuration::get('VG_POSTNORD_SHOP_ADDRESS', true), true);
if (empty($address)) {
return [
'shop_name' => '',
'shop_street' => '',
'shop_postcode' => '',
'shop_city' => '',
'shop_country' => '',
'shop_phone' => '',
];
}
return $address;
}
/**
* Create a form to store shop address
* address will be stored in VG_POSTNORD_RETURN_ADDRESS as json
*/
protected function getReturnAddressConfigForm(): array
{
return [
'form' => [
'legend' => [
'title' => $this->trans('Return Address Setting', [], 'Modules.Vgpostnord.Admin'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'text',
'name' => 'return_name',
'label' => $this->trans('Return name', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender name', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'return_street',
'label' => $this->trans('Return street address', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender street address', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'return_postcode',
'label' => $this->trans('Return postal code', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender postal code', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'text',
'name' => 'return_city',
'label' => $this->trans('Return city', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Sender city', [], 'Modules.Vgpostnord.Admin'),
],
[
'type' => 'select',
'name' => 'return_country',
'label' => $this->trans('Return country', [], 'Modules.Vgpostnord.Admin'),
'options' => [
'query' => [
['id' => 'FI', 'name' => 'Finland'],
['id' => 'AX', 'name' => 'Åland'],
['id' => 'SE', 'name' => 'Sweden'],
['id' => 'DK', 'name' => 'Denmark'],
['id' => 'NO', 'name' => 'Norway'],
],
'id' => 'id',
'name' => 'name',
'default' => null,
],
'desc' => $this->trans('Sender country', [], 'Modules.Vgpostnord.Admin'),
],
],
'submit' => [
'title' => $this->trans('Save', [], 'Modules.Vgpostnord.Admin'),
],
],
];
}
/**
* parse VG_POSTNORD_RETURN_ADDRESS to config form values
*/
public function getReturnAddressConfigFormValues(): array
{
$address = json_decode(Configuration::get('VG_POSTNORD_RETURN_ADDRESS', true), true);
if (empty($address)) {
return [
'return_name' => '',
'return_street' => '',
'return_postcode' => '',
'return_city' => '',
'return_country' => '',
];
}
return $address;
}
/**
* Creates a form for mapping carriers to Postnord delivery methods.
*
* If api connection fails shows a warning message instead of the form
*
* These carrier configs are saved in VG_POSTNORD_CARRIER_SETTINGS as json
*
* And postprocess and getValues handles converting the values
*/
protected function getCarrierConfigForm(): array
{
$carriers = Carrier::getCarriers((int) $this->context->language->id, false, false, false, null, Carrier::ALL_CARRIERS);
$form = [
'form' => [
'legend' => [
'title' => $this->trans('Carrier Delivery Method Settings', [], 'Modules.Vgpostnord.Admin'),
'icon' => 'icon-cogs',
],
'submit' => [
'title' => $this->trans('Save', [], 'Modules.Vgpostnord.Admin'),
],
],
];
$host = Configuration::get('VG_POSTNORD_HOST');
$apikey = Configuration::get('VG_POSTNORD_APIKEY');
$issuerCountry = Configuration::get('VG_POSTNORD_ISSUER_COUNTRY');
// if settings are not yet complete, show message instead of the form
if (!$host || !$apikey) {
$form['form']['warning'] = $this->trans('Please complete Host and Apikey settings to configure Carriers.', [], 'Modules.Vgpostnord.Admin');
return $form;
}
// get listing of possible Postnord service codes and extra services that are available for it
try {
// first selection is empty
$ServiceCodes[] = [
'serviceCode_consigneeCountry' => 0,
'serviceName' => ' --- ',
];
// get the possible service codes
$client = new PostnordClient($host, $apikey);
$BasicServiceCodes = $client->getBasicServiceCodesFilterByIssuerCountryCode($issuerCountry);
$valid_combinations = $client->getValidCombinationsOfServiceCodes()["data"];
Media::addJsDef([
'validCombinations' => $valid_combinations
]);
// sort by id and name and consignee country to have some resemblance of logic in the list
array_multisort(
array_column($BasicServiceCodes, 'serviceCode'),
array_column($BasicServiceCodes, 'serviceName'),
array_column($BasicServiceCodes, 'allowedConsigneeCountry'),
SORT_ASC,
$BasicServiceCodes
);
// and add them to the dropdown list
foreach ($BasicServiceCodes as $BasicServiceCode) {
$name = sprintf('%s, %s (%s => %s)', $BasicServiceCode['serviceCode'], $BasicServiceCode['serviceName'], $BasicServiceCode['allowedConsigneeCountry'], $BasicServiceCode['allowedConsignorCountry']);
$ServiceCodes[] = [
'serviceCode_consigneeCountry' => $BasicServiceCode['serviceCode'] . '_' . $BasicServiceCode['allowedConsigneeCountry'],
'serviceName' => $name,
];
}
} catch (Exception $e) {
$form['form']['error'] = $this->trans('Failed fetching data from Postnord, check Host and Apikey', [], 'Modules.Vgpostnord.Admin');
$form['form']['description'] = $e->getMessage();
return $form;
}
$carrier_selections = [];
// build setting fields for each carrier,
// each carrier is prefixed with id_carrier_reference
// and then their reference id
// and then the setting
foreach ($carriers as $carrier) {
// just a label
$carrier_selections[] = [
'type' => 'free',
'name' => 'id_carrier_reference_' . $carrier['id_reference'],
'label' => '<b>' . $carrier['name'] . '</b>',
];
// which service code to use
$carrier_selections[] = [
'type' => 'select',
'options' => [
'query' => $ServiceCodes,
'id' => 'serviceCode_consigneeCountry',
'name' => 'serviceName',
'default' => null,
],
'name' => 'id_carrier_reference_' . $carrier['id_reference'] . '_service_code_consigneecountry',
'label' => $this->trans('Service code', [], 'Modules.Vgpostnord.Admin'),
'class' => 'fixed-width-xxl',
'desc' => $this->trans('Service code for this carrier', [], 'Modules.Vgpostnord.Admin'),
];
// which service codes to fetch pickup locations for
$carrier_selections[] = [
'type' => 'text',
'name' => 'id_carrier_reference_' . $carrier['id_reference'] . '_service_codes',
'label' => $this->trans('Service codes for pickup', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Comma separated list of service codes to use to filter pickuppoints. See possible values below. Leave empty for no filtering.', [], 'Modules.Vgpostnord.Admin'),
];
// additional service as a hidden text which will be filled with checkbox
$carrier_selections[] = [
'type' => 'text',
'name' => 'id_carrier_reference_' . $carrier['id_reference'] . '_additional_service_codes',
'label' => $this->trans('Additional service codes', [], 'Modules.Vgpostnord.Admin'),
'desc' => $this->trans('Set default additional service codes for this delivery method.', [], 'Modules.Vgpostnord.Admin'),
'class' => 'additional_service_codes hidden'
];
}
if (!$carrier_selections) {
$form['form']['description'] = $this->trans('No carriers found.', [], 'Modules.Vgpostnord.Admin');
}
$form['form']['input'] = $carrier_selections;
return $form;
}
/**
* parse VG_POSTNORD_CARRIER_SETTINGS to config form values
*/
public function getCarrierConfigFormValues(): array
{
$carriers = Carrier::getCarriers((int) $this->context->language->id, false, false, false, null, Carrier::ALL_CARRIERS);
$carrierValues = [];
$carrierSettings = $this->getCarrierConfigurations();
foreach ($carriers as $carrier) {
// just for the label (free text). always empty data
$carrierValues['id_carrier_reference_' . $carrier['id_reference']] = '';
$keys = ['service_code_consigneecountry', 'service_codes'];
foreach ($keys as $key) {
$carrierValues['id_carrier_reference_' . $carrier['id_reference'] . '_' . $key] = $carrierSettings[$carrier['id_reference']][$key] ?? '';
}
// special case: convert additional service codes into a JSON string for the hidden text input
$additional_service_codes = '';
if (array_key_exists($carrier['id_reference'], $carrierSettings)) {
$additional_service_codes = json_encode($carrierSettings[$carrier['id_reference']]['additional_service_codes']);
}
$carrierValues['id_carrier_reference_' . $carrier['id_reference'] . '_additional_service_codes'] = $additional_service_codes;
}
return $carrierValues;
}
/**
* get All carrier configurations, basically just decoded configuration
* The array id is carrier id_reference
*/
public function getCarrierConfigurations(): array
{
return json_decode(Configuration::get('VG_POSTNORD_CARRIER_SETTINGS'), true);
}
/**
* get one carrier configuration
*/
public function getCarrierConfiguration($id_carrier_reference): array
{
return $this->getCarrierConfigurations()[$id_carrier_reference];
}
/**
* Get both mandatory and additional service codes for a given carrier config
*
* @param array $carrier_config
*
* @return array
*/
public static function getCombinedServiceCodesForConfig(array $carrier_config): array
{
$mandatory = $additional = [];
if (array_key_exists("additional_service_codes", $carrier_config)) {
$additional = $carrier_config["additional_service_codes"];
}
if (array_key_exists("mandatory_service_codes", $carrier_config)) {
$mandatory = $carrier_config["mandatory_service_codes"];
}
return array_unique(array_merge($mandatory, $additional));
}
/**
* Save form data.
*/
protected function postProcess(): bool
{
$result = true;
// basic config form values
$config_form_values = $this->getConfigFormValues();
foreach (array_keys($config_form_values) as $key) {
$result &= Configuration::updateValue($key, Tools::getValue($key));
}
if (!VgPostnordPartyIdValidator::partyIdIsValid(Tools::getValue("VG_POSTNORD_PARTY_ID"))) {
$this->context->controller->errors[] = $this->trans("Party ID is not valid.", [], "Modules.Vgpostnord.Admin");
}
// address config into json
$address_form_values = $this->getAddressConfigFormValues();
$address_config = [];
foreach (array_keys($address_form_values) as $key) {
$address_config[$key] = Tools::getValue($key);
}
$result &= Configuration::updateValue('VG_POSTNORD_SHOP_ADDRESS', json_encode($address_config));
// address config into json
$return_address_form_values = $this->getReturnAddressConfigFormValues();
$return_address_config = [];
foreach (array_keys($return_address_form_values) as $key) {
$return_address_config[$key] = Tools::getValue($key);
}
$result &= Configuration::updateValue('VG_POSTNORD_RETURN_ADDRESS', json_encode($return_address_config));
// carrier settings into one json
$carrier_form_values = $this->getCarrierConfigFormValues();
$carrier_config = [];
foreach (array_keys($carrier_form_values) as $key) {
// format is id_carrier_reference_IDX_key (except for the label which does not have a key at all)
$newkey = str_replace('id_carrier_reference_', '', $key);
$idx = filter_var($newkey, FILTER_SANITIZE_NUMBER_INT);
// skip the label
if ($newkey == $idx) {
continue;
}
$newkey = str_replace($idx . '_', '', $newkey);
$carrier_config[$idx][$newkey] = Tools::getValue($key);
}
try {
$client = new PostnordClient(
Configuration::get("VG_POSTNORD_HOST"),
Configuration::get("VG_POSTNORD_APIKEY")
);
$valid_combinations = $client->getValidCombinationsOfServiceCodes()["data"];
} catch (Exception | ExceptionInterface $e) {
$msg = $this->trans("Error fetching service code combinations: %error%", ["%error%" => $e->getMessage()], "Modules.Vgpostnord.Admin");
$this->context->controller->errors[] = $msg;
return false;
}
foreach ($carrier_config as $id_carrier_reference => &$oneconfig) {
// set the carriers that are marked to use pickup to is_module so that it can do displayCarrierExtraContent
if ($oneconfig['service_code_consigneecountry']) {
$this->setCarrierToPostNord($id_carrier_reference, true);
} else {
$this->setCarrierToPostNord($id_carrier_reference, false);
}
// convert additional_service_codes from JSON string to array for storage,
// so it won't be double-encoded inside the database
$asc = json_decode($oneconfig["additional_service_codes"]) ?? [];
$oneconfig["additional_service_codes"] = $asc;
// TODO: swear there's a better way to do whatever the following lines do
if (!$oneconfig["service_code_consigneecountry"]) {
$oneconfig["mandatory_service_codes"] = [];
continue;
}
$split = explode("_", $oneconfig["service_code_consigneecountry"]);
[$service_code, $consignee_country] = $split;
// find combinations related to issuer country
$valid_country_combinations = array_filter($valid_combinations, function ($element) use ($consignee_country) {
return $element['issuerCountryCode'] === $consignee_country ? $element : null;
});
if (empty($valid_country_combinations)) {
$oneconfig["mandatory_service_codes"] = [];
continue;
}
// find mandatory services for service code and consignee country
$valid_country_combinations = reset($valid_country_combinations)["adnlServiceCodeCombDetails"];
$mandatory_combinations = array_filter($valid_country_combinations, function ($element) use ($service_code, $consignee_country) {
return $element["mandatory"] === true
&& $element["serviceCode"] === $service_code
&& $element["allowedConsigneeCountry"] === $consignee_country;
});
// grab 'adnlServiceCode' from every matching service
$mandatory_service_codes = array_column($mandatory_combinations, "adnlServiceCode");
$oneconfig["mandatory_service_codes"] = $mandatory_service_codes;
}
unset($oneconfig);
// and save the carrier config
$result &= Configuration::updateValue('VG_POSTNORD_CARRIER_SETTINGS', json_encode($carrier_config));
return $result;
}
/**
* Set carrier to `is_module` = 1 to get displayCarrierExtraContent to trigger
*/
public function setCarrierToPostNord(int $id_carrier_reference, bool $status): bool
{
$db = \Db::getInstance();
if ($status) {
return $db->Execute(
'UPDATE `' . _DB_PREFIX_ . 'carrier`
SET
`external_module_name` = "vg_postnord",
`is_module` = 1,
`need_range` = 1
WHERE `id_reference` = ' . (int) $id_carrier_reference
);
} else {
return $db->Execute(
'UPDATE `' . _DB_PREFIX_ . 'carrier`
SET `external_module_name` = "",
`is_module` = 0,
`need_range` = 0
WHERE `id_reference` = ' . (int) $id_carrier_reference
. ' AND external_module_name="vg_postnord"'
);
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookActionAdminControllerSetMedia()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
if (Tools::getValue('controller') == 'AdminOrders') {
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
if (Tools::getValue('configure') === $this->name) {
$this->context->controller->addJS($this->_path . '/views/js/config.js');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookDisplayHeader()
{
$this->context->controller->addJS($this->_path . '/views/js/front.js');
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
/**
* FRONT OFFICE / Carrier selection
*
* If the selected carrier is marked as a postnord carrier that has pickup locations show a selection screen of
* pickup point to the customer
*
* The pickup point will be saved as an ajax request to be used for label creation later
*/
public function hookDisplayCarrierExtraContent($params)
{
// don't show pickup point selection if the "optional service point" additional service hasn't been
// selected and isn't mandatory
$carrier_config = $this->getCarrierConfiguration((int) $params["carrier"]["id_reference"]);
$service_codes = static::getCombinedServiceCodesForConfig($carrier_config);
if (!in_array("A7", $service_codes)) {
return null;
}
// prefill with the zipcode user has already given
$id_address = $params['cart']->id_address_delivery;