-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Upominac.php
624 lines (541 loc) · 19.7 KB
/
Upominac.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
<?php
declare(strict_types=1);
/**
* This file is part of the AbraFlexi Reminder package
*
* https://github.com/VitexSoftware/abraflexi-reminder
*
* (c) Vítězslav Dvořák <http://vitexsoftware.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AbraFlexi\Reminder;
/**
* Description of Upominka.
*
* @author vitex
*/
class Upominac extends \AbraFlexi\RW
{
public \AbraFlexi\Bricks\Customer $customer;
/**
* Invoice.
*/
public \AbraFlexi\FakturaVydana $invoicer;
/**
* Reminder.
*
* @param array $init
* @param array $options
*/
public function __construct($init = null, $options = [])
{
parent::__construct($init, $options);
$this->customer = new \AbraFlexi\Bricks\Customer();
$this->invoicer = new \AbraFlexi\FakturaVydana(null, ['defaultUrlParams' => ['limit' => 0]]);
}
/**
* Obtain customer debts Array.
*
* @param array $skipLabels labels of Customer (AddressBook) to skip
* @param bool $cleanLabels clean debtor labels when all is paid
*
* @return array of all customer's documents after due date
*/
public function getCustomersDebts($skipLabels = [], $cleanLabels = false)
{
$allDebts = [];
$this->addStatusMessage(_('Getting clients'), 'debug');
$clients = $this->customer->getCustomerList();
$debtCount = 0;
$this->addStatusMessage(sprintf(_('%s Clients Found'), \count($clients)));
$this->addStatusMessage(_('Getting debts'), 'debug');
$pos = 0;
foreach ($clients as $cid => $clientIDs) {
++$pos;
$stitky = \AbraFlexi\Stitek::listToArray($clientIDs['stitky']);
if (\count($skipLabels) && array_intersect($skipLabels, $stitky)) {
continue;
}
$debts = $this->customer->getCustomerDebts((int) $clientIDs['id']);
$this->customer->invoicer->setEvidence('pohledavka');
$debts2 = $this->customer->getCustomerDebts((int) $clientIDs['id']);
$this->customer->invoicer->setEvidence('faktura-vydana');
$debts3 = array_merge(empty($debts) ? [] : $debts, empty($debts2) ? [] : $debts2);
if (!empty($debts3) && \count($debts3)) {
foreach ($debts3 as $did => $debtInfo) {
$allDebts[$cid][$did] = $debtInfo;
++$debtCount;
}
} else { // All OK
if ($cleanLabels) {
$this->everythingPaidOff($cid, $stitky);
}
}
// $this->addStatusMessage($pos.'/'.count($clients).' '.$cid, 'debug');
}
$this->addStatusMessage(sprintf(_('%s Debts Found'), $debtCount));
return $allDebts;
}
/**
* What to do when no debts found for customer.
*
* @param int $clientID AddressBook ID
* @param array $stitky Customer's labels
*
* @return bool customer well processed
*/
public function everythingPaidOff($clientID, $stitky)
{
return $this->enableCustomer(implode(',', $stitky), $clientID);
}
/**
* Enable customer.
*
* @param string $stitky Labels
* @param int $cid AbraFlexi AddressID
*
* @return bool Customer connect status
*/
public function enableCustomer($stitky, $cid)
{
$result = true;
if (strstr($stitky, 'UPOMINKA') || strstr($stitky, 'NEPLATIC')) {
$newStitky = array_combine(explode(
',',
str_replace(' ', '', $stitky),
), explode(',', $stitky));
unset($newStitky['UPOMINKA1'], $newStitky['UPOMINKA2'], $newStitky['UPOMINKA3'], $newStitky['NEPLATIC']);
if (
$this->customer->adresar->insertToAbraFlexi(['id' => $cid, 'stitky@removeAll' => 'true',
'stitky' => $newStitky])
) {
$this->addStatusMessage(sprintf(
_('No debts. Clear %s Remind labels'),
$cid,
), 'success');
} else {
$this->addStatusMessage(sprintf(
_('No debts. Clear %s Remind labels'),
$cid,
), 'error');
$result = false;
}
}
return $result;
}
/**
* Process All Debts of All Customers.
*
* @param array $skipLabels Skip Customers (AddressBook) with any of given labels
*
* @return int All Debts count
*/
public function processAllDebts($skipLabels = [])
{
$allDebths = $this->getCustomersDebts($skipLabels, true);
$this->addStatusMessage(sprintf(
_('%d clients to remind process'),
\count($allDebths),
));
$counter = 0;
foreach ($allDebths as $cid => $debts) {
++$counter;
$this->customer->adresar->loadFromAbraFlexi($cid);
$this->addStatusMessage(sprintf(
_('(%d / %d) #%s code: %s %s '),
$counter,
\count($allDebths),
$this->customer->adresar->getDataValue('id'),
$this->customer->adresar->getDataValue('kod'),
$this->customer->adresar->getDataValue('nazev'),
), 'debug');
$this->processUserDebts($cid, $debts);
}
return $counter;
}
/**
* Process Customer debts.
*
* @param array $clientInfo AbraFlexi Address (Customer)
* @param array $clientDebts Array provided by customer::getCustomerDebts()
*
* @return int max debt score 1: 0-7 days 1: 8-14 days 3: 15 days and more
*/
public function processUserDebts($clientInfo, $clientDebts)
{
$this->customer->adresar->dataReset();
$this->customer->adresar->setData($clientInfo);
$this->customer->adresar->updateApiURL();
$zewlScore = 0;
$stitky = $clientInfo['stitky'];
$ddifs = [];
$invoicesToSave = [];
$invoicesToLock = [];
foreach ($clientDebts as $did => $debt) {
switch ($debt['zamekK']) {
case 'zamek.zamceno':
$this->invoicer->dataReset();
$this->invoicer->setMyKey(\AbraFlexi\RO::code($did));
$unlock = $this->invoicer->performAction('unlock', 'int');
if ($unlock['success'] === 'false') {
$this->addStatusMessage(
_('Invoice locked: skipping process'),
'warning',
);
break;
}
$invoicesToLock[$debt['id']] = ['id' => $did];
// no break
case 'zamek.otevreno':
default:
$invoicesToSave[$debt['id']] = ['id' => \AbraFlexi\RO::code((string) $did),
'evidence' => $debt['evidence']];
$ddiff = \AbraFlexi\FakturaVydana::overdueDays($debt['datSplat']);
$ddifs[$debt['id']] = $ddiff;
if (($ddiff <= 7) && ($ddiff >= 1)) {
$zewlScore = self::maxScore($zewlScore, 1);
} else {
if (($ddiff > 7) && ($ddiff <= 14)) {
$zewlScore = self::maxScore($zewlScore, 2);
} else {
if ($ddiff > 14) {
$zewlScore = self::maxScore($zewlScore, 3);
}
}
}
break;
}
}
if ($zewlScore === 3 && !\array_key_exists('UPOMINKA2', $stitky)) {
$zewlScore = 2;
}
if (!\array_key_exists('UPOMINKA1', $stitky)) {
$zewlScore = 1;
}
if ($zewlScore > 0 && (array_sum($ddifs) > 0) && \count($invoicesToSave)) {
if (!\array_key_exists('UPOMINKA'.$zewlScore, $stitky)) {
if (!\array_key_exists('NEUPOMINAT', $stitky)) {
if ($this->posliUpominku($zewlScore, $clientDebts)) {
foreach ($invoicesToSave as $invoiceCode => $invoiceData) {
switch ($zewlScore) {
case 1:
$colname = 'datUp1';
break;
case 2:
$colname = 'datUp2';
break;
case 3:
$colname = 'datSmir';
break;
default:
$colname = 'poznam';
break;
}
$invoiceData[$colname] = self::timestampToFlexiDate(time());
if ($colname === 'poznam') {
$invoiceData[$colname] = 'Inventarizace:'.$invoiceData[$colname];
}
$this->invoicer->setEvidence($invoiceData['evidence']);
if ($this->invoicer->insertToAbraFlexi($invoiceData)) {
$this->addStatusMessage(sprintf(
_('%s %s remind %s date saved'),
$invoiceData['evidence'],
$invoiceCode,
$colname,
), 'info');
} else {
$this->addStatusMessage(sprintf(
_('%s %s remind %s date save failed'),
$invoiceData['evidence'],
$invoiceCode,
$colname,
), 'error');
}
}
}
} else {
$this->addStatusMessage(_('Remind send disbled'));
}
} else {
$this->addStatusMessage(sprintf(
_('Remind %d already sent'),
$zewlScore,
));
}
} else {
$this->addStatusMessage(_('No debts to remind'), 'debug');
}
if (\count($invoicesToLock)) {
foreach ($invoicesToLock as $invoiceCode => $invoiceData) {
$this->invoicer->dataReset();
$this->invoicer->setMyKey(\AbraFlexi\RO::code($did));
$lock = $this->invoicer->performAction('lock', 'int');
if ($lock['success'] === 'true') {
$this->addStatusMessage(sprintf(
_('Invoice %s locked again'),
$invoiceCode,
), 'info');
} else {
$this->addStatusMessage(sprintf(
_('Invoice %s locking failed'),
$invoiceCode,
), 'error');
}
}
}
return $zewlScore;
}
/**
* Obtain Customer "Score".
*
* @param int $addressID AbraFlexi user ID
*
* @return int ZewlScore
*/
public function getCustomerScore($addressID)
{
$score = 0;
$debts = $this->customer->getCustomerDebts($addressID);
$stitkyRaw = $this->customer->adresar->getColumnsFromAbraFlexi(
['stitky'],
['id' => $addressID],
);
$stitky = $stitkyRaw[0]['stitky'];
if (!empty($debts)) {
foreach ($debts as $did => $debt) {
$ddiff = \AbraFlexi\FakturaVydana::overdueDays($debt['datSplat']);
if (($ddiff <= 7) && ($ddiff >= 1)) {
$score = self::maxScore($score, 1);
} else {
if (($ddiff > 7) && ($ddiff <= 14)) {
$score = self::maxScore($score, 2);
} else {
if ($ddiff > 14) {
$score = self::maxScore($score, 3);
}
}
}
}
}
if ($score === 3 && !strstr($stitky, 'UPOMINKA2')) {
$score = 2;
}
if (!strstr($stitky, 'UPOMINKA1') && !empty($debts)) {
$score = 1;
}
return $score;
}
/**
* Get Last Sent Inventarization days Day.
*
* @param array $clientDebts
*
* @return int
*/
public static function getDaysToLastInventarization($clientDebts)
{
$days = 0;
$daysToLastInvent = [];
foreach ($clientDebts as $did => $debt) {
if (strstr($debt['poznam'], 'Inventarizace:')) {
foreach (explode("\n", $debt['poznam']) as $invRow) {
if (strstr($invRow, 'Inventarizace:')) {
$daysToLastInvent[] = \AbraFlexi\FakturaVydana::overdueDays(new \AbraFlexi\Date(str_replace(
'Inventarizace:',
'',
$invRow,
)));
}
}
} else {
$daysToLastInvent[] = \AbraFlexi\FakturaVydana::overdueDays(empty($debt['datSmir']) ? (empty($debt['datUp2']) ? (empty($debt['datUp1']) ? $debt['datVyst'] : $debt['datUp1']) : $debt['datUp2']) : $debt['datSmir']);
}
}
return min($daysToLastInvent);
}
/**
* Send remind.
*
* @param int $score ZewlScore
* @param array $clientDebts Array provided by customer::getCustomerDebts()
*
* @return bool
*/
public function posliUpominku($score, $clientDebts)
{
$result = false;
foreach ($this->processNotifyModules($score, $clientDebts) as $modResult) {
if ($modResult) {
$result = true;
}
}
return $result;
}
/**
* Include all classes in modules directory.
*
* @param int $score weeks of due
* @param array $debts array of debts by current customer
*
* @return array Sent results
*/
public function processNotifyModules($score, $debts)
{
$result = [];
$notifiersNamespace = 'AbraFlexi\\Reminder\\Notifier';
\Ease\Functions::loadClassesInNamespace($notifiersNamespace);
foreach (\Ease\Functions::classesInNamespace($notifiersNamespace) as $notifierClass) {
$class = $notifiersNamespace.'\\'.$notifierClass;
$result[$notifierClass] = new $class($this, $score, $debts);
}
return $result;
}
/**
* Return all unsettled documents in evidence.
*
* @param string $evidence override default evidence
* @param array $conditions for debts obtaining
*
* @return array
*/
public function getEvidenceDebts($evidence = null, $conditions = [])
{
if ($evidence) {
$evBackup = $this->invoicer->getEvidence();
$this->invoicer->setEvidence($evidence);
} else {
$evBackup = false;
}
$what = array_merge(["datSplat lte '".\AbraFlexi\RW::dateToFlexiDate(new \DateTime())."' AND (stavUhrK is null OR stavUhrK eq 'stavUhr.castUhr') AND storno eq false AND sumCelkem > 0"], $conditions);
$result = [];
$colsToGet = [
'id',
'kod',
'stavUhrK',
'firma',
'buc',
'popis',
'varSym',
'specSym',
'sumCelkem',
'sumCelkemMen',
'duzpPuv',
'typDokl(typDoklK,kod)',
'datSplat',
'zbyvaUhradit',
'zbyvaUhraditMen',
'mena',
'poznam',
'zamekK',
'datVyst',
'stitky',
];
if ($this->invoicer->getColumnInfo('stavMailK', $evidence)) {
$colsToGet[] = 'stavMailK';
}
$this->invoicer->defaultUrlParams['order'] = 'datVyst@A';
$this->invoicer->defaultUrlParams['includes'] = '/'.$this->invoicer->getEvidence().'/typDokl';
$invoices = $this->invoicer->getColumnsFromAbraFlexi(
$colsToGet,
$what,
'kod',
);
if ($this->invoicer->lastResponseCode === 200) {
$docTypeSkipList = [];
if (\Ease\Shared::cfg('REMINDER_SKIPDOCTYPE')) {
$docTypeSkipList = \AbraFlexi\Stitek::listToArray(\Ease\Shared::cfg('REMINDER_SKIPDOCTYPE'));
}
$evidenceUsed = $this->invoicer->getEvidence();
foreach ($invoices as $invoiceId => $invoiceData) {
$invoiceData['evidence'] = $evidenceUsed;
if (
\array_key_exists(
\AbraFlexi\Functions::uncode((string) $invoiceData['typDokl']),
$docTypeSkipList,
)
) {
continue;
}
$result[$invoiceId] = $invoiceData;
}
}
if ($evBackup) {
$this->invoicer->setEvidence($evBackup);
}
return $result;
}
/**
* Get All debts.
*
* @param array $conditions for debts obtaining
*
* @return array
*/
public function getAllDebts($conditions = [])
{
// je třeba upravit rozesílání upomínke v system a multiflexi tak, aby do upomínání nevstupovaly
// doklady se zápornou částkou
// dobropisy
// doklady s částkou 0
// tj současný filtr na "neuhrazeno" je třeba rozšířit ... castka > 0, typdokladu <> dobropis
$debts = $this->getEvidenceDebts('faktura-vydana', $conditions);
foreach ($debts as $did => $ddata) {
if ($ddata['typDokl']->value[0]['typDoklK'] === 'typDokladu.dobropis') {
unset($debts[$did]);
}
}
$debts2 = $this->getEvidenceDebts('pohledavka', $conditions);
return \Ease\Functions::reindexArrayBy(array_merge(
empty($debts) ? [] : $debts,
empty($debts2) ? [] : $debts2,
), 'kod');
}
/**
* Get Customer listing.
*
* @param mixed $conditions
*
* @return array clients indexed by code
*/
public function getCustomerList($conditions = [])
{
// [/* 'typVztahuK'=>'typVztahu.odberDodav' */]
$conditions['limit'] = 0;
$allClients = $this->customer->adresar->getColumnsFromAbraFlexi(['id', 'nazev',
'stitky'], $conditions, 'kod');
if (!empty($allClients)) {
foreach ($allClients as $clientCode => $clientInfo) {
$allClients[$clientCode]['stitky'] = \AbraFlexi\Stitek::listToArray($clientInfo['stitky']);
}
}
return $allClients;
}
/**
* Totals array as string.
*/
public static function formatTotals(array $totals): string
{
$tmp = [];
foreach ($totals as $currency => $value) {
$tmp[] = \AbraFlexi\Reminder\Upominka::formatCurrency($value).' '.$currency;
}
return implode(',', $tmp);
}
/**
* Overdue group.
*
* @param int $score current score value
* @param int $level current level
*
* @return int max of all levels processed
*/
private static function maxScore($score, $level)
{
if ($level > $score) {
$score = $level;
}
return $score;
}
}