-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwopayment.php
More file actions
3409 lines (3049 loc) · 169 KB
/
twopayment.php
File metadata and controls
3409 lines (3049 loc) · 169 KB
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
/**
* @author Plugin Developer from Two <jgang@two.inc> <support@two.inc>
* @copyright Since 2021 Two Team
* @license Two Commercial License
*/
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
if (!defined('_PS_VERSION_')) {
exit;
}
class Twopayment extends PaymentModule
{
// Constants for order building logic
const GROSS_AMOUNT_TOLERANCE = 0.02; // 2 cents tolerance for rounding differences
const ORDER_INTENT_EXPIRY_SECONDS = 1800; // 30 minutes
// Constants for payment terms
const DEFAULT_PAYMENT_TERM_DAYS = 30; // Default payment term in days
const PAYMENT_TERMS_OPTIONS = [7, 15, 20, 30, 45, 60, 90]; // Available payment term options
// Constants for API timeouts (seconds)
const API_TIMEOUT_SHORT = 30; // Standard API timeout
const API_TIMEOUT_LONG = 60; // Extended timeout for file uploads
// Constants for validation tolerances
const TAX_FORMULA_TOLERANCE = 0.01; // Tolerance for tax formula validation
const NET_FORMULA_TOLERANCE = 0.05; // Tolerance for net formula validation
// Constants for delivery dates
const DEFAULT_DELIVERY_DAYS_OFFSET = 7; // Default expected delivery date offset
// Constants for HTTP status codes
const HTTP_STATUS_OK = 200;
const HTTP_STATUS_CREATED = 201;
const HTTP_STATUS_BAD_REQUEST = 400;
const HTTP_STATUS_SERVER_ERROR = 500;
// Constants for cookie/session expiry (seconds)
const COOKIE_EXPIRY_ONE_HOUR = 3600; // 1 hour
protected $output = '';
protected $errors = array();
protected $verifiedMerchantId = null;
protected $verifiedMerchantShortName = null;
public function __construct()
{
$this->name = 'twopayment';
$this->tab = 'payments_gateways';
$this->version = '2.2.0';
$this->ps_versions_compliancy = array('min' => '1.7.6.0', 'max' => _PS_VERSION_);
$this->author = 'Two';
$this->bootstrap = true;
$this->module_key = '0dff0a98ae080e510d4e23d22abcfe9c';
$this->author_address = '';
parent::__construct();
$this->languages = Language::getLanguages(false);
$this->displayName = $this->l('Two - BNPL for businesses');
$this->description = $this->l('This module allows any merchant to accept payments with Two payment gateway.');
$this->merchant_short_name = Configuration::get('PS_TWO_MERCHANT_SHORT_NAME');
$this->api_key = Configuration::get('PS_TWO_MERCHANT_API_KEY');
$this->enable_company_name = Configuration::get('PS_TWO_ENABLE_COMPANY_NAME');
$this->enable_company_id = Configuration::get('PS_TWO_ENABLE_COMPANY_ID');
$this->enable_department = Configuration::get('PS_TWO_ENABLE_DEPARTMENT');
$this->enable_project = Configuration::get('PS_TWO_ENABLE_PROJECT');
$this->enable_order_intent = Configuration::get('PS_TWO_ENABLE_ORDER_INTENT');
$this->use_account_type = Configuration::get('PS_TWO_USE_ACCOUNT_TYPE');
$this->finalize_purchase_shipping = Configuration::get('PS_TWO_FINALIZE_PURCHASE');
// Ensure custom Two states exist (for existing installations)
$this->ensureCustomStatesExist();
}
/**
* Ensure custom Two order states exist, create them if they don't
* This handles existing installations that didn't have custom states
*/
private function ensureCustomStatesExist()
{
// Check if the main custom state exists
if (!Configuration::get('PS_TWO_OS_AWAITING_VERIFICATION')) {
// Create custom states and set up default mappings
$this->createTwoOrderState();
// Set up default mappings if they don't exist
if (!Configuration::get('PS_TWO_OS_AWAITING_VERIFICATION_MAP')) {
Configuration::updateValue('PS_TWO_OS_AWAITING_VERIFICATION_MAP', Configuration::get('PS_OS_PREPARATION'));
Configuration::updateValue('PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT_MAP', Configuration::get('PS_OS_PREPARATION'));
Configuration::updateValue('PS_TWO_OS_FULFILLED_MAP', Configuration::get('PS_OS_SHIPPING'));
Configuration::updateValue('PS_TWO_OS_PAYMENT_ERROR_MAP', Configuration::get('PS_OS_ERROR'));
Configuration::updateValue('PS_TWO_OS_CANCELLED_MAP', Configuration::get('PS_OS_CANCELED'));
Configuration::updateValue('PS_TWO_OS_REFUNDED_MAP', Configuration::get('PS_OS_REFUND'));
}
}
}
public function install()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return parent::install() &&
$this->registerHook('actionAdminControllerSetMedia') &&
$this->registerHook('actionFrontControllerSetMedia') &&
$this->registerHook('actionOrderStatusUpdate') &&
$this->registerHook('paymentOptions') &&
$this->registerHook('displayPaymentReturn') &&
$this->registerHook('displayAdminOrderLeft') &&
$this->registerHook('displayAdminOrderTabLink') &&
$this->registerHook('displayAdminOrderTabContent') &&
$this->registerHook('displayOrderDetail') &&
$this->registerHook('actionOrderEdited') &&
$this->registerHook('actionAdminOrdersTrackingNumberUpdate') &&
$this->registerHook('actionCustomerAddressSave') &&
$this->installTwoSettings() &&
$this->createTwoOrderState() &&
$this->createTwoTables();
}
protected function installTwoSettings()
{
$installData = array();
foreach ($this->languages as $language) {
$installData['PS_TWO_TITLE'][(int) $language['id_lang']] = 'Business invoice 30 days';
$installData['PS_TWO_SUB_TITLE'][(int) $language['id_lang']] = 'Buy now, pay later - instant credit';
}
Configuration::updateValue('PS_TWO_TAB_VALUE', 1);
Configuration::updateValue('PS_TWO_TITLE', $installData['PS_TWO_TITLE']);
Configuration::updateValue('PS_TWO_SUB_TITLE', $installData['PS_TWO_SUB_TITLE']);
Configuration::updateValue('PS_TWO_ENVIRONMENT', 'development'); // Default to development for safety
Configuration::updateValue('PS_TWO_MERCHANT_SHORT_NAME', '');
Configuration::updateValue('PS_TWO_MERCHANT_API_KEY', '');
Configuration::updateValue('PS_TWO_MERCHANT_ID', '');
Configuration::updateValue('PS_TWO_API_KEY_VERIFIED', 0);
Configuration::updateValue('PS_TWO_DISABLE_SSL_VERIFY', 0); // Default: SSL verification enabled (secure)
Configuration::updateValue('PS_TWO_ENABLE_COMPANY_NAME', 1);
Configuration::updateValue('PS_TWO_ENABLE_COMPANY_ID', 1);
Configuration::updateValue('PS_TWO_FINALIZE_PURCHASE', 1);
Configuration::updateValue('PS_TWO_ENABLE_ORDER_INTENT', 1);
Configuration::updateValue('PS_TWO_USE_ACCOUNT_TYPE', 0);
Configuration::updateValue('PS_TWO_USE_OWN_INVOICES', 0); // Disabled by default - must be enabled after coordinating with Two
Configuration::updateValue('PS_TWO_PAYMENT_TERMS_30', 1); // Default: 30 days enabled
// Custom Two order states will be created by createTwoOrderState()
// Set sensible default mappings to standard PrestaShop states
// Processing states default to their Two-branded states out-of-the-box
Configuration::updateValue('PS_TWO_OS_AWAITING_VERIFICATION_MAP', Configuration::get('PS_TWO_OS_AWAITING_VERIFICATION'));
Configuration::updateValue('PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT_MAP', Configuration::get('PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT'));
Configuration::updateValue('PS_TWO_OS_FULFILLED_MAP', json_encode(array((int)Configuration::get('PS_OS_SHIPPING')))); // "Shipped" - stored as JSON array
Configuration::updateValue('PS_TWO_OS_PAYMENT_ERROR_MAP', Configuration::get('PS_OS_ERROR')); // "Payment error"
Configuration::updateValue('PS_TWO_OS_CANCELLED_MAP', Configuration::get('PS_OS_CANCELED')); // "Canceled"
Configuration::updateValue('PS_TWO_OS_REFUNDED_MAP', Configuration::get('PS_OS_REFUND')); // "Refunded"
return true;
}
/**
* Clean approach: No modifications to core PrestaShop tables
* Company data is handled through form fields and session state
*/
protected function createTwoOrderState()
{
$orderStates = [
[
'config_key' => 'PS_TWO_OS_AWAITING_VERIFICATION',
'name' => 'Two: Awaiting Buyer Verification',
'color' => '#FF9500',
'paid' => 0,
'invoice' => 0,
'shipped' => 0,
'delivery' => 0,
'logable' => 1,
],
[
'config_key' => 'PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT',
'name' => 'Two: Verified - Ready for Fulfillment',
'color' => '#007CFF',
'paid' => 1,
'invoice' => 1,
'shipped' => 0,
'delivery' => 0,
'logable' => 1,
],
[
'config_key' => 'PS_TWO_OS_FULFILLED',
'name' => 'Two: Order Fulfilled - Payment Terms Active',
'color' => '#34C759',
'paid' => 1,
'invoice' => 1,
'shipped' => 1,
'delivery' => 0,
'logable' => 1,
],
[
'config_key' => 'PS_TWO_OS_PAYMENT_ERROR',
'name' => 'Two: Payment Processing Error',
'color' => '#FF3B30',
'paid' => 0,
'invoice' => 0,
'shipped' => 0,
'delivery' => 0,
'logable' => 1,
],
[
'config_key' => 'PS_TWO_OS_CANCELLED',
'name' => 'Two: Order Cancelled',
'color' => '#8E8E93',
'paid' => 0,
'invoice' => 0,
'shipped' => 0,
'delivery' => 0,
'logable' => 1,
],
[
'config_key' => 'PS_TWO_OS_REFUNDED',
'name' => 'Two: Order Refunded',
'color' => '#AF52DE',
'paid' => 0,
'invoice' => 1,
'shipped' => 0,
'delivery' => 0,
'logable' => 1,
],
];
foreach ($orderStates as $stateConfig) {
if (!Configuration::get($stateConfig['config_key'])) {
$orderStateObj = new OrderState();
$orderStateObj->send_email = 0;
$orderStateObj->module_name = $this->name;
$orderStateObj->invoice = $stateConfig['invoice'];
$orderStateObj->color = $stateConfig['color'];
$orderStateObj->logable = $stateConfig['logable'];
$orderStateObj->shipped = $stateConfig['shipped'];
$orderStateObj->unremovable = 1;
$orderStateObj->delivery = $stateConfig['delivery'];
$orderStateObj->hidden = 0;
$orderStateObj->paid = $stateConfig['paid'];
$orderStateObj->pdf_delivery = 0;
$orderStateObj->pdf_invoice = $stateConfig['invoice'];
$orderStateObj->deleted = 0;
foreach ($this->languages as $language) {
$orderStateObj->name[$language['id_lang']] = $stateConfig['name'];
}
if ($orderStateObj->add()) {
Configuration::updateValue($stateConfig['config_key'], (int) $orderStateObj->id);
} else {
return false;
}
}
}
return true;
}
protected function createTwoTables()
{
// Only create our own payment tracking table - no modifications to core PrestaShop tables
$sql = array();
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'twopayment` (
`id_two` int(11) NOT NULL AUTO_INCREMENT,
`id_order` INT( 11 ) UNSIGNED,
`two_order_id` TEXT NULL,
`two_order_reference` TEXT NULL,
`two_order_state` TEXT NULL,
`two_order_status` TEXT NULL,
`two_day_on_invoice` TEXT NULL,
`two_invoice_url` TEXT NULL,
`two_invoice_id` VARCHAR(255) NULL,
`two_invoice_upload_status` ENUM("PENDING", "UPLOADING", "UPLOADED", "FAILED", "NOT_APPLICABLE") DEFAULT "NOT_APPLICABLE",
`two_invoice_upload_reference` VARCHAR(255) NULL,
`two_invoice_upload_error` TEXT NULL,
`two_invoice_uploaded_at` DATETIME NULL,
PRIMARY KEY (`id_two`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
return true;
}
public function uninstall()
{
return parent::uninstall() &&
$this->unregisterHook('actionAdminControllerSetMedia') &&
$this->unregisterHook('actionFrontControllerSetMedia') &&
$this->unregisterHook('actionOrderStatusUpdate') &&
$this->unregisterHook('paymentOptions') &&
$this->unregisterHook('displayPaymentReturn') &&
$this->unregisterHook('displayAdminOrderLeft') &&
$this->unregisterHook('displayAdminOrderTabLink') &&
$this->unregisterHook('displayAdminOrderTabContent') &&
$this->unregisterHook('displayOrderDetail') &&
$this->unregisterHook('actionOrderEdited') &&
$this->unregisterHook('actionAdminOrdersTrackingNumberUpdate') &&
$this->unregisterHook('actionCustomerAddressSave') &&
$this->uninstallTwoSettings() &&
$this->deleteTwoTables();
}
protected function uninstallTwoSettings()
{
Configuration::deleteByName('PS_TWO_TAB_VALUE');
Configuration::deleteByName('PS_TWO_TITLE');
Configuration::deleteByName('PS_TWO_SUB_TITLE');
Configuration::deleteByName('PS_TWO_MERCHANT_SHORT_NAME');
Configuration::deleteByName('PS_TWO_MERCHANT_API_KEY');
Configuration::deleteByName('PS_TWO_MERCHANT_ID');
Configuration::deleteByName('PS_TWO_API_KEY_VERIFIED');
Configuration::deleteByName('PS_TWO_DISABLE_SSL_VERIFY');
Configuration::deleteByName('PS_TWO_ENABLE_COMPANY_NAME');
Configuration::deleteByName('PS_TWO_ENABLE_COMPANY_ID');
Configuration::deleteByName('PS_TWO_ENABLE_DEPARTMENT');
Configuration::deleteByName('PS_TWO_ENABLE_PROJECT');
Configuration::deleteByName('PS_TWO_FINALIZE_PURCHASE');
Configuration::deleteByName('PS_TWO_ENABLE_ORDER_INTENT');
Configuration::deleteByName('PS_TWO_USE_ACCOUNT_TYPE');
return true;
}
protected function deleteTwoTables()
{
$sql = array();
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
return true;
}
public function getContent()
{
if (((bool) Tools::isSubmit('submitTwoGeneralForm')) == true) {
Configuration::updateValue('PS_TWO_TAB_VALUE', 1);
$this->validTwoGeneralFormValues();
if (!count($this->errors)) {
$this->saveTwoGeneralFormValues();
} else {
foreach ($this->errors as $err) {
$this->output .= $this->displayError($err);
}
}
}
if (((bool) Tools::isSubmit('submitTwoOtherForm')) == true) {
Configuration::updateValue('PS_TWO_TAB_VALUE', 2);
$this->validTwoOtherFormValues();
if (!count($this->errors)) {
$this->saveTwoOtherFormValues();
} else {
foreach ($this->errors as $err) {
$this->output .= $this->displayError($err);
}
}
}
if (((bool) Tools::isSubmit('submitTwoOrderStatusForm')) == true) {
Configuration::updateValue('PS_TWO_TAB_VALUE', 3);
$this->saveTwoOrderStatusFormValues();
}
$this->context->smarty->assign(
array(
'renderTwoGeneralForm' => $this->renderTwoGeneralForm(),
'renderTwoOtherForm' => $this->renderTwoOtherForm(),
'renderTwoOrderStatusForm' => $this->renderTwoOrderStatusForm(),
'twotabvalue' => Configuration::get('PS_TWO_TAB_VALUE'),
'two_api_verified' => (int) Configuration::get('PS_TWO_API_KEY_VERIFIED'),
'two_merchant_id' => Configuration::get('PS_TWO_MERCHANT_ID'),
'two_merchant_short_name' => Configuration::get('PS_TWO_MERCHANT_SHORT_NAME'),
'two_env' => Configuration::get('PS_TWO_ENVIRONMENT'),
)
);
$this->output .= $this->display(__FILE__, 'views/templates/admin/configuration.tpl');
return $this->output;
}
protected function renderTwoGeneralForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
$helper->module = $this;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitTwoGeneralForm';
$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 = array(
'uri' => $this->getPathUri(),
'fields_value' => $this->getTwoGeneralFormValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getTwoGeneralForm()));
}
protected function getTwoGeneralForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('General Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Title'),
'desc' => $this->l('Enter a title which is appear on checkout page as payment method title.'),
'name' => 'PS_TWO_TITLE',
'required' => true,
'lang' => true,
),
array(
'type' => 'text',
'label' => $this->l('Sub title'),
'desc' => $this->l('Enter a sub title which is appear on checkout page as payment method sub title.'),
'name' => 'PS_TWO_SUB_TITLE',
'required' => true,
'lang' => true,
),
array(
'type' => 'password',
'label' => $this->l('Api key'),
'name' => 'PS_TWO_MERCHANT_API_KEY',
'required' => true,
'desc' => $this->l('Enter your api key which is provided by Two.'),
),
array(
'type' => 'select',
'label' => $this->l('Environment'),
'name' => 'PS_TWO_ENVIRONMENT',
'desc' => $this->l('Select the Two API environment to use. Production for live transactions, Development for testing.'),
'required' => true,
'options' => array(
'query' => array(
array('id_option' => 'development', 'name' => $this->l('Development')),
array('id_option' => 'production', 'name' => $this->l('Production')),
),
'id' => 'id_option',
'name' => 'name'
)
),
array(
'type' => 'checkbox',
'label' => $this->l('Available Payment Terms'),
'name' => 'PS_TWO_PAYMENT_TERMS',
'desc' => $this->l('Select which payment terms you want to offer to your customers at checkout. If only one term is selected, it will be used as the default. Multiple terms will show a selector.'),
'values' => array(
'query' => array(
array(
'id' => '7',
'name' => $this->l('7 days'),
'val' => '1'
),
array(
'id' => '15',
'name' => $this->l('15 days'),
'val' => '1'
),
array(
'id' => '20',
'name' => $this->l('20 days'),
'val' => '1'
),
array(
'id' => '30',
'name' => $this->l('30 days'),
'val' => '1'
),
array(
'id' => '45',
'name' => $this->l('45 days'),
'val' => '1'
),
array(
'id' => '60',
'name' => $this->l('60 days'),
'val' => '1'
),
array(
'id' => '90',
'name' => $this->l('90 days'),
'val' => '1'
),
),
'id' => 'id',
'name' => 'name'
)
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
return $fields_form;
}
protected function getTwoGeneralFormValues()
{
$fields_values = array();
foreach ($this->languages as $language) {
$fields_values['PS_TWO_TITLE'][$language['id_lang']] = Tools::getValue('PS_TWO_TITLE_' . (int) $language['id_lang'], Configuration::get('PS_TWO_TITLE', (int) $language['id_lang']));
$fields_values['PS_TWO_SUB_TITLE'][$language['id_lang']] = Tools::getValue('PS_TWO_SUB_TITLE_' . (int) $language['id_lang'], Configuration::get('PS_TWO_SUB_TITLE', (int) $language['id_lang']));
}
$fields_values['PS_TWO_MERCHANT_SHORT_NAME'] = Tools::getValue('PS_TWO_MERCHANT_SHORT_NAME', Configuration::get('PS_TWO_MERCHANT_SHORT_NAME'));
$fields_values['PS_TWO_MERCHANT_API_KEY'] = Tools::getValue('PS_TWO_MERCHANT_API_KEY', Configuration::get('PS_TWO_MERCHANT_API_KEY'));
$fields_values['PS_TWO_ENVIRONMENT'] = Tools::getValue('PS_TWO_ENVIRONMENT', Configuration::get('PS_TWO_ENVIRONMENT'));
// Payment terms checkboxes
$payment_terms = array_map('strval', self::PAYMENT_TERMS_OPTIONS);
foreach ($payment_terms as $term) {
$fields_values['PS_TWO_PAYMENT_TERMS_' . $term] = Tools::getValue('PS_TWO_PAYMENT_TERMS_' . $term, Configuration::get('PS_TWO_PAYMENT_TERMS_' . $term));
}
return $fields_values;
}
protected function validTwoGeneralFormValues()
{
foreach ($this->languages as $language) {
if (Tools::isEmpty(Tools::getValue('PS_TWO_TITLE_' . (int) $language['id_lang']))) {
$this->errors[] = $this->l('Enter a title.');
}
if (Tools::isEmpty(Tools::getValue('PS_TWO_SUB_TITLE_' . (int) $language['id_lang']))) {
$this->errors[] = $this->l('Enter a sub title.');
}
}
if (Tools::isEmpty(Tools::getValue('PS_TWO_MERCHANT_API_KEY'))) {
$this->errors[] = $this->l('Enter an API key.');
}
// Validate environment
$environment = Tools::getValue('PS_TWO_ENVIRONMENT');
if (Tools::isEmpty($environment) || !in_array($environment, array('production', 'development'))) {
$this->errors[] = $this->l('Please select a valid environment (Production or Development).');
}
// Validate payment terms
$payment_terms = array_map('strval', self::PAYMENT_TERMS_OPTIONS);
$selected_terms = array();
foreach ($payment_terms as $term) {
if (Tools::getValue('PS_TWO_PAYMENT_TERMS_' . $term)) {
$selected_terms[] = $term;
}
}
if (empty($selected_terms)) {
$this->errors[] = $this->l('You must select at least one payment term.');
}
// Verify API key with Two against selected environment and capture merchant id and short name
$apiKey = trim(Tools::getValue('PS_TWO_MERCHANT_API_KEY'));
$env = Tools::getValue('PS_TWO_ENVIRONMENT');
if (!empty($apiKey) && in_array($env, array('production','development'))) {
$verify = $this->verifyTwoApiKey($apiKey, $env);
if ($verify === false) {
$this->errors[] = $this->l('API key verification failed. Please check your API key.');
} else {
if (!isset($verify['id']) || !isset($verify['short_name'])) {
$this->errors[] = $this->l('Invalid verification response from Two.');
} else {
$this->verifiedMerchantId = $verify['id'];
$this->verifiedMerchantShortName = $verify['short_name'];
}
}
}
}
protected function saveTwoGeneralFormValues()
{
$values = array();
foreach ($this->languages as $language) {
$values['PS_TWO_TITLE'][(int) $language['id_lang']] = Tools::getValue('PS_TWO_TITLE_' . (int) $language['id_lang']);
$values['PS_TWO_SUB_TITLE'][(int) $language['id_lang']] = Tools::getValue('PS_TWO_SUB_TITLE_' . (int) $language['id_lang']);
}
Configuration::updateValue('PS_TWO_TITLE', $values['PS_TWO_TITLE']);
Configuration::updateValue('PS_TWO_SUB_TITLE', $values['PS_TWO_SUB_TITLE']);
// If verification succeeded, use verified short name; else fallback to form (kept for safety)
$shortNameToSave = $this->verifiedMerchantShortName ? $this->verifiedMerchantShortName : trim(Tools::getValue('PS_TWO_MERCHANT_SHORT_NAME'));
Configuration::updateValue('PS_TWO_MERCHANT_SHORT_NAME', $shortNameToSave);
Configuration::updateValue('PS_TWO_MERCHANT_API_KEY', trim(Tools::getValue('PS_TWO_MERCHANT_API_KEY')));
Configuration::updateValue('PS_TWO_ENVIRONMENT', Tools::getValue('PS_TWO_ENVIRONMENT'));
Configuration::updateValue('PS_TWO_DISABLE_SSL_VERIFY', (int)Tools::getValue('PS_TWO_DISABLE_SSL_VERIFY', 0));
if ($this->verifiedMerchantId) {
Configuration::updateValue('PS_TWO_MERCHANT_ID', $this->verifiedMerchantId);
Configuration::updateValue('PS_TWO_API_KEY_VERIFIED', 1);
} else {
// Ensure flag not stale when verification fails/non-run
Configuration::updateValue('PS_TWO_API_KEY_VERIFIED', 0);
}
// Save payment terms checkboxes
$payment_terms = array_map('strval', self::PAYMENT_TERMS_OPTIONS);
foreach ($payment_terms as $term) {
Configuration::updateValue('PS_TWO_PAYMENT_TERMS_' . $term, Tools::getValue('PS_TWO_PAYMENT_TERMS_' . $term) ? 1 : 0);
}
$this->output .= $this->displayConfirmation($this->l('General settings are updated.'));
}
protected function renderTwoOtherForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
$helper->module = $this;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitTwoOtherForm';
$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 = array(
'uri' => $this->getPathUri(),
'fields_value' => $this->getTwoOtherFormValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getTwoOtherForm()));
}
protected function getTwoOtherForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Other Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Use Account Type selection'),
'name' => 'PS_TWO_USE_ACCOUNT_TYPE',
'is_bool' => true,
'desc' => $this->l('If Yes, the address form will show Account Type and company fields become required for business. If No, the address form will not show Account Type and Two will prompt for company only at payment time.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_USE_ACCOUNT_TYPE_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_USE_ACCOUNT_TYPE_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Activate company name auto-complete'),
'name' => 'PS_TWO_ENABLE_COMPANY_NAME',
'is_bool' => true,
'desc' => $this->l('If you choose YES then customers to use search api to find their company names.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_ENABLE_COMPANY_NAME_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_ENABLE_COMPANY_NAME_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Activate company org.id auto-complete'),
'name' => 'PS_TWO_ENABLE_COMPANY_ID',
'is_bool' => true,
'desc' => $this->l('If you choose YES then customers to use search api to fins their company id (number) automatically.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_ENABLE_COMPANY_ID_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_ENABLE_COMPANY_ID_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Show Department field'),
'name' => 'PS_TWO_ENABLE_DEPARTMENT',
'is_bool' => true,
'desc' => $this->l('If you choose YES then customers will see department field in checkout.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_ENABLE_DEPARTMENT_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_ENABLE_DEPARTMENT_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Show Project field'),
'name' => 'PS_TWO_ENABLE_PROJECT',
'is_bool' => true,
'desc' => $this->l('If you choose YES then customers will see project field in checkout.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_ENABLE_PROJECT_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_ENABLE_PROJECT_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Automatically fulfill orders with Two'),
'name' => 'PS_TWO_FINALIZE_PURCHASE',
'is_bool' => true,
'desc' => $this->l('When enabled, orders are automatically marked as fulfilled in Two when their status changes to one of your configured fulfillment trigger statuses (see Order Status Mapping). This activates buyer payment terms and begins the payout cycle. If disabled, you must fulfill orders manually in Two\'s Merchant Portal.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_FINALIZE_PURCHASE_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_FINALIZE_PURCHASE_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Using Own Invoices'),
'name' => 'PS_TWO_USE_OWN_INVOICES',
'is_bool' => true,
'desc' => $this->l('Only to be used if you are handling your own invoice and credit note distribution and must be communicated to Two as part of your implementation to ensure Two\'s invoice generation is disabled. If this toggle is enabled, PrestaShop invoices will be uploaded to Two when orders are fulfilled.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_USE_OWN_INVOICES_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_USE_OWN_INVOICES_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Pre-approve the buyer during checkout and disable two if the buyer is declined'),
'name' => 'PS_TWO_ENABLE_ORDER_INTENT',
'is_bool' => true,
'desc' => $this->l('If you choose YES then pre-approve the buyer during checkout and disable two if the buyer is declined.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_ENABLE_ORDER_INTENT_ON',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'PS_TWO_ENABLE_ORDER_INTENT_OFF',
'value' => 0,
'label' => $this->l('No')
),
),
),
array(
'type' => 'switch',
'label' => $this->l('Disable SSL Verification (Corporate Networks Only)'),
'name' => 'PS_TWO_DISABLE_SSL_VERIFY',
'is_bool' => true,
'desc' => $this->l('WARNING: Only enable this if you are behind a corporate proxy with custom SSL certificates. This disables SSL certificate verification and is a SECURITY RISK. NOT RECOMMENDED for production.'),
'required' => true,
'values' => array(
array(
'id' => 'PS_TWO_DISABLE_SSL_VERIFY_ON',
'value' => 1,
'label' => $this->l('Yes (Not Recommended)')
),
array(
'id' => 'PS_TWO_DISABLE_SSL_VERIFY_OFF',
'value' => 0,
'label' => $this->l('No (Secure)')
),
),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
return $fields_form;
}
protected function getTwoOtherFormValues()
{
$fields_values = array();
$fields_values['PS_TWO_USE_ACCOUNT_TYPE'] = Tools::getValue('PS_TWO_USE_ACCOUNT_TYPE', Configuration::get('PS_TWO_USE_ACCOUNT_TYPE'));
$fields_values['PS_TWO_ENABLE_COMPANY_NAME'] = Tools::getValue('PS_TWO_ENABLE_COMPANY_NAME', Configuration::get('PS_TWO_ENABLE_COMPANY_NAME'));
$fields_values['PS_TWO_ENABLE_COMPANY_ID'] = Tools::getValue('PS_TWO_ENABLE_COMPANY_ID', Configuration::get('PS_TWO_ENABLE_COMPANY_ID'));
$fields_values['PS_TWO_ENABLE_DEPARTMENT'] = Tools::getValue('PS_TWO_ENABLE_DEPARTMENT', Configuration::get('PS_TWO_ENABLE_DEPARTMENT'));
$fields_values['PS_TWO_ENABLE_PROJECT'] = Tools::getValue('PS_TWO_ENABLE_PROJECT', Configuration::get('PS_TWO_ENABLE_PROJECT'));
$fields_values['PS_TWO_FINALIZE_PURCHASE'] = Tools::getValue('PS_TWO_FINALIZE_PURCHASE', Configuration::get('PS_TWO_FINALIZE_PURCHASE'));
$fields_values['PS_TWO_USE_OWN_INVOICES'] = Tools::getValue('PS_TWO_USE_OWN_INVOICES', Configuration::get('PS_TWO_USE_OWN_INVOICES'));
$fields_values['PS_TWO_ENABLE_ORDER_INTENT'] = Tools::getValue('PS_TWO_ENABLE_ORDER_INTENT', Configuration::get('PS_TWO_ENABLE_ORDER_INTENT'));
$fields_values['PS_TWO_ENABLE_B2B_B2C'] = Tools::getValue('PS_TWO_ENABLE_B2B_B2C', Configuration::get('PS_TWO_ENABLE_B2B_B2C'));
$fields_values['PS_TWO_DISABLE_SSL_VERIFY'] = Tools::getValue('PS_TWO_DISABLE_SSL_VERIFY', Configuration::get('PS_TWO_DISABLE_SSL_VERIFY'));
return $fields_values;
}
protected function validTwoOtherFormValues()
{
// No validation needed for current Other Settings
}
protected function saveTwoOtherFormValues()
{
Configuration::updateValue('PS_TWO_USE_ACCOUNT_TYPE', Tools::getValue('PS_TWO_USE_ACCOUNT_TYPE'));
Configuration::updateValue('PS_TWO_ENABLE_COMPANY_NAME', Tools::getValue('PS_TWO_ENABLE_COMPANY_NAME'));
Configuration::updateValue('PS_TWO_ENABLE_COMPANY_ID', Tools::getValue('PS_TWO_ENABLE_COMPANY_ID'));
Configuration::updateValue('PS_TWO_ENABLE_DEPARTMENT', Tools::getValue('PS_TWO_ENABLE_DEPARTMENT'));
Configuration::updateValue('PS_TWO_ENABLE_PROJECT', Tools::getValue('PS_TWO_ENABLE_PROJECT'));
Configuration::updateValue('PS_TWO_FINALIZE_PURCHASE', Tools::getValue('PS_TWO_FINALIZE_PURCHASE'));
Configuration::updateValue('PS_TWO_USE_OWN_INVOICES', Tools::getValue('PS_TWO_USE_OWN_INVOICES'));
Configuration::updateValue('PS_TWO_ENABLE_ORDER_INTENT', Tools::getValue('PS_TWO_ENABLE_ORDER_INTENT'));
Configuration::updateValue('PS_TWO_ENABLE_B2B_B2C', Tools::getValue('PS_TWO_ENABLE_B2B_B2C'));
$this->output .= $this->displayConfirmation($this->l('Other settings are updated.'));
}
protected function renderTwoOrderStatusForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
$helper->module = $this;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitTwoOrderStatusForm';
$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 = array(
'uri' => $this->getPathUri(),
'fields_value' => $this->getTwoOrderStatusFormValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getTwoOrderStatusForm()));
}
protected function getTwoOrderStatusForm()
{
// Get all available PrestaShop order states for mapping
$orderStates = OrderState::getOrderStates($this->context->language->id);
// Build a filtered list excluding Two custom states (for Group A mapping selects)
$twoCustomStateIds = array_values(array_filter(array(
(int) Configuration::get('PS_TWO_OS_AWAITING_VERIFICATION'),
(int) Configuration::get('PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT'),
(int) Configuration::get('PS_TWO_OS_FULFILLED'),
(int) Configuration::get('PS_TWO_OS_PAYMENT_ERROR'),
(int) Configuration::get('PS_TWO_OS_CANCELLED'),
(int) Configuration::get('PS_TWO_OS_REFUNDED'),
), function ($v) { return $v > 0; }));
$orderStatesNoTwo = array_values(array_filter($orderStates, function ($state) use ($twoCustomStateIds) {
return !in_array((int) $state['id_order_state'], $twoCustomStateIds);
}));
// Build restricted lists for processing states: allow only the matching Two state + non-Two states
$awaitingId = (int) Configuration::get('PS_TWO_OS_AWAITING_VERIFICATION');
$verifiedId = (int) Configuration::get('PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT');
$awaitingState = null;
$verifiedState = null;
foreach ($orderStates as $st) {
if ((int) $st['id_order_state'] === $awaitingId) {
$awaitingState = $st;
} elseif ((int) $st['id_order_state'] === $verifiedId) {
$verifiedState = $st;
}
}
$orderStatesAwaitingOnly = $orderStatesNoTwo;
if ($awaitingState) {
$orderStatesAwaitingOnly[] = $awaitingState;
}
$orderStatesVerifiedOnly = $orderStatesNoTwo;
if ($verifiedState) {
$orderStatesVerifiedOnly[] = $verifiedState;
}
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Two Order Status Mapping'),
'icon' => 'icon-cogs',
),
'description' => $this->l('Map Two payment states to PrestaShop order states for workflow integration. Two creates its own branded order states automatically, but you can map them to existing PrestaShop states if needed.') . '<br><br><strong>' . $this->l('Default Mappings:') . '</strong><br>' .
'• ' . $this->l('Awaiting Buyer Verification → Two: Awaiting Buyer Verification') . '<br>' .
'• ' . $this->l('Verified - Ready for Fulfillment → Two: Verified - Ready for Fulfillment') . '<br>' .
'• ' . $this->l('Order Fulfilled → Shipped') . '<br>' .
'• ' . $this->l('Payment Error → Payment error') . '<br>' .
'• ' . $this->l('Order Cancelled → Canceled') . '<br>' .
'• ' . $this->l('Order Refunded → Refunded'),
'input' => array(
array(
'type' => 'select',
'name' => 'PS_TWO_OS_AWAITING_VERIFICATION_MAP',
'label' => $this->l('Two: Awaiting Buyer Verification'),
'desc' => $this->l('When the buyer needs to complete order verification with Two before payment processing can begin. Default: Preparation in progress'),
'required' => true,
'options' => array(
'query' => $orderStatesAwaitingOnly,
'id' => 'id_order_state',
'name' => 'name'
)
),
array(
'type' => 'select',
'name' => 'PS_TWO_OS_VERIFIED_PENDING_FULFILLMENT_MAP',
'label' => $this->l('Two: Verified - Ready for Fulfillment'),
'desc' => $this->l('Payment is verified and order is ready for merchant fulfillment. Merchant can now process and ship the order. Default: Preparation in progress'),
'required' => true,
'options' => array(
'query' => $orderStatesVerifiedOnly,
'id' => 'id_order_state',
'name' => 'name'
)
),
array(
'type' => 'select',
'name' => 'PS_TWO_OS_FULFILLED_MAP',
'label' => $this->l('Two: Order Fulfilled - Trigger Statuses'),
'desc' => $this->buildFulfillmentStatusDescription(),
'required' => true,
'multiple' => true,
'size' => 8,
'options' => array(
'query' => $orderStatesNoTwo,
'id' => 'id_order_state',
'name' => 'name'
)
),
array(
'type' => 'select',
'name' => 'PS_TWO_OS_PAYMENT_ERROR_MAP',
'label' => $this->l('Two: Payment Processing Error'),
'desc' => $this->l('Payment processing failed. Merchant should investigate and contact Two support if needed. Default: Payment error'),
'required' => true,
'options' => array(
'query' => $orderStatesNoTwo,
'id' => 'id_order_state',
'name' => 'name'
)
),
array(
'type' => 'select',
'name' => 'PS_TWO_OS_CANCELLED_MAP',