dolibarr 24.0.0-beta
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 while ($i < $num) {
448 $row = $this->db->fetch_object($resql);
449 $result[$i]['year'] = (string) $row->year;
450 $result[$i]['nb'] = (int) $row->nb;
451 if ($i > 0 && $row->nb > 0) {
452 $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
453 }
454 // For some $sql only
455 if (property_exists($row, 'total')) {
456 $result[$i]['total'] = (float) $row->total;
457 if ($i > 0 && $row->total > 0) {
458 $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
459 }
460 }
461 // For some $sql only
462 if (property_exists($row, 'total')) {
463 $result[$i]['avg'] = (float) $row->avg;
464 if ($i > 0 && $row->avg > 0) {
465 $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
466 }
467 }
468 // For some $sql only
469 if (property_exists($row, 'weighted')) {
470 $result[$i]['weighted'] = (float) $row->weighted;
471 if ($i > 0 && $row->weighted > 0) {
472 $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
473 }
474 }
475 $i++;
476 }
477 $this->db->free($resql);
478 } else {
479 dol_print_error($this->db);
480 }
481 return $result;
482 }
483
484 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
493 protected function _getNbByMonth($year, $sql, $format = 0)
494 {
495 // phpcs:enable
496 global $langs;
497
498 $result = array();
499 $res = array();
500
501 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
502 $resql = $this->db->query($sql);
503 if ($resql) {
504 $num = $this->db->num_rows($resql);
505 $i = 0;
506 $j = 0;
507 while ($i < $num) {
508 $row = $this->db->fetch_row($resql);
509 $j = $row[0] * 1;
510 $result[$j] = $row[1];
511 $i++;
512 }
513 $this->db->free($resql);
514 } else {
515 dol_print_error($this->db);
516 }
517
518 for ($i = 1; $i < 13; $i++) {
519 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
520 }
521
522 $data = array();
523
524 for ($i = 1; $i < 13; $i++) {
525 $month = 'unknown';
526 if ($format == 0) {
527 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
528 } elseif ($format == 1) {
529 $month = $i;
530 } elseif ($format == 2) {
531 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
532 }
533 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
534 //$month=dol_substr($month,0,3);
535 $data[$i - 1] = array($month, $res[$i]);
536 }
537
538 return $data;
539 }
540
541 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
550 protected function _getAmountByMonth($year, $sql, $format = 0)
551 {
552 // phpcs:enable
553 global $langs;
554
555 $result = array();
556 $res = array();
557
558 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
559
560 $resql = $this->db->query($sql);
561 if ($resql) {
562 $num = $this->db->num_rows($resql);
563 $i = 0;
564 while ($i < $num) {
565 $row = $this->db->fetch_row($resql);
566 $j = $row[0] * 1;
567 $result[$j] = $row[1];
568 $i++;
569 }
570 $this->db->free($resql);
571 } else {
572 dol_print_error($this->db);
573 }
574
575 for ($i = 1; $i < 13; $i++) {
576 $res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
577 }
578
579 $data = array();
580
581 for ($i = 1; $i < 13; $i++) {
582 $month = 'unknown';
583 if ($format == 0) {
584 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
585 } elseif ($format == 1) {
586 $month = $i;
587 } elseif ($format == 2) {
588 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
589 }
590 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
591 //$month=dol_substr($month,0,3);
592 $data[$i - 1] = array($month, $res[$i]);
593 }
594
595 return $data;
596 }
597
598 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
607 protected function _getAverageByMonth($year, $sql, $format = 0)
608 {
609 // phpcs:enable
610 global $langs;
611
612 $result = array();
613 $res = array();
614
615 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
616 $resql = $this->db->query($sql);
617 if ($resql) {
618 $num = $this->db->num_rows($resql);
619 $i = 0;
620 $j = 0;
621 while ($i < $num) {
622 $row = $this->db->fetch_row($resql);
623 $j = $row[0] * 1;
624 $result[$j] = $row[1];
625 $i++;
626 }
627 $this->db->free($resql);
628 } else {
629 dol_print_error($this->db);
630 }
631
632 for ($i = 1; $i < 13; $i++) {
633 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
634 }
635
636 $data = array();
637
638 for ($i = 1; $i < 13; $i++) {
639 $month = 'unknown';
640 if ($format == 0) {
641 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
642 } elseif ($format == 1) {
643 $month = $i;
644 } elseif ($format == 2) {
645 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
646 }
647 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
648 //$month=dol_substr($month,0,3);
649 $data[$i - 1] = array($month, $res[$i]);
650 }
651
652 return $data;
653 }
654
655
656 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
664 protected function _getAllByProduct($sql, $limit = 10)
665 {
666 // phpcs:enable
667 global $langs;
668
669 $result = array();
670
671 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
672 $resql = $this->db->query($sql);
673 if ($resql) {
674 $num = $this->db->num_rows($resql);
675 $i = 0;
676 $other = 0;
677 while ($i < $num) {
678 $row = $this->db->fetch_row($resql);
679 if ($i < $limit || $num == $limit) {
680 $result[$i] = array($row[0], $row[1]); // Ref of product, nb
681 } else {
682 $other += $row[1];
683 }
684 $i++;
685 }
686 if ($num > $limit) {
687 $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
688 }
689 $this->db->free($resql);
690 } else {
691 dol_print_error($this->db);
692 }
693
694 return $result;
695 }
696
697 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
703 protected function _getAmountByYear($sql)
704 {
705 $result = array();
706 $resql = $this->db->query($sql);
707 if ($resql) {
708 $num = $this->db->num_rows($resql);
709 $i = 0;
710 while ($i < $num) {
711 $row = $this->db->fetch_row($resql);
712 $result[] = [
713 0 => (int) $row[0],
714 1 => (int) $row[1],
715 ];
716 $i++;
717 }
718 $this->db->free($resql);
719 }
720 return $result;
721 }
722
723
731 public function getAllByProduct($year, $limit = 0)
732 {
733 // Needs to be implemented in child class when used
734 $msg = get_class($this)."::".__FUNCTION__." not implemented";
735 dol_syslog($msg, LOG_ERR);
736 $l = array(1,0); // Dummy result
737 return array($l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l);
738 }
739}
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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)
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php