projectstats.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 <http://www.gnu.org/licenses/>.
  17. */
  18. include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php';
  19. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  20. /**
  21. * Class to manage statistics on projects
  22. */
  23. class ProjectStats extends Stats
  24. {
  25. private $project;
  26. public $userid;
  27. public $socid;
  28. public $year;
  29. /**
  30. * Constructor
  31. *
  32. * @param DoliDB $db Database handler
  33. */
  34. function __construct($db)
  35. {
  36. global $conf, $user;
  37. $this->db = $db;
  38. require_once 'project.class.php';
  39. $this->project = new Project($this->db);
  40. }
  41. /**
  42. * Return all leads grouped by opportunity status.
  43. * Warning: There is no filter on WON/LOST because we want this for statistics.
  44. *
  45. * @param int $limit Limit results
  46. * @return array|int Array with value or -1 if error
  47. * @throws Exception
  48. */
  49. function getAllProjectByStatus($limit = 5)
  50. {
  51. global $conf, $user, $langs;
  52. $datay = array ();
  53. $sql = "SELECT";
  54. $sql .= " SUM(t.opp_amount), t.fk_opp_status, cls.code, cls.label";
  55. $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
  56. // No check is done on company permission because readability is managed by public status of project and assignement.
  57. //if (! $user->rights->societe->client->voir && ! $user->socid)
  58. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  59. $sql .= ", ".MAIN_DB_PREFIX."c_lead_status as cls";
  60. $sql .= $this->buildWhere();
  61. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  62. //if ($socid > 0) $sql.= " AND t.fk_soc = ".$socid;
  63. // No check is done on company permission because readability is managed by public status of project and assignement.
  64. //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
  65. $sql .= " AND t.fk_opp_status = cls.rowid";
  66. $sql .= " AND t.fk_statut <> 0"; // We want historic also, so all projects not draft
  67. $sql .= " GROUP BY t.fk_opp_status, cls.code, cls.label";
  68. $result = array ();
  69. $res = array ();
  70. dol_syslog(get_class($this) . '::' . __METHOD__ . "", LOG_DEBUG);
  71. $resql = $this->db->query($sql);
  72. if ($resql) {
  73. $num = $this->db->num_rows($resql);
  74. $i = 0;
  75. $other = 0;
  76. while ( $i < $num ) {
  77. $row = $this->db->fetch_row($resql);
  78. if ($i < $limit || $num == $limit)
  79. {
  80. $label = (($langs->trans("OppStatus".$row[2]) != "OppStatus".$row[2]) ? $langs->trans("OppStatus".$row[2]) : $row[2]);
  81. $result[$i] = array(
  82. $label. ' (' . price(price2num($row[0], 'MT'), 1, $langs, 1, -1, -1, $conf->currency) . ')',
  83. $row[0]
  84. );
  85. }
  86. else
  87. $other += $row[1];
  88. $i++;
  89. }
  90. if ($num > $limit)
  91. $result[$i] = array (
  92. $langs->transnoentitiesnoconv("Other"),
  93. $other
  94. );
  95. $this->db->free($resql);
  96. } else {
  97. $this->error = "Error " . $this->db->lasterror();
  98. dol_syslog(get_class($this) . '::' . __METHOD__ . ' ' . $this->error, LOG_ERR);
  99. return -1;
  100. }
  101. return $result;
  102. }
  103. /**
  104. * Return count, and sum of products
  105. *
  106. * @return array of values
  107. */
  108. function getAllByYear()
  109. {
  110. global $conf, $user, $langs;
  111. $datay = array ();
  112. $wonlostfilter=0; // No filter on status WON/LOST
  113. $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,";
  114. $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";
  115. $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";
  116. // No check is done on company permission because readability is managed by public status of project and assignement.
  117. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  118. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  119. $sql.= $this->buildWhere();
  120. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  121. //if ($socid > 0) $sql.= " AND t.fk_soc = ".$socid;
  122. // No check is done on company permission because readability is managed by public status of project and assignement.
  123. //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
  124. $sql.= " GROUP BY year";
  125. $sql.= $this->db->order('year', 'DESC');
  126. return $this->_getAllByYear($sql);
  127. }
  128. /**
  129. * Build the where part
  130. *
  131. * @return string
  132. */
  133. public function buildWhere()
  134. {
  135. global $user;
  136. $sqlwhere_str = '';
  137. $sqlwhere = array();
  138. // Get list of project id allowed to user (in a string list separated by coma)
  139. $object = new Project($this->db);
  140. $projectsListId='';
  141. if (! $user->rights->projet->all->lire) $projectsListId = $object->getProjectsAuthorizedForUser($user,0,1,$user->socid);
  142. $sqlwhere[] = ' t.entity IN (' . getEntity('project') . ')';
  143. if (! empty($this->userid))
  144. $sqlwhere[] = ' t.fk_user_resp=' . $this->userid;
  145. // Forced filter on socid is similar to forced filter on project. TODO Use project assignement to allow to not use filter on project
  146. if (! empty($this->socid))
  147. $sqlwhere[] = ' t.fk_soc=' . $this->socid;
  148. if (! empty($this->year) && empty($this->yearmonth))
  149. $sqlwhere[] = " date_format(t.datec,'%Y')='" . $this->db->escape($this->year) . "'";
  150. if (! empty($this->yearmonth))
  151. $sqlwhere[] = " t.datec BETWEEN '" . $this->db->idate(dol_get_first_day($this->yearmonth)) . "' AND '" . $this->db->idate(dol_get_last_day($this->yearmonth)) . "'";
  152. if (! empty($this->status))
  153. $sqlwhere[] = " t.fk_opp_status IN (" . $this->status . ")";
  154. if (! $user->rights->projet->all->lire) $sqlwhere[] = " t.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users
  155. if (count($sqlwhere) > 0) {
  156. $sqlwhere_str = ' WHERE ' . implode(' AND ', $sqlwhere);
  157. }
  158. return $sqlwhere_str;
  159. }
  160. /**
  161. * Return Project number by month for a year
  162. *
  163. * @param int $year Year to scan
  164. * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
  165. * @return array Array of values
  166. */
  167. function getNbByMonth($year, $format=0)
  168. {
  169. global $user;
  170. $this->yearmonth = $year;
  171. $sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(*) as nb";
  172. $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
  173. // No check is done on company permission because readability is managed by public status of project and assignement.
  174. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  175. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  176. $sql .= $this->buildWhere();
  177. $sql .= " GROUP BY dm";
  178. $sql .= $this->db->order('dm', 'DESC');
  179. $this->yearmonth=0;
  180. $res = $this->_getNbByMonth($year, $sql, $format);
  181. // var_dump($res);print '<br>';
  182. return $res;
  183. }
  184. /**
  185. * Return the Project amount by month for a year
  186. *
  187. * @param int $year Year to scan
  188. * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
  189. * @return array Array with amount by month
  190. */
  191. function getAmountByMonth($year, $format=0)
  192. {
  193. global $user;
  194. $this->yearmonth = $year;
  195. $sql = "SELECT date_format(t.datec,'%m') as dm, SUM(t.opp_amount)";
  196. $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
  197. // No check is done on company permission because readability is managed by public status of project and assignement.
  198. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  199. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  200. $sql .= $this->buildWhere();
  201. $sql .= " GROUP BY dm";
  202. $sql .= $this->db->order('dm', 'DESC');
  203. $this->yearmonth=0;
  204. $res = $this->_getAmountByMonth($year, $sql, $format);
  205. // var_dump($res);print '<br>';
  206. return $res;
  207. }
  208. /**
  209. * Return amount of elements by month for several years
  210. *
  211. * @param int $endyear Start year
  212. * @param int $startyear End year
  213. * @param int $cachedelay Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
  214. * @param int $wonlostfilter Add a filter on status won/lost
  215. * @return array Array of values
  216. */
  217. function getWeightedAmountByMonthWithPrevYear($endyear,$startyear,$cachedelay=0,$wonlostfilter=1)
  218. {
  219. global $conf,$user,$langs;
  220. if ($startyear > $endyear) return -1;
  221. $datay=array();
  222. // Search into cache
  223. if (! empty($cachedelay))
  224. {
  225. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  226. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  227. }
  228. $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_user'.$user->id.'.cache';
  229. $newmask='0644';
  230. $nowgmt = dol_now();
  231. $foundintocache=0;
  232. if ($cachedelay > 0)
  233. {
  234. $filedate=dol_filemtime($newpathofdestfile);
  235. if ($filedate >= ($nowgmt - $cachedelay))
  236. {
  237. $foundintocache=1;
  238. $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
  239. }
  240. else
  241. {
  242. 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.");
  243. }
  244. }
  245. // Load file into $data
  246. if ($foundintocache) // Cache file found and is not too old
  247. {
  248. dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
  249. $data = json_decode(file_get_contents($newpathofdestfile), true);
  250. }
  251. else
  252. {
  253. $year=$startyear;
  254. while($year <= $endyear)
  255. {
  256. $datay[$year] = $this->getWeightedAmountByMonth($year,$wonlostfilter);
  257. $year++;
  258. }
  259. $data = array();
  260. // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
  261. for ($i = 0 ; $i < 12 ; $i++)
  262. {
  263. $data[$i][]=$datay[$endyear][$i][0]; // set label
  264. $year=$startyear;
  265. while($year <= $endyear)
  266. {
  267. $data[$i][]=$datay[$year][$i][1]; // set yval for x=i
  268. $year++;
  269. }
  270. }
  271. }
  272. // Save cache file
  273. if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
  274. {
  275. dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
  276. if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
  277. $fp = fopen($newpathofdestfile, 'w');
  278. if ($fp)
  279. {
  280. fwrite($fp, json_encode($data));
  281. fclose($fp);
  282. if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
  283. @chmod($newpathofdestfile, octdec($newmask));
  284. }
  285. else dol_syslog("Failed to write cache file", LOG_ERR);
  286. $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
  287. }
  288. return $data;
  289. }
  290. /**
  291. * Return the Project weighted opp amount by month for a year.
  292. *
  293. * @param int $year Year to scan
  294. * @param int $wonlostfilter Add a filter on status won/lost
  295. * @return array Array with amount by month
  296. */
  297. function getWeightedAmountByMonth($year, $wonlostfilter=1)
  298. {
  299. global $user;
  300. $this->yearmonth = $year;
  301. $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)";
  302. $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';
  303. // No check is done on company permission because readability is managed by public status of project and assignement.
  304. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  305. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  306. $sql .= $this->buildWhere();
  307. $sql .= " GROUP BY dm";
  308. $sql .= $this->db->order('dm', 'DESC');
  309. $this->yearmonth=0;
  310. $res = $this->_getAmountByMonth($year, $sql);
  311. // var_dump($res);print '<br>';
  312. return $res;
  313. }
  314. /**
  315. * Return amount of elements by month for several years
  316. *
  317. * @param int $endyear End year
  318. * @param int $startyear Start year
  319. * @param int $cachedelay accept for cache file (0=No read, no save of cache, -1=No read but save)
  320. * @return array of values
  321. */
  322. function getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0)
  323. {
  324. global $conf, $user, $langs;
  325. if ($startyear > $endyear) return - 1;
  326. $datay = array();
  327. // Search into cache
  328. if (! empty($cachedelay))
  329. {
  330. include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  331. include_once DOL_DOCUMENT_ROOT . '/core/lib/json.lib.php';
  332. }
  333. $newpathofdestfile = $conf->user->dir_temp . '/' . get_class($this) . '_' . __FUNCTION__ . '_' . (empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix . '_') . $langs->defaultlang . '_user' . $user->id . '.cache';
  334. $newmask = '0644';
  335. $nowgmt = dol_now();
  336. $foundintocache = 0;
  337. if ($cachedelay > 0) {
  338. $filedate = dol_filemtime($newpathofdestfile);
  339. if ($filedate >= ($nowgmt - $cachedelay)) {
  340. $foundintocache = 1;
  341. $this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $filedate;
  342. } else {
  343. 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.");
  344. }
  345. }
  346. // Load file into $data
  347. if ($foundintocache) // Cache file found and is not too old
  348. {
  349. dol_syslog(get_class($this) . '::' . __FUNCTION__ . " read data from cache file " . $newpathofdestfile . " " . $filedate . ".");
  350. $data = json_decode(file_get_contents($newpathofdestfile), true);
  351. } else {
  352. $year = $startyear;
  353. while ( $year <= $endyear ) {
  354. $datay[$year] = $this->getTransformRateByMonth($year);
  355. $year ++;
  356. }
  357. $data = array ();
  358. // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
  359. for($i = 0; $i < 12; $i ++) {
  360. $data[$i][] = $datay[$endyear][$i][0]; // set label
  361. $year = $startyear;
  362. while ( $year <= $endyear ) {
  363. $data[$i][] = $datay[$year][$i][1]; // set yval for x=i
  364. $year ++;
  365. }
  366. }
  367. }
  368. // Save cache file
  369. if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
  370. dol_syslog(get_class($this) . '::' . __FUNCTION__ . " save cache file " . $newpathofdestfile . " onto disk.");
  371. if (! dol_is_dir($conf->user->dir_temp))
  372. dol_mkdir($conf->user->dir_temp);
  373. $fp = fopen($newpathofdestfile, 'w');
  374. fwrite($fp, json_encode($data));
  375. fclose($fp);
  376. if (! empty($conf->global->MAIN_UMASK))
  377. $newmask = $conf->global->MAIN_UMASK;
  378. @chmod($newpathofdestfile, octdec($newmask));
  379. $this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $nowgmt;
  380. }
  381. return $data;
  382. }
  383. /**
  384. * Return the Project transformation rate by month for a year
  385. *
  386. * @param int $year Year to scan
  387. * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
  388. * @return array Array with amount by month
  389. */
  390. function getTransformRateByMonth($year, $format=0)
  391. {
  392. global $user;
  393. $this->yearmonth = $year;
  394. $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
  395. $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
  396. // No check is done on company permission because readability is managed by public status of project and assignement.
  397. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  398. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  399. $sql .= $this->buildWhere();
  400. $sql .= " GROUP BY dm";
  401. $sql .= $this->db->order('dm', 'DESC');
  402. $res_total = $this->_getNbByMonth($year, $sql, $format);
  403. $this->status=6;
  404. $sql = "SELECT date_format(t.datec,'%m') as dm, count(t.opp_amount)";
  405. $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
  406. // No check is done on company permission because readability is managed by public status of project and assignement.
  407. //if (! $user->rights->societe->client->voir && ! $user->soc_id)
  408. // $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=" . $user->id;
  409. $sql .= $this->buildWhere();
  410. $sql .= " GROUP BY dm";
  411. $sql .= $this->db->order('dm', 'DESC');
  412. $this->status=0;
  413. $this->yearmonth=0;
  414. $res_only_wined = $this->_getNbByMonth($year, $sql, $format);
  415. $res=array();
  416. foreach($res_total as $key=>$total_row) {
  417. //var_dump($total_row);
  418. if (!empty($total_row[1])) {
  419. $res[$key]=array($total_row[0],(100*$res_only_wined[$key][1])/$total_row[1]);
  420. } else {
  421. $res[$key]=array($total_row[0],0);
  422. }
  423. }
  424. // var_dump($res);print '<br>';
  425. return $res;
  426. }
  427. }