dolibarr 21.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 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
31abstract class Stats
32{
33 protected $db;
34 protected $lastfetchdate = array(); // Dates of cache file read by methods
35 public $cachefilesuffix = ''; // Suffix to add to name of cache file (to avoid file name conflicts)
36
40 public $from;
41
45 public $where;
49 public $from_line;
53 public $field_date;
57 public $field;
61 public $field_line;
62
66 public $error;
67
71 public $year;
72
76 public $month;
77
83 abstract protected function getNbByMonth($year, $format = 0);
84
95 public function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
96 {
97 global $conf, $user, $langs;
98
99 if ($startyear > $endyear) {
100 return array();
101 }
102
103 $data = array(); // This is the return value
104 $datay = array(); // This is a work value
105
106 // Search into cache
107 if (!empty($cachedelay)) {
108 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
109 }
110
111 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
112 $newmask = '0644';
113
114 $nowgmt = dol_now();
115
116 $foundintocache = 0;
117 if ($cachedelay > 0) {
118 $filedate = dol_filemtime($newpathofdestfile);
119 if ($filedate >= ($nowgmt - $cachedelay)) {
120 $foundintocache = 1;
121
122 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
123 } else {
124 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.");
125 }
126 }
127 // Load file into $data
128 if ($foundintocache) { // Cache file found and is not too old
129 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
130 $data = json_decode(file_get_contents($newpathofdestfile), true);
131 '@phan-var-force array<int<0,11>,array{0:int<1,12>,1:int}> $data';
132 } else {
133 $year = $startyear;
134 $sm = $startmonth - 1;
135 if ($sm != 0) {
136 $year = $year - 1;
137 }
138 while ($year <= $endyear) {
139 $datay[$year] = $this->getNbByMonth($year, $format);
140 $year++;
141 }
142
143 for ($i = 0; $i < 12; $i++) {
144 $data[$i][] = $datay[$endyear][($i + $sm) % 12][0];
145 $year = $startyear;
146 while ($year <= $endyear) {
147 // 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
148 $data[$i][] = $datay[$year - (1 - (int) floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1];
149 $year++;
150 }
151 }
152 }
153
154
155 // Save cache file
156 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
157 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
158 if (!dol_is_dir($conf->user->dir_temp)) {
159 dol_mkdir($conf->user->dir_temp);
160 }
161 $fp = @fopen($newpathofdestfile, 'w');
162 if ($fp) {
163 fwrite($fp, json_encode($data));
164 fclose($fp);
165 } else {
166 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
167 }
168 dolChmod($newpathofdestfile);
169
170 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
171 }
172
173 return $data;
174 }
175
181 abstract protected function getAmountByMonth($year, $format = 0);
182
196 public function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
197 {
198 global $conf, $user, $langs;
199
200 if ($startyear > $endyear) {
201 return array();
202 }
203
204 $datay = array();
205 $data = array(); // Return value
206
207 // Search into cache
208 if (!empty($cachedelay)) {
209 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
210 }
211
212 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
213 $newmask = '0644';
214
215 $nowgmt = dol_now();
216
217 $foundintocache = 0;
218 if ($cachedelay > 0) {
219 $filedate = dol_filemtime($newpathofdestfile);
220 if ($filedate >= ($nowgmt - $cachedelay)) {
221 $foundintocache = 1;
222
223 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
224 } else {
225 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.");
226 }
227 }
228
229 // Load file into $data
230 if ($foundintocache) { // Cache file found and is not too old
231 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
232 $data = json_decode(file_get_contents($newpathofdestfile), true);
233 } else {
234 $year = $startyear;
235 $sm = $startmonth - 1;
236 if ($sm != 0) {
237 $year = $year - 1;
238 }
239 while ($year <= $endyear) {
240 $datay[$year] = $this->getAmountByMonth($year, $format);
241 $year++;
242 }
243
244 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
245 for ($i = 0; $i < 12; $i++) {
246 $data[$i][] = isset($datay[$endyear][($i + $sm) % 12]['label']) ? $datay[$endyear][($i + $sm) % 12]['label'] : $datay[$endyear][($i + $sm) % 12][0]; // set label
247 $year = $startyear;
248 while ($year <= $endyear) {
249 // 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
250 $data[$i][] = $datay[$year - (1 - floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1]; // set yval for x=i
251 $year++;
252 }
253 }
254 }
255
256 // Save cache file
257 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
258 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
259 if (!dol_is_dir($conf->user->dir_temp)) {
260 dol_mkdir($conf->user->dir_temp);
261 }
262 $fp = @fopen($newpathofdestfile, 'w');
263 if ($fp) {
264 fwrite($fp, json_encode($data));
265 fclose($fp);
266 } else {
267 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
268 }
269 dolChmod($newpathofdestfile);
270
271 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
272 }
273
274 return $data;
275 }
276
281 abstract protected function getAverageByMonth($year);
282
290 public function getAverageByMonthWithPrevYear($endyear, $startyear)
291 {
292 if ($startyear > $endyear) {
293 return array();
294 }
295
296 $datay = array();
297 $data = array();
298
299 $year = $startyear;
300 while ($year <= $endyear) {
301 $datay[$year] = $this->getAverageByMonth($year);
302 $year++;
303 }
304
305 for ($i = 0; $i < 12; $i++) {
306 $data[$i][] = $datay[$endyear][$i][0];
307 $year = $startyear;
308 while ($year <= $endyear) {
309 $data[$i][] = $datay[$year][$i][1];
310 $year++;
311 }
312 }
313
314 return $data;
315 }
316
325 public function getAllByProductEntry($year, $cachedelay = 0, $limit = 10)
326 {
327 global $conf, $user, $langs;
328
329 $data = array();
330
331 // Search in cache
332 if (!empty($cachedelay)) {
333 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
334 }
335
336 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
337 $newmask = '0644';
338
339 $nowgmt = dol_now();
340
341 $foundintocache = 0;
342 if ($cachedelay > 0) {
343 $filedate = dol_filemtime($newpathofdestfile);
344 if ($filedate >= ($nowgmt - $cachedelay)) {
345 $foundintocache = 1;
346
347 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
348 } else {
349 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.");
350 }
351 }
352
353 // Load file into $data
354 if ($foundintocache) { // Cache file found and is not too old
355 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
356 $data = json_decode(file_get_contents($newpathofdestfile), true);
357 '@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
358 } else {
359 // This method is defined in parent object only, not into abstract, so we disable phpstan warning
361 $data = $this->getAllByProduct($year, $limit);
362 }
363
364 // Save cache file
365 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
366 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
367 if (!dol_is_dir($conf->user->dir_temp)) {
368 dol_mkdir($conf->user->dir_temp);
369 }
370 $fp = @fopen($newpathofdestfile, 'w');
371 if ($fp) {
372 fwrite($fp, json_encode($data));
373 fclose($fp);
374 } else {
375 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
376 }
377 dolChmod($newpathofdestfile);
378
379 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
380 }
381
382 return $data;
383 }
384
385
386 // Here we have low level of shared code called by XxxStats.class.php
387
388
389 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
396 protected function _getNbByYear($sql)
397 {
398 // phpcs:enable
399 $result = array();
400
401 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
402 $resql = $this->db->query($sql);
403 if ($resql) {
404 $num = $this->db->num_rows($resql);
405 $i = 0;
406 while ($i < $num) {
407 $row = $this->db->fetch_row($resql);
408 $result[$i] = $row;
409 $i++;
410 }
411 $this->db->free($resql);
412 } else {
413 dol_print_error($this->db);
414 }
415 return $result;
416 }
417
418 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
425 protected function _getAllByYear($sql)
426 {
427 // phpcs:enable
428 $result = array();
429
430 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
431 $resql = $this->db->query($sql);
432 if ($resql) {
433 $num = $this->db->num_rows($resql);
434 $i = 0;
435 while ($i < $num) {
436 $row = $this->db->fetch_object($resql);
437 $result[$i]['year'] = $row->year;
438 $result[$i]['nb'] = $row->nb;
439 if ($i > 0 && $row->nb > 0) {
440 $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
441 }
442 // For some $sql only
443 if (property_exists($row, 'total')) {
444 $result[$i]['total'] = $row->total;
445 if ($i > 0 && $row->total > 0) {
446 $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
447 }
448 }
449 // For some $sql only
450 if (property_exists($row, 'total')) {
451 $result[$i]['avg'] = $row->avg;
452 if ($i > 0 && $row->avg > 0) {
453 $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
454 }
455 }
456 // For some $sql only
457 if (property_exists($row, 'weighted')) {
458 $result[$i]['weighted'] = $row->weighted;
459 if ($i > 0 && $row->weighted > 0) {
460 $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
461 }
462 }
463 $i++;
464 }
465 $this->db->free($resql);
466 } else {
467 dol_print_error($this->db);
468 }
469 return $result;
470 }
471
472 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
482 protected function _getNbByMonth($year, $sql, $format = 0)
483 {
484 // phpcs:enable
485 global $langs;
486
487 $result = array();
488 $res = array();
489
490 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
491 $resql = $this->db->query($sql);
492 if ($resql) {
493 $num = $this->db->num_rows($resql);
494 $i = 0;
495 $j = 0;
496 while ($i < $num) {
497 $row = $this->db->fetch_row($resql);
498 $j = $row[0] * 1;
499 $result[$j] = $row[1];
500 $i++;
501 }
502 $this->db->free($resql);
503 } else {
504 dol_print_error($this->db);
505 }
506
507 for ($i = 1; $i < 13; $i++) {
508 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
509 }
510
511 $data = array();
512
513 for ($i = 1; $i < 13; $i++) {
514 $month = 'unknown';
515 if ($format == 0) {
516 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
517 } elseif ($format == 1) {
518 $month = $i;
519 } elseif ($format == 2) {
520 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
521 }
522 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
523 //$month=dol_substr($month,0,3);
524 $data[$i - 1] = array($month, $res[$i]);
525 }
526
527 return $data;
528 }
529
530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
539 protected function _getAmountByMonth($year, $sql, $format = 0)
540 {
541 // phpcs:enable
542 global $langs;
543
544 $result = array();
545 $res = array();
546
547 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
548
549 $resql = $this->db->query($sql);
550 if ($resql) {
551 $num = $this->db->num_rows($resql);
552 $i = 0;
553 while ($i < $num) {
554 $row = $this->db->fetch_row($resql);
555 $j = $row[0] * 1;
556 $result[$j] = $row[1];
557 $i++;
558 }
559 $this->db->free($resql);
560 } else {
561 dol_print_error($this->db);
562 }
563
564 for ($i = 1; $i < 13; $i++) {
565 $res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
566 }
567
568 $data = array();
569
570 for ($i = 1; $i < 13; $i++) {
571 $month = 'unknown';
572 if ($format == 0) {
573 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
574 } elseif ($format == 1) {
575 $month = $i;
576 } elseif ($format == 2) {
577 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
578 }
579 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
580 //$month=dol_substr($month,0,3);
581 $data[$i - 1] = array($month, $res[$i]);
582 }
583
584 return $data;
585 }
586
587 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
596 protected function _getAverageByMonth($year, $sql, $format = 0)
597 {
598 // phpcs:enable
599 global $langs;
600
601 $result = array();
602 $res = array();
603
604 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
605 $resql = $this->db->query($sql);
606 if ($resql) {
607 $num = $this->db->num_rows($resql);
608 $i = 0;
609 $j = 0;
610 while ($i < $num) {
611 $row = $this->db->fetch_row($resql);
612 $j = $row[0] * 1;
613 $result[$j] = $row[1];
614 $i++;
615 }
616 $this->db->free($resql);
617 } else {
618 dol_print_error($this->db);
619 }
620
621 for ($i = 1; $i < 13; $i++) {
622 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
623 }
624
625 $data = array();
626
627 for ($i = 1; $i < 13; $i++) {
628 $month = 'unknown';
629 if ($format == 0) {
630 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
631 } elseif ($format == 1) {
632 $month = $i;
633 } elseif ($format == 2) {
634 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
635 }
636 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
637 //$month=dol_substr($month,0,3);
638 $data[$i - 1] = array($month, $res[$i]);
639 }
640
641 return $data;
642 }
643
644
645 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
653 protected function _getAllByProduct($sql, $limit = 10)
654 {
655 // phpcs:enable
656 global $langs;
657
658 $result = array();
659
660 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
661 $resql = $this->db->query($sql);
662 if ($resql) {
663 $num = $this->db->num_rows($resql);
664 $i = 0;
665 $other = 0;
666 while ($i < $num) {
667 $row = $this->db->fetch_row($resql);
668 if ($i < $limit || $num == $limit) {
669 $result[$i] = array($row[0], $row[1]); // Ref of product, nb
670 } else {
671 $other += $row[1];
672 }
673 $i++;
674 }
675 if ($num > $limit) {
676 $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
677 }
678 $this->db->free($resql);
679 } else {
680 dol_print_error($this->db);
681 }
682
683 return $result;
684 }
685
686 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
692 protected function _getAmountByYear($sql)
693 {
694 $result = array();
695 $resql = $this->db->query($sql);
696 if ($resql) {
697 $num = $this->db->num_rows($resql);
698 $i = 0;
699 while ($i < $num) {
700 $row = $this->db->fetch_row($resql);
701 $result[] = [
702 0 => (int) $row[0],
703 1 => (int) $row[1],
704 ];
705 $i++;
706 }
707 $this->db->free($resql);
708 }
709 return $result;
710 }
711}
Parent class of statistics class.
getNbByMonth($year, $format=0)
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)
Renvoie le nombre de documents par mois pour une annee donnee Return number of documents per month fo...
dol_filemtime($pathoffile)
Return time of a file.
dol_is_dir($folder)
Test if filename is a directory.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
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)