forked from chilek/lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lms-payments.php
executable file
·1822 lines (1678 loc) · 76.9 KB
/
lms-payments.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
#!/usr/bin/env php
<?php
/*
* LMS version 1.11-git
*
* (C) Copyright 2001-2020 LMS Developers
*
* Please, see the doc/AUTHORS for more information about authors!
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*
* $Id$
*/
// REPLACE THIS WITH PATH TO YOUR CONFIG FILE
// PLEASE DO NOT MODIFY ANYTHING BELOW THIS LINE UNLESS YOU KNOW
// *EXACTLY* WHAT ARE YOU DOING!!!
// *******************************************************************
ini_set('error_reporting', E_ALL&~E_NOTICE);
$parameters = array(
'config-file:' => 'C:',
'quiet' => 'q',
'help' => 'h',
'version' => 'v',
'fakedate:' => 'f:',
'customerid:' => null,
'division:' => null,
'customergroups:' => 'g:',
'customer-status:' => null,
);
$long_to_shorts = array();
foreach ($parameters as $long => $short) {
$long = str_replace(':', '', $long);
if (isset($short)) {
$short = str_replace(':', '', $short);
}
$long_to_shorts[$long] = $short;
}
$options = getopt(
implode(
'',
array_filter(
array_values($parameters),
function ($value) {
return isset($value);
}
)
),
array_keys($parameters)
);
foreach (array_flip(array_filter($long_to_shorts, function ($value) {
return isset($value);
})) as $short => $long) {
if (array_key_exists($short, $options)) {
$options[$long] = $options[$short];
unset($options[$short]);
}
}
if (array_key_exists('version', $options)) {
print <<<EOF
lms-payments.php
(C) 2001-2020 LMS Developers
EOF;
exit(0);
}
if (array_key_exists('help', $options)) {
print <<<EOF
lms-payments.php
(C) 2001-2020 LMS Developers
-C, --config-file=/etc/lms/lms.ini alternate config file (default: /etc/lms/lms.ini);
-h, --help print this help and exit;
-v, --version print version info and exit;
-q, --quiet suppress any output, except errors;
-f, --fakedate=YYYY/MM/DD override system date;
--customerid=<id> limit assignments to specifed customer
--division=<shortname>
limit assignments to customers which belong to specified
division
-g, --customergroups=<group1,group2,...>
allow to specify customer groups to which customers
should be assigned
--customer-status=<status1,status2,...>
take assignment of customers with specified status only
EOF;
exit(0);
}
$quiet = array_key_exists('quiet', $options);
if (!$quiet) {
print <<<EOF
lms-payments.php
(C) 2001-2020 LMS Developers
EOF;
}
if (array_key_exists('config-file', $options)) {
$CONFIG_FILE = $options['config-file'];
} else {
$CONFIG_FILE = DIRECTORY_SEPARATOR . 'etc' . DIRECTORY_SEPARATOR . 'lms' . DIRECTORY_SEPARATOR . 'lms.ini';
}
if (!$quiet) {
echo "Using file ".$CONFIG_FILE." as config." . PHP_EOL;
}
if (!is_readable($CONFIG_FILE)) {
die('Unable to read configuration file ['.$CONFIG_FILE.']!');
}
define('CONFIG_FILE', $CONFIG_FILE);
$CONFIG = (array) parse_ini_file($CONFIG_FILE, true);
// Check for configuration vars and set default values
$CONFIG['directories']['sys_dir'] = (!isset($CONFIG['directories']['sys_dir']) ? getcwd() : $CONFIG['directories']['sys_dir']);
$CONFIG['directories']['lib_dir'] = (!isset($CONFIG['directories']['lib_dir']) ? $CONFIG['directories']['sys_dir'] . DIRECTORY_SEPARATOR . 'lib' : $CONFIG['directories']['lib_dir']);
$CONFIG['directories']['plugin_dir'] = (!isset($CONFIG['directories']['plugin_dir']) ? $CONFIG['directories']['sys_dir'] . DIRECTORY_SEPARATOR . 'plugins' : $CONFIG['directories']['plugin_dir']);
$CONFIG['directories']['plugins_dir'] = $CONFIG['directories']['plugin_dir'];
define('SYS_DIR', $CONFIG['directories']['sys_dir']);
define('LIB_DIR', $CONFIG['directories']['lib_dir']);
define('PLUGIN_DIR', $CONFIG['directories']['plugin_dir']);
define('PLUGINS_DIR', $CONFIG['directories']['plugin_dir']);
// Load autoloader
$composer_autoload_path = SYS_DIR . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($composer_autoload_path)) {
require_once $composer_autoload_path;
} else {
die("Composer autoload not found. Run 'composer install' command from LMS directory and try again. More informations at https://getcomposer.org/" . PHP_EOL);
}
// Init database
$DB = null;
try {
$DB = LMSDB::getInstance();
} catch (Exception $ex) {
trigger_error($ex->getMessage(), E_USER_WARNING);
// can't working without database
die("Fatal error: cannot connect to database!" . PHP_EOL);
}
// Include required files (including sequence is important)
require_once(LIB_DIR . DIRECTORY_SEPARATOR . 'common.php');
require_once(LIB_DIR . DIRECTORY_SEPARATOR . 'language.php');
require_once(LIB_DIR . DIRECTORY_SEPARATOR . 'definitions.php');
$SYSLOG = SYSLOG::getInstance();
// Initialize Session, Auth and LMS classes
$AUTH = null;
$LMS = new LMS($DB, $AUTH, $SYSLOG);
$plugin_manager = new LMSPluginManager();
$LMS->setPluginManager($plugin_manager);
$divisionid = isset($options['division']) ? $LMS->getDivisionIdByShortName($options['division']) : null;
if (!empty($divisionid)) {
ConfigHelper::setFilter($divisionid);
}
$deadline = ConfigHelper::getConfig('payments.deadline', 14);
$sdate_next = ConfigHelper::checkConfig('payments.saledate_next_month');
$paytype = ConfigHelper::getConfig('payments.paytype', 2); // TRANSFER
$comment = ConfigHelper::getConfig('payments.comment', "Tariff %tariff - %attribute subscription for period %period");
$backward_comment = ConfigHelper::getConfig('payments.backward_comment', $comment);
$s_comment = ConfigHelper::getConfig('payments.settlement_comment', $comment);
$s_backward_comment = ConfigHelper::getConfig('payments.settlement_backward_comment', $s_comment);
$suspension_description = ConfigHelper::getConfig('payments.suspension_description', '');
$suspension_percentage = ConfigHelper::getConfig('finances.suspension_percentage', 0);
$unit_name = trans(ConfigHelper::getConfig('payments.default_unit_name'));
$check_invoices = ConfigHelper::checkConfig('payments.check_invoices');
$proforma_generates_commitment = ConfigHelper::checkConfig('phpui.proforma_invoice_generates_commitment');
$delete_old_assignments_after_days = intval(ConfigHelper::getConfig('payments.delete_old_assignments_after_days', 30));
$prefer_settlement_only = ConfigHelper::checkConfig('payments.prefer_settlement_only');
$prefer_netto = ConfigHelper::checkConfig('payments.prefer_netto');
$customergroups = ConfigHelper::getConfig('payments.customergroups', '', true);
$force_telecom_service_flag = ConfigHelper::checkValue(ConfigHelper::getConfig('invoices.force_telecom_service_flag', 'true'));
$check_customer_vat_payer_flag_for_telecom_service = ConfigHelper::checkConfig('invoices.check_customer_vat_payer_flag_for_telecom_service');
$allowed_customer_status =
Utils::determineAllowedCustomerStatus(
isset($options['customer-status'])
? $options['customer-status']
: ConfigHelper::getConfig('payments.allowed_customer_status', ''),
-1
);
if (empty($allowed_customer_status)) {
$customer_status_condition = '';
} else {
$customer_status_condition = ' AND c.status IN (' . implode(',', $allowed_customer_status) . ')';
}
function localtime2()
{
global $fakedate;
if (!empty($fakedate)) {
$date = explode("/", $fakedate);
return mktime(0, 0, 0, $date[1], $date[2], $date[0]);
} else {
return time();
}
}
$fakedate = isset($options['fakedate']) ? $options['fakedate'] : null;
$customerid = isset($options['customerid']) && intval($options['customerid']) ? $options['customerid'] : null;
$currtime = strftime("%s", localtime2());
$month = intval(strftime("%m", localtime2()));
$dom = intval(strftime("%d", localtime2()));
$year = strftime("%Y", localtime2());
$weekday = strftime("%u", localtime2());
$yearday = strftime("%j", localtime2());
$last_dom = date('j', mktime(0, 0, 0, $month + 1, 0, $year)) == date('j', $currtime);
if (is_leap_year($year) && $yearday > 31 + 28) {
$yearday -= 1;
}
if (!empty($fakedate)) {
$today = $currtime;
} else {
$today = mktime(0, 0, 0, $month, $dom, $year);
}
if ($month == 1 || $month == 4 || $month == 7 || $month == 10) {
$quarter = $dom;
} elseif ($month == 2 || $month == 5 || $month == 8 || $month == 11) {
$quarter = $dom + 100;
} else {
$quarter = $dom + 200;
}
if ($month > 6) {
$halfyear = $dom + ($month - 7) * 100;
} else {
$halfyear = $dom + ($month - 1) * 100;
}
$date_format = ConfigHelper::getConfig('payments.date_format');
$forward_periods = array(
DAILY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)),
WEEKLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom+6, $year)),
MONTHLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+1, $dom-1, $year)),
QUARTERLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+3, $dom-1, $year)),
HALFYEARLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+6, $dom-1, $year)),
YEARLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year+1)),
DISPOSABLE => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year)),
);
$forward_aligned_periods = array(
DAILY => $forward_periods[DAILY],
WEEKLY => $forward_periods[WEEKLY],
MONTHLY => strftime($date_format, mktime(12, 0, 0, $month, 1, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+1, 0, $year)),
QUARTERLY => strftime($date_format, mktime(12, 0, 0, $month, 1, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+3, 0, $year)),
HALFYEARLY => strftime($date_format, mktime(12, 0, 0, $month, 1, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month+6, 0, $year)),
YEARLY => strftime($date_format, mktime(12, 0, 0, $month, 1, $year)).' - '.strftime($date_format, mktime(12, 0, 0, $month, 0, $year+1)),
DISPOSABLE => $forward_periods[DISPOSABLE],
);
$backward_periods = array(
DAILY => strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
WEEKLY => strftime($date_format, mktime(12, 0, 0, $month, $dom-7, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
MONTHLY => strftime($date_format, mktime(12, 0, 0, $month-1, $dom, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
QUARTERLY => strftime($date_format, mktime(12, 0, 0, $month-3, $dom, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
HALFYEARLY => strftime($date_format, mktime(12, 0, 0, $month-6, $dom, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
YEARLY => strftime($date_format, mktime(12, 0, 0, $month, $dom, $year-1)).' - '.strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year)),
DISPOSABLE => strftime($date_format, mktime(12, 0, 0, $month, $dom-1, $year))
);
$last_sunday = strtotime('last Sunday '.date("Y-m-d"));
$backward_aligned_periods = array(
DAILY => $backward_periods[DAILY],
WEEKLY => strftime($date_format, $last_sunday-518400) .' - '.strftime($date_format, $last_sunday),
MONTHLY => strftime($date_format, mktime(12, 0, 0, $month-1, 1, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, 0, $year)),
QUARTERLY => strftime($date_format, mktime(12, 0, 0, $month-3, 1, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, 0, $year)),
HALFYEARLY => strftime($date_format, mktime(12, 0, 0, $month-6, 1, $year)) .' - '.strftime($date_format, mktime(12, 0, 0, $month, 0, $year)),
YEARLY => strftime($date_format, mktime(12, 0, 0, $month, 1, $year-1)).' - '.strftime($date_format, mktime(12, 0, 0, $month, 0, $year)),
DISPOSABLE => $backward_periods[DISPOSABLE]
);
// Special case, ie. you have 01.01.2005-01.31.2005 on invoice, but invoice/
// assignment is made not January, the 1st:
$current_month = strftime($date_format, mktime(12, 0, 0, $month, 1, $year))." - ".strftime($date_format, mktime(12, 0, 0, $month + 1, 0, $year));
$previous_month = strftime($date_format, mktime(12, 0, 0, $month - 1, 1, $year))." - ".strftime($date_format, mktime(12, 0, 0, $month, 0, $year));
$current_period = strftime("%m/%Y", mktime(12, 0, 0, $month, 1, $year));
$next_period = strftime("%m/%Y", mktime(12, 0, 0, $month + 1, 1, $year));
$prev_period = strftime("%m/%Y", mktime(12, 0, 0, $month - 1, 1, $year));
// sale date setting
$saledate = $currtime;
if ($sdate_next) {
$saledate = strftime("%s", mktime(12, 0, 0, $month + 1, 1, $year));
}
// calculate start and end of numbering period
function get_period($period)
{
global $dom, $month, $year;
if (empty($period)) {
$period = YEARLY;
}
$start = 0;
$end = 0;
switch ($period) {
case DAILY:
$start = strftime("%s", mktime(0, 0, 0, $month, $dom, $year));
$end = strftime("%s", mktime(0, 0, 0, $month, $dom + 1, $year));
break;
case WEEKLY:
$startweek = $dom - $weekday + 1;
$start = strftime("%s", mktime(0, 0, 0, $month, $startweek, $year));
$end = strftime("%s", mktime(0, 0, 0, $month, $startweek + 7, $year));
break;
case MONTHLY:
$start = strftime("%s", mktime(0, 0, 0, $month, 1, $year));
$end = strftime("%s", mktime(0, 0, 0, $month + 1, 1, $year));
break;
case QUARTERLY:
if ($month <= 3) {
$startmonth = 1;
} elseif ($month <= 6) {
$startmonth = 4;
} elseif ($month <= 9) {
$startmonth = 7;
} else {
$startmonth = 10;
}
$start = strftime("%s", mktime(0, 0, 0, $startmonth, 1, $year));
$end = strftime("%s", mktime(0, 0, 0, $startmonth + 3, 1, $year));
break;
case HALFYEARLY:
if ($month <= 6) {
$startmonth = 1;
} else {
$startmonth = 7;
}
$start = strftime("%s", mktime(0, 0, 0, $startmonth, 1, $year));
$end = strftime("%s", mktime(0, 0, 0, $startmonth + 6, 1, $year));
break;
case CONTINUOUS:
$start = strftime("%s", mktime(0, 0, 0, 1, 1, 1970));
$end = strftime("%s", mktime(0, 0, 0, $month, $dom + 1, $year));
break;
default:
$start = strftime("%s", mktime(0, 0, 0, 1, 1, $year));
$end = strftime("%s", mktime(0, 0, 0, 1, 1, $year + 1));
}
return array('start' => $start, 'end' => $end);
}
$plans = array();
$periods = array(
0 => YEARLY,
);
$query = "SELECT n.id, n.period, doctype, COALESCE(a.divisionid, 0) AS divid, isdefault
FROM numberplans n
LEFT JOIN numberplanassignments a ON (a.planid = n.id)
WHERE doctype IN (?, ?, ?)";
$results = $DB->GetAll($query, array(DOC_INVOICE, DOC_INVOICE_PRO, DOC_DNOTE));
if (!empty($results)) {
foreach ($results as $row) {
if ($row['isdefault']) {
$plans[$row['divid']][$row['doctype']] = $row['id'];
}
$periods[$row['id']] = ($row['period'] ? $row['period'] : YEARLY);
}
}
// prepare customergroups in sql query
if (isset($options['customergroups'])) {
$customergroups = $options['customergroups'];
}
if (!empty($customergroups)) {
$ORs = preg_split("/([\s]+|[\s]*,[\s]*)/", mb_strtoupper($customergroups), -1, PREG_SPLIT_NO_EMPTY);
$customergroup_ORs = array();
foreach ($ORs as $OR) {
$ANDs = preg_split("/([\s]*\+[\s]*)/", $OR, -1, PREG_SPLIT_NO_EMPTY);
$customergroup_ANDs_regular = array();
$customergroup_ANDs_inversed = array();
foreach ($ANDs as $AND) {
if (strpos($AND, '!') === false) {
$customergroup_ANDs_regular[] = $AND;
} else {
$customergroup_ANDs_inversed[] = substr($AND, 1);
}
}
$customergroup_ORs[] = '('
. (empty($customergroup_ANDs_regular) ? '1 = 1' : "EXISTS (SELECT COUNT(*) FROM customergroups
JOIN customerassignments ON customerassignments.customergroupid = customergroups.id
WHERE customerassignments.customerid = %customerid_alias%
AND UPPER(customergroups.name) IN ('" . implode("', '", $customergroup_ANDs_regular) . "')
HAVING COUNT(*) = " . count($customergroup_ANDs_regular) . ')')
. (empty($customergroup_ANDs_inversed) ? '' : " AND NOT EXISTS (SELECT COUNT(*) FROM customergroups
JOIN customerassignments ON customerassignments.customergroupid = customergroups.id
WHERE customerassignments.customerid = %customerid_alias%
AND UPPER(customergroups.name) IN ('" . implode("', '", $customergroup_ANDs_inversed) . "')
HAVING COUNT(*) > 0)")
. ')';
}
$customergroups = ' AND (' . implode(' OR ', $customergroup_ORs) . ')';
}
// invoice auto-closes
if ($check_invoices) {
$DB->Execute(
"UPDATE documents SET closed = 1
WHERE " . ($customerid ? 'customerid = ' . $customerid : '1 = 1') . " AND customerid IN (
SELECT cash.customerid
FROM cash
JOIN customers c ON c.id = cash.customerid
WHERE cash.time <= ?NOW?"
. ($divisionid ? ' AND c.divisionid = ' . $divisionid : '')
. ($customergroups ? str_replace('%customerid_alias%', 'cash.customerid', $customergroups) : '') . "
GROUP BY cash.customerid
HAVING SUM(cash.value * cash.currencyvalue) >= 0
) AND type IN (?, ?, ?)
AND cdate <= ?NOW?
AND closed = 0",
array(DOC_INVOICE, DOC_CNOTE, DOC_DNOTE)
);
}
// solid payments
$assigns = $DB->GetAll(
"SELECT * FROM payments WHERE value <> 0
AND (period = ? OR (period = ? AND at = ?)
OR (period = ? AND at = ?)
OR (period = ? AND at = ?)
OR (period = ? AND at = ?)
OR (period = ? AND at = ?))",
array(DAILY, WEEKLY, $weekday, MONTHLY, $dom, QUARTERLY, $quarter, HALFYEARLY, $halfyear, YEARLY, $yearday)
);
if (!empty($assigns)) {
foreach ($assigns as $assign) {
$DB->Execute(
"INSERT INTO cash (time, type, value, customerid, comment)
VALUES (?, ?, ?, ?, ?)",
array($currtime, 1, $assign['value'] * -1, null, $assign['name']."/".$assign['creditor'])
);
if (!$quiet) {
print "CID:0\tVAL:".$assign['value']."\tDESC:".$assign['name']."/".$assign['creditor'] . PHP_EOL;
}
}
}
// let's go, fetch *ALL* assignments in given day
$query = "SELECT a.id, a.tariffid, a.liabilityid, a.customerid, a.recipient_address_id,
a.period, a.backwardperiod, a.at, a.suspended, a.settlement, a.datefrom, a.dateto, a.pdiscount, a.vdiscount,
a.invoice, a.separatedocument, c.type AS customertype,
(CASE WHEN c.type = ? THEN 0 ELSE (CASE WHEN a.liabilityid IS NULL THEN t.splitpayment ELSE l.splitpayment END) END) AS splitpayment,
(CASE WHEN a.liabilityid IS NULL THEN t.taxcategory ELSE l.taxcategory END) AS taxcategory,
t.description AS description, a.id AS assignmentid,
c.divisionid, c.paytype, c.flags AS customerflags,
a.paytype AS a_paytype, a.numberplanid, a.attribute,
p.name AS promotion_name, ps.name AS promotion_schema_name, ps.length AS promotion_schema_length,
d.inv_paytype AS d_paytype, t.period AS t_period, t.numberplanid AS tariffnumberplanid,
t.flags,
(CASE WHEN a.liabilityid IS NULL THEN t.type ELSE l.type END) AS tarifftype,
(CASE WHEN a.liabilityid IS NULL THEN t.name ELSE l.name END) AS name,
(CASE WHEN a.liabilityid IS NULL THEN t.taxid ELSE l.taxid END) AS taxid,
(CASE WHEN a.liabilityid IS NULL THEN t.prodid ELSE l.prodid END) AS prodid,
ROUND(((((100 - a.pdiscount) * (CASE WHEN a.liabilityid IS NULL THEN t.value ELSE l.value END)) / 100) - a.vdiscount) *
(CASE a.suspended WHEN 0
THEN 1.0
ELSE $suspension_percentage / 100
END), 2) AS unitary_value,
ROUND(((((100 - a.pdiscount) * (CASE WHEN a.liabilityid IS NULL THEN t.value ELSE l.value END)) / 100) - a.vdiscount) *
(CASE a.suspended WHEN 0
THEN 1.0
ELSE $suspension_percentage / 100
END), 2) * a.count AS value,
(CASE WHEN a.liabilityid IS NULL THEN t.currency ELSE l.currency END) AS currency,
a.count AS count,
(SELECT COUNT(id) FROM assignments
WHERE customerid = c.id AND tariffid IS NULL AND liabilityid IS NULL
AND datefrom <= $currtime
AND (dateto > $currtime OR dateto = 0)) AS allsuspended
FROM assignments a
JOIN customers c ON (a.customerid = c.id)
LEFT JOIN promotionschemas ps ON ps.id = a.promotionschemaid
LEFT JOIN promotions p ON p.id = ps.promotionid
LEFT JOIN tariffs t ON (a.tariffid = t.id)
LEFT JOIN liabilities l ON (a.liabilityid = l.id)
LEFT JOIN divisions d ON (d.id = c.divisionid)
WHERE " . ($customerid ? 'c.id = ' . $customerid : '1 = 1')
. $customer_status_condition
. ($divisionid ? ' AND c.divisionid = ' . $divisionid : '')
. " AND a.commited = 1
AND ((a.period = ? AND at = ?)
OR ((a.period = ?
OR (a.period = ? AND at = ?)
OR (a.period = ? AND at = ?)
OR (a.period = ? AND at = ?)
OR (a.period = ? AND at = ?)
OR (a.period = ? AND at = ?))
AND a.datefrom <= ? AND (a.dateto > ? OR a.dateto = 0)))"
. ($customergroups ? str_replace('%customerid_alias%', 'c.id', $customergroups) : '')
." ORDER BY a.customerid, a.recipient_address_id, a.invoice, a.paytype, a.numberplanid, a.separatedocument, currency, value DESC, a.id";
$services = $DB->GetAll(
$query,
array(
CTYPES_PRIVATE, DISPOSABLE, $today, DAILY, WEEKLY, $weekday, MONTHLY, $last_dom ? 0 : $dom, QUARTERLY, $quarter, HALFYEARLY, $halfyear, YEARLY, $yearday,
$currtime, $currtime
)
);
$billing_invoice_description = ConfigHelper::getConfig('payments.billing_invoice_description', 'Phone calls between %backward_periods (for %phones)');
$query = "SELECT
a.id, a.tariffid, a.customerid, a.period, a.backwardperiod, a.at, a.suspended, a.settlement, a.datefrom,
0 AS pdiscount, 0 AS vdiscount, a.invoice, a.separatedocument, c.type AS customertype,
(CASE WHEN a.liabilityid IS NULL THEN t.type ELSE l.type END) AS tarifftype,
(CASE WHEN c.type = ? THEN 0 ELSE t.splitpayment END) AS splitpayment,
t.taxcategory AS taxcategory,
t.description AS description, a.id AS assignmentid,
c.divisionid, c.paytype, c.flags AS customerflags,
a.paytype AS a_paytype, a.numberplanid, a.attribute,
p.name AS promotion_name, ps.name AS promotion_schema_name, ps.length AS promotion_schema_length,
d.inv_paytype AS d_paytype, t.period AS t_period, t.numberplanid AS tariffnumberplanid,
t.taxid AS taxid, '' as prodid, voipcost.value, t.currency, voipphones.phones,
'set' AS liabilityid, '$billing_invoice_description' AS name,
? AS count,
(SELECT COUNT(id)
FROM assignments
WHERE
customerid = c.id AND
tariffid IS NULL AND
liabilityid IS NULL AND
datefrom <= $currtime AND
(dateto > $currtime OR dateto = 0)) AS allsuspended
FROM assignments a
LEFT JOIN promotionschemas ps ON ps.id = a.promotionschemaid
LEFT JOIN promotions p ON p.id = ps.promotionid
JOIN customers c ON (a.customerid = c.id)
JOIN (
SELECT ROUND(sum(price), 2) AS value, va.ownerid AS customerid,
a2.id AS assignmentid
FROM voip_cdr vc
JOIN voipaccounts va ON vc.callervoipaccountid = va.id
JOIN voip_numbers vn ON vn.voip_account_id = va.id AND vn.phone = vc.caller
JOIN voip_number_assignments vna ON vna.number_id = vn.id
JOIN assignments a2 ON a2.id = vna.assignment_id
WHERE
vc.call_start_time >= (CASE a2.period
WHEN " . YEARLY . ' THEN ' . mktime(0, 0, 0, $month, 1, $year-1) . '
WHEN ' . HALFYEARLY . ' THEN ' . mktime(0, 0, 0, $month-6, 1, $year) . '
WHEN ' . QUARTERLY . ' THEN ' . mktime(0, 0, 0, $month-3, 1, $year) . '
WHEN ' . MONTHLY . ' THEN ' . mktime(0, 0, 0, $month-1, 1, $year) . '
WHEN ' . DISPOSABLE . ' THEN ' . $currtime . "
END) AND
vc.call_start_time < (CASE a2.period
WHEN " . YEARLY . ' THEN ' . mktime(0, 0, 0, $month, 1, $year) . '
WHEN ' . HALFYEARLY . ' THEN ' . mktime(0, 0, 0, $month, 1, $year) . '
WHEN ' . QUARTERLY . ' THEN ' . mktime(0, 0, 0, $month, 1, $year) . '
WHEN ' . MONTHLY . ' THEN ' . mktime(0, 0, 0, $month, 1, $year) . '
WHEN ' . DISPOSABLE . ' THEN ' . ($currtime + 86400) . "
END)
GROUP BY va.ownerid, a2.id
) voipcost ON voipcost.customerid = a.customerid AND voipcost.assignmentid = a.id
LEFT JOIN (
SELECT vna2.assignment_id, " . $DB->GroupConcat('vn2.phone', ', ') . " AS phones
FROM voip_number_assignments vna2
LEFT JOIN voip_numbers vn2 ON vn2.id = vna2.number_id
GROUP BY vna2.assignment_id
) voipphones ON voipphones.assignment_id = a.id
LEFT JOIN tariffs t ON (a.tariffid = t.id)
LEFT JOIN liabilities l ON (a.liabilityid = l.id)
LEFT JOIN divisions d ON (d.id = c.divisionid)
WHERE " . ($customerid ? 'c.id = ' . $customerid : '1 = 1')
. $customer_status_condition
. ($divisionid ? ' AND c.divisionid = ' . $divisionid : '')
. " AND t.type = ? AND
a.commited = 1 AND
((a.period = ? AND at = ?) OR
((a.period = ? OR
(a.period = ? AND at = ?) OR
(a.period = ? AND at = ?) OR
(a.period = ? AND at = ?) OR
(a.period = ? AND at = ?) OR
(a.period = ? AND at = ?)) AND
a.datefrom <= ? AND
(a.dateto > ? OR a.dateto = 0)))"
. ($customergroups ? str_replace('%customerid_alias%', 'c.id', $customergroups) : '')
." ORDER BY a.customerid, a.recipient_address_id, a.invoice, a.paytype, a.numberplanid, a.separatedocument, currency, voipcost.value DESC, a.id";
$billings = $DB->GetAll(
$query,
array(
CTYPES_PRIVATE, 1, SERVICE_PHONE,
DISPOSABLE, $today, DAILY, WEEKLY, $weekday, MONTHLY, $last_dom ? 0 : $dom, QUARTERLY, $quarter, HALFYEARLY, $halfyear, YEARLY, $yearday,
$currtime, $currtime
)
);
$assigns = array();
if ($billings) {
// intelligent merge of service and billing assignment records
$billing_idx = 0;
$billing_count = count($billings);
foreach ($services as $service_idx => &$service) {
$assigns[] = $service;
if ($billing_idx == $billing_count || $service['tarifftype'] != SERVICE_PHONE) {
continue;
}
$service_customerid = $service['customerid'];
while ($billing_idx < $billing_count && $billings[$billing_idx]['customerid'] < $service_customerid) {
$billing_idx++;
}
if ($billing_idx === $billing_count) {
continue;
}
$old_billing_idx = $billing_idx;
while ($billing_idx < $billing_count && $billings[$billing_idx]['customerid'] == $service_customerid
&& $service['id'] != $billings[$billing_idx]['id']) {
$billing_idx++;
}
if ($billing_idx == $billing_count || $billings[$billing_idx]['customerid'] != $service_customerid) {
$billing_idx = $old_billing_idx;
continue;
} else {
$assigns[] = $billings[$billing_idx];
$billing_idx++;
}
}
unset($service);
} else {
$assigns = $services;
}
unset($services);
$currencyvalues = array();
// correct currency values for foreign currency documents with today's cdate or sdate
// which have estimated currency value earlier (in the moment of document issue)
$daystart = mktime(0, 0, 0, date('n', $currtime), date('j', $currtime), date('Y', $currtime));
$dayend = $daystart + 86399;
$currencydaystart = strtotime('yesterday', $daystart);
$currencycurrtime = strtotime('yesterday', $currtime);
$currencydayend = strtotime('yesterday', $dayend);
$documents = $DB->GetAll(
'SELECT d.id, d.currency FROM documents d
JOIN customers c ON c.id = d.customerid
WHERE ' . ($customerid ? 'd.customerid = ' . $customerid : '1 = 1')
. ($divisionid ? ' AND c.divisionid = ' . $divisionid : '')
. ' AND d.type IN (?, ?, ?, ?, ?) AND ((sdate = 0 AND cdate >= ? AND cdate <= ?)
OR (sdate > 0 AND ((sdate < cdate AND sdate >= ? AND sdate <= ?) OR (sdate >= cdate AND cdate >= ? AND cdate <= ?))))
AND currency <> ?',
array(
DOC_INVOICE,
DOC_CNOTE,
DOC_INVOICE_PRO,
DOC_RECEIPT,
DOC_DNOTE,
$currencydaystart,
$currencydayend,
$currencydaystart,
$currencydayend,
$currencydaystart,
$currencydayend,
Localisation::getCurrentCurrency(),
)
);
if (!empty($documents)) {
foreach ($documents as &$document) {
$currency = $document['currency'];
if (empty($currency)) {
continue;
}
if (!isset($currencyvalues[$currency])) {
$currencyvalues[$currency] = $LMS->getCurrencyValue($currency, $currencydaystart);
if (!isset($currencyvalues[$currency])) {
echo 'Unable to determine currency value for document ID ' . $document['id'] . ' and currency ' . $currency . '.' . PHP_EOL;
continue;
}
}
$DB->Execute(
'UPDATE documents
SET currencyvalue = ?
WHERE id = ?',
array(
$currencyvalues[$currency],
$document['id'],
)
);
$DB->Execute(
'UPDATE cash
SET currencyvalue = ?
WHERE docid = ?',
array(
$currencyvalues[$currency],
$document['id'],
)
);
echo 'Corrected currency value for document ID ' . $document['id'] . ' with currency ' . $currency . '.' . PHP_EOL;
}
unset($document);
}
$cashes = $DB->GetAll(
'SELECT cash.id, cash.currency FROM cash
LEFT JOIN customers c ON c.id = cash.customerid
WHERE ' . ($customerid ? 'cash.customerid = ' . $customerid : '1 = 1')
. ($divisionid ? ' AND c.divisionid = ' . $divisionid : '')
. ' AND cash.docid IS NULL AND cash.currency <> ? AND cash.time >= ? AND cash.time <= ?',
array(
Localisation::getCurrentCurrency(),
$currencydaystart,
$currencydayend,
)
);
if (!empty($cashes)) {
foreach ($cashes as &$cash) {
$currency = $cash['currency'];
if (empty($currency)) {
continue;
}
if (!isset($currencyvalues[$currency])) {
$currencyvalues[$currency] = $LMS->getCurrencyValue($currency, $currencydaystart);
if (!isset($currencyvalues[$currency])) {
echo 'Unable to determine currency value for cash ID ' . $cash['id'] . ' and currency ' . $currency . '.' . PHP_EOL;
continue;
}
}
$DB->Execute(
'UPDATE cash
SET currencyvalue = ?
WHERE id = ?',
array(
$currencyvalues[$currency],
$cash['id'],
)
);
echo 'Corrected currency value for cash ID ' . $cash['id'] . ' with currency ' . $currency . '.' . PHP_EOL;
}
unset($cash);
}
if (empty($assigns)) {
die;
}
// get dominating link technology per customer assignments when customer
// node are directly connected to operator network device
$assignment_linktechnologies = $DB->GetAllByKey("SELECT a.id, b.technology, MAX(b.technologycount) AS technologycount
FROM assignments a
JOIN (
SELECT a.id, n.linktechnology AS technology, COUNT(n.linktechnology) AS technologycount
FROM nodeassignments na
JOIN assignments a ON a.id = na.assignmentid
JOIN tariffs t ON t.id = a.tariffid
JOIN nodes n ON n.id = na.nodeid
WHERE n.linktechnology > 0 AND n.ownerid IS NOT NULL
GROUP BY a.id, n.linktechnology
) b ON b.id = a.id
GROUP BY a.id, b.technology
ORDER BY a.id", 'id');
if (empty($assignment_linktechnologies)) {
$assignment_linktechnologies = array();
}
// get dominating link technology per customer assignments when customer
// node or customer network devices nodes are connected to operator through customer subnetwork
// ************
// get assignments which match to nodes or network device nodes in customer subnetworks
$node_assignments = $DB->GetAllByKey("SELECT " . $DB->GroupConcat('na.assignmentid', ',', true) . " AS assignments,
na.nodeid
FROM nodeassignments na
JOIN nodes n ON n.id = na.nodeid
JOIN assignments a ON a.id = na.assignmentid
LEFT JOIN netdevices nd ON nd.id = n.netdev
WHERE nd.ownerid IS NOT NULL AND ((n.ownerid IS NULL AND n.netdev IS NOT NULL)
OR n.ownerid IS NOT NULL)
AND a.suspended = 0
AND a.period IN (" . implode(',', array(YEARLY, HALFYEARLY, QUARTERLY, MONTHLY, DISPOSABLE)) . ")
AND a.datefrom < ?NOW? AND (a.dateto = 0 OR a.dateto > ?NOW?)
AND NOT EXISTS (
SELECT id FROM assignments aa
WHERE aa.customerid = (CASE WHEN n.ownerid IS NULL THEN nd.ownerid ELSE n.ownerid END)
AND aa.tariffid IS NULL AND aa.liabilityid IS NULL
AND aa.datefrom < ?NOW?
AND (aa.dateto > ?NOW? OR aa.dateto = 0)
)
GROUP BY na.nodeid", 'nodeid');
if (empty($node_assignments)) {
$node_assignments = array();
} else {
foreach ($node_assignments as $nodeid => $assignments) {
$node_assignments[$nodeid] = explode(',', $assignments['assignments']);
}
}
if (!empty($node_assignments)) {
// search for links between operator network devices and customer network devices
$uni_links = $DB->GetAllByKey(
"SELECT nl.id AS netlinkid, nl.technology AS technology,
c.id AS customerid,
(CASE WHEN ndsrc.ownerid IS NULL THEN nl.src ELSE nl.dst END) AS operator_netdevid,
(CASE WHEN ndsrc.ownerid IS NULL THEN nl.dst ELSE nl.dst END) AS netdevid
FROM netlinks nl
JOIN netdevices ndsrc ON ndsrc.id = nl.src
JOIN netdevices nddst ON nddst.id = nl.dst
JOIN customers c ON (ndsrc.ownerid IS NULL AND c.id = nddst.ownerid)
OR (nddst.ownerid IS NULL AND c.id = ndsrc.ownerid)
WHERE nl.technology > 0 AND ((ndsrc.ownerid IS NULL AND nddst.ownerid IS NOT NULL)
OR (nddst.ownerid IS NULL AND ndsrc.ownerid IS NOT NULL))
ORDER BY nl.id",
'netlinkid'
);
if (!empty($uni_links)) {
function find_nodes_for_netdev($customerid, $netdevid, &$customer_nodes, &$customer_netlinks)
{
if (isset($customer_nodes[$customerid . '_' . $netdevid])) {
$nodeids = explode(',', $customer_nodes[$customerid . '_' . $netdevid]['nodeids']);
} else {
$nodeids = array();
}
if (!empty($customer_netlinks)) {
foreach ($customer_netlinks as &$customer_netlink) {
if ($customer_netlink['src'] == $netdevid) {
$next_netdevid = $customer_netlink['dst'];
} else if ($customer_netlink['dst'] == $netdevid) {
$next_netdevid = $customer_netlink['src'];
} else {
continue;
}
$nodeids = array_merge($nodeids, find_nodes_for_netdev(
$customerid,
$next_netdevid,
$customer_nodes,
$customer_netlinks
));
}
unset($customer_netlink);
}
return $nodeids;
}
$customer_netlinks = $DB->GetAllByKey(
"SELECT " . $DB->Concat('nl.src', "'_'", 'nl.dst') . " AS netlink
FROM netlinks nl
JOIN netdevices ndsrc ON ndsrc.id = nl.src
JOIN netdevices nddst ON nddst.id = nl.dst
WHERE ndsrc.ownerid IS NOT NULL AND nddst.ownerid IS NOT NULL
AND ndsrc.ownerid = nddst.ownerid",
'netlink'
);
$customer_nodes = $DB->GetAllByKey(
"SELECT " . $DB->GroupConcat('n.id') . " AS nodeids,
" . $DB->Concat('CASE WHEN n.ownerid IS NULL THEN nd.ownerid ELSE n.ownerid END', "'_'", 'n.netdev') . " AS customerid_netdev
FROM nodes n
LEFT JOIN netdevices nd ON nd.id = n.netdev AND n.ownerid IS NULL AND nd.ownerid IS NOT NULL
WHERE n.ownerid IS NOT NULL OR nd.ownerid IS NOT NULL
AND EXISTS (
SELECT na.id FROM nodeassignments na
JOIN assignments a ON a.id = na.assignmentid
WHERE na.nodeid = n.id AND a.suspended = 0
AND a.period IN (" . implode(',', array(YEARLY, HALFYEARLY, QUARTERLY, MONTHLY, DISPOSABLE)) . ")
AND a.datefrom < ?NOW? AND (a.dateto = 0 OR a.dateto > ?NOW?)
)
AND NOT EXISTS (
SELECT id FROM assignments aa
WHERE aa.customerid = (CASE WHEN n.ownerid IS NULL THEN nd.ownerid ELSE n.ownerid END)
AND aa.tariffid IS NULL AND aa.liabilityid IS NULL
AND aa.datefrom < ?NOW?
AND (aa.dateto > ?NOW? OR aa.dateto = 0)
)
GROUP BY customerid_netdev",
'customerid_netdev'
);
// collect customer node/node-netdev identifiers connected to customer subnetwork
// and then fill assignment linktechnologies relations
foreach ($uni_links as $netlinkid => &$netlink) {
$nodes = find_nodes_for_netdev(
$netlink['customerid'],
$netlink['netdevid'],
$customer_nodes,
$customer_netlinks
);
if (!empty($nodes)) {
foreach ($nodes as $nodeid) {
if (isset($node_assignments[$nodeid])) {
foreach ($node_assignments[$nodeid] as $assignmentid) {
$assignment_linktechnologies[$assignmentid] = array(
'id' => $assignmentid,
'technology' => $netlink['technology'],
'technologycount' => 1,
);
}
}
}
}
}
unset($netlink);
unset($uni_links);
unset($customer_netlinks);
unset($customer_nodes);
}
}
$suspended = 0;
$numbers = array();
$customernumbers = array();
$numbertemplates = array();
$invoices = array();
$telecom_services = array();
$currencies = array();
$doctypes = array();
$paytypes = array();
$addresses = array();
$numberplans = array();
$divisions = array();
$result = $LMS->ExecuteHook(
'payments_before_assignment_loop',
array(
'assignments' => $assigns,
'date' => sprintf('%04d/%02d/%02d', $year, $month, $dom),
)
);
if ($result['assignments']) {
$assigns = $result['assignments'];
}
if ($prefer_netto) {
$taxeslist = $LMS->GetTaxes();
}
// find assignments with tariff reward/penalty flag
// and check if customer applies to this
$reward_to_check = array();
$reward_period_to_check = array();
foreach ($assigns as $assign) {
$cid = $assign['customerid'];
if (isset($reward_to_check[$cid]) || ($assign['flags'] & TARIFF_FLAG_REWARD_PENALTY)) {
$reward_to_check[$cid] = $cid;
}
if ($reward_to_check[$cid]) {
if (!isset($reward_period_to_check[$cid])) {
$reward_period_to_check[$cid] = DAILY;
}
if ($assign['period'] >= WEEKLY && $assign['period'] <= YEARLY) {
$reward_period_to_check[$cid] = max($reward_period_to_check[$cid], $assign['period']);
} elseif ($assign['period'] == HALFYEARLY && $reward_period_to_check[$cid] < YEARLY) {
$reward_period_to_check[$cid] = HALFYEARLY;
}
}
}
$period_end = mktime(0, 0, 0, date('m', $currtime), date('d', $currtime), date('Y', $currtime));
$period_starts = array(
DAILY => strtotime('yesterday', $period_end),
WEEKLY => strtotime('1 week ago', $period_end),
MONTHLY => strtotime('1 month ago', $period_end),