Repository navigation
Expand file tree
/
Copy pathService.php
More file actions
664 lines (590 loc) · 32.5 KB
/
Copy pathService.php
File metadata and controls
664 lines (590 loc) · 32.5 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
<?php
declare(strict_types=1);
namespace Box\Mod\Billinganalytics;
use DateInterval;
use DateTimeImmutable;
use FOSSBilling\InformationException;
use FOSSBilling\InjectionAwareInterface;
class Service implements InjectionAwareInterface
{
private const DEFAULT_LIMIT = 10;
private const MAX_LIMIT = 1000;
private const MAX_RANGE_DAYS = 3660;
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function install(): bool
{
$dbal = $this->di['dbal'];
$dbal->beginTransaction();
try {
$groups = $dbal->executeQuery(
'SELECT id, permissions FROM admin_group WHERE permissions IS NOT NULL'
)->fetchAllAssociative();
foreach ($groups as $group) {
$permissions = json_decode((string) $group['permissions'], true);
if (!is_array($permissions) || !isset($permissions['orderanalytics'])) {
continue;
}
if (!isset($permissions['billinganalytics'])) {
$permissions['billinganalytics'] = $permissions['orderanalytics'];
}
unset($permissions['orderanalytics']);
$dbal->executeStatement(
'UPDATE admin_group SET permissions = :permissions, updated_at = :updated_at WHERE id = :id',
[
'permissions' => json_encode($permissions, JSON_THROW_ON_ERROR),
'updated_at' => date('Y-m-d H:i:s'),
'id' => $group['id'],
]
);
}
// Replace only the old module registration. No invoices or client data are changed.
$dbal->executeStatement("DELETE FROM extension WHERE type = 'mod' AND name = 'orderanalytics'");
$dbal->commit();
} catch (\Throwable $e) {
$dbal->rollBack();
throw $e;
}
return true;
}
public function getModulePermissions(): array
{
return [
'view' => [
'type' => 'bool',
'display_name' => __trans('View billing analytics'),
'description' => __trans('Allows the staff member to view billing analytics and invoice charts.'),
],
];
}
private function parseDate(string $value, string $field): DateTimeImmutable
{
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
$errors = DateTimeImmutable::getLastErrors();
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format('Y-m-d') !== $value) {
throw new InformationException('Invalid :field date. Expected YYYY-MM-DD.', [':field' => $field]);
}
return $date;
}
private function shiftMonthsClamped(DateTimeImmutable $date, int $months): DateTimeImmutable
{
$target = $date->modify('first day of this month')->modify(sprintf('%+d months', $months));
$day = min((int) $date->format('j'), (int) $target->format('t'));
return $target->setDate((int) $target->format('Y'), (int) $target->format('n'), $day);
}
private function shiftYearsClamped(DateTimeImmutable $date, int $years): DateTimeImmutable
{
$year = (int) $date->format('Y') + $years;
$month = (int) $date->format('n');
$lastDay = (int) (new DateTimeImmutable(sprintf('%04d-%02d-01', $year, $month)))->format('t');
return $date->setDate($year, $month, min((int) $date->format('j'), $lastDay));
}
private function shiftMonthSameDay(DateTimeImmutable $date): ?DateTimeImmutable
{
$shifted = $this->shiftMonthsClamped($date, -1);
return $shifted->format('j') === $date->format('j') ? $shifted : null;
}
private function shiftYearSameDay(DateTimeImmutable $date): ?DateTimeImmutable
{
$shifted = $this->shiftYearsClamped($date, -1);
return $shifted->format('m-d') === $date->format('m-d') ? $shifted : null;
}
private function parseDateRange(array $data): array
{
$start = $this->parseDate((string) ($data['start_date'] ?? date('Y-m-01')), 'start');
$end = $this->parseDate((string) ($data['end_date'] ?? date('Y-m-d')), 'end');
if ($start > $end) {
throw new InformationException('Start date must not be after end date.');
}
$dayCount = (int) $start->diff($end)->days + 1;
if ($dayCount > self::MAX_RANGE_DAYS) {
throw new InformationException('Date range must not exceed :days days.', [':days' => self::MAX_RANGE_DAYS]);
}
$preset = (string) ($data['preset'] ?? 'custom');
$allowedPresets = ['today', 'last_7_days', 'last_30_days', 'this_month', 'last_month', 'year_to_date', 'this_year', 'custom'];
if (!in_array($preset, $allowedPresets, true)) {
throw new InformationException('Invalid date preset.');
}
if (in_array($preset, ['this_month', 'last_month'], true)) {
if ($start->format('Y-m') !== $end->format('Y-m')) {
throw new InformationException('Month presets must stay within one calendar month.');
}
$comparisonMode = 'same_day_previous_month';
$previousStart = $this->shiftMonthsClamped($start, -1);
$previousEnd = $this->shiftMonthsClamped($end, -1);
} elseif (in_array($preset, ['this_year', 'year_to_date'], true)) {
if ($start->format('Y') !== $end->format('Y')) {
throw new InformationException('Year presets must stay within one calendar year.');
}
$comparisonMode = 'same_day_previous_year';
$previousStart = $this->shiftYearsClamped($start, -1);
$previousEnd = $this->shiftYearsClamped($end, -1);
} else {
$comparisonMode = 'previous_equal_period';
$previousEnd = $start->sub(new DateInterval('P1D'));
$previousStart = $previousEnd->sub(new DateInterval('P' . ($dayCount - 1) . 'D'));
}
return [
'start' => $start->format('Y-m-d 00:00:00'),
'end' => $end->format('Y-m-d 23:59:59'),
'prev_start' => $previousStart->format('Y-m-d 00:00:00'),
'prev_end' => $previousEnd->format('Y-m-d 23:59:59'),
'start_date' => $start->format('Y-m-d'),
'end_date' => $end->format('Y-m-d'),
'prev_start_date' => $previousStart->format('Y-m-d'),
'prev_end_date' => $previousEnd->format('Y-m-d'),
'comparison_mode' => $comparisonMode,
'day_count' => $dayCount,
];
}
private function getGrowth(float $current, float $previous): float
{
if ($previous > 0) {
return round((($current - $previous) / $previous) * 100, 1);
}
return $current > 0 ? 100.0 : 0.0;
}
private function normalizeLimit(mixed $value, int $default = self::DEFAULT_LIMIT): int
{
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
return $default;
}
return max(1, min(self::MAX_LIMIT, (int) $value));
}
private function getInvoiceNumberPadding(): int
{
try {
$padding = $this->di['mod_service']('system')->getParamValue('invoice_number_padding');
return ($padding !== null && $padding !== '') ? max(0, (int) $padding) : 5;
} catch (\Throwable) {
return 5;
}
}
private function isTruthy(mixed $value): bool
{
return $value === true || $value === 1 || $value === '1' || $value === 'true';
}
private function getPaidOnlyFilter(array $data, string $tableAlias = ''): array
{
$active = $this->isTruthy($data['paid_only'] ?? $data['exclude_pending'] ?? false);
$prefix = $tableAlias !== '' ? $tableAlias . '.' : '';
return $active
? ['where' => " AND {$prefix}status IN ('paid', 'refunded')", 'date_col' => $prefix . 'paid_at', 'is_paid' => true]
: ['where' => '', 'date_col' => $prefix . 'created_at', 'is_paid' => false];
}
private function getInvoiceCategoryFilter(array $data, string $alias = 'inv', string $invoiceColumn = 'id'): array
{
$category = $data['category_id'] ?? 'all';
if ($category === '' || $category === null || $category === 'all') {
return ['sql' => '', 'params' => []];
}
$prefix = $alias !== '' ? $alias . '.' : '';
$invoiceReference = $prefix . $invoiceColumn;
if ($category === 'custom') {
return [
'sql' => " AND {$invoiceReference} IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM invoice_item cat_ii WHERE cat_ii.invoice_id = {$invoiceReference} AND cat_ii.type = 'order')",
'params' => [],
];
}
if (filter_var($category, FILTER_VALIDATE_INT) === false || (int) $category < 1) {
throw new InformationException('Invalid product category.');
}
return [
'sql' => " AND EXISTS (
SELECT 1 FROM invoice_item cat_ii
JOIN client_order cat_co ON cat_co.id = cat_ii.rel_id
JOIN product cat_p ON cat_p.id = cat_co.product_id
WHERE cat_ii.invoice_id = {$invoiceReference}
AND cat_ii.type = 'order'
AND cat_p.product_category_id = :category_id
)",
'params' => ['category_id' => (int) $category],
];
}
private function invoiceTotalsJoin(string $invoiceAlias = 'inv', string $totalsAlias = 'invoice_totals', string $currencyAlias = 'invoice_currency'): string
{
return " LEFT JOIN (
SELECT invoice_id,
COALESCE(SUM(COALESCE(price, 0) * COALESCE(quantity, 1)), 0) AS subtotal,
COALESCE(SUM(CASE WHEN taxed = 1 THEN COALESCE(price, 0) * COALESCE(quantity, 1) ELSE 0 END), 0) AS taxable_subtotal
FROM invoice_item GROUP BY invoice_id
) {$totalsAlias} ON {$totalsAlias}.invoice_id = {$invoiceAlias}.id
LEFT JOIN currency {$currencyAlias} ON {$currencyAlias}.code = {$invoiceAlias}.currency ";
}
private function invoiceTotalExpression(string $invoiceAlias = 'inv', string $totalsAlias = 'invoice_totals'): string
{
return "(COALESCE({$totalsAlias}.subtotal, 0) + ROUND(COALESCE({$totalsAlias}.taxable_subtotal, 0) * COALESCE({$invoiceAlias}.taxrate, 0) / 100, 2))";
}
private function baseInvoiceTotalExpression(string $invoiceAlias = 'inv', string $totalsAlias = 'invoice_totals', string $currencyAlias = 'invoice_currency'): string
{
$total = $this->invoiceTotalExpression($invoiceAlias, $totalsAlias);
return "({$total} / COALESCE(NULLIF({$invoiceAlias}.currency_rate, 0), NULLIF({$currencyAlias}.conversion_rate, 0), 1))";
}
private function queryFinancials(array $dates, array $data, bool $previous = false): array
{
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$baseTotal = $this->baseInvoiceTotalExpression();
$startKey = $previous ? 'prev_start' : 'start';
$endKey = $previous ? 'prev_end' : 'end';
$sql = "SELECT
COALESCE(SUM(CASE WHEN billing.base_total > 0 THEN billing.base_total ELSE 0 END), 0) AS gross,
COALESCE(SUM(CASE WHEN billing.base_total < 0 THEN ABS(billing.base_total) ELSE 0 END + billing.base_refund), 0) AS refunds,
COALESCE(SUM(billing.base_total - billing.base_refund), 0) AS net,
COALESCE(SUM(CASE WHEN billing.base_total > 0 THEN 1 ELSE 0 END), 0) AS positive_count
FROM (
SELECT {$baseTotal} AS base_total, COALESCE(inv.base_refund, 0) AS base_refund
FROM invoice inv" . $this->invoiceTotalsJoin() . "
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . "
) billing";
$params = array_merge(['start' => $dates[$startKey], 'end' => $dates[$endKey]], $category['params']);
$row = $this->di['dbal']->executeQuery($sql, $params)->fetchAssociative() ?: [];
return [
'gross' => round((float) ($row['gross'] ?? 0), 2),
'refunds' => round((float) ($row['refunds'] ?? 0), 2),
'net' => round((float) ($row['net'] ?? 0), 2),
'positive_count' => (int) ($row['positive_count'] ?? 0),
];
}
private function getBaseCurrency(): array
{
$row = $this->di['dbal']->executeQuery(
'SELECT code, format_pattern, fraction_digits FROM currency WHERE is_default = 1 LIMIT 1'
)->fetchAssociative();
return [
'code' => (string) ($row['code'] ?? ''),
'format_pattern' => isset($row['format_pattern']) ? (string) $row['format_pattern'] : null,
'fraction_digits' => isset($row['fraction_digits']) ? (int) $row['fraction_digits'] : null,
];
}
public function getBillingSummary(array $data = []): array
{
$dates = $this->parseDateRange($data);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$countSql = "SELECT COUNT(1) FROM invoice inv WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'];
$paidSql = "SELECT COUNT(1) FROM invoice inv WHERE inv.status IN ('paid', 'refunded') AND inv.paid_at BETWEEN :start AND :end" . $category['sql'];
$unpaidSql = "SELECT COUNT(1) FROM invoice inv WHERE inv.status = 'unpaid' AND inv.created_at BETWEEN :start AND :end" . $category['sql'];
$params = $category['params'];
$period = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $params);
$previous = array_merge(['start' => $dates['prev_start'], 'end' => $dates['prev_end']], $params);
$today = array_merge(['start' => date('Y-m-d 00:00:00'), 'end' => date('Y-m-d 23:59:59')], $params);
$total = (int) $this->di['dbal']->executeQuery($countSql, $period)->fetchOne();
$paid = (int) $this->di['dbal']->executeQuery($paidSql, $period)->fetchOne();
$unpaid = $paidOnly['is_paid'] ? 0 : (int) $this->di['dbal']->executeQuery($unpaidSql, $period)->fetchOne();
$previousTotal = (int) $this->di['dbal']->executeQuery($countSql, $previous)->fetchOne();
$previousPaid = (int) $this->di['dbal']->executeQuery($paidSql, $previous)->fetchOne();
return [
'total' => $total,
'paid' => $paid,
'unpaid' => $unpaid,
'today' => (int) $this->di['dbal']->executeQuery($countSql, $today)->fetchOne(),
'total_growth' => $this->getGrowth((float) $total, (float) $previousTotal),
'paid_growth' => $this->getGrowth((float) $paid, (float) $previousPaid),
];
}
public function getRevenueStats(array $data = []): array
{
$dates = $this->parseDateRange($data);
$current = $this->queryFinancials($dates, $data);
$previous = $this->queryFinancials($dates, $data, true);
$todayData = $data;
$todayData['paid_only'] = true;
$todayDates = $this->parseDateRange(['start_date' => date('Y-m-d'), 'end_date' => date('Y-m-d'), 'preset' => 'custom']);
$yesterdayDates = $this->parseDateRange(['start_date' => date('Y-m-d', strtotime('-1 day')), 'end_date' => date('Y-m-d', strtotime('-1 day')), 'preset' => 'custom']);
$today = $this->queryFinancials($todayDates, $todayData);
$yesterday = $this->queryFinancials($yesterdayDates, $todayData);
$aov = $current['positive_count'] > 0 ? round($current['gross'] / $current['positive_count'], 2) : 0.0;
$previousAov = $previous['positive_count'] > 0 ? round($previous['gross'] / $previous['positive_count'], 2) : 0.0;
return [
'total' => $current['gross'],
'refunds' => $current['refunds'],
'net' => $current['net'],
'aov' => $aov,
'today' => $today['net'],
'yesterday' => $yesterday['net'],
'growth' => $this->getGrowth($current['gross'], $previous['gross']),
'refunds_growth' => $this->getGrowth($current['refunds'], $previous['refunds']),
'net_growth' => $this->getGrowth($current['net'], $previous['net']),
'aov_growth' => $this->getGrowth($aov, $previousAov),
'currency' => $this->getBaseCurrency(),
];
}
private function buildPeriodAxis(array $dates): array
{
$start = new DateTimeImmutable($dates['start_date']);
$end = new DateTimeImmutable($dates['end_date']);
$previousStart = new DateTimeImmutable($dates['prev_start_date']);
$previousEnd = new DateTimeImmutable($dates['prev_end_date']);
$monthly = $dates['day_count'] > 90;
$labels = $currentKeys = $previousKeys = $currentDates = $previousDates = [];
if ($monthly) {
$cursor = $start->modify('first day of this month');
$last = $end->modify('first day of this month');
$index = 0;
while ($cursor <= $last) {
if ($dates['comparison_mode'] === 'same_day_previous_year') {
$comparison = $this->shiftYearsClamped($cursor, -1);
} elseif ($dates['comparison_mode'] === 'same_day_previous_month') {
$comparison = $this->shiftMonthsClamped($cursor, -1);
} else {
$comparison = $previousStart->modify('first day of this month')->modify('+' . $index . ' months');
if ($comparison > $previousEnd->modify('first day of this month')) {
$comparison = null;
}
}
$labels[] = $cursor->format('M Y');
$currentKeys[] = $cursor->format('Y-m');
$previousKeys[] = $comparison?->format('Y-m');
$currentDates[] = $cursor->format('Y-m-d');
$previousDates[] = $comparison?->format('Y-m-d') ?? '';
$cursor = $cursor->modify('+1 month');
++$index;
}
} else {
$cursor = $start;
$index = 0;
while ($cursor <= $end) {
if ($dates['comparison_mode'] === 'same_day_previous_month') {
$comparison = $this->shiftMonthSameDay($cursor);
} elseif ($dates['comparison_mode'] === 'same_day_previous_year') {
$comparison = $this->shiftYearSameDay($cursor);
} else {
$comparison = $previousStart->modify('+' . $index . ' days');
if ($comparison > $previousEnd) {
$comparison = null;
}
}
$labels[] = $cursor->format('d M');
$currentKeys[] = $cursor->format('Y-m-d');
$previousKeys[] = $comparison?->format('Y-m-d');
$currentDates[] = $cursor->format('Y-m-d');
$previousDates[] = $comparison?->format('Y-m-d') ?? '';
$cursor = $cursor->modify('+1 day');
++$index;
}
}
return [
'monthly' => $monthly,
'labels' => $labels,
'current_keys' => $currentKeys,
'previous_keys' => $previousKeys,
'curr_dates' => $currentDates,
'prev_dates' => $previousDates,
];
}
private function getPeriodLabels(array $dates): array
{
$current = (new DateTimeImmutable($dates['start_date']))->format('d M Y') . ' - ' . (new DateTimeImmutable($dates['end_date']))->format('d M Y');
$previous = (new DateTimeImmutable($dates['prev_start_date']))->format('d M Y') . ' - ' . (new DateTimeImmutable($dates['prev_end_date']))->format('d M Y');
return [$current, $previous];
}
public function getBillingsByPeriod(array $data = []): array
{
$dates = $this->parseDateRange($data);
$axis = $this->buildPeriodAxis($dates);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$format = $axis['monthly'] ? '%Y-%m' : '%Y-%m-%d';
$sql = "SELECT DATE_FORMAT({$paidOnly['date_col']}, '{$format}') AS period_key, COUNT(1) AS item_count
FROM invoice inv
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . " GROUP BY period_key";
$load = function (string $start, string $end) use ($sql, $category): array {
$params = array_merge(['start' => $start, 'end' => $end], $category['params']);
$rows = $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
$values = [];
foreach ($rows as $row) {
$values[(string) $row['period_key']] = (int) $row['item_count'];
}
return $values;
};
$currentValues = $load($dates['start'], $dates['end']);
$previousValues = $load($dates['prev_start'], $dates['prev_end']);
[$currentLabel, $previousLabel] = $this->getPeriodLabels($dates);
return [
'labels' => $axis['labels'],
'curr_dates' => $axis['curr_dates'],
'prev_dates' => $axis['prev_dates'],
'data' => array_map(static fn (string $key): int => $currentValues[$key] ?? 0, $axis['current_keys']),
'prev_data' => array_map(static fn (?string $key): ?int => $key === null ? null : ($previousValues[$key] ?? 0), $axis['previous_keys']),
'curr_label' => $currentLabel,
'prev_label' => $previousLabel,
];
}
public function getRevenueByPeriod(array $data = []): array
{
$dates = $this->parseDateRange($data);
$axis = $this->buildPeriodAxis($dates);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$format = $axis['monthly'] ? '%Y-%m' : '%Y-%m-%d';
$baseTotal = $this->baseInvoiceTotalExpression();
$sql = "SELECT DATE_FORMAT({$paidOnly['date_col']}, '{$format}') AS period_key,
COALESCE(SUM({$baseTotal} - COALESCE(inv.base_refund, 0)), 0) AS amount
FROM invoice inv" . $this->invoiceTotalsJoin() . "
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . " GROUP BY period_key";
$load = function (string $start, string $end) use ($sql, $category): array {
$params = array_merge(['start' => $start, 'end' => $end], $category['params']);
$rows = $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
$values = [];
foreach ($rows as $row) {
$values[(string) $row['period_key']] = round((float) $row['amount'], 2);
}
return $values;
};
$currentValues = $load($dates['start'], $dates['end']);
$previousValues = $load($dates['prev_start'], $dates['prev_end']);
[$currentLabel, $previousLabel] = $this->getPeriodLabels($dates);
return [
'labels' => $axis['labels'],
'curr_dates' => $axis['curr_dates'],
'prev_dates' => $axis['prev_dates'],
'data' => array_map(static fn (string $key): float => $currentValues[$key] ?? 0.0, $axis['current_keys']),
'prev_data' => array_map(static fn (?string $key): ?float => $key === null ? null : ($previousValues[$key] ?? 0.0), $axis['previous_keys']),
'curr_label' => $currentLabel,
'prev_label' => $previousLabel,
'currency' => $this->getBaseCurrency(),
];
}
public function getTopProducts(array $data = []): array
{
$dates = $this->parseDateRange($data);
$limit = $this->normalizeLimit($data['limit'] ?? self::DEFAULT_LIMIT);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$lineBase = "((COALESCE(ii.price, 0) * COALESCE(ii.quantity, 1)) *
(CASE WHEN ii.taxed = 1 THEN 1 + COALESCE(inv.taxrate, 0) / 100 ELSE 1 END) /
COALESCE(NULLIF(inv.currency_rate, 0), NULLIF(invoice_currency.conversion_rate, 0), 1))";
$invoiceBaseTotal = $this->baseInvoiceTotalExpression();
$lineNet = "({$lineBase} - CASE
WHEN COALESCE(inv.base_refund, 0) > 0 AND {$invoiceBaseTotal} > 0
THEN COALESCE(inv.base_refund, 0) * ({$lineBase} / {$invoiceBaseTotal})
ELSE 0
END)";
$sql = "SELECT ii.title AS product_title, pc.title AS category_title,
COUNT(DISTINCT inv.id) AS invoice_count,
ROUND(COALESCE(SUM({$lineNet}), 0), 2) AS total_revenue
FROM invoice_item ii
JOIN invoice inv ON inv.id = ii.invoice_id
" . $this->invoiceTotalsJoin() . "
LEFT JOIN client_order co ON co.id = ii.rel_id AND ii.type = 'order'
LEFT JOIN product p ON p.id = co.product_id
LEFT JOIN product_category pc ON pc.id = p.product_category_id
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . "
GROUP BY ii.title, pc.title ORDER BY total_revenue DESC LIMIT {$limit}";
$params = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $category['params']);
return $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
}
public function getTopClients(array $data = []): array
{
$dates = $this->parseDateRange($data);
$limit = $this->normalizeLimit($data['limit'] ?? self::DEFAULT_LIMIT);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$baseTotal = $this->baseInvoiceTotalExpression();
$sql = "SELECT c.id AS client_id, CONCAT(c.first_name, ' ', c.last_name) AS client_name,
c.email AS client_email, c.company AS client_company,
COUNT(DISTINCT inv.id) AS invoice_count,
ROUND(COALESCE(SUM({$baseTotal} - COALESCE(inv.base_refund, 0)), 0), 2) AS total_spent
FROM invoice inv" . $this->invoiceTotalsJoin() . "
JOIN client c ON c.id = inv.client_id
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . "
GROUP BY c.id, c.first_name, c.last_name, c.email, c.company
ORDER BY total_spent DESC LIMIT {$limit}";
$params = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $category['params']);
return $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
}
public function getRecentInvoices(array $data = []): array
{
$dates = $this->parseDateRange($data);
$limit = $this->normalizeLimit($data['limit'] ?? self::DEFAULT_LIMIT);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$padding = $this->getInvoiceNumberPadding();
$total = $this->invoiceTotalExpression();
$baseTotal = $this->baseInvoiceTotalExpression();
$sql = "SELECT inv.id,
CONCAT(COALESCE(inv.serie, ''), LPAD(inv.nr, GREATEST(CHAR_LENGTH(inv.nr), {$padding}), '0')) AS invoice_number,
inv.status, inv.currency, ROUND({$total}, 2) AS total,
ROUND({$baseTotal} - COALESCE(inv.base_refund, 0), 2) AS base_total,
inv.created_at, inv.paid_at,
TRIM(CONCAT(COALESCE(c.first_name, inv.buyer_first_name, ''), ' ', COALESCE(c.last_name, inv.buyer_last_name, ''))) AS client_name,
COALESCE(c.email, inv.buyer_email, '') AS client_email,
COALESCE(c.company, inv.buyer_company, '') AS client_company, c.id AS client_id
FROM invoice inv" . $this->invoiceTotalsJoin() . "
LEFT JOIN client c ON c.id = inv.client_id
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . "
ORDER BY {$paidOnly['date_col']} DESC, inv.id DESC LIMIT {$limit}";
$params = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $category['params']);
return $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
}
public function getProductCategoryDistribution(array $data = []): array
{
$dates = $this->parseDateRange($data);
$paidOnly = $this->getPaidOnlyFilter($data, 'inv');
$category = $this->getInvoiceCategoryFilter($data, 'inv');
$params = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $category['params']);
$sql = "SELECT pc.title AS category_title, COUNT(DISTINCT inv.id) AS item_count
FROM invoice inv
JOIN invoice_item ii ON ii.invoice_id = inv.id AND ii.type = 'order'
JOIN client_order co ON co.id = ii.rel_id
JOIN product p ON p.id = co.product_id
JOIN product_category pc ON pc.id = p.product_category_id
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . $category['sql'] . "
GROUP BY pc.title ORDER BY item_count DESC";
$rows = $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
if (in_array($data['category_id'] ?? 'all', ['all', ''], true)) {
$customSql = "SELECT COUNT(DISTINCT inv.id) FROM invoice inv
WHERE {$paidOnly['date_col']} BETWEEN :start AND :end" . $paidOnly['where'] . "
AND NOT EXISTS (SELECT 1 FROM invoice_item ii WHERE ii.invoice_id = inv.id AND ii.type = 'order')";
$customCount = (int) $this->di['dbal']->executeQuery($customSql, ['start' => $dates['start'], 'end' => $dates['end']])->fetchOne();
if ($customCount > 0) {
$rows[] = ['category_title' => 'Custom Invoice', 'item_count' => $customCount];
}
}
$colors = ['#206bc4', '#4299e1', '#4eb690', '#f76707', '#f59f00', '#ae3ec9', '#d63939', '#6c757d', '#2fb344', '#66ccff'];
if ($rows === []) {
return ['labels' => ['No billing data'], 'data' => [1], 'colors' => ['#e0e5ec'], 'empty' => true];
}
return [
'labels' => array_map(static fn (array $row): string => (string) $row['category_title'], $rows),
'data' => array_map(static fn (array $row): int => (int) $row['item_count'], $rows),
'colors' => array_map(static fn (int $index): string => $colors[$index % count($colors)], array_keys($rows)),
'empty' => false,
];
}
public function getPaymentMethods(array $data = []): array
{
$dates = $this->parseDateRange($data);
$category = $this->getInvoiceCategoryFilter($data, 't', 'invoice_id');
$sql = "SELECT COALESCE(pg.name, CASE WHEN t.gateway_id IS NULL THEN 'Balance / Unknown' ELSE CONCAT('Gateway ', t.gateway_id) END) AS gateway_name,
COUNT(1) AS item_count
FROM transaction t
LEFT JOIN pay_gateway pg ON pg.id = t.gateway_id
WHERE t.status = 'received' AND t.created_at BETWEEN :start AND :end" . $category['sql'] . "
GROUP BY t.gateway_id, pg.name ORDER BY item_count DESC";
$params = array_merge(['start' => $dates['start'], 'end' => $dates['end']], $category['params']);
$rows = $this->di['dbal']->executeQuery($sql, $params)->fetchAllAssociative();
return [
'labels' => array_map(static fn (array $row): string => (string) $row['gateway_name'], $rows),
'data' => array_map(static fn (array $row): int => (int) $row['item_count'], $rows),
];
}
public function getProductCategoryPairs(): array
{
$rows = $this->di['dbal']->executeQuery('SELECT id, title FROM product_category ORDER BY title ASC')->fetchAllAssociative();
$pairs = [];
foreach ($rows as $row) {
$pairs[(string) $row['id']] = (string) $row['title'];
}
return $pairs;
}
}