dolibarr 25.0.0-alpha
index.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
7 * Copyright (C) 2020 Maxime DEMAREST <maxime@indelog.fr>
8 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
11 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
33// Load Dolibarr environment
34require '../../main.inc.php';
42require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
43require_once DOL_DOCUMENT_ROOT.'/contrat/class/contratstats.class.php';
44require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
48
51
52$mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer';
53
54$hookmanager->initHooks(array('contratstats', 'globalcard'));
55
56$object_status = GETPOST('object_status', 'intcomma');
57
58
59$typent_id = GETPOSTINT('typent_id');
60$categ_id = GETPOSTINT('categ_id');
61
62$userid = GETPOSTINT('userid');
63$socid = GETPOSTINT('socid');
64// Security check
65if ($user->socid > 0) {
66 $action = '';
67 $socid = $user->socid;
68}
69$result = restrictedArea($user, 'contrat', 0);
70
71$usercanreadcustumerstatistic = $user->hasRight('contrat', 'lire');
72if (getDolGlobalInt('MAIN_NEED_EXPORT_PERMISSION_TO_READ_STATISTICS')) {
73 $usercanreadcustumerstatistic = $user->hasRight('contrat', 'export');
74}
75if (!$usercanreadcustumerstatistic) {
77}
78
79$parameters = array();
80$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
81if ($reshook < 0) {
82 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
83}
84
85$nowyear = (int) dol_print_date(dol_now('gmt'), "%Y", 'gmt');
86$year = GETPOSTINT('year') > 0 ? GETPOSTINT('year') : $nowyear;
87$startyear = $year - (!getDolGlobalInt('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalInt('MAIN_STATS_GRAPHS_SHOW_N_YEARS'))));
88$endyear = $year;
89
90// Load translation files required by the page
91$langs->loadLangs(array('contracts', 'companies', 'other', 'suppliers'));
92
93
94/*
95 * View
96 */
97
98$form = new Form($db);
99$formcompany = new FormCompany($db);
100$formother = new FormOther($db);
101
102$picto = 'contract';
103$title = $langs->trans("Contracts");
104$dir = $conf->contract->dir_temp;
105
106
107llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-contract page-stats');
108
109$page = 0;
110$param = '';
111$sortfield = '';
112$sortorder = '';
113$massactionbutton = '';
114$num = 0;
115$nbtotalofrecords = $langs->trans("Statistics");
116$limit = 0;
117
118$urlnew = DOL_URL_ROOT.'/contrat/card.php?action=create';
119if (!empty($socid)) {
120 $urlnew .= '&socid='.$socid;
121}
122
123$newcardbutton = '';
124$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/contrat/list.php?mode=common', '', 1, array('morecss' => 'reposition'));
125$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', DOL_URL_ROOT.'/contrat/list.php?mode=kanban', '', 1, array('morecss' => 'reposition'));
126$newcardbutton .= dolGetButtonTitle($langs->trans('Statistics'), '', 'fa fa-chart-bar imgforviewmode', DOL_URL_ROOT.'/contrat/stats/index.php', '', 2, array('morecss' => 'reposition'));
127$newcardbutton .= dolGetButtonTitleSeparator();
128$newcardbutton .= dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $urlnew, '', $user->hasRight('contrat', 'creer'));
129
130print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
131
132dol_mkdir($dir);
133
134$stats = new ContratStats($db, $socid, $mode, ($userid > 0 ? $userid : 0), ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0));
135
136if ($object_status != '' && $object_status >= -1) {
137 $stats->where .= ' AND c.statut IN ('.$db->sanitize($object_status).')';
138}
139
140
141
142// Build graphic number of object
143$data = $stats->getNbByMonthWithPrevYear($endyear, $startyear);
144
145//var_dump($data);
146// $data = array(array('Lib',val1,val2,val3),...)
147
148
149$fileurlnb = '';
150if (!$user->hasRight('societe', 'client', 'voir')) {
151 $filenamenb = $dir.'/contractsnbinyear-'.$user->id.'-'.$year.'.png';
152 $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=contractstats&file=contractsnbinyear-'.$user->id.'-'.$year.'.png';
153} else {
154 $filenamenb = $dir.'/contractsnbinyear-'.$year.'.png';
155 $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=contractstats&file=contractsnbinyear-'.$year.'.png';
156}
157
158$px1 = new DolGraph();
159$mesg = $px1->isGraphKo();
160if (!$mesg) {
161 $px1->SetData($data);
162 $i = $startyear;
163 $legend = array();
164 while ($i <= $endyear) {
165 $legend[] = $i;
166 $i++;
167 }
168 $px1->SetLegend($legend);
169 $px1->SetMaxValue($px1->GetCeilMaxValue());
170 $px1->SetMinValue(min(0, $px1->GetFloorMinValue()));
171 $px1->SetWidth($WIDTH);
172 $px1->SetHeight($HEIGHT);
173 $px1->SetYLabel($langs->trans("NbOfContracts"));
174 $px1->SetShading(3);
175 $px1->SetHorizTickIncrement(1);
176 $px1->mode = 'depth';
177 $px1->SetTitle($langs->trans("NumberOfContractsByMonth"));
178
179 $px1->draw($filenamenb, $fileurlnb);
180}
181
182// Build graphic amount of object
183$data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear);
184//var_dump($data);
185// $data = array(array('Lib',val1,val2,val3),...)
186
187$fileurlamount = '';
188if (!$user->hasRight('societe', 'client', 'voir')) {
189 $filenameamount = $dir.'/contractsamountinyear-'.$user->id.'-'.$year.'.png';
190 $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=contractstats&file=contractsamountinyear-'.$user->id.'-'.$year.'.png';
191} else {
192 $filenameamount = $dir.'/contractsamountinyear-'.$year.'.png';
193 $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=contractstats&file=contractsamountinyear-'.$year.'.png';
194}
195
196$px2 = new DolGraph();
197$mesg = $px2->isGraphKo();
198if (!$mesg) {
199 $px2->SetData($data);
200 $i = $startyear;
201 $legend = array();
202 while ($i <= $endyear) {
203 $legend[] = $i;
204 $i++;
205 }
206 $px2->SetLegend($legend);
207 $px2->SetMaxValue($px2->GetCeilMaxValue());
208 $px2->SetMinValue(min(0, $px2->GetFloorMinValue()));
209 $px2->SetWidth($WIDTH);
210 $px2->SetHeight($HEIGHT);
211 $px2->SetYLabel($langs->trans("AmountOfServices"));
212 $px2->SetShading(3);
213 $px2->SetHorizTickIncrement(1);
214 $px2->mode = 'depth';
215 $px2->SetTitle($langs->trans("AmountOfServicesByMonthHT"));
216
217 $px2->draw($filenameamount, $fileurlamount);
218}
219
220
221
222// Show array
223$data = $stats->getAllByYear();
224$arrayyears = array();
225foreach ($data as $val) {
226 if (!empty($val['year'])) {
227 $arrayyears[$val['year']] = $val['year'];
228 }
229}
230if (!count($arrayyears)) {
231 $arrayyears[$nowyear] = $nowyear;
232}
233
234$h = 0;
235$head = array();
236$head[$h][0] = DOL_URL_ROOT.'/contrat/stats/index.php?mode='.$mode;
237$head[$h][1] = $langs->trans("ByMonthYear");
238$head[$h][2] = 'byyear';
239$h++;
240
241$type = 'contract_stats';
242
243
244complete_head_from_modules($conf, $langs, null, $head, $h, $type);
245
246print dol_get_fiche_head($head, 'byyear', '', -1);
247
248
249print '<div class="fichecenter"><div class="fichethirdleft">';
250
251
252// Show filter box
253print '<form name="stats" method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
254print '<input type="hidden" name="token" value="'.newToken().'">';
255print '<input type="hidden" name="mode" value="'.$mode.'">';
256
257print '<table class="noborder centpercent">';
258print '<tr class="liste_titre"><td class="liste_titre" colspan="2">'.$langs->trans("Filter").'</td></tr>';
259// Company
260print '<tr><td class="left">'.$langs->trans("ThirdParty").'</td><td class="left">';
261$filter = '';
262if ($mode == 'customer') {
263 $filter = '(s.client:IN:1,2,3)';
264}
265if ($mode == 'supplier') {
266 $filter = '(s.fournisseur:=:1)';
267}
268print img_picto('', 'company', 'class="pictofixedwidth"');
269print $form->select_company($socid, 'socid', $filter, 1, 0, 0, array(), 0, 'widthcentpercentminusx maxwidth300');
270print '</td></tr>';
271// ThirdParty Type
272print '<tr><td>'.$langs->trans("ThirdPartyType").'</td><td>';
273$sortparam_typent = (!getDolGlobalString('SOCIETE_SORT_ON_TYPEENT') ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label.
274print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1);
275if ($user->admin) {
276 print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
277}
278print '</td></tr>';
279// Category
280$cat_type = 0;
281$cat_label = '';
282if ($mode == 'customer') {
283 $cat_type = Categorie::TYPE_CUSTOMER;
284 $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer"));
285}
286if ($mode == 'supplier') {
287 $cat_type = Categorie::TYPE_SUPPLIER;
288 $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Supplier"));
289}
290print '<tr><td>'.$cat_label.'</td><td>';
291print img_picto('', 'category', 'class="pictofixedwidth"');
292print $formother->select_categories($cat_type, $categ_id, 'categ_id', 0, 1, 'widthcentpercentminusx maxwidth300');
293print '</td></tr>';
294// User
295print '<tr><td>'.$langs->trans("CreatedBy").'</td><td>';
296print img_picto('', 'user', 'class="pictofixedwidth"');
297print $form->select_dolusers($userid, 'userid', 1, null, 0, '', '', '0', 0, 0, '', 0, '', 'widthcentpercentminusx maxwidth300');
298// Status
299print '<tr><td>'.$langs->trans("Status").'</td><td>';
300
301$liststatus = array(
302 Contrat::STATUS_DRAFT => $langs->trans("ContractStatusDraft"),
303 Contrat::STATUS_VALIDATED => $langs->trans("ContractStatusValidated"),
304 Contrat::STATUS_CLOSED => $langs->trans("ContractStatusClosed"),
305);
306print $form->selectarray('object_status', $liststatus, GETPOST('object_status', 'intcomma'), -4);
307
308
309print '</td></tr>';
310// Year
311print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">';
312if (!in_array($year, $arrayyears)) {
313 $arrayyears[$year] = $year;
314}
315if (!in_array($nowyear, $arrayyears)) {
316 $arrayyears[$nowyear] = $nowyear;
317}
318arsort($arrayyears);
319print img_picto('', 'calendar', 'class="pictofixedwidth"');
320print $form->selectarray('year', $arrayyears, $year, 0, 0, 0, '', 0, 0, 0, '', 'width75');
321print '</td></tr>';
322print '<tr><td align="center" colspan="2"><input type="submit" class="button small" name="submit" value="'.$langs->trans("Refresh").'"></td></tr>';
323print '</table>';
324print '</form>';
325print '<br><br>';
326
327
328print '<div class="div-table-responsive-no-min">';
329print '<table class="noborder centpercent">';
330print '<tr class="liste_titre" height="24">';
331print '<td class="center">'.$langs->trans("Year").'</td>';
332print '<td class="right">'.$langs->trans("NbOfContracts").'</td>';
333print '<td class="right">%</td>';
334print '<td class="right">'.$langs->trans("AmountTotal").'</td>';
335print '<td class="right">%</td>';
336print '<td class="right">'.$langs->trans("AmountAverage").'</td>';
337print '<td class="right">%</td>';
338print '</tr>';
339
340$oldyear = 0;
341foreach ($data as $val) {
342 $year = $val['year'];
343 while (!empty($year) && $oldyear > (int) $year + 1) { // If we have empty year
344 $oldyear--;
345
346 print '<tr class="oddeven" height="24">';
347 print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.'&mode='.$mode.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$oldyear.'</a></td>';
348 // Empty year just after a year with records: delta is -100%
349 $isyearbeforeval = ($oldyear == (int) $year + 1);
350 print '<td class="right">0</td>';
351 print '<td class="right opacitylow" style="color: red;">'.(($isyearbeforeval && $val['nb'] > 0) ? '-100%' : '').'</td>';
352 print '<td class="right">0</td>';
353 print '<td class="right opacitylow" style="color: red;">'.(($isyearbeforeval && $val['total'] > 0) ? '-100%' : '').'</td>';
354 print '<td class="right">0</td>';
355 print '<td class="right opacitylow" style="color: red;">'.(($isyearbeforeval && $val['avg'] > 0) ? '-100%' : '').'</td>';
356 print '</tr>';
357 }
358
359
360 print '<tr class="oddeven" height="24">';
361 print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&mode='.$mode.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$year.'</a></td>';
362 print '<td class="right">'.$val['nb'].'</td>';
363 print '<td class="right opacitylow" style="'.((!isset($val['nb_diff']) || $val['nb_diff'] >= 0) ? 'color: green;' : 'color: red;').'">'.(isset($val['nb_diff']) ? ($val['nb_diff'] < 0 ? '' : '+').round($val['nb_diff']).'%' : '').'</td>';
364 print '<td class="right">'.price(price2num($val['total'], 'MT'), 1).'</td>';
365 print '<td class="right opacitylow" style="'.((!isset($val['total_diff']) || $val['total_diff'] >= 0) ? 'color: green;' : 'color: red;').'">'.(isset($val['total_diff']) ? ($val['total_diff'] < 0 ? '' : '+').round($val['total_diff']).'%' : '').'</td>';
366 print '<td class="right">'.price(price2num($val['avg'], 'MT'), 1).'</td>';
367 print '<td class="right opacitylow" style="'.((!isset($val['avg_diff']) || $val['avg_diff'] >= 0) ? 'color: green;' : 'color: red;').'">'.(isset($val['avg_diff']) ? ($val['avg_diff'] < 0 ? '' : '+').round($val['avg_diff']).'%' : '').'</td>';
368 print '</tr>';
369 $oldyear = $year;
370}
371
372print '</table>';
373print '</div>';
374
375
376print '</div><div class="fichetwothirdright">';
377
378
379// Show graphs
380print '<table class="border centpercent"><tr class="pair nohover"><td align="center">';
381if ($mesg) {
382 print $mesg;
383} else {
384 print $px1->show();
385 print "<br>\n";
386 print $px2->show();
387}
388print '</td></tr></table>';
389
390
391print '</div></div>';
392print '<div class="clearboth"></div>';
393
394print dol_get_fiche_end();
395
396// End of page
397llxFooter();
398$db->close();
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage contract statistics.
Class to build graphs.
static getDefaultGraphSizeForStats($direction, $defaultsize='')
getDefaultGraphSizeForStats
Class to build HTML component for third parties management Only common components are here.
Class to manage generation of HTML components Only common components must be here.
Class to help generate other html components Only common components are here.
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode='add', $filterorigmodule='')
Complete or removed entries into a head array (used to build tabs).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
dolGetButtonTitleSeparator($moreClass="")
Add space between dolGetButtonTitle.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.