dolibarr 20.0.0
projectstats.class.php
1<?php
2/* Lead
3 * Copyright (C) 2014-2015 Florian HENRY <florian.henry@open-concept.pro>
4 * Copyright (C) 2024 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{
28 private $project;
29 public $userid;
30 public $socid;
31 public $status;
32 public $opp_status;
33
34 //SQL stat
35 public $field;
36 public $from;
37 public $where;
38
39
45 public function __construct($db)
46 {
47 global $conf, $user;
48
49 $this->db = $db;
50
51 require_once 'project.class.php';
52 $this->project = new Project($this->db);
53
54 $this->from = MAIN_DB_PREFIX.$this->project->table_element;
55 $this->field = 'opp_amount';
56 $this->where = " entity = ".$conf->entity;
57 if ($this->socid > 0) {
58 $this->where .= " AND fk_soc = ".((int) $this->socid);
59 }
60 if (is_array($this->userid) && count($this->userid) > 0) {
61 $this->where .= ' AND fk_user IN ('.$this->db->sanitize(implode(',', $this->userid)).')';
62 } elseif ($this->userid > 0) {
63 $this->where .= " AND fk_user = ".((int) $this->userid);
64 }
65 }
66
67
76 public function getAllProjectByStatus($limit = 5)
77 {
78 global $conf, $user, $langs;
79
80 $datay = array();
81
82 $sql = "SELECT";
83 $sql .= " SUM(t.opp_amount), t.fk_opp_status, cls.code, cls.label";
84 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
85 // No check is done on company permission because readability is managed by public status of project and assignment.
86 //if (! $user->rights->societe->client->voir && ! $user->socid)
87 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
88 $sql .= ", ".MAIN_DB_PREFIX."c_lead_status as cls";
89 $sql .= $this->buildWhere();
90 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
91 //if ($socid > 0) $sql.= " AND t.fk_soc = ".((int) $socid);
92 // No check is done on company permission because readability is managed by public status of project and assignment.
93 //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))";
94 $sql .= " AND t.fk_opp_status = cls.rowid";
95 $sql .= " AND t.fk_statut <> 0"; // We want historic also, so all projects not draft
96 $sql .= " GROUP BY t.fk_opp_status, cls.code, cls.label";
97
98 $result = array();
99
100 dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
101 $resql = $this->db->query($sql);
102 if ($resql) {
103 $num = $this->db->num_rows($resql);
104 $i = 0;
105 $other = 0;
106 while ($i < $num) {
107 $row = $this->db->fetch_row($resql);
108 if ($i < $limit || $num == $limit) {
109 $label = (($langs->trans("OppStatus".$row[2]) != "OppStatus".$row[2]) ? $langs->trans("OppStatus".$row[2]) : $row[2]);
110 $result[$i] = array(
111 $label.' ('.price(price2num($row[0], 'MT'), 1, $langs, 1, -1, -1, $conf->currency).')',
112 $row[0]
113 );
114 } else {
115 $other += $row[1];
116 }
117 $i++;
118 }
119 if ($num > $limit) {
120 $result[$i] = array(
121 $langs->transnoentitiesnoconv("Other"),
122 $other
123 );
124 }
125 $this->db->free($resql);
126 } else {
127 $this->error = "Error ".$this->db->lasterror();
128 dol_syslog(get_class($this).'::'.__METHOD__.' '.$this->error, LOG_ERR);
129 return -1;
130 }
131
132 return $result;
133 }
134
140 public function getAllByYear()
141 {
142 global $conf, $user, $langs;
143
144 $datay = array();
145
146 $wonlostfilter = 0; // No filter on status WON/LOST
147
148 $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,";
149 $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";
150 $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";
151 // No check is done on company permission because readability is managed by public status of project and assignment.
152 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
153 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
154 $sql .= $this->buildWhere();
155 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
156 //if ($socid > 0) $sql.= " AND t.fk_soc = ".((int) $socid);
157 // No check is done on company permission because readability is managed by public status of project and assignment.
158 //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))";
159 $sql .= " GROUP BY year";
160 $sql .= $this->db->order('year', 'DESC');
161
162 return $this->_getAllByYear($sql);
163 }
164
165
171 public function buildWhere()
172 {
173 global $user;
174
175 $sqlwhere_str = '';
176 $sqlwhere = array();
177
178 // Get list of project id allowed to user (in a string list separated by coma)
179 $object = new Project($this->db);
180 $projectsListId = '';
181 if (!$user->hasRight('projet', 'all', 'lire')) {
182 $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid);
183 }
184
185 $sqlwhere[] = ' t.entity IN ('.getEntity('project').')';
186
187 if (!empty($this->userid)) {
188 $sqlwhere[] = ' t.fk_user_resp = '.((int) $this->userid);
189 }
190
191 // Forced filter on socid is similar to forced filter on project. TODO Use project assignment to allow to not use filter on project
192 if (!empty($this->socid)) {
193 $sqlwhere[] = ' t.fk_soc = '.((int) $this->socid);
194 }
195 if (!empty($this->year) && empty($this->month)) {
196 $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))."'";
197 }
198 if (!empty($this->year) && !empty($this->month)) {
199 $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))."'";
200 }
201
202 if (!empty($this->status)) {
203 $sqlwhere[] = " t.fk_statut IN (".$this->db->sanitize($this->status).")";
204 }
205
206 if (!empty($this->opp_status)) {
207 if (is_numeric($this->opp_status) && $this->opp_status > 0) {
208 $sqlwhere[] = " t.fk_opp_status = ".((int) $this->opp_status);
209 }
210 if ($this->opp_status == 'all') {
211 $sqlwhere[] = " (t.fk_opp_status IS NOT NULL AND t.fk_opp_status <> -1)";
212 }
213 if ($this->opp_status == 'openedopp') {
214 $sqlwhere[] = " (t.fk_opp_status IS NOT NULL AND t.fk_opp_status <> -1 AND t.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST')))";
215 }
216 if ($this->opp_status == 'notopenedopp') {
217 $sqlwhere[] = " (t.fk_opp_status IS NULL OR t.fk_opp_status = -1 OR t.fk_opp_status IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code = 'WON'))";
218 }
219 if ($this->opp_status == 'none') {
220 $sqlwhere[] = " (t.fk_opp_status IS NULL OR t.fk_opp_status = -1)";
221 }
222 }
223
224 if (!$user->hasRight('projet', 'all', 'lire')) {
225 $sqlwhere[] = " t.rowid IN (".$this->db->sanitize($projectsListId).")"; // public and assigned to, or restricted to company for external users
226 }
227
228 if (count($sqlwhere) > 0) {
229 $sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere);
230 }
231
232 return $sqlwhere_str;
233 }
234
242 public function getNbByMonth($year, $format = 0)
243 {
244 $this->year = $year;
245
246 $sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(*) as nb";
247 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
248 // No check is done on company permission because readability is managed by public status of project and assignment.
249 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
250 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
251 $sql .= $this->buildWhere();
252 $sql .= " GROUP BY dm";
253 $sql .= $this->db->order('dm', 'DESC');
254
255 $res = $this->_getNbByMonth($year, $sql, $format);
256 // var_dump($res);print '<br>';
257 return $res;
258 }
259
267 public function getAmountByMonth($year, $format = 0)
268 {
269 $this->year = $year;
270
271 $sql = "SELECT date_format(t.datec,'%m') as dm, SUM(t.opp_amount)";
272 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
273 // No check is done on company permission because readability is managed by public status of project and assignment.
274 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
275 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
276 $sql .= $this->buildWhere();
277 $sql .= " GROUP BY dm";
278 $sql .= $this->db->order('dm', 'DESC');
279
280 $res = $this->_getAmountByMonth($year, $sql, $format);
281 // var_dump($res);print '<br>';
282 return $res;
283 }
284
285
295 public function getWeightedAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $wonlostfilter = 1)
296 {
297 global $conf, $user, $langs;
298
299 if ($startyear > $endyear) {
300 return -1;
301 }
302
303 $datay = array();
304
305 // Search into cache
306 if (!empty($cachedelay)) {
307 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
308 include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
309 }
310
311 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
312 $newmask = '0644';
313
314 $nowgmt = dol_now();
315
316 $foundintocache = 0;
317 if ($cachedelay > 0) {
318 $filedate = dol_filemtime($newpathofdestfile);
319 if ($filedate >= ($nowgmt - $cachedelay)) {
320 $foundintocache = 1;
321
322 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
323 } else {
324 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.");
325 }
326 }
327
328 // Load file into $data
329 if ($foundintocache) { // Cache file found and is not too old
330 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
331 $data = json_decode(file_get_contents($newpathofdestfile), true);
332 '@phan-var-force array $data'; // Phan can not interpret json_decode
333 } else {
334 $year = $startyear;
335 while ($year <= $endyear) {
336 $datay[$year] = $this->getWeightedAmountByMonth($year, $wonlostfilter);
337 $year++;
338 }
339
340 $data = array();
341 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
342 for ($i = 0; $i < 12; $i++) {
343 $data[$i][] = $datay[$endyear][$i][0]; // set label
344 $year = $startyear;
345 while ($year <= $endyear) {
346 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
347 $year++;
348 }
349 }
350 }
351
352 // Save cache file
353 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
354 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
355 if (!dol_is_dir($conf->user->dir_temp)) {
356 dol_mkdir($conf->user->dir_temp);
357 }
358 $fp = fopen($newpathofdestfile, 'w');
359 if ($fp) {
360 fwrite($fp, json_encode($data));
361 fclose($fp);
362 dolChmod($newpathofdestfile);
363 } else {
364 dol_syslog("Failed to write cache file", LOG_ERR);
365 }
366 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
367 }
368
369 return $data;
370 }
371
372
380 public function getWeightedAmountByMonth($year, $wonlostfilter = 1)
381 {
382 $this->year = $year;
383
384 $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)";
385 $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';
386 // No check is done on company permission because readability is managed by public status of project and assignment.
387 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
388 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
389 $sql .= $this->buildWhere();
390 $sql .= " GROUP BY dm";
391 $sql .= $this->db->order('dm', 'DESC');
392
393 $res = $this->_getAmountByMonth($year, $sql);
394 // var_dump($res);print '<br>';
395 return $res;
396 }
397
406 public function getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0)
407 {
408 global $conf, $user, $langs;
409
410 if ($startyear > $endyear) {
411 return -1;
412 }
413
414 $datay = array();
415
416 // Search into cache
417 if (!empty($cachedelay)) {
418 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
419 include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
420 }
421
422 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
423 $newmask = '0644';
424
425 $nowgmt = dol_now();
426
427 $foundintocache = 0;
428 if ($cachedelay > 0) {
429 $filedate = dol_filemtime($newpathofdestfile);
430 if ($filedate >= ($nowgmt - $cachedelay)) {
431 $foundintocache = 1;
432
433 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
434 } else {
435 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.");
436 }
437 }
438
439 // Load file into $data
440 if ($foundintocache) { // Cache file found and is not too old
441 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
442 $data = json_decode(file_get_contents($newpathofdestfile), true);
443 '@phan-var-force array $data'; // Phan can not interpret json_decode
444 } else {
445 $year = $startyear;
446 while ($year <= $endyear) {
447 $datay[$year] = $this->getTransformRateByMonth($year);
448 $year++;
449 }
450
451 $data = array();
452 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
453 for ($i = 0; $i < 12; $i++) {
454 $data[$i][] = $datay[$endyear][$i][0]; // set label
455 $year = $startyear;
456 while ($year <= $endyear) {
457 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
458 $year++;
459 }
460 }
461 }
462
463 // Save cache file
464 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
465 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
466 if (!dol_is_dir($conf->user->dir_temp)) {
467 dol_mkdir($conf->user->dir_temp);
468 }
469 $fp = fopen($newpathofdestfile, 'w');
470 if ($fp) {
471 fwrite($fp, json_encode($data));
472 fclose($fp);
473 dolChmod($newpathofdestfile);
474 }
475
476 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
477 }
478
479 return $data;
480 }
481
489 public function getTransformRateByMonth($year, $format = 0)
490 {
491 $this->year = $year;
492
493 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
494 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
495 // No check is done on company permission because readability is managed by public status of project and assignment.
496 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
497 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
498 $sql .= $this->buildWhere();
499 $sql .= " GROUP BY dm";
500 $sql .= $this->db->order('dm', 'DESC');
501
502 $res_total = $this->_getNbByMonth($year, $sql, $format);
503
504 $this->status = 6;
505
506 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
507 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
508 // No check is done on company permission because readability is managed by public status of project and assignment.
509 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
510 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
511 $sql .= $this->buildWhere();
512 $sql .= " GROUP BY dm";
513 $sql .= $this->db->order('dm', 'DESC');
514
515 $this->status = 0;
516
517 $res_only_wined = $this->_getNbByMonth($year, $sql, $format);
518
519 $res = array();
520
521 foreach ($res_total as $key => $total_row) {
522 //var_dump($total_row);
523 if (!empty($total_row[1])) {
524 $res[$key] = array($total_row[0], (100 * $res_only_wined[$key][1]) / $total_row[1]);
525 } else {
526 $res[$key] = array($total_row[0], 0);
527 }
528 }
529 // var_dump($res);print '<br>';
530 return $res;
531 }
532
538 protected function getAverageByMonth($year)
539 {
540 $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->field.")";
541 $sql .= " FROM ".$this->from;
542 $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
543 $sql .= " AND ".$this->where;
544 $sql .= " GROUP BY dm";
545 $sql .= $this->db->order('dm', 'DESC');
546
547 return $this->_getAverageByMonth($year, $sql);
548 }
549}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:636
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)
Renvoie le nombre de documents par mois pour une annee donnee Return number of documents per month fo...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:594
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:613
dol_filemtime($pathoffile)
Return time of a file.
dol_is_dir($folder)
Test if filename is a directory.
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_now($mode='auto')
Return date for now.
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)