Repository navigation
Expand file tree
/
Copy pathPrestashopAPI.php
More file actions
1758 lines (1460 loc) · 67.1 KB
/
Copy pathPrestashopAPI.php
File metadata and controls
1758 lines (1460 loc) · 67.1 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 MEG Venture <[email protected]>
* @copyright 2019-2026 MEG Venture & Consulting Ltd.
* @license https://opensource.org/licenses/MIT MIT License
*/
if (!defined('_PS_VERSION_')) {
exit;
}
require_once dirname(__FILE__) . '/classes/SellerApiClient.php';
require_once dirname(__FILE__) . '/classes/SellerStats.php';
require_once dirname(__FILE__) . '/classes/SellerThreadState.php';
/**
* Seller Dashboard: brings PrestaShop Addons marketplace sales into the shop's own back office.
*
* Two rules govern the whole module:
*
* 1. The storefront never calls the API. Marketplace data reaches the front office only
* through a small precomputed map in Configuration, refreshed from the back office or by
* cron. v1 made two uncached cURL calls per product page view, per visitor.
* 2. Nothing marketplace-related may break a page. Every hook body is wrapped in
* catch (Throwable) because an undefined method is an Error, not an Exception, and would
* otherwise sail straight past a catch (Exception) guard.
*/
class PrestashopAPI extends Module
{
/** @var string Kept in a constant so the API client can send it as a user agent. */
const MODULE_VERSION = '2.1.1';
/** @var string Query parameter for config-page actions. "action" is reserved by the admin dispatcher. */
const ACTION_PARAM = 'psapi_action';
/** @var array Reporting windows offered in the settings form. */
const PERIODS = array('30d', '3m', '6m', '12m', 'ytd', 'all', 'custom');
/** @var array Allowed cache lifetimes, in minutes. */
const TTL_CHOICES = array(15, 30, 60, 180, 720, 1440);
/** @var string Date the marketplace opened. Used as the lower bound for the "all time" window. */
const EPOCH = '2008-01-01';
/** @var int Largest reply attachment accepted, in bytes. */
const ATTACHMENT_MAX = 8388608;
/** @var array Extensions a buyer support reply may carry. */
const ATTACHMENT_TYPES = array(
'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp',
'pdf', 'txt', 'log', 'csv', 'zip', 'doc', 'docx', 'xls', 'xlsx',
);
/** @var array Every hook the module needs. Checked on each visit to the config page. */
const HOOKS = array(
'actionFrontControllerSetMedia',
'displayProductAdditionalInfo',
'displayDashboardTop',
);
/** @var string */
private $html = '';
/** @var array */
private $errors_list = array();
public function __construct()
{
$this->name = 'PrestashopAPI';
$this->tab = 'administration';
$this->version = self::MODULE_VERSION;
$this->author = 'MEG Venture';
$this->need_instance = 0;
$this->bootstrap = true;
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
parent::__construct();
$this->displayName = $this->l('Seller Dashboard - Marketplace Sales, Messages and Payouts');
$this->description = $this->l('See how your PrestaShop Addons marketplace products are selling without leaving your own back office. Revenue, units, refunds, buyer countries and monthly trends, combined with the sales of the same products in your own shop, plus your buyer messages and payouts.');
$this->confirmUninstall = $this->l('Your API key, product links and cached marketplace data will be deleted. Your sales history on the marketplace is not affected. Do you confirm?');
}
/* ================================================================ *
* Install / uninstall
* ================================================================ */
public function install()
{
require_once dirname(__FILE__) . '/classes/MegVentureReviewNudge.php';
if (!parent::install()) {
return false;
}
if (!SellerApiClient::installCache() || !SellerThreadState::install()) {
return false;
}
$defaults = array(
'PRESTASHOPAPI_KEY' => '',
'PRESTASHOPAPI_PERIOD' => '12m',
'PRESTASHOPAPI_DATE_FROM' => '',
'PRESTASHOPAPI_DATE_TO' => '',
'PRESTASHOPAPI_CURRENCY' => SellerStats::DEFAULT_MARKETPLACE_CURRENCY,
'PRESTASHOPAPI_CACHE_TTL' => 60,
'PRESTASHOPAPI_BADGE_ENABLED' => 0,
'PRESTASHOPAPI_BADGE_MIN' => 10,
'PRESTASHOPAPI_BADGE_SCOPE' => 'total',
'PRESTASHOPAPI_LINKS' => '{}',
'PRESTASHOPAPI_BADGE_MAP' => '{}',
);
foreach ($defaults as $key => $value) {
// Never clobber a value left behind by a previous install.
if (Configuration::get($key) === false) {
Configuration::updateValue($key, $value);
}
}
Configuration::updateValue('PRESTASHOPAPI_CRON_TOKEN', Tools::passwdGen(32, 'ALPHANUMERIC'));
// The configuration page loads its own assets with tags in the template, so no
// back-office media hook is needed.
foreach (self::HOOKS as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
return MegVentureReviewNudge::onInstall();
}
public function uninstall()
{
require_once dirname(__FILE__) . '/classes/MegVentureReviewNudge.php';
MegVentureReviewNudge::onUninstall();
$keys = array(
'PRESTASHOPAPI_KEY', 'PRESTASHOPAPI_PERIOD', 'PRESTASHOPAPI_DATE_FROM',
'PRESTASHOPAPI_DATE_TO', 'PRESTASHOPAPI_CURRENCY', 'PRESTASHOPAPI_CACHE_TTL',
'PRESTASHOPAPI_BADGE_ENABLED', 'PRESTASHOPAPI_BADGE_MIN', 'PRESTASHOPAPI_BADGE_SCOPE',
'PRESTASHOPAPI_LINKS', 'PRESTASHOPAPI_BADGE_MAP', 'PRESTASHOPAPI_SEEN',
'PRESTASHOPAPI_CRON_TOKEN', 'PRESTASHOPAPI_LAST_SYNC', 'PRESTASHOPAPI_LAST_ERROR',
// The unprefixed v1 names (PRODUCT_PAGE_FRONT_ENABLE, API_DATE_FROM,
// API_DATE_TO) are deliberately NOT deleted: configuration is
// shop-wide and the module cannot prove another module does not own
// a row by one of those names. A stale leftover row is harmless.
);
foreach ($keys as $key) {
Configuration::deleteByName($key);
}
SellerApiClient::uninstallCache();
SellerThreadState::uninstall();
return parent::uninstall();
}
/* ================================================================ *
* Period handling
* ================================================================ */
/**
* Turns the saved reporting period into a concrete date window.
*
* v1 asked the merchant to type two YYYY-MM-DD strings and validated neither, so a typo
* silently returned the API's default three-month window instead of what was asked for.
*
* @return array{0: string, 1: string} from, to (YYYY-MM-DD)
*/
public static function resolvePeriod()
{
$period = (string) Configuration::get('PRESTASHOPAPI_PERIOD');
$today = date('Y-m-d');
switch ($period) {
case '30d':
return array(date('Y-m-d', strtotime('-30 days')), $today);
case '3m':
return array(date('Y-m-d', strtotime('-3 months')), $today);
case '6m':
return array(date('Y-m-d', strtotime('-6 months')), $today);
case 'ytd':
return array(date('Y-01-01'), $today);
case 'all':
return array(self::EPOCH, $today);
case 'custom':
$from = (string) Configuration::get('PRESTASHOPAPI_DATE_FROM');
$to = (string) Configuration::get('PRESTASHOPAPI_DATE_TO');
return array(
$from !== '' ? $from : date('Y-m-d', strtotime('-12 months')),
$to !== '' ? $to : $today,
);
case '12m':
default:
return array(date('Y-m-d', strtotime('-12 months')), $today);
}
}
/**
* @return SellerApiClient Configured for the saved reporting window.
*/
private function client($allow_refresh = true)
{
$dates = self::resolvePeriod();
return new SellerApiClient($allow_refresh, $dates[0], $dates[1]);
}
/* ================================================================ *
* Configuration page
* ================================================================ */
public function getContent()
{
require_once _PS_MODULE_DIR_ . 'PrestashopAPI/classes/MegVentureAdsWidget.php';
require_once _PS_MODULE_DIR_ . 'PrestashopAPI/classes/MegVentureReviewNudge.php';
// May redirect (review click) — before anything renders on purpose.
// Concatenated configure URL on purpose: getAdminLink()'s $params
// argument does not exist on the oldest supported cores.
$nudge = MegVentureReviewNudge::handleRequest($this)
. MegVentureReviewNudge::render(
$this,
$this->context->link->getAdminLink('AdminModules', true) . '&configure=' . $this->name
);
$this->html = '';
$this->ensureHooks();
$this->ensureSchema();
if (Tools::isSubmit('submitPrestashopAPISettings')) {
$this->saveSettings();
} elseif (Tools::isSubmit('submitPrestashopAPILinks')) {
$this->saveLinks();
} elseif (Tools::isSubmit('submitPrestashopAPIReply')) {
$this->sendReply();
} else {
$this->handleAction();
}
$this->html .= $this->renderFlash();
if (!SellerApiClient::isCurlAvailable()) {
$this->html .= $this->displayError($this->l('The PHP cURL extension is not enabled on this server, so this module cannot contact the marketplace. Please ask your hosting provider to enable it.'));
}
return $nudge . $this->html . $this->renderPage() . MegVentureAdsWidget::render('https://megventure.com/index.php?fc=module&module=virtualproductcombination&controller=adswidget');
}
/**
* Registers any hook the installed copy is missing.
*
* install() runs exactly once, so a hook introduced in a later revision than the one a
* merchant installed stays unregistered for ever, and whatever it powered silently does
* nothing. That is what happened to the Dashboard notice. Reconciling here costs one
* cached query per visit to this page and removes a whole class of "why is nothing
* showing" reports, without asking anyone to reset the module and lose their settings.
*
* @return string[] Hooks that had to be repaired.
*/
private function ensureHooks()
{
$repaired = array();
foreach (self::HOOKS as $hook) {
if (!$this->isRegisteredInHook($hook)) {
$this->registerHook($hook);
$repaired[] = $hook;
}
}
return $repaired;
}
/**
* Creates tables introduced after the merchant installed the module.
*
* Same reasoning as ensureHooks(): install() runs once, so a table added in a later
* revision never appears on an existing install, and everything built on it silently does
* nothing. Seeds the conversation state on first creation so the merchant does not have to
* hit Refresh before the inbox works.
*/
private function ensureSchema()
{
if (SellerThreadState::tableExists()) {
return;
}
SellerThreadState::install();
$threads = $this->client(false)->getThreads();
if (is_array($threads) && $threads) {
SellerThreadState::sync($threads);
}
}
/**
* Handles link-style actions. Everything redirects back so a refresh cannot replay them.
*/
private function handleAction()
{
switch (Tools::getValue(self::ACTION_PARAM)) {
case 'refresh':
$this->refreshData();
$this->redirectBack(2);
break;
case 'test':
$result = $this->client()->testConnection();
$this->redirectBack($result['success'] ? 6 : 0, $result['success'] ? '' : $result['message']);
break;
case 'clear':
SellerApiClient::purgeCache();
Configuration::updateValue('PRESTASHOPAPI_BADGE_MAP', '{}');
$this->redirectBack(5);
break;
case 'export':
$this->exportCsv();
break;
case 'readall':
SellerThreadState::setRead(null, true);
$this->redirectBack(7, '', 'messages');
break;
case 'read':
SellerThreadState::setRead((int) Tools::getValue('psapi_id'), true);
$this->redirectBack(8, '', 'messages');
break;
case 'unread':
SellerThreadState::setRead((int) Tools::getValue('psapi_id'), false);
$this->redirectBack(9, '', 'messages');
break;
case 'pin':
SellerThreadState::setPinned((int) Tools::getValue('psapi_id'), true);
$this->redirectBack(10, '', 'messages');
break;
case 'unpin':
SellerThreadState::setPinned((int) Tools::getValue('psapi_id'), false);
$this->redirectBack(11, '', 'messages');
break;
}
}
/**
* Post/redirect/get so that the browser's reload button cannot resubmit an action.
*/
private function redirectBack($conf, $error = '', $tab = '')
{
$url = $this->configUrl();
if ($conf) {
$url .= '&psapi_conf=' . (int) $conf;
}
if ($error !== '') {
// Survives the redirect without needing a session flash bag.
Configuration::updateValue('PRESTASHOPAPI_LAST_ERROR', Tools::substr($error, 0, 500));
$url .= '&psapi_err=1';
}
if ($tab !== '') {
$url .= '#psapi-' . $tab;
}
Tools::redirectAdmin($url);
}
private function configUrl()
{
return $this->context->link->getAdminLink('AdminModules', true)
. '&configure=' . $this->name
. '&module_name=' . $this->name
. '&tab_module=' . $this->tab;
}
private function renderFlash()
{
$html = '';
$messages = array(
1 => $this->l('Settings saved.'),
2 => $this->l('Marketplace data refreshed.'),
3 => $this->l('Product links saved.'),
4 => $this->l('Your reply has been sent to the buyer.'),
5 => $this->l('Cached marketplace data cleared.'),
6 => $this->l('Connection to the marketplace works.'),
7 => $this->l('All conversations marked as read.'),
8 => $this->l('Conversation marked as read.'),
9 => $this->l('Conversation marked as unread.'),
10 => $this->l('Conversation pinned.'),
11 => $this->l('Conversation unpinned.'),
);
$conf = (int) Tools::getValue('psapi_conf');
if (isset($messages[$conf])) {
$html .= $this->displayConfirmation($messages[$conf]);
}
if (Tools::getValue('psapi_err')) {
$error = Configuration::get('PRESTASHOPAPI_LAST_ERROR');
Configuration::updateValue('PRESTASHOPAPI_LAST_ERROR', '');
if ($error) {
$html .= $this->displayError($error);
}
}
foreach ($this->errors_list as $error) {
$html .= $this->displayError($error);
}
return $html;
}
/* ================================================================ *
* Actions
* ================================================================ */
/**
* Pulls every endpoint we display and rebuilds the storefront badge map.
*/
private function refreshData()
{
$client = $this->client();
if (!$client->hasKey()) {
return false;
}
$client->getProducts(true);
$sales = $client->getOrders(true);
$threads = $client->getThreads(true);
$client->getInvoices(true);
// Reconcile read/pinned state against what just arrived: new conversations appear
// unread, and anything whose fingerprint moved goes back to unread.
if (is_array($threads)) {
SellerThreadState::sync($threads);
}
if ($sales === false) {
$this->errors_list[] = $client->getLastError();
return false;
}
$this->rebuildBadgeMap($sales);
return true;
}
/**
* Collapses the sales rows into "marketplace product id => units sold" and stores it in
* Configuration, which PrestaShop already loads into memory on every request. That is
* what lets the storefront badge cost zero queries and zero HTTP calls.
*/
private function rebuildBadgeMap(array $sales)
{
$map = array();
foreach ($sales as $sale) {
$id = (string) (isset($sale['id_product']) ? $sale['id_product'] : '');
if ($id === '') {
continue;
}
$qty = (int) (isset($sale['product_quantity']) ? $sale['product_quantity'] : 0);
$ref = (int) (isset($sale['product_quantity_refunded']) ? $sale['product_quantity_refunded'] : 0);
if (!isset($map[$id])) {
$map[$id] = 0;
}
$map[$id] += $qty - $ref;
}
Configuration::updateValue('PRESTASHOPAPI_BADGE_MAP', json_encode($map));
}
private function saveSettings()
{
$key = trim((string) Tools::getValue('PRESTASHOPAPI_KEY'));
$period = (string) Tools::getValue('PRESTASHOPAPI_PERIOD');
$from = trim((string) Tools::getValue('PRESTASHOPAPI_DATE_FROM'));
$to = trim((string) Tools::getValue('PRESTASHOPAPI_DATE_TO'));
$currency = Tools::strtoupper(trim((string) Tools::getValue('PRESTASHOPAPI_CURRENCY')));
$ttl = (int) Tools::getValue('PRESTASHOPAPI_CACHE_TTL');
$badge_min = (int) Tools::getValue('PRESTASHOPAPI_BADGE_MIN');
$scope = (string) Tools::getValue('PRESTASHOPAPI_BADGE_SCOPE');
// A key pasted out of the seller account page often arrives with stray whitespace,
// or the merchant pastes the whole URL of the API page instead of the key.
if ($key !== '') {
if (Tools::strlen($key) < 8 || !preg_match('/^[A-Za-z0-9\-_]+$/', $key)) {
$this->errors_list[] = $this->l('That does not look like an API key. Copy only the key itself from your seller account (letters, digits, dashes), without any surrounding text or URL.');
}
}
if (!in_array($period, self::PERIODS, true)) {
$period = '12m';
}
if ($period === 'custom') {
if ($from === '' || !Validate::isDate($from)) {
$this->errors_list[] = $this->l('The "from" date is not a valid date. Expected format: YYYY-MM-DD.');
}
if ($to !== '' && !Validate::isDate($to)) {
$this->errors_list[] = $this->l('The "to" date is not a valid date. Expected format: YYYY-MM-DD.');
}
if ($from !== '' && $to !== '' && Validate::isDate($from) && Validate::isDate($to)
&& strtotime($from) > strtotime($to)) {
$this->errors_list[] = $this->l('The "from" date is later than the "to" date.');
}
}
if ($currency === '' || !preg_match('/^[A-Z]{3}$/', $currency)) {
$this->errors_list[] = $this->l('The marketplace currency must be a three-letter ISO code, for example EUR.');
}
if (!in_array($ttl, self::TTL_CHOICES, true)) {
$ttl = 60;
}
if ($badge_min < 0 || $badge_min > 1000000) {
$this->errors_list[] = $this->l('The minimum sales figure for the badge must be between 0 and 1000000.');
}
if (!in_array($scope, array('addons', 'total'), true)) {
$scope = 'total';
}
if ($this->errors_list) {
return false;
}
$key_changed = $key !== (string) Configuration::get('PRESTASHOPAPI_KEY');
$period_changed = $period !== (string) Configuration::get('PRESTASHOPAPI_PERIOD')
|| $from !== (string) Configuration::get('PRESTASHOPAPI_DATE_FROM')
|| $to !== (string) Configuration::get('PRESTASHOPAPI_DATE_TO');
Configuration::updateValue('PRESTASHOPAPI_KEY', $key);
Configuration::updateValue('PRESTASHOPAPI_PERIOD', $period);
Configuration::updateValue('PRESTASHOPAPI_DATE_FROM', $from);
Configuration::updateValue('PRESTASHOPAPI_DATE_TO', $to);
Configuration::updateValue('PRESTASHOPAPI_CURRENCY', $currency);
Configuration::updateValue('PRESTASHOPAPI_CACHE_TTL', $ttl);
Configuration::updateValue('PRESTASHOPAPI_BADGE_ENABLED', (bool) Tools::getValue('PRESTASHOPAPI_BADGE_ENABLED'));
Configuration::updateValue('PRESTASHOPAPI_BADGE_MIN', $badge_min);
Configuration::updateValue('PRESTASHOPAPI_BADGE_SCOPE', $scope);
// Cached rows belong to the old key or the old window, so they are now misleading.
if ($key_changed || $period_changed) {
SellerApiClient::purgeCache();
$this->refreshData();
}
$this->redirectBack(1, '', 'settings');
}
private function saveLinks()
{
$submitted = Tools::getValue('psapi_link');
$links = array();
if (is_array($submitted)) {
foreach ($submitted as $marketplace_id => $id_local) {
if ((int) $id_local > 0) {
$links[(string) $marketplace_id] = (int) $id_local;
}
}
}
SellerStats::setManualLinks($links);
$this->redirectBack(3, '', 'products');
}
private function sendReply()
{
$id_thread = (int) Tools::getValue('psapi_id_thread');
$message = (string) Tools::getValue('psapi_message');
if ($id_thread <= 0) {
$this->errors_list[] = $this->l('Unknown conversation.');
return false;
}
if (Tools::strlen(trim($message)) < 2) {
$this->errors_list[] = $this->l('Please write a message before sending.');
return false;
}
$path = null;
$name = null;
if (isset($_FILES['psapi_attachment']) && (int) $_FILES['psapi_attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
$attachment = $this->validateAttachment($_FILES['psapi_attachment']);
if ($attachment === false) {
return false;
}
$path = $attachment['path'];
$name = $attachment['name'];
}
$client = $this->client();
if (!$client->sendMessage($id_thread, $message, $path, $name)) {
$this->redirectBack(0, $client->getLastError(), 'messages');
return false;
}
$this->redirectBack(4, '', 'messages');
return true;
}
/**
* Checks one uploaded reply attachment.
*
* @return array{path: string, name: string}|false False with errors_list populated.
*/
private function validateAttachment(array $file)
{
$error = (int) $file['error'];
if ($error !== UPLOAD_ERR_OK) {
// A file larger than PHP accepts never reaches the size test below, so the upload
// error codes have to be reported in their own right or the form fails silently.
if ($error === UPLOAD_ERR_INI_SIZE || $error === UPLOAD_ERR_FORM_SIZE) {
$this->errors_list[] = sprintf(
$this->l('That file is larger than this server accepts (%s).'),
ini_get('upload_max_filesize')
);
} else {
$this->errors_list[] = $this->l('The file could not be uploaded. Please try again.');
}
return false;
}
// Guards against a crafted path being passed off as an upload.
if (!is_uploaded_file($file['tmp_name'])) {
$this->errors_list[] = $this->l('The file could not be uploaded. Please try again.');
return false;
}
if ((int) $file['size'] <= 0) {
$this->errors_list[] = $this->l('That file is empty.');
return false;
}
if ((int) $file['size'] > self::ATTACHMENT_MAX) {
$this->errors_list[] = sprintf(
$this->l('That file is too large. The limit is %d MB.'),
self::ATTACHMENT_MAX / 1048576
);
return false;
}
// basename() strips any directory component the client put in the name.
$name = basename(str_replace('\\', '/', (string) $file['name']));
$extension = Tools::strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (!in_array($extension, self::ATTACHMENT_TYPES, true)) {
$this->errors_list[] = sprintf(
$this->l('Files of type "%s" cannot be attached. Allowed: %s.'),
$extension === '' ? '?' : $extension,
implode(', ', self::ATTACHMENT_TYPES)
);
return false;
}
return array('path' => $file['tmp_name'], 'name' => $name);
}
/* ================================================================ *
* Conversations
* ================================================================ */
/**
* Turns a marketplace message body into readable plain text.
*
* Bodies arrive as HTML ("<p>Dear customer,</p><p><br /></p>...") and are sometimes
* entity-encoded on top of that, so a buyer's apostrophe reaches us as "d'acheter".
* Escaping that for display, which is what the first version did, printed the markup at
* the merchant instead of the message.
*
* The bodies are NOT rendered as HTML. This is buyer-supplied content shown inside an
* authenticated back office; one <script> or one <img onerror> in a support message would
* run with the merchant's session. Formatting worth keeping in a support thread is
* paragraphs and line breaks, and those survive as newlines, so nothing of value is lost
* by reducing to text.
*
* @return string
*/
private static function messageToText($raw)
{
$text = (string) $raw;
// Decode first: the entities are part of the payload, not of our escaping. Doing this
// before strip_tags also means an entity-encoded tag cannot survive as markup.
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// Block boundaries become newlines, or every paragraph runs into the next.
$text = preg_replace('#<br\s*/?>#i', "\n", $text);
$text = preg_replace('#</(p|div|li|tr|h[1-6])>#i', "\n", $text);
$text = preg_replace('#<li[^>]*>#i', "- ", $text);
$text = strip_tags($text);
// Normalise the blank-line runs that "<p><br /></p>" leaves behind.
$text = str_replace("\r\n", "\n", $text);
$text = preg_replace("/[ \t]+\n/", "\n", $text);
$text = preg_replace("/\n{3,}/", "\n\n", $text);
return trim($text);
}
/**
* @return int 0 when the row carries no id.
*/
private static function threadId(array $thread)
{
return SellerThreadState::threadId($thread);
}
/**
* Streams the sales rows as CSV.
*
* Downloads from getContent() only work while the admin layout has not been flushed, so
* the state is checked rather than assumed; if it has, the merchant gets a message
* instead of a corrupted page.
*/
private function exportCsv()
{
$client = $this->client();
$sales = $client->getOrders();
if ($sales === false) {
$this->redirectBack(0, $client->getLastError());
return;
}
if (headers_sent()) {
$this->errors_list[] = $this->l('The export could not start because the page had already begun rendering. Please try again.');
return;
}
$columns = array(
'order_date' => $this->l('Date'),
'id_order' => $this->l('Order'),
'id_product' => $this->l('Product ID'),
'product_name' => $this->l('Product'),
'product_type' => $this->l('Type'),
'iso_code' => $this->l('Country'),
'amount' => $this->l('Unit amount'),
'product_quantity' => $this->l('Quantity'),
'product_quantity_refunded' => $this->l('Refunded'),
);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="marketplace-sales-' . date('Y-m-d') . '.csv"');
header('Pragma: no-cache');
$out = fopen('php://output', 'w');
// Excel needs the BOM to read UTF-8 product names correctly.
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, array_values($columns), ';');
foreach ($sales as $sale) {
$line = array();
foreach (array_keys($columns) as $field) {
$line[] = self::csvCell(isset($sale[$field]) ? $sale[$field] : '');
}
fputcsv($out, $line, ';');
}
fclose($out);
exit;
}
/**
* A cell starting with = + - or @ is executed as a formula when the file is opened in a
* spreadsheet, so neutralise it with a leading tab.
*/
private static function csvCell($value)
{
$value = (string) $value;
return $value !== '' && strpos('=+-@', $value[0]) !== false ? "\t" . $value : $value;
}
/* ================================================================ *
* Rendering
* ================================================================ */
private function renderPage()
{
$client = $this->client();
$has_key = $client->hasKey();
$products = $has_key ? $client->getProducts() : array();
$sales = $has_key ? $client->getOrders() : array();
$api_error = '';
if ($products === false || $sales === false) {
$api_error = $client->getLastError();
$products = is_array($products) ? $products : array();
$sales = is_array($sales) ? $sales : array();
}
$stats = new SellerStats($sales, $products);
$link_health = $stats->getLinkHealth();
$dates = self::resolvePeriod();
$summary = $stats->getSummary();
// Kept apart from the products/sales error. safeList() used to fold a failure into an
// empty array, so a broken conversations call rendered as "no conversations" — a
// statement about the account when it was really a statement about the request.
$threads = array();
$threads_error = '';
if ($has_key) {
$threads = $client->getThreads();
if ($threads === false) {
$threads_error = $client->getLastError();
$threads = array();
}
}
$built = $this->buildThreads($threads);
$filtered = $this->filterThreads($built);
$counts = SellerThreadState::counts();
$this->context->smarty->assign(array(
'psapi_has_key' => $has_key,
'psapi_api_error' => $api_error,
'psapi_stale' => $client->isStale(),
'psapi_curl' => SellerApiClient::isCurlAvailable(),
'psapi_last_sync' => SellerApiClient::getLastSync(),
'psapi_period_from' => $dates[0],
'psapi_period_to' => $dates[1],
'psapi_summary' => $summary,
'psapi_money' => $this->formatSummary($summary),
'psapi_products' => $this->decorateProducts($stats->getProductRows()),
'psapi_sales' => array_slice($sales, 0, 500),
'psapi_sales_total' => count($sales),
'psapi_months' => $this->prepareChart($stats->getMonthlySeries(12)),
'psapi_countries' => $stats->getCountryBreakdown(8),
// Filtered before the cap, so "unread" reaches every unread conversation rather
// than only those inside the first 300 rendered rows.
'psapi_threads' => array_slice($filtered, 0, 300),
'psapi_threads_shown' => count($filtered),
'psapi_threads_filter' => $this->threadFilter(),
'psapi_threads_counts' => $counts,
'psapi_threads_total' => count($threads),
'psapi_threads_error' => $threads_error,
// Rows arrived but none were usable: the response is a shape this module does not
// understand. That is a third state, and reporting it as "you have no
// conversations" is how the wrong wrapper key stayed hidden for three rounds.
'psapi_threads_unrecognised' => $threads && !$built,
// Printed inline with that warning rather than behind the Help tab. A diagnostic
// one click away from the failure is a diagnostic nobody reads.
'psapi_threads_debug' => $threads && !$built ? $this->threadsDebug($client, $threads) : '',
'psapi_unread' => $counts['unread'],
'psapi_invoices' => $this->normalizeTable($has_key ? $this->safeList($client->getInvoices()) : array()),
'psapi_thread' => $this->currentThread($client, $threads),
'psapi_attachment_types' => implode(', ', self::ATTACHMENT_TYPES),
'psapi_attachment_max' => (int) (self::ATTACHMENT_MAX / 1048576),
'psapi_link_health' => $link_health,
'psapi_currency_mismatch' => $stats->hasCurrencyMismatch(),
'psapi_marketplace_iso' => $stats->getMarketplaceIso(),
'psapi_shop_iso' => $stats->getShopIso(),
'psapi_local_products' => $this->localProductChoices(),
'psapi_diag' => $this->diagnostics($client, $threads, $sales, $products, $threads_error),
'psapi_config_url' => $this->configUrl(),
'psapi_action_param' => self::ACTION_PARAM,
'psapi_cron_url' => $this->cronUrl(),
'psapi_module_dir' => $this->_path,
'psapi_version' => self::MODULE_VERSION,
'psapi_asset_v' => $this->assetVersion(),
'psapi_settings_form' => $this->renderSettingsForm(),
));
// fetch(), not display(): display() resolves templates through the front-office theme
// override paths, which do not apply to a back-office template.
return $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
}
/**
* @return array Always a list, even when the endpoint failed.
*/
private function safeList($value)
{
return is_array($value) ? $value : array();
}
/**
* Money is formatted here rather than in the template, because PrestaShop 9 removed
* Tools::displayPrice() and Smarty has no equivalent that works across 1.7 to 9.
*
* Marketplace figures stay in the marketplace currency; anything combining marketplace
* and local sales is shown in the shop currency, since that is the only currency both
* halves can share.
*/
private function formatSummary(array $summary)
{
$iso = Configuration::get('PRESTASHOPAPI_CURRENCY');
return array(
'addons_revenue' => SellerStats::formatMarketplacePrice($summary['addons_revenue'], $iso),
'addons_last30' => SellerStats::formatMarketplacePrice($summary['addons_last30'], $iso),
'addons_average' => SellerStats::formatMarketplacePrice($summary['addons_average'], $iso),
'addons_refund_value' => SellerStats::formatMarketplacePrice($summary['addons_refund_value'], $iso),
'local_revenue' => SellerStats::formatShopPrice($summary['local_revenue']),
'total_revenue' => $summary['total_revenue'] === null
? null
: SellerStats::formatShopPrice($summary['total_revenue']),
);
}
/**
* Adds display strings to the product rows.
*/
private function decorateProducts(array $rows)
{
$iso = Configuration::get('PRESTASHOPAPI_CURRENCY');
foreach ($rows as $index => $row) {
$rows[$index]['price_display'] = SellerStats::formatMarketplacePrice($row['price'], $iso);
$rows[$index]['addons_revenue_display'] = SellerStats::formatMarketplacePrice($row['addons_revenue'], $iso);
$rows[$index]['local_revenue_display'] = SellerStats::formatShopPrice($row['local_revenue']);
$rows[$index]['total_revenue_display'] = $row['total_revenue'] === null
? null
: SellerStats::formatShopPrice($row['total_revenue']);
}
return $rows;
}
/**
* Loads the messages of the thread the merchant opened, if any.
*/
private function currentThread(SellerApiClient $client, array $threads)
{
$id_thread = (int) Tools::getValue('psapi_id_thread');
if ($id_thread <= 0) {
return null;
}
// Opening a conversation marks it read, as any inbox does. "Mark as unread" puts it
// back, which is how the merchant flags the ones they still owe an answer.
SellerThreadState::setRead($id_thread, true);
$messages = array();
foreach ($this->safeList($client->getMessages($id_thread)) as $message) {
if (!is_array($message)) {
continue;
}
$meta = array();
foreach (array('date_add', 'author', 'customer_name', 'employee_name', 'name') as $field) {
if (isset($message[$field]) && is_scalar($message[$field]) && (string) $message[$field] !== '') {
// Escaped here because the joined string is printed with nofilter, the
// separator being markup.
$meta[] = htmlspecialchars((string) $message[$field], ENT_QUOTES, 'UTF-8');