dolibarr 25.0.0-alpha
projectstats.class.php
1<?php
2/* Lead
3 * Copyright (C) 2014-2015 Florian HENRY <florian.henry@open-concept.pro>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php';
20include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
21
22
26class ProjectStats extends Stats
27{
31 private $project;
35 public $userid;
39 public $socid;
43 public $status;
47 public $opp_status;
48
49 //SQL stat
53 public $field;
57 public $from;
61 public $where;
62
63
69 public function __construct($db)
70 {
71 global $conf, $user;
72
73 $this->db = $db;
74
75 require_once 'project.class.php';
76 $this->project = new Project($this->db);
77
78 $this->from = MAIN_DB_PREFIX.$this->project->table_element;
79 $this->field = 'opp_amount';
80 $this->where = " entity = ".((int) $conf->entity);
81 if ($this->socid > 0) {
82 $this->where .= " AND fk_soc = ".((int) $this->socid);
83 }
84 if (is_array($this->userid) && count($this->userid) > 0) {
85 $this->where .= ' AND fk_user IN ('.$this->db->sanitize(implode(',', $this->userid)).')';
86 } elseif ($this->userid > 0) {
87 $this->where .= " AND fk_user = ".((int) $this->userid);
88 }
89 }
90
91
100 public function getAllProjectByStatus($limit = 5)
101 {
102 global $conf, $user, $langs;
103
104 $datay = array();
105
106 $sql = "SELECT";
107 $sql .= " SUM(t.opp_amount), t.fk_opp_status, cls.code, cls.label";
108 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
109 // No check is done on company permission because readability is managed by public status of project and assignment.
110 //if (! $user->rights->societe->client->voir && ! $user->socid)
111 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
112 $sql .= ", ".MAIN_DB_PREFIX."c_lead_status as cls";
113 $sql .= $this->buildWhere();
114 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
115 //if ($socid > 0) $sql.= " AND t.fk_soc = ".((int) $socid);
116 // No check is done on company permission because readability is managed by public status of project and assignment.
117 //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
118 $sql .= " AND t.fk_opp_status = cls.rowid";
119 $sql .= " AND t.fk_statut <> 0"; // We want historic also, so all projects not draft
120 $sql .= " GROUP BY t.fk_opp_status, cls.code, cls.label";
121
122 $result = array();
123
124 dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
125 $resql = $this->db->query($sql);
126 if ($resql) {
127 $num = $this->db->num_rows($resql);
128 $i = 0;
129 $other = 0;
130 while ($i < $num) {
131 $row = $this->db->fetch_row($resql);
132 if ($i < $limit || $num == $limit) {
133 $label = (($langs->trans("OppStatus".$row[2]) != "OppStatus".$row[2]) ? $langs->trans("OppStatus".$row[2]) : $row[2]);
134 $result[$i] = array(
135 $label.' ('.price(price2num($row[0], 'MT'), 1, $langs, 1, -1, -1, $conf->currency).')',
136 $row[0]
137 );
138 } else {
139 $other += $row[1];
140 }
141 $i++;
142 }
143 if ($num > $limit) {
144 $result[$i] = array(
145 $langs->transnoentitiesnoconv("Other"),
146 $other
147 );
148 }
149 $this->db->free($resql);
150 } else {
151 $this->error = "Error ".$this->db->lasterror();
152 dol_syslog(get_class($this).'::'.__METHOD__.' '.$this->error, LOG_ERR);
153 return -1;
154 }
155
156 return $result;
157 }
158
164 public function getAllByYear()
165 {
166 global $conf, $user, $langs;
167
168 $datay = array();
169
170 $wonlostfilter = 0; // No filter on status WON/LOST
171
172 $sql = "SELECT date_format(t.datec,'%Y') as year, COUNT(t.rowid) as nb, SUM(t.opp_amount) as total, AVG(t.opp_amount) as avg,";
173 $sql .= " SUM(t.opp_amount * ".$this->db->ifsql("t.opp_percent IS NULL".($wonlostfilter ? " OR cls.code IN ('WON','LOST')" : ""), '0', 't.opp_percent')." / 100) as weighted";
174 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls ON cls.rowid = t.fk_opp_status";
175 // No check is done on company permission because readability is managed by public status of project and assignment.
176 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
177 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
178 $sql .= $this->buildWhere();
179 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
180 //if ($socid > 0) $sql.= " AND t.fk_soc = ".((int) $socid);
181 // No check is done on company permission because readability is managed by public status of project and assignment.
182 //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
183 $sql .= " GROUP BY year";
184 $sql .= $this->db->order('year', 'DESC');
185
186 return $this->_getAllByYear($sql);
187 }
188
189
195 public function buildWhere()
196 {
197 global $user;
198
199 $sqlwhere_str = '';
200 $sqlwhere = array();
201
202 // Get list of project id allowed to user (in a string list separated by coma)
203 $object = new Project($this->db);
204 $projectsListId = '';
205 if (!$user->hasRight('projet', 'all', 'lire')) {
206 $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid);
207 }
208
209 $sqlwhere[] = ' t.entity IN ('.getEntity('project').')';
210
211 if (!empty($this->userid)) {
212 $sqlwhere[] = ' t.fk_user_resp = '.((int) $this->userid);
213 }
214
215 // Forced filter on socid is similar to forced filter on project. TODO Use project assignment to allow to not use filter on project
216 if (!empty($this->socid)) {
217 $sqlwhere[] = ' t.fk_soc = '.((int) $this->socid);
218 }
219 if (!empty($this->year) && empty($this->month)) {
220 $sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->year, 1))."' AND '".$this->db->idate(dol_get_last_day($this->year, 12))."'";
221 }
222 if (!empty($this->year) && !empty($this->month)) {
223 $sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->year, $this->month))."' AND '".$this->db->idate(dol_get_last_day($this->year, $this->month))."'";
224 }
225
226 if (!empty($this->status)) {
227 $sqlwhere[] = " t.fk_statut IN (".$this->db->sanitize((string) $this->status).")";
228 }
229
230 if (!empty($this->opp_status)) {
231 if (is_numeric($this->opp_status) && $this->opp_status > 0) {
232 $sqlwhere[] = " t.fk_opp_status = ".((int) $this->opp_status);
233 }
234 if ($this->opp_status == 'all') {
235 $sqlwhere[] = " (t.fk_opp_status IS NOT NULL AND t.fk_opp_status <> -1)";
236 }
237 // Both filters use the same partition helper, so a LOST opportunity is reported by
238 // 'notopenedopp' instead of being missing from both filters.
239 if ($this->opp_status == 'openedopp') {
240 $sqlwhere[] = $object->getViewFilterSQL('openedopp', 't');
241 }
242 if ($this->opp_status == 'notopenedopp') {
243 $sqlwhere[] = $object->getViewFilterSQL('notopenedopp', 't');
244 }
245 if ($this->opp_status == 'none') {
246 $sqlwhere[] = " (t.fk_opp_status IS NULL OR t.fk_opp_status = -1)";
247 }
248 }
249
250 if (!$user->hasRight('projet', 'all', 'lire')) {
251 $sqlwhere[] = " t.rowid IN (".$this->db->sanitize($projectsListId).")"; // public and assigned to, or restricted to company for external users
252 }
253
254 if (count($sqlwhere) > 0) {
255 $sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere);
256 }
257
258 return $sqlwhere_str;
259 }
260
268 public function getNbByMonth($year, $format = 0)
269 {
270 $this->year = $year;
271
272 $sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(*) as nb";
273 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
274 // No check is done on company permission because readability is managed by public status of project and assignment.
275 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
276 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
277 $sql .= $this->buildWhere();
278 $sql .= " GROUP BY dm";
279 $sql .= $this->db->order('dm', 'DESC');
280
281 $res = $this->_getNbByMonth($year, $sql, $format);
282 // var_dump($res);print '<br>';
283 return $res;
284 }
285
293 public function getAmountByMonth($year, $format = 0)
294 {
295 $this->year = $year;
296
297 $sql = "SELECT date_format(t.datec,'%m') as dm, SUM(t.opp_amount)";
298 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
299 // No check is done on company permission because readability is managed by public status of project and assignment.
300 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
301 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
302 $sql .= $this->buildWhere();
303 $sql .= " GROUP BY dm";
304 $sql .= $this->db->order('dm', 'DESC');
305
306 $res = $this->_getAmountByMonth($year, $sql, $format);
307 // var_dump($res);print '<br>';
308 return $res;
309 }
310
311
321 public function getWeightedAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $wonlostfilter = 1)
322 {
323 global $conf, $user, $langs;
324
325 if ($startyear > $endyear) {
326 return -1;
327 }
328
329 $datay = array();
330
331 // Search into 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.'_user'.$user->id.'.cache';
337 $newmask = '0644';
338
339 $nowgmt = dol_now();
340
341 $foundintocache = 0;
342 $filedate = 0;
343 if ($cachedelay > 0) {
344 $filedate = dol_filemtime($newpathofdestfile);
345 if ($filedate >= ($nowgmt - $cachedelay)) {
346 $foundintocache = 1;
347
348 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
349 } else {
350 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.");
351 }
352 }
353
354 // Load file into $data
355 if ($foundintocache) { // Cache file found and is not too old
356 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
357 $data = json_decode(file_get_contents($newpathofdestfile), true);
358 '@phan-var-force array $data'; // Phan can not interpret json_decode
359 } else {
360 $year = $startyear;
361 while ($year <= $endyear) {
362 $datay[$year] = $this->getWeightedAmountByMonth($year, $wonlostfilter);
363 $year++;
364 }
365
366 $data = array();
367 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
368 for ($i = 0; $i < 12; $i++) {
369 $data[$i][] = $datay[$endyear][$i][0]; // set label
370 $year = $startyear;
371 while ($year <= $endyear) {
372 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
373 $year++;
374 }
375 }
376 }
377
378 // Save cache file
379 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
380 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
381 if (!dol_is_dir($conf->user->dir_temp)) {
382 dol_mkdir($conf->user->dir_temp);
383 }
384 $fp = fopen($newpathofdestfile, 'w');
385 if ($fp) {
386 fwrite($fp, json_encode($data));
387 fclose($fp);
388 dolChmod($newpathofdestfile);
389 } else {
390 dol_syslog("Failed to write cache file", LOG_ERR);
391 }
392 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
393 }
394
395 return $data;
396 }
397
398
406 public function getWeightedAmountByMonth($year, $wonlostfilter = 1)
407 {
408 $this->year = $year;
409
410 $sql = "SELECT date_format(t.datec,'%m') as dm, SUM(t.opp_amount * ".$this->db->ifsql("t.opp_percent IS NULL".($wonlostfilter ? " OR cls.code IN ('WON','LOST')" : ""), '0', 't.opp_percent')." / 100)";
411 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t LEFT JOIN ".MAIN_DB_PREFIX.'c_lead_status as cls ON t.fk_opp_status = cls.rowid';
412 // No check is done on company permission because readability is managed by public status of project and assignment.
413 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
414 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
415 $sql .= $this->buildWhere();
416 $sql .= " GROUP BY dm";
417 $sql .= $this->db->order('dm', 'DESC');
418
419 $res = $this->_getAmountByMonth($year, $sql);
420 // var_dump($res);print '<br>';
421 return $res;
422 }
423
432 public function getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0)
433 {
434 global $conf, $user, $langs;
435
436 if ($startyear > $endyear) {
437 return -1;
438 }
439
440 $datay = array();
441
442 // Search into cache
443 if (!empty($cachedelay)) {
444 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
445 }
446
447 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
448 $newmask = '0644';
449
450 $nowgmt = dol_now();
451
452 $foundintocache = 0;
453 $filedate = 0;
454 if ($cachedelay > 0) {
455 $filedate = dol_filemtime($newpathofdestfile);
456 if ($filedate >= ($nowgmt - $cachedelay)) {
457 $foundintocache = 1;
458
459 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
460 } else {
461 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.");
462 }
463 }
464
465 // Load file into $data
466 if ($foundintocache) { // Cache file found and is not too old
467 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
468 $data = json_decode(file_get_contents($newpathofdestfile), true);
469 '@phan-var-force array $data'; // Phan can not interpret json_decode
470 } else {
471 $year = $startyear;
472 while ($year <= $endyear) {
473 $datay[$year] = $this->getTransformRateByMonth($year);
474 $year++;
475 }
476
477 $data = array();
478 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
479 for ($i = 0; $i < 12; $i++) {
480 $data[$i][] = $datay[$endyear][$i][0]; // set label
481 $year = $startyear;
482 while ($year <= $endyear) {
483 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
484 $year++;
485 }
486 }
487 }
488
489 // Save cache file
490 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
491 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
492 if (!dol_is_dir($conf->user->dir_temp)) {
493 dol_mkdir($conf->user->dir_temp);
494 }
495 $fp = fopen($newpathofdestfile, 'w');
496 if ($fp) {
497 fwrite($fp, json_encode($data));
498 fclose($fp);
499 dolChmod($newpathofdestfile);
500 }
501
502 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
503 }
504
505 return $data;
506 }
507
515 public function getTransformRateByMonth($year, $format = 0)
516 {
517 $this->year = $year;
518
519 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
520 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
521 // No check is done on company permission because readability is managed by public status of project and assignment.
522 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
523 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
524 $sql .= $this->buildWhere();
525 $sql .= " GROUP BY dm";
526 $sql .= $this->db->order('dm', 'DESC');
527
528 $res_total = $this->_getNbByMonth($year, $sql, $format);
529
530 $this->status = 6;
531
532 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
533 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
534 // No check is done on company permission because readability is managed by public status of project and assignment.
535 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
536 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
537 $sql .= $this->buildWhere();
538 $sql .= " GROUP BY dm";
539 $sql .= $this->db->order('dm', 'DESC');
540
541 $this->status = 0;
542
543 $res_only_wined = $this->_getNbByMonth($year, $sql, $format);
544
545 $res = array();
546
547 foreach ($res_total as $key => $total_row) {
548 //var_dump($total_row);
549 if (!empty($total_row[1])) {
550 $res[$key] = array($total_row[0], (100 * $res_only_wined[$key][1]) / $total_row[1]);
551 } else {
552 $res[$key] = array($total_row[0], 0);
553 }
554 }
555 // var_dump($res);print '<br>';
556 return $res;
557 }
558
564 protected function getAverageByMonth($year)
565 {
566 $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->db->sanitize($this->field).")";
567 $sql .= " FROM ".$this->db->sanitize($this->from, 0, 1, 1);
568 $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
569 $sql .= " AND ".$this->where;
570 $sql .= " GROUP BY dm";
571 $sql .= $this->db->order('dm', 'DESC');
572
573 return $this->_getAverageByMonth($year, $sql);
574 }
575}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage projects.
Class to manage statistics on projects.
getAmountByMonth($year, $format=0)
Return the Project amount by month for a year.
__construct($db)
Constructor.
buildWhere()
Build the where part.
getAllByYear()
Return count, and sum of products.
getTransformRateByMonth($year, $format=0)
Return the Project transformation rate by month for a year.
getAllProjectByStatus($limit=5)
Return all leads grouped by opportunity status.
getNbByMonth($year, $format=0)
Return Project number by month for a year.
getWeightedAmountByMonth($year, $wonlostfilter=1)
Return the Project weighted opp amount by month for a year.
getAverageByMonth($year)
Return average of entity by month.
getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay=0)
Return amount of elements by month for several years.
getWeightedAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $wonlostfilter=1)
Return amount of elements by month for several years.
Parent class of statistics class.
_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.
_getAllByYear($sql)
Return nb of elements, total amount and avg amount each year.
_getNbByMonth($year, $sql, $format=0)
Return number of documents per month for a given year.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:616
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
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)