customreports.php 33 KB

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