dolibarr 25.0.0-alpha
stats.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2008-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
32abstract class Stats
33{
37 protected $db;
41 protected $lastfetchdate = array();
42
46 public $cachefilesuffix = '';
47
51 public $from;
52
56 public $where;
60 public $from_line;
64 public $field_date;
68 public $field;
72 public $field_line;
73
77 public $error;
78
82 public $year;
83
87 public $month;
88
94 abstract protected function getNbByMonth($year, $format = 0);
95
106 public function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
107 {
108 global $conf, $user, $langs;
109
110 if ($startyear > $endyear) {
111 return array();
112 }
113
114 $data = array(); // This is the return value
115 $datay = array(); // This is a work value
116
117 // Search into cache
118 if (!empty($cachedelay)) {
119 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
120 }
121
122 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
123 $newmask = '0644';
124
125 $nowgmt = dol_now();
126
127 $foundintocache = 0;
128 $filedate = -1;
129 if ($cachedelay > 0) {
130 $filedate = dol_filemtime($newpathofdestfile);
131 if ($filedate >= ($nowgmt - $cachedelay)) {
132 $foundintocache = 1;
133
134 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
135 } else {
136 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
137 }
138 }
139 // Load file into $data
140 if ($foundintocache) { // Cache file found and is not too old
141 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
142 $data = json_decode(file_get_contents($newpathofdestfile), true);
143 '@phan-var-force array<int<0,11>,array{0:int<1,12>,1:int}> $data';
144 } else {
145 $year = $startyear;
146 $sm = $startmonth - 1;
147 if ($sm != 0) {
148 $year -= 1;
149 }
150 while ($year <= $endyear) {
151 $datay[$year] = $this->getNbByMonth($year, $format);
152 $year++;
153 }
154
155 for ($i = 0; $i < 12; $i++) {
156 $data[$i][] = $datay[$endyear][($i + $sm) % 12][0];
157 $year = $startyear;
158 while ($year <= $endyear) {
159 // floor(($i + $sm) / 12)) is 0 if we are after the month start $sm and same year, become 1 when we reach january of next year
160 $data[$i][] = $datay[$year - (1 - (int) floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1];
161 $year++;
162 }
163 }
164 }
165
166
167 // Save cache file
168 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
169 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
170 if (!dol_is_dir($conf->user->dir_temp)) {
171 dol_mkdir($conf->user->dir_temp);
172 }
173 $fp = @fopen($newpathofdestfile, 'w');
174 if ($fp) {
175 fwrite($fp, json_encode($data));
176 fclose($fp);
177 } else {
178 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
179 }
180 dolChmod($newpathofdestfile);
181
182 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
183 }
184
185 return $data;
186 }
187
193 abstract protected function getAmountByMonth($year, $format = 0);
194
208 public function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
209 {
210 global $conf, $user, $langs;
211
212 if ($startyear > $endyear) {
213 return array();
214 }
215
216 $datay = array();
217 $data = array(); // Return value
218
219 // Search into cache
220 if (!empty($cachedelay)) {
221 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
222 }
223
224 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
225 $newmask = '0644';
226
227 $nowgmt = dol_now();
228
229 $foundintocache = 0;
230 $filedate = -1;
231 if ($cachedelay > 0) {
232 $filedate = dol_filemtime($newpathofdestfile);
233 if ($filedate >= ($nowgmt - $cachedelay)) {
234 $foundintocache = 1;
235
236 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
237 } else {
238 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
239 }
240 }
241
242 // Load file into $data
243 if ($foundintocache) { // Cache file found and is not too old
244 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
245 $data = json_decode(file_get_contents($newpathofdestfile), true);
246 } else {
247 $year = $startyear;
248 $sm = $startmonth - 1;
249 if ($sm != 0) {
250 $year -= 1;
251 }
252 while ($year <= $endyear) {
253 $datay[$year] = $this->getAmountByMonth($year, $format);
254 $year++;
255 }
256
257 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
258 for ($i = 0; $i < 12; $i++) {
259 $data[$i][] = isset($datay[$endyear][($i + $sm) % 12]['label']) ? $datay[$endyear][($i + $sm) % 12]['label'] : $datay[$endyear][($i + $sm) % 12][0]; // set label
260 $year = $startyear;
261 while ($year <= $endyear) {
262 // floor(($i + $sm) / 12)) is 0 if we are after the month start $sm and same year, become 1 when we reach january of next year
263 $data[$i][] = $datay[$year - (1 - (int) floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1]; // set yval for x=i
264 $year++;
265 }
266 }
267 }
268
269 // Save cache file
270 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
271 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
272 if (!dol_is_dir($conf->user->dir_temp)) {
273 dol_mkdir($conf->user->dir_temp);
274 }
275 $fp = @fopen($newpathofdestfile, 'w');
276 if ($fp) {
277 fwrite($fp, json_encode($data));
278 fclose($fp);
279 } else {
280 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
281 }
282 dolChmod($newpathofdestfile);
283
284 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
285 }
286
287 return $data;
288 }
289
294 abstract protected function getAverageByMonth($year);
295
303 public function getAverageByMonthWithPrevYear($endyear, $startyear)
304 {
305 if ($startyear > $endyear) {
306 return array();
307 }
308
309 $datay = array();
310 $data = array();
311
312 $year = $startyear;
313 while ($year <= $endyear) {
314 $datay[$year] = $this->getAverageByMonth($year);
315 $year++;
316 }
317
318 for ($i = 0; $i < 12; $i++) {
319 $data[$i][] = $datay[$endyear][$i][0];
320 $year = $startyear;
321 while ($year <= $endyear) {
322 $data[$i][] = $datay[$year][$i][1];
323 $year++;
324 }
325 }
326
327 return $data;
328 }
329
338 public function getAllByProductEntry($year, $cachedelay = 0, $limit = 10)
339 {
340 global $conf, $user, $langs;
341
342 $data = array();
343
344 // Search in cache
345 if (!empty($cachedelay)) {
346 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
347 }
348
349 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
350 $newmask = '0644';
351
352 $nowgmt = dol_now();
353
354 $foundintocache = 0;
355 $filedate = -1;
356 if ($cachedelay > 0) {
357 $filedate = dol_filemtime($newpathofdestfile);
358 if ($filedate >= ($nowgmt - $cachedelay)) {
359 $foundintocache = 1;
360
361 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
362 } else {
363 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
364 }
365 }
366
367 // Load file into $data
368 if ($foundintocache) { // Cache file found and is not too old
369 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
370 $data = json_decode(file_get_contents($newpathofdestfile), true);
371 '@phan-var-force array<int<0,11>,array{0:int<1,12>,1:int|float}> $data'; // Phan can't decode json_decode's return value
372 } else {
373 $data = $this->getAllByProduct($year, $limit);
374 }
375
376 // Save cache file
377 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
378 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
379 if (!dol_is_dir($conf->user->dir_temp)) {
380 dol_mkdir($conf->user->dir_temp);
381 }
382 $fp = @fopen($newpathofdestfile, 'w');
383 if ($fp) {
384 fwrite($fp, json_encode($data));
385 fclose($fp);
386 } else {
387 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
388 }
389 dolChmod($newpathofdestfile);
390
391 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
392 }
393
394 return $data;
395 }
396
397
398 // Here we have low level of shared code called by XxxStats.class.php
399
400
401 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
408 protected function _getNbByYear($sql)
409 {
410 // phpcs:enable
411 $result = array();
412
413 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
414 $resql = $this->db->query($sql);
415 if ($resql) {
416 $num = $this->db->num_rows($resql);
417 $i = 0;
418 while ($i < $num) {
419 $row = $this->db->fetch_row($resql);
420 $result[$i] = $row;
421 $i++;
422 }
423 $this->db->free($resql);
424 } else {
425 dol_print_error($this->db);
426 }
427 return $result;
428 }
429
430 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
437 protected function _getAllByYear($sql)
438 {
439 // phpcs:enable
440 $result = array();
441
442 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
443 $resql = $this->db->query($sql);
444 if ($resql) {
445 $num = $this->db->num_rows($resql);
446 $i = 0;
447 // Values of the previous row (rows are sorted by year desc), kept in local vars so they are typed
448 $prevyear = 0;
449 $prevnb = 0;
450 $prevtotal = 0.0;
451 $prevavg = 0.0;
452 $prevweighted = 0.0;
453 while ($i < $num) {
454 $row = $this->db->fetch_object($resql);
455 $result[$i]['year'] = (string) $row->year;
456 $result[$i]['nb'] = (int) $row->nb;
457 // Delta is computed only against the immediately previous year (no delta if that year has no record)
458 $hasprevyear = ($i > 0 && $prevyear == (int) $row->year + 1);
459 if ($hasprevyear && $row->nb > 0) {
460 $result[$i - 1]['nb_diff'] = ($prevnb - $row->nb) / $row->nb * 100;
461 }
462 // For some $sql only
463 if (property_exists($row, 'total')) {
464 $result[$i]['total'] = (float) $row->total;
465 if ($hasprevyear && $row->total > 0) {
466 $result[$i - 1]['total_diff'] = ($prevtotal - $row->total) / $row->total * 100;
467 }
468 $prevtotal = (float) $row->total;
469 }
470 // For some $sql only
471 if (property_exists($row, 'total')) {
472 $result[$i]['avg'] = (float) $row->avg;
473 if ($hasprevyear && $row->avg > 0) {
474 $result[$i - 1]['avg_diff'] = ($prevavg - $row->avg) / $row->avg * 100;
475 }
476 $prevavg = (float) $row->avg;
477 }
478 // For some $sql only
479 if (property_exists($row, 'weighted')) {
480 $result[$i]['weighted'] = (float) $row->weighted;
481 if ($hasprevyear && $row->weighted > 0) {
482 $result[$i - 1]['avg_weighted'] = ($prevweighted - $row->weighted) / $row->weighted * 100;
483 }
484 $prevweighted = (float) $row->weighted;
485 }
486 $prevyear = (int) $row->year;
487 $prevnb = (int) $row->nb;
488 $i++;
489 }
490 $this->db->free($resql);
491 } else {
492 dol_print_error($this->db);
493 }
494 return $result;
495 }
496
497 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
506 protected function _getNbByMonth($year, $sql, $format = 0)
507 {
508 // phpcs:enable
509 global $langs;
510
511 $result = array();
512 $res = array();
513
514 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
515 $resql = $this->db->query($sql);
516 if ($resql) {
517 $num = $this->db->num_rows($resql);
518 $i = 0;
519 $j = 0;
520 while ($i < $num) {
521 $row = $this->db->fetch_row($resql);
522 $j = $row[0] * 1;
523 $result[$j] = $row[1];
524 $i++;
525 }
526 $this->db->free($resql);
527 } else {
528 dol_print_error($this->db);
529 }
530
531 for ($i = 1; $i < 13; $i++) {
532 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
533 }
534
535 $data = array();
536
537 for ($i = 1; $i < 13; $i++) {
538 $month = 'unknown';
539 if ($format == 0) {
540 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
541 } elseif ($format == 1) {
542 $month = $i;
543 } elseif ($format == 2) {
544 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
545 }
546 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
547 //$month=dol_substr($month,0,3);
548 $data[$i - 1] = array($month, $res[$i]);
549 }
550
551 return $data;
552 }
553
554 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
563 protected function _getAmountByMonth($year, $sql, $format = 0)
564 {
565 // phpcs:enable
566 global $langs;
567
568 $result = array();
569 $res = array();
570
571 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
572
573 $resql = $this->db->query($sql);
574 if ($resql) {
575 $num = $this->db->num_rows($resql);
576 $i = 0;
577 while ($i < $num) {
578 $row = $this->db->fetch_row($resql);
579 $j = $row[0] * 1;
580 $result[$j] = $row[1];
581 $i++;
582 }
583 $this->db->free($resql);
584 } else {
585 dol_print_error($this->db);
586 }
587
588 for ($i = 1; $i < 13; $i++) {
589 $res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
590 }
591
592 $data = array();
593
594 for ($i = 1; $i < 13; $i++) {
595 $month = 'unknown';
596 if ($format == 0) {
597 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
598 } elseif ($format == 1) {
599 $month = $i;
600 } elseif ($format == 2) {
601 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
602 }
603 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
604 //$month=dol_substr($month,0,3);
605 $data[$i - 1] = array($month, $res[$i]);
606 }
607
608 return $data;
609 }
610
611 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
620 protected function _getAverageByMonth($year, $sql, $format = 0)
621 {
622 // phpcs:enable
623 global $langs;
624
625 $result = array();
626 $res = array();
627
628 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
629 $resql = $this->db->query($sql);
630 if ($resql) {
631 $num = $this->db->num_rows($resql);
632 $i = 0;
633 $j = 0;
634 while ($i < $num) {
635 $row = $this->db->fetch_row($resql);
636 $j = $row[0] * 1;
637 $result[$j] = $row[1];
638 $i++;
639 }
640 $this->db->free($resql);
641 } else {
642 dol_print_error($this->db);
643 }
644
645 for ($i = 1; $i < 13; $i++) {
646 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
647 }
648
649 $data = array();
650
651 for ($i = 1; $i < 13; $i++) {
652 $month = 'unknown';
653 if ($format == 0) {
654 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
655 } elseif ($format == 1) {
656 $month = $i;
657 } elseif ($format == 2) {
658 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
659 }
660 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
661 //$month=dol_substr($month,0,3);
662 $data[$i - 1] = array($month, $res[$i]);
663 }
664
665 return $data;
666 }
667
668
669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
677 protected function _getAllByProduct($sql, $limit = 10)
678 {
679 // phpcs:enable
680 global $langs;
681
682 $result = array();
683
684 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
685 $resql = $this->db->query($sql);
686 if ($resql) {
687 $num = $this->db->num_rows($resql);
688 $i = 0;
689 $other = 0;
690 while ($i < $num) {
691 $row = $this->db->fetch_row($resql);
692 if ($i < $limit || $num == $limit) {
693 $result[$i] = array($row[0], $row[1]); // Ref of product, nb
694 } else {
695 $other += $row[1];
696 }
697 $i++;
698 }
699 if ($num > $limit) {
700 $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
701 }
702 $this->db->free($resql);
703 } else {
704 dol_print_error($this->db);
705 }
706
707 return $result;
708 }
709
710 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
716 protected function _getAmountByYear($sql)
717 {
718 $result = array();
719 $resql = $this->db->query($sql);
720 if ($resql) {
721 $num = $this->db->num_rows($resql);
722 $i = 0;
723 while ($i < $num) {
724 $row = $this->db->fetch_row($resql);
725 $result[] = [
726 0 => (int) $row[0],
727 1 => (int) $row[1],
728 ];
729 $i++;
730 }
731 $this->db->free($resql);
732 }
733 return $result;
734 }
735
736
744 public function getAllByProduct($year, $limit = 0)
745 {
746 // Needs to be implemented in child class when used
747 $msg = get_class($this)."::".__FUNCTION__." not implemented";
748 dol_syslog($msg, LOG_ERR);
749 $l = array(1,0); // Dummy result
750 return array($l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l);
751 }
752}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Parent class of statistics class.
getNbByMonth($year, $format=0)
getAllByProduct($year, $limit=0)
Return nb, amount of predefined product for year.
getAmountByMonth($year, $format=0)
getAverageByMonth($year)
_getAmountByYear($sql)
Returns the summed amounts per year for a given number of past years ending now.
_getAverageByMonth($year, $sql, $format=0)
Return the amount average par month for a given year.
_getAmountByMonth($year, $sql, $format=0)
Return the amount per month for a given year.
_getNbByYear($sql)
Return nb of elements by year.
_getAllByYear($sql)
Return nb of elements, total amount and avg amount each year.
getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0, $startmonth=1)
Return amount of elements by month for several years.
getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0, $startmonth=1)
Return nb of elements by month for several years.
getAllByProductEntry($year, $cachedelay=0, $limit=10)
Return count, and sum of products.
getAverageByMonthWithPrevYear($endyear, $startyear)
Return average of entity by month for several years.
_getAllByProduct($sql, $limit=10)
Return number or total of product refs.
_getNbByMonth($year, $sql, $format=0)
Return number of documents per month for a given year.
dol_filemtime($pathoffile)
Return time of a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)