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