dolibarr 21.0.0-beta
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{
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 = ".$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($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 if ($this->opp_status == 'openedopp') {
238 $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')))";
239 }
240 if ($this->opp_status == 'notopenedopp') {
241 $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'))";
242 }
243 if ($this->opp_status == 'none') {
244 $sqlwhere[] = " (t.fk_opp_status IS NULL OR t.fk_opp_status = -1)";
245 }
246 }
247
248 if (!$user->hasRight('projet', 'all', 'lire')) {
249 $sqlwhere[] = " t.rowid IN (".$this->db->sanitize($projectsListId).")"; // public and assigned to, or restricted to company for external users
250 }
251
252 if (count($sqlwhere) > 0) {
253 $sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere);
254 }
255
256 return $sqlwhere_str;
257 }
258
266 public function getNbByMonth($year, $format = 0)
267 {
268 $this->year = $year;
269
270 $sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(*) as nb";
271 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
272 // No check is done on company permission because readability is managed by public status of project and assignment.
273 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
274 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
275 $sql .= $this->buildWhere();
276 $sql .= " GROUP BY dm";
277 $sql .= $this->db->order('dm', 'DESC');
278
279 $res = $this->_getNbByMonth($year, $sql, $format);
280 // var_dump($res);print '<br>';
281 return $res;
282 }
283
291 public function getAmountByMonth($year, $format = 0)
292 {
293 $this->year = $year;
294
295 $sql = "SELECT date_format(t.datec,'%m') as dm, SUM(t.opp_amount)";
296 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
297 // No check is done on company permission because readability is managed by public status of project and assignment.
298 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
299 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
300 $sql .= $this->buildWhere();
301 $sql .= " GROUP BY dm";
302 $sql .= $this->db->order('dm', 'DESC');
303
304 $res = $this->_getAmountByMonth($year, $sql, $format);
305 // var_dump($res);print '<br>';
306 return $res;
307 }
308
309
319 public function getWeightedAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $wonlostfilter = 1)
320 {
321 global $conf, $user, $langs;
322
323 if ($startyear > $endyear) {
324 return -1;
325 }
326
327 $datay = array();
328
329 // Search into cache
330 if (!empty($cachedelay)) {
331 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
332 }
333
334 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
335 $newmask = '0644';
336
337 $nowgmt = dol_now();
338
339 $foundintocache = 0;
340 $filedate = 0;
341 if ($cachedelay > 0) {
342 $filedate = dol_filemtime($newpathofdestfile);
343 if ($filedate >= ($nowgmt - $cachedelay)) {
344 $foundintocache = 1;
345
346 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
347 } else {
348 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.");
349 }
350 }
351
352 // Load file into $data
353 if ($foundintocache) { // Cache file found and is not too old
354 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
355 $data = json_decode(file_get_contents($newpathofdestfile), true);
356 '@phan-var-force array $data'; // Phan can not interpret json_decode
357 } else {
358 $year = $startyear;
359 while ($year <= $endyear) {
360 $datay[$year] = $this->getWeightedAmountByMonth($year, $wonlostfilter);
361 $year++;
362 }
363
364 $data = array();
365 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
366 for ($i = 0; $i < 12; $i++) {
367 $data[$i][] = $datay[$endyear][$i][0]; // set label
368 $year = $startyear;
369 while ($year <= $endyear) {
370 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
371 $year++;
372 }
373 }
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 dolChmod($newpathofdestfile);
387 } else {
388 dol_syslog("Failed to write cache file", LOG_ERR);
389 }
390 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
391 }
392
393 return $data;
394 }
395
396
404 public function getWeightedAmountByMonth($year, $wonlostfilter = 1)
405 {
406 $this->year = $year;
407
408 $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)";
409 $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';
410 // No check is done on company permission because readability is managed by public status of project and assignment.
411 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
412 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
413 $sql .= $this->buildWhere();
414 $sql .= " GROUP BY dm";
415 $sql .= $this->db->order('dm', 'DESC');
416
417 $res = $this->_getAmountByMonth($year, $sql);
418 // var_dump($res);print '<br>';
419 return $res;
420 }
421
430 public function getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0)
431 {
432 global $conf, $user, $langs;
433
434 if ($startyear > $endyear) {
435 return -1;
436 }
437
438 $datay = array();
439
440 // Search into cache
441 if (!empty($cachedelay)) {
442 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
443 }
444
445 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
446 $newmask = '0644';
447
448 $nowgmt = dol_now();
449
450 $foundintocache = 0;
451 $filedate = 0;
452 if ($cachedelay > 0) {
453 $filedate = dol_filemtime($newpathofdestfile);
454 if ($filedate >= ($nowgmt - $cachedelay)) {
455 $foundintocache = 1;
456
457 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
458 } else {
459 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.");
460 }
461 }
462
463 // Load file into $data
464 if ($foundintocache) { // Cache file found and is not too old
465 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
466 $data = json_decode(file_get_contents($newpathofdestfile), true);
467 '@phan-var-force array $data'; // Phan can not interpret json_decode
468 } else {
469 $year = $startyear;
470 while ($year <= $endyear) {
471 $datay[$year] = $this->getTransformRateByMonth($year);
472 $year++;
473 }
474
475 $data = array();
476 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
477 for ($i = 0; $i < 12; $i++) {
478 $data[$i][] = $datay[$endyear][$i][0]; // set label
479 $year = $startyear;
480 while ($year <= $endyear) {
481 $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
482 $year++;
483 }
484 }
485 }
486
487 // Save cache file
488 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
489 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
490 if (!dol_is_dir($conf->user->dir_temp)) {
491 dol_mkdir($conf->user->dir_temp);
492 }
493 $fp = fopen($newpathofdestfile, 'w');
494 if ($fp) {
495 fwrite($fp, json_encode($data));
496 fclose($fp);
497 dolChmod($newpathofdestfile);
498 }
499
500 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
501 }
502
503 return $data;
504 }
505
513 public function getTransformRateByMonth($year, $format = 0)
514 {
515 $this->year = $year;
516
517 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
518 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
519 // No check is done on company permission because readability is managed by public status of project and assignment.
520 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
521 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
522 $sql .= $this->buildWhere();
523 $sql .= " GROUP BY dm";
524 $sql .= $this->db->order('dm', 'DESC');
525
526 $res_total = $this->_getNbByMonth($year, $sql, $format);
527
528 $this->status = 6;
529
530 $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
531 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
532 // No check is done on company permission because readability is managed by public status of project and assignment.
533 //if (! $user->rights->societe->client->voir && ! $user->soc_id)
534 // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user = ".((int) $user->id);
535 $sql .= $this->buildWhere();
536 $sql .= " GROUP BY dm";
537 $sql .= $this->db->order('dm', 'DESC');
538
539 $this->status = 0;
540
541 $res_only_wined = $this->_getNbByMonth($year, $sql, $format);
542
543 $res = array();
544
545 foreach ($res_total as $key => $total_row) {
546 //var_dump($total_row);
547 if (!empty($total_row[1])) {
548 $res[$key] = array($total_row[0], (100 * $res_only_wined[$key][1]) / $total_row[1]);
549 } else {
550 $res[$key] = array($total_row[0], 0);
551 }
552 }
553 // var_dump($res);print '<br>';
554 return $res;
555 }
556
562 protected function getAverageByMonth($year)
563 {
564 $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->field.")";
565 $sql .= " FROM ".$this->from;
566 $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
567 $sql .= " AND ".$this->where;
568 $sql .= " GROUP BY dm";
569 $sql .= $this->db->order('dm', 'DESC');
570
571 return $this->_getAverageByMonth($year, $sql);
572 }
573}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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...
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:171
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:600
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:619
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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79