customreports.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. <?php
  2. /* Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. * Note: This tool can be included into a list page with :
  18. * define('USE_CUSTOME_REPORT_AS_INCLUDE', 1);
  19. * include DOL_DOCUMENT_ROOT.'/core/customreports.php';
  20. */
  21. /**
  22. * \file htdocs/core/customreports.php
  23. * \ingroup core
  24. * \brief Page to make custom reports
  25. */
  26. if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE'))
  27. {
  28. require '../main.inc.php';
  29. // Get parameters
  30. $action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
  31. $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
  32. $mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : 'graph';
  33. $objecttype = GETPOST('objecttype', 'aZ09');
  34. $tabfamily = GETPOST('tabfamily', 'aZ09');
  35. if (empty($objecttype)) $objecttype = 'thirdparty';
  36. $search_filters = GETPOST('search_filters', 'array');
  37. $search_measures = GETPOST('search_measures', 'array');
  38. //$search_xaxis = GETPOST('search_xaxis', 'array');
  39. if (GETPOST('search_xaxis', 'alpha') && GETPOST('search_xaxis', 'alpha') != '-1') $search_xaxis = array(GETPOST('search_xaxis', 'alpha'));
  40. else $search_xaxis = array();
  41. //$search_groupby = GETPOST('search_groupby', 'array');
  42. if (GETPOST('search_groupby', 'alpha') && GETPOST('search_groupby', 'alpha') != '-1') $search_groupby = array(GETPOST('search_groupby', 'alpha'));
  43. else $search_groupby = array();
  44. $search_yaxis = GETPOST('search_yaxis', 'array');
  45. $search_graph = GETPOST('search_graph', 'none');
  46. // Load variable for pagination
  47. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  48. $sortfield = GETPOST('sortfield', 'alpha');
  49. $sortorder = GETPOST('sortorder', 'alpha');
  50. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  51. if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
  52. $offset = $limit * $page;
  53. $pageprev = $page - 1;
  54. $pagenext = $page + 1;
  55. $diroutputmassaction = $conf->user->dir_temp.'/'.$user->id.'/customreport';
  56. }
  57. require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
  58. require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php";
  59. require_once DOL_DOCUMENT_ROOT."/core/class/dolgraph.class.php";
  60. require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
  61. require_once DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php";
  62. // Load traductions files requiredby by page
  63. $langs->loadLangs(array("companies", "other", "exports", "sendings"));
  64. $extrafields = new ExtraFields($db);
  65. $hookmanager->initHooks(array('customreport')); // Note that conf->hooks_modules contains array
  66. $title = '';
  67. $picto = '';
  68. $head = array();
  69. $object = null;
  70. $ObjectClassName = '';
  71. // Objects available by default
  72. $arrayoftype = array(
  73. 'thirdparty' => array('label' => 'ThirdParties', 'ObjectClassName' => 'Societe', 'enabled' => $conf->societe->enabled, 'ClassPath' => "/societe/class/societe.class.php"),
  74. 'contact' => array('label' => 'Contacts', 'ObjectClassName' => 'Contact', 'enabled' => $conf->societe->enabled, 'ClassPath' => "/contact/class/contact.class.php"),
  75. 'proposal' => array('label' => 'Proposals', 'ObjectClassName' => 'Propal', 'enabled' => $conf->propal->enabled, 'ClassPath' => "/comm/propal/class/propal.class.php"),
  76. 'order' => array('label' => 'Orders', 'ObjectClassName' => 'Commande', 'enabled' => $conf->commande->enabled, 'ClassPath' => "/commande/class/commande.class.php"),
  77. 'invoice' => array('label' => 'Invoices', 'ObjectClassName' => 'Facture', 'enabled' => $conf->facture->enabled, 'ClassPath' => "/compta/facture/class/facture.class.php"),
  78. 'invoice_template'=>array('label' => 'PredefinedInvoices', 'ObjectClassName' => 'FactureRec', 'enabled' => $conf->facture->enabled, 'ClassPath' => "/compta/class/facturerec.class.php", 'langs'=>'bills'),
  79. 'contract' => array('label' => 'Contracts', 'ObjectClassName' => 'Contrat', 'enabled' => $conf->contrat->enabled, 'ClassPath' => "/contrat/class/contrat.class.php", 'langs'=>'contract'),
  80. 'bom' => array('label' => 'BOM', 'ObjectClassName' => 'Bom', 'enabled' => $conf->bom->enabled),
  81. 'mo' => array('label' => 'MO', 'ObjectClassName' => 'Mo', 'enabled' => $conf->mrp->enabled, 'ClassPath' => "/mrp/class/mo.class.php"),
  82. 'ticket' => array('label' => 'Ticket', 'ObjectClassName' => 'Ticket', 'enabled' => $conf->ticket->enabled),
  83. 'member' => array('label' => 'Adherent', 'ObjectClassName' => 'Adherent', 'enabled' => $conf->adherent->enabled, 'ClassPath' => "/adherents/class/adherent.class.php", 'langs'=>'members'),
  84. 'cotisation' => array('label' => 'Subscriptions', 'ObjectClassName' => 'Subscription', 'enabled' => $conf->adherent->enabled, 'ClassPath' => "/adherents/class/subscription.class.php", 'langs'=>'members'),
  85. );
  86. // Complete $arrayoftype by external modules
  87. $parameters = array('objecttype'=>$objecttype, 'tabfamily'=>$tabfamily);
  88. $reshook = $hookmanager->executeHooks('loadDataForCustomReports', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  89. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  90. elseif (is_array($hookmanager->resArray)) {
  91. if (!empty($hookmanager->resArray['title'])) { // Add entries for tabs
  92. $title = $hookmanager->resArray['title'];
  93. }
  94. if (!empty($hookmanager->resArray['picto'])) { // Add entries for tabs
  95. $picto = $hookmanager->resArray['picto'];
  96. }
  97. if (!empty($hookmanager->resArray['head'])) { // Add entries for tabs
  98. $head = array_merge($head, $hookmanager->resArray['head']);
  99. }
  100. if (!empty($hookmanager->resArray['arrayoftype'])) { // Add entries from hook
  101. foreach ($hookmanager->resArray['arrayoftype'] as $key => $val) {
  102. $arrayoftype[$key] = $val;
  103. }
  104. }
  105. }
  106. if ($objecttype) {
  107. try {
  108. if (!empty($arrayoftype[$objecttype]['ClassPath'])) {
  109. dol_include_once($arrayoftype[$objecttype]['ClassPath']);
  110. } else {
  111. dol_include_once("/".$objecttype."/class/".$objecttype.".class.php");
  112. }
  113. $ObjectClassName = $arrayoftype[$objecttype]['ObjectClassName'];
  114. $object = new $ObjectClassName($db);
  115. }
  116. catch (Exception $e) {
  117. print 'Failed to load class for type '.$objecttype;
  118. }
  119. }
  120. // Security check
  121. $socid = 0;
  122. if ($user->socid > 0) // Protection if external user
  123. {
  124. //$socid = $user->socid;
  125. accessforbidden();
  126. }
  127. $result = restrictedArea($user, $object->element, 0, '');
  128. // Fetch optionals attributes and labels
  129. $extrafields->fetch_name_optionals_label($object->table_element);
  130. //$extrafields->fetch_name_optionals_label($object->table_element_line);
  131. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  132. $search_component_params = array('');
  133. $MAXUNIQUEVALFORGROUP = 20;
  134. $MAXMEASURESINBARGRAPH = 20;
  135. $YYYY = substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1);
  136. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  137. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  138. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  139. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  140. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  141. $arrayofmesures = array('t.count'=>'Count');
  142. $arrayofxaxis = array();
  143. $arrayofgroupby = array();
  144. $arrayofyaxis = array();
  145. $arrayofvaluesforgroupby = array();
  146. /*
  147. * Actions
  148. */
  149. /*
  150. * View
  151. */
  152. $form = new Form($db);
  153. $formother = new FormOther($db);
  154. if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE')) {
  155. llxHeader('', $langs->transnoentitiesnoconv('CustomReports'), '');
  156. dol_fiche_head($head, 'customreports', $title, -1, $picto);
  157. }
  158. // Check parameters
  159. if ($action == 'viewgraph') {
  160. if (!count($search_measures)) {
  161. setEventMessages($langs->trans("AtLeastOneMeasureIsRequired"), null, 'warnings');
  162. } elseif ($mode == 'graph' && count($search_xaxis) > 1) {
  163. setEventMessages($langs->trans("OnlyOneFieldForXAxisIsPossible"), null, 'warnings');
  164. $search_xaxis = array(0 => $search_xaxis[0]);
  165. }
  166. if (count($search_groupby) >= 2) {
  167. setEventMessages($langs->trans("ErrorOnlyOneFieldForGroupByIsPossible"), null, 'warnings');
  168. $search_groupby = array(0 => $search_groupby[0]);
  169. }
  170. if (!count($search_xaxis)) {
  171. setEventMessages($langs->trans("AtLeastOneXAxisIsRequired"), null, 'warnings');
  172. } elseif ($mode == 'graph' && $search_graph == 'bars' && count($search_measures) > $MAXMEASURESINBARGRAPH) {
  173. $langs->load("errors");
  174. setEventMessages($langs->trans("GraphInBarsAreLimitedToNMeasures", $MAXMEASURESINBARGRAPH), null, 'warnings');
  175. $search_graph = 'lines';
  176. }
  177. }
  178. // Get all possible values of fields when a 'group by' is set, and save this into $arrayofvaluesforgroupby
  179. // $arrayofvaluesforgroupby will be used to forge lael of each grouped series
  180. if (is_array($search_groupby) && count($search_groupby)) {
  181. foreach ($search_groupby as $gkey => $gval) {
  182. $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
  183. if (preg_match('/\-year$/', $search_groupby[$gkey])) {
  184. $tmpval = preg_replace('/\-year$/', '', $search_groupby[$gkey]);
  185. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y')";
  186. } elseif (preg_match('/\-month$/', $search_groupby[$gkey])) {
  187. $tmpval = preg_replace('/\-month$/', '', $search_groupby[$gkey]);
  188. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m')";
  189. } elseif (preg_match('/\-day$/', $search_groupby[$gkey])) {
  190. $tmpval = preg_replace('/\-day$/', '', $search_groupby[$gkey]);
  191. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d')";
  192. } else {
  193. $fieldtocount = $search_groupby[$gkey];
  194. }
  195. $sql = 'SELECT DISTINCT '.$fieldtocount.' as val';
  196. if (strpos($fieldtocount, 'te.') === 0) {
  197. $sql .= ' FROM '.MAIN_DB_PREFIX.$object->table_element.'_extrafields as te';
  198. } else {
  199. $sql .= ' FROM '.MAIN_DB_PREFIX.$object->table_element.' as t';
  200. }
  201. // TODO Add the where here
  202. $sql .= ' LIMIT '.($MAXUNIQUEVALFORGROUP + 1);
  203. //print $sql;
  204. $resql = $db->query($sql);
  205. if (!$resql) {
  206. dol_print_error($db);
  207. }
  208. while ($obj = $db->fetch_object($resql)) {
  209. if (is_null($obj->val)) {
  210. $keytouse = '__NULL__';
  211. $valuetranslated = $langs->transnoentitiesnoconv("NotDefined");
  212. }
  213. elseif ($obj->val === '') {
  214. $keytouse = '';
  215. $valuetranslated = $langs->transnoentitiesnoconv("Empty");
  216. }
  217. else {
  218. $keytouse = (string) $obj->val;
  219. $valuetranslated = $obj->val;
  220. }
  221. $regs = array();
  222. if (!empty($object->fields[$gvalwithoutprefix]['arrayofkeyval'])) {
  223. $valuetranslated = $object->fields[$gvalwithoutprefix]['arrayofkeyval'][$obj->val];
  224. if (is_null($valuetranslated)) $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
  225. $valuetranslated = $langs->trans($valuetranslated);
  226. }
  227. elseif (preg_match('/integer:([^:]+):([^:]+)$/', $object->fields[$gvalwithoutprefix]['type'], $regs)) {
  228. $classname = $regs[1];
  229. $classpath = $regs[2];
  230. dol_include_once($classpath);
  231. if (class_exists($classname)) {
  232. $tmpobject = new $classname($db);
  233. $tmpobject->fetch($obj->val);
  234. foreach ($tmpobject->fields as $fieldkey => $field) {
  235. if ($field['showoncombobox']) {
  236. $valuetranslated = $tmpobject->$fieldkey;
  237. //if ($valuetranslated == '-') $valuetranslated = $langs->transnoentitiesnoconv("Unknown")
  238. break;
  239. }
  240. }
  241. //$valuetranslated = $tmpobject->ref.'eee';
  242. }
  243. }
  244. $arrayofvaluesforgroupby['g_'.$gkey][$keytouse] = $valuetranslated;
  245. }
  246. asort($arrayofvaluesforgroupby['g_'.$gkey]);
  247. if (count($arrayofvaluesforgroupby['g_'.$gkey]) > $MAXUNIQUEVALFORGROUP) {
  248. $langs->load("errors");
  249. //var_dump($gkey.' '.$gval.' '.$gvalwithoutprefix);
  250. $gvalwithoutprefix = preg_replace('/\-(year|month|day)/', '', $gvalwithoutprefix);
  251. $labeloffield = $langs->transnoentitiesnoconv($object->fields[$gvalwithoutprefix]['label']);
  252. setEventMessages($langs->trans("ErrorTooManyDifferentValueForSelectedGroupBy", $MAXUNIQUEVALFORGROUP, $labeloffield), null, 'warnings');
  253. $search_groupby = array();
  254. }
  255. $db->free($resql);
  256. }
  257. }
  258. //var_dump($arrayofvaluesforgroupby);exit;
  259. $tmparray = dol_getdate(dol_now());
  260. $endyear = $tmparray['year'];
  261. $endmonth = $tmparray['mon'];
  262. $datelastday = dol_get_last_day($endyear, $endmonth, 1);
  263. $startyear = $endyear - 2;
  264. $param = '';
  265. print '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';
  266. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  267. print '<input type="hidden" name="action" value="viewgraph">';
  268. print '<input type="hidden" name="tabfamily" value="'.$tabfamily.'">';
  269. print '<div class="liste_titre liste_titre_bydiv centpercent">';
  270. // Select object
  271. print '<div class="divadvancedsearchfield center floatnone">';
  272. print '<div class="inline-block"><span class="opacitymedium">'.$langs->trans("StatisticsOn").'</span></div> ';
  273. $newarrayoftype = array();
  274. foreach ($arrayoftype as $key => $val) {
  275. if (dol_eval($val['enabled'], 1)) {
  276. $newarrayoftype[$key] = $arrayoftype[$key];
  277. }
  278. if ($val['langs']) {
  279. $langs->load($val['langs']);
  280. }
  281. }
  282. print $form->selectarray('objecttype', $newarrayoftype, $objecttype, 0, 0, 0, '', 1, 0, 0, '', 'minwidth200', 1);
  283. if (empty($conf->use_javascript_ajax)) print '<input type="submit" class="button buttongen" name="changeobjecttype" value="'.$langs->trans("Refresh").'">';
  284. else {
  285. print '<script type="text/javascript" language="javascript">
  286. jQuery(document).ready(function() {
  287. jQuery("#objecttype").change(function() {
  288. console.log("Reload for "+jQuery("#objecttype").val());
  289. location.href = "'.$_SERVER["PHP_SELF"].'?objecttype="+jQuery("#objecttype").val()+"'.($tabfamily ? '&tabfamily='.$tabfamily : '').'";
  290. });
  291. });
  292. </script>';
  293. }
  294. print '</div><div class="clearboth"></div>';
  295. // Add Filter
  296. print '<div class="divadvancedsearchfield quatrevingtpercent">';
  297. print $form->searchComponent(array($object->element => $object->fields), $search_component_params);
  298. print '</div>';
  299. // Add measures into array
  300. print '<div class="divadvancedsearchfield clearboth">';
  301. foreach ($object->fields as $key => $val) {
  302. if (!empty($val['isameasure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1))) {
  303. $arrayofmesures['t.'.$key.'-sum'] = $langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>';
  304. $arrayofmesures['t.'.$key.'-average'] = $langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Average").')</span>';
  305. $arrayofmesures['t.'.$key.'-min'] = $langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>';
  306. $arrayofmesures['t.'.$key.'-max'] = $langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>';
  307. }
  308. }
  309. // Add extrafields to Measures
  310. if ($object->isextrafieldmanaged) {
  311. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  312. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key]) && (!isset($extrafields->attributes[$object->table_element]['enabled'][$key]) || dol_eval($extrafields->attributes[$object->table_element]['enabled'][$key], 1))) {
  313. $arrayofmesures['te.'.$key.'-sum'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>';
  314. $arrayofmesures['te.'.$key.'-average'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Average").')</span>';
  315. $arrayofmesures['te.'.$key.'-min'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>';
  316. $arrayofmesures['te.'.$key.'-max'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>';
  317. }
  318. }
  319. }
  320. print '<div class="inline-block"><span class="fas fa-chart-line paddingright" title="'.$langs->trans("Measures").'"></span>'.$langs->trans("Measures").'</div> ';
  321. print $form->multiselectarray('search_measures', $arrayofmesures, $search_measures, 0, 0, 'minwidth500', 1);
  322. print '</div>';
  323. // Group by
  324. print '<div class="divadvancedsearchfield">';
  325. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-horizontal paddingright" title="'.$langs->trans("GroupBy").'"></span>'.$langs->trans("GroupBy").'</div> ';
  326. print $formother->selectGroupByField($object, $search_groupby, $arrayofgroupby);
  327. print '</div>';
  328. // XAxis
  329. print '<div class="divadvancedsearchfield">';
  330. print '<div class="inline-block"><span class="fas fa-ruler-horizontal paddingright" title="'.$langs->trans("XAxis").'"></span>'.$langs->trans("XAxis").'</div> ';
  331. print $formother->selectXAxisField($object, $search_xaxis, $arrayofxaxis);
  332. print '</div>';
  333. if ($mode == 'grid') {
  334. // YAxis
  335. print '<div class="divadvancedsearchfield">';
  336. foreach ($object->fields as $key => $val) {
  337. if (empty($val['measure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1))) {
  338. if (in_array($key, array('id', 'rowid', 'entity', 'last_main_doc', 'extraparams'))) continue;
  339. if (preg_match('/^fk_/', $key)) continue;
  340. if (in_array($val['type'], array('html', 'text'))) continue;
  341. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  342. $arrayofyaxis['t.'.$key.'-year'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.')', 'position' => $val['position']);
  343. $arrayofyaxis['t.'.$key.'-month'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')', 'position' => $val['position']);
  344. $arrayofyaxis['t.'.$key.'-day'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')', 'position' => $val['position']);
  345. } else {
  346. $arrayofyaxis['t.'.$key] = array('label' => $val['label'], 'position' => (int) $val['position']);
  347. }
  348. }
  349. // Add measure from extrafields
  350. if ($object->isextrafieldmanaged) {
  351. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  352. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key]) && (!isset($extrafields->attributes[$object->table_element]['enabled'][$key]) || dol_eval($extrafields->attributes[$object->table_element]['enabled'][$key], 1))) {
  353. $arrayofyaxis['te.'.$key] = array('label' => $extrafields->attributes[$object->table_element]['label'][$key], 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key]);
  354. }
  355. }
  356. }
  357. }
  358. $arrayofyaxis = dol_sort_array($arrayofyaxis, 'position');
  359. $arrayofyaxislabel = array();
  360. foreach ($arrayofyaxis as $key => $val) {
  361. $arrayofyaxislabel[$key] = $val['label'];
  362. }
  363. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-vertical paddingright" title="'.$langs->trans("YAxis").'"></span>'.$langs->trans("YAxis").'</div> ';
  364. print $form->multiselectarray('search_yaxis', $arrayofyaxislabel, $search_yaxis, 0, 0, 'minwidth100', 1);
  365. print '</div>';
  366. }
  367. if ($mode == 'graph') {
  368. print '<div class="divadvancedsearchfield">';
  369. $arrayofgraphs = array('bars' => 'Bars', 'lines' => 'Lines'); // also 'pies'
  370. print '<div class="inline-block opacitymedium"><span class="fas fa-chart-area paddingright" title="'.$langs->trans("Graph").'"></span>'.$langs->trans("Graph").'</div> ';
  371. print $form->selectarray('search_graph', $arrayofgraphs, $search_graph, 0, 0, 0, 'minwidth100', 1);
  372. print '</div>';
  373. }
  374. print '<div class="divadvancedsearchfield">';
  375. print '<input type="submit" class="button buttongen" value="'.$langs->trans("Refresh").'">';
  376. print '</div>';
  377. print '</div>';
  378. print '</form>';
  379. // Generate the SQL request
  380. $sql = '';
  381. if (!empty($search_measures) && !empty($search_xaxis))
  382. {
  383. $fieldid = 'rowid';
  384. $sql = 'SELECT ';
  385. foreach ($search_xaxis as $key => $val) {
  386. if (preg_match('/\-year$/', $val)) {
  387. $tmpval = preg_replace('/\-year$/', '', $val);
  388. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y') as x_".$key.', ';
  389. } elseif (preg_match('/\-month$/', $val)) {
  390. $tmpval = preg_replace('/\-month$/', '', $val);
  391. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m') as x_".$key.', ';
  392. } elseif (preg_match('/\-day$/', $val)) {
  393. $tmpval = preg_replace('/\-day$/', '', $val);
  394. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d') as x_".$key.', ';
  395. }
  396. else $sql .= $val.' as x_'.$key.', ';
  397. }
  398. foreach ($search_groupby as $key => $val) {
  399. if (preg_match('/\-year$/', $val)) {
  400. $tmpval = preg_replace('/\-year$/', '', $val);
  401. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y') as g_".$key.', ';
  402. } elseif (preg_match('/\-month$/', $val)) {
  403. $tmpval = preg_replace('/\-month$/', '', $val);
  404. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m') as g_".$key.', ';
  405. } elseif (preg_match('/\-day$/', $val)) {
  406. $tmpval = preg_replace('/\-day$/', '', $val);
  407. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d') as g_".$key.', ';
  408. }
  409. else $sql .= $val.' as g_'.$key.', ';
  410. }
  411. foreach ($search_measures as $key => $val) {
  412. if ($val == 't.count') $sql .= 'COUNT(t.'.$fieldid.') as y_'.$key.', ';
  413. elseif (preg_match('/\-sum$/', $val)) {
  414. $tmpval = preg_replace('/\-sum$/', '', $val);
  415. $sql .= 'SUM('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
  416. }
  417. elseif (preg_match('/\-average$/', $val)) {
  418. $tmpval = preg_replace('/\-average$/', '', $val);
  419. $sql .= 'AVG('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
  420. }
  421. elseif (preg_match('/\-min$/', $val)) {
  422. $tmpval = preg_replace('/\-min$/', '', $val);
  423. $sql .= 'MIN('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
  424. }
  425. elseif (preg_match('/\-max$/', $val)) {
  426. $tmpval = preg_replace('/\-max$/', '', $val);
  427. $sql .= 'MAX('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
  428. }
  429. }
  430. $sql = preg_replace('/,\s*$/', '', $sql);
  431. $sql .= ' FROM '.MAIN_DB_PREFIX.$object->table_element.' as t';
  432. // Add measure from extrafields
  433. if ($object->isextrafieldmanaged) {
  434. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.$object->table_element.'_extrafields as te ON te.fk_object = t.'.$fieldid;
  435. }
  436. if ($object->ismultientitymanaged) {
  437. if ($object->ismultientitymanaged == 1) {
  438. // Nothing here
  439. } else {
  440. $tmparray = explode('@', $object->ismultientitymanaged);
  441. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON t.'.$tmparray[0].' = parenttable.rowid';
  442. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  443. }
  444. }
  445. $sql .= ' WHERE 1 = 1';
  446. if ($object->ismultientitymanaged == 1) {
  447. $sql .= ' AND entity IN ('.getEntity($object->element).')';
  448. }
  449. foreach ($search_filters as $key => $val) {
  450. // TODO Add the where here
  451. }
  452. $sql .= ' GROUP BY ';
  453. foreach ($search_xaxis as $key => $val) {
  454. if (preg_match('/\-year$/', $val)) {
  455. $tmpval = preg_replace('/\-year$/', '', $val);
  456. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), ";
  457. } elseif (preg_match('/\-month$/', $val)) {
  458. $tmpval = preg_replace('/\-month$/', '', $val);
  459. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), ";
  460. } elseif (preg_match('/\-day$/', $val)) {
  461. $tmpval = preg_replace('/\-day$/', '', $val);
  462. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), ";
  463. }
  464. else $sql .= $val.', ';
  465. }
  466. foreach ($search_groupby as $key => $val) {
  467. if (preg_match('/\-year$/', $val)) {
  468. $tmpval = preg_replace('/\-year$/', '', $val);
  469. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), ";
  470. } elseif (preg_match('/\-month$/', $val)) {
  471. $tmpval = preg_replace('/\-month$/', '', $val);
  472. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), ";
  473. } elseif (preg_match('/\-day$/', $val)) {
  474. $tmpval = preg_replace('/\-day$/', '', $val);
  475. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), ";
  476. }
  477. else $sql .= $val.', ';
  478. }
  479. $sql = preg_replace('/,\s*$/', '', $sql);
  480. $sql .= ' ORDER BY ';
  481. foreach ($search_xaxis as $key => $val) {
  482. if (preg_match('/\-year$/', $val)) {
  483. $tmpval = preg_replace('/\-year$/', '', $val);
  484. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), ";
  485. } elseif (preg_match('/\-month$/', $val)) {
  486. $tmpval = preg_replace('/\-month$/', '', $val);
  487. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), ";
  488. } elseif (preg_match('/\-day$/', $val)) {
  489. $tmpval = preg_replace('/\-day$/', '', $val);
  490. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), ";
  491. }
  492. else $sql .= $val.', ';
  493. }
  494. foreach ($search_groupby as $key => $val) {
  495. if (preg_match('/\-year$/', $val)) {
  496. $tmpval = preg_replace('/\-year$/', '', $val);
  497. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), ";
  498. } elseif (preg_match('/\-month$/', $val)) {
  499. $tmpval = preg_replace('/\-month$/', '', $val);
  500. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), ";
  501. } elseif (preg_match('/\-day$/', $val)) {
  502. $tmpval = preg_replace('/\-day$/', '', $val);
  503. $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), ";
  504. }
  505. else $sql .= $val.', ';
  506. }
  507. $sql = preg_replace('/,\s*$/', '', $sql);
  508. }
  509. //print $sql;
  510. $legend = array();
  511. foreach ($search_measures as $key => $val) {
  512. $legend[] = $langs->trans($arrayofmesures[$val]);
  513. }
  514. $useagroupby = (is_array($search_groupby) && count($search_groupby));
  515. //var_dump($useagroupby);
  516. //var_dump($arrayofvaluesforgroupby);
  517. // Execute the SQL request
  518. $totalnbofrecord = 0;
  519. $data = array();
  520. if ($sql) {
  521. $resql = $db->query($sql);
  522. if (!$resql) {
  523. dol_print_error($db);
  524. }
  525. $ifetch = 0; $xi = 0; $oldlabeltouse = '';
  526. while ($obj = $db->fetch_object($resql)) {
  527. $ifetch++;
  528. if ($useagroupby) {
  529. $xval = $search_xaxis[0];
  530. $fieldforxkey = 'x_0';
  531. $xlabel = $obj->$fieldforxkey;
  532. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  533. // Define $xlabel
  534. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  535. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  536. }
  537. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->trans("Empty") : $langs->trans("NotDefined")));
  538. if ($oldlabeltouse && ($labeltouse != $oldlabeltouse)) {
  539. $xi++; // Increase $xi
  540. }
  541. //var_dump($labeltouse.' '.$oldlabeltouse.' '.$xi);
  542. $oldlabeltouse = $labeltouse;
  543. /* Example of value for $arrayofvaluesforgroupby
  544. * array (size=1)
  545. * 'g_0' =>
  546. * array (size=6)
  547. * 0 => string '0' (length=1)
  548. * '' => string 'Empty' (length=5)
  549. * '__NULL__' => string 'Not defined' (length=11)
  550. * 'done' => string 'done' (length=4)
  551. * 'processing' => string 'processing' (length=10)
  552. * 'undeployed' => string 'undeployed' (length=10)
  553. */
  554. foreach ($search_measures as $key => $val) {
  555. $gi = 0;
  556. foreach ($search_groupby as $gkey) {
  557. //var_dump('*** Fetch #'.$ifetch.' for labeltouse='.$labeltouse.' measure number '.$key.' and group g_'.$gi);
  558. //var_dump($arrayofvaluesforgroupby);
  559. foreach ($arrayofvaluesforgroupby['g_'.$gi] as $gvaluepossiblekey => $gvaluepossiblelabel) {
  560. $ykeysuffix = $gvaluepossiblelabel;
  561. $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
  562. $fieldfory = 'y_'.$key;
  563. $fieldforg = 'g_'.$gi;
  564. $fieldforybis = 'y_'.$key.'_'.$ykeysuffix;
  565. //var_dump('gvaluepossiblekey='.$gvaluepossiblekey.' gvaluepossiblelabel='.$gvaluepossiblelabel.' ykeysuffix='.$ykeysuffix.' gval='.$gval.' gvalwithoutsuffix='.$gvalwithoutprefix);
  566. //var_dump('fieldforg='.$fieldforg.' obj->$fieldforg='.$obj->$fieldforg.' fieldfory='.$fieldfory.' obj->$fieldfory='.$obj->$fieldfory.' fieldforybis='.$fieldforybis);
  567. if (!is_array($data[$xi])) $data[$xi] = array();
  568. if (!array_key_exists('label', $data[$xi])) {
  569. $data[$xi] = array();
  570. $data[$xi]['label'] = $labeltouse;
  571. }
  572. $objfieldforg = $obj->$fieldforg;
  573. if (is_null($objfieldforg)) $objfieldforg = '__NULL__';
  574. if ($gvaluepossiblekey == '0') { // $gvaluepossiblekey can have type int or string. So we create a special if, used when value is '0'
  575. //var_dump($objfieldforg.' == \'0\' -> '.($objfieldforg == '0'));
  576. if ($objfieldforg == '0') {
  577. // The record we fetch is for this group
  578. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  579. }
  580. // The record we fetch is not for this group
  581. elseif (!isset($data[$xi][$fieldforybis])) {
  582. $data[$xi][$fieldforybis] = '0';
  583. }
  584. } else {
  585. //var_dump((string) $objfieldforg.' === '.(string) $gvaluepossiblekey.' -> '.((string) $objfieldforg === (string) $gvaluepossiblekey));
  586. if ((string) $objfieldforg === (string) $gvaluepossiblekey) {
  587. // The record we fetch is for this group
  588. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  589. }
  590. // The record we fetch is not for this group
  591. elseif (!isset($data[$xi][$fieldforybis])) {
  592. $data[$xi][$fieldforybis] = '0';
  593. }
  594. }
  595. }
  596. //var_dump($data[$xi]);
  597. $gi++;
  598. }
  599. }
  600. } else { // No group by
  601. $xval = $search_xaxis[0];
  602. $fieldforxkey = 'x_0';
  603. $xlabel = $obj->$fieldforxkey;
  604. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  605. // Define $xlabel
  606. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  607. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  608. }
  609. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->trans("Empty") : $langs->trans("NotDefined")));
  610. $xarrayforallseries = array('label' => $labeltouse);
  611. foreach ($search_measures as $key => $val) {
  612. $fieldfory = 'y_'.$key;
  613. $xarrayforallseries[$fieldfory] = $obj->$fieldfory;
  614. }
  615. $data[$xi] = $xarrayforallseries;
  616. $xi++;
  617. }
  618. }
  619. $totalnbofrecord = count($data);
  620. }
  621. //var_dump($data);
  622. print '<div class="customreportsoutput'.($totalnbofrecord ? '' : ' customreportsoutputnotdata').'">';
  623. if ($mode == 'grid') {
  624. // TODO
  625. }
  626. if ($mode == 'graph') {
  627. $WIDTH = '80%';
  628. $HEIGHT = 200;
  629. // Show graph
  630. $px1 = new DolGraph();
  631. $mesg = $px1->isGraphKo();
  632. if (!$mesg)
  633. {
  634. /*var_dump($legend);
  635. var_dump($data);*/
  636. $px1->SetData($data);
  637. unset($data);
  638. $arrayoftypes = array();
  639. foreach ($search_measures as $key => $val) {
  640. $arrayoftypes[] = $search_graph;
  641. }
  642. $px1->SetLegend($legend);
  643. $px1->SetMinValue($px1->GetFloorMinValue());
  644. $px1->SetMaxValue($px1->GetCeilMaxValue());
  645. $px1->SetWidth($WIDTH);
  646. $px1->SetHeight($HEIGHT);
  647. $px1->SetYLabel($langs->trans("Y"));
  648. $px1->SetShading(3);
  649. $px1->SetHorizTickIncrement(1);
  650. $px1->SetCssPrefix("cssboxes");
  651. $px1->SetType($arrayoftypes);
  652. $px1->mode = 'depth';
  653. $px1->SetTitle('');
  654. $dir = $conf->user->dir_temp;
  655. dol_mkdir($dir);
  656. $filenamenb = $dir.'/customreport_'.$object->element.'.png';
  657. $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=user&file=customreport_'.$object->element.'.png';
  658. $px1->draw($filenamenb, $fileurlnb);
  659. $texttoshow = $langs->trans("NoRecordFound");
  660. if (!GETPOSTISSET('search_measures') || !GETPOSTISSET('search_xaxis')) {
  661. $texttoshow = $langs->trans("SelectYourGraphOptionsFirst");
  662. }
  663. print $px1->show($totalnbofrecord ? 0 : $texttoshow);
  664. }
  665. }
  666. if ($sql) {
  667. // Show admin info
  668. print '<br>'.info_admin($langs->trans("SQLUsedForExport").':<br> '.$sql, 0, 0, 1, '', 'TechnicalInformation');
  669. }
  670. print '<div>';
  671. if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE')) {
  672. dol_fiche_end();
  673. }
  674. // End of page
  675. llxFooter();
  676. $db->close();