1<?php
2/* Copyright (C) 2005      Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@inodbox.com>
5 * Copyright (C) 2013      Charles-Fr BENKE     <charles.fr@benke.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21/**
22 *		\file        htdocs/compta/bank/annuel.php
23 *		\ingroup     banque
24 *		\brief       Page to report input-output of a bank account
25 */
26
27require '../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
31
32// Load translation files required by the page
33$langs->loadLangs(array('banks', 'categories'));
34
35$WIDTH = DolGraph::getDefaultGraphSizeForStats('width', 380); // Large for one graph in a smarpthone.
36$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height', 160);
37
38$id = GETPOST('account') ?GETPOST('account', 'alpha') : GETPOST('id');
39$ref = GETPOST('ref');
40
41// Security check
42$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
43$fieldtype = (!empty($ref) ? 'ref' : 'rowid');
44if ($user->socid) {
45	$socid = $user->socid;
46}
47$result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype);
48
49$year_start = GETPOST('year_start');
50$year_current = strftime("%Y", time());
51if (!$year_start) {
52	$year_start = $year_current - 2;
53	$year_end = $year_current;
54} else {
55	$year_end = $year_start + 2;
56}
57
58
59
60/*
61 * View
62 */
63
64$title = $langs->trans("FinancialAccount").' - '.$langs->trans("IOMonthlyReporting");
65$helpurl = "";
66llxHeader('', $title, $helpurl);
67
68$form = new Form($db);
69
70// Get account informations
71$object = new Account($db);
72if ($id > 0 && !preg_match('/,/', $id)) {	// if for a particular account and not a list
73	$result = $object->fetch($id);
74	$id = $object->id;
75}
76if (!empty($ref)) {
77	$result = $object->fetch(0, $ref);
78	$id = $object->id;
79}
80
81
82// Ce rapport de tresorerie est base sur llx_bank (car doit inclure les transactions sans facture)
83// plutot que sur llx_paiement + llx_paiementfourn
84
85$sql = "SELECT SUM(b.amount)";
86$sql .= ", date_format(b.dateo,'%Y-%m') as dm";
87$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
88$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
89$sql .= " WHERE b.fk_account = ba.rowid";
90$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
91$sql .= " AND b.amount >= 0";
92if (!empty($id)) {
93	$sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")";
94}
95$sql .= " GROUP BY dm";
96
97$resql = $db->query($sql);
98if ($resql) {
99	$num = $db->num_rows($resql);
100	$i = 0;
101	while ($i < $num) {
102		$row = $db->fetch_row($resql);
103		$encaiss[$row[1]] = $row[0];
104		$i++;
105	}
106} else {
107	dol_print_error($db);
108}
109
110$sql = "SELECT SUM(b.amount)";
111$sql .= ", date_format(b.dateo,'%Y-%m') as dm";
112$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
113$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
114$sql .= " WHERE b.fk_account = ba.rowid";
115$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
116$sql .= " AND b.amount <= 0";
117if (!empty($id)) {
118	$sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")";
119}
120$sql .= " GROUP BY dm";
121
122$resql = $db->query($sql);
123if ($resql) {
124	$num = $db->num_rows($resql);
125	$i = 0;
126	while ($i < $num) {
127		$row = $db->fetch_row($resql);
128		$decaiss[$row[1]] = -$row[0];
129		$i++;
130	}
131} else {
132	dol_print_error($db);
133}
134
135
136// Onglets
137$head = bank_prepare_head($object);
138print dol_get_fiche_head($head, 'annual', $langs->trans("FinancialAccount"), 0, 'account');
139
140$title = $langs->trans("FinancialAccount")." : ".$object->label;
141$link = ($year_start ? '<a href="'.$_SERVER["PHP_SELF"].'?account='.$object->id.'&year_start='.($year_start - 1).'">'.img_previous('', 'class="valignbottom"')."</a> ".$langs->trans("Year").' <a href="'.$_SERVER["PHP_SELF"].'?account='.$object->id.'&year_start='.($year_start + 1).'">'.img_next('', 'class="valignbottom"').'</a>' : '');
142
143$linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
144
145$morehtmlref = '';
146
147if (!empty($id)) {
148	if (!preg_match('/,/', $id)) {
149		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
150	} else {
151		$bankaccount = new Account($db);
152		$listid = explode(',', $id);
153		foreach ($listid as $key => $aId) {
154			$bankaccount->fetch($aId);
155			$bankaccount->label = $bankaccount->ref;
156			print $bankaccount->getNomUrl(1);
157			if ($key < (count($listid) - 1)) {
158				print ', ';
159			}
160		}
161	}
162} else {
163	print $langs->trans("AllAccounts");
164}
165
166print dol_get_fiche_end();
167
168
169// Affiche tableau
170print load_fiche_titre('', $link, '');
171
172print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
173print '<table class="noborder centpercent">';
174
175print '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Month").'</td>';
176for ($annee = $year_start; $annee <= $year_end; $annee++) {
177	print '<td align="center" width="20%" colspan="2" class="liste_titre borderrightlight">'.$annee.'</td>';
178}
179print '</tr>';
180
181print '<tr class="liste_titre">';
182print '<td class="liste_titre">&nbsp;</td>';
183for ($annee = $year_start; $annee <= $year_end; $annee++) {
184	print '<td class="liste_titre" align="center">'.$langs->trans("Debit").'</td><td class="liste_titre" align="center">'.$langs->trans("Credit").'</td>';
185}
186print '</tr>';
187
188for ($mois = 1; $mois < 13; $mois++) {
189	print '<tr class="oddeven">';
190	print "<td>".dol_print_date(dol_mktime(1, 1, 1, $mois, 1, 2000), "%B")."</td>";
191	for ($annee = $year_start; $annee <= $year_end; $annee++) {
192		$case = sprintf("%04s-%02s", $annee, $mois);
193
194		print '<td class="right" width="10%">&nbsp;';
195		if ($decaiss[$case] > 0) {
196			print price($decaiss[$case]);
197			$totsorties[$annee] += $decaiss[$case];
198		}
199		print "</td>";
200
201		print '<td class="right borderrightlight" width="10%">&nbsp;';
202		if ($encaiss[$case] > 0) {
203			print price($encaiss[$case]);
204			$totentrees[$annee] += $encaiss[$case];
205		}
206		print "</td>";
207	}
208	print '</tr>';
209}
210
211// Total debit-credit
212print '<tr class="liste_total"><td><b>'.$langs->trans("Total")."</b></td>";
213for ($annee = $year_start; $annee <= $year_end; $annee++) {
214	print '<td class="right nowraponall"><b>'.price($totsorties[$annee]).'</b></td><td class="right nowraponall"><b>'.price($totentrees[$annee]).'</b></td>';
215}
216print "</tr>\n";
217
218print "</table>";
219print "</div>";
220
221print '<br>';
222
223
224// Current balance
225$balance = 0;
226
227$sql = "SELECT SUM(b.amount) as total";
228$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
229$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
230$sql .= " WHERE b.fk_account = ba.rowid";
231$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
232if (!empty($id)) {
233	$sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")";
234}
235
236$resql = $db->query($sql);
237if ($resql) {
238	$obj = $db->fetch_object($resql);
239	if ($obj) {
240		$balance = $obj->total;
241	}
242} else {
243	dol_print_error($db);
244}
245
246print '<table class="noborder centpercent">';
247
248print '<tr class="liste_total"><td><b>'.$langs->trans("CurrentBalance")."</b></td>";
249print '<td colspan="'.($nbcol).'" class="right">'.price($balance).'</td>';
250print "</tr>\n";
251
252print "</table>";
253
254// BUILDING GRAPHICS
255
256$year = $year_end;
257
258$result = dol_mkdir($conf->bank->dir_temp);
259if ($result < 0) {
260	$langs->load("errors");
261	$error++;
262	setEventMessages($langs->trans("ErrorFailedToCreateDir"), null, 'errors');
263} else {
264	// Calcul de $min et $max
265	$sql = "SELECT MIN(b.datev) as min, MAX(b.datev) as max";
266	$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
267	$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
268	$sql .= " WHERE b.fk_account = ba.rowid";
269	$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
270	if ($id && $_GET["option"] != 'all') {
271		$sql .= " AND b.fk_account IN (".$db->sanitize($id).")";
272	}
273
274	$resql = $db->query($sql);
275	if ($resql) {
276		$num = $db->num_rows($resql);
277		$obj = $db->fetch_object($resql);
278		$min = $db->jdate($obj->min);
279		$max = $db->jdate($obj->max);
280	} else {
281		dol_print_error($db);
282	}
283	$log = "graph.php: min=".$min." max=".$max;
284	dol_syslog($log);
285
286	// CRED PART
287	// Chargement du tableau des années
288	$tblyear[0] = array();
289	$tblyear[1] = array();
290	$tblyear[2] = array();
291
292	for ($annee = 0; $annee < 3; $annee++) {
293		$sql = "SELECT date_format(b.datev,'%m')";
294		$sql .= ", SUM(b.amount)";
295		$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
296		$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
297		$sql .= " WHERE b.fk_account = ba.rowid";
298		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
299		$sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'";
300		$sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'";
301		$sql .= " AND b.amount > 0";
302		if ($id && $_GET["option"] != 'all') {
303			$sql .= " AND b.fk_account IN (".$db->sanitize($id).")";
304		}
305		$sql .= " GROUP BY date_format(b.datev,'%m');";
306
307		$resql = $db->query($sql);
308		if ($resql) {
309			$num = $db->num_rows($resql);
310			$i = 0;
311			while ($i < $num) {
312				$row = $db->fetch_row($resql);
313				$tblyear[$annee][$row[0]] = $row[1];
314				$i++;
315			}
316			$db->free($resql);
317		} else {
318			dol_print_error($db);
319		}
320	}
321	// Chargement de labels et data_xxx pour tableau 4 Mouvements
322	$labels = array();
323	$data_year_0 = array();
324	$data_year_1 = array();
325	$data_year_2 = array();
326
327	for ($i = 0; $i < 12; $i++) {
328		$data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0;
329		$data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0;
330		$data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0;
331		$labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i + 1));
332		$datamin[$i] = 0;
333	}
334
335	// Fabrication tableau 4b
336	$file = $conf->bank->dir_temp."/credmovement".$id."-".$year.".png";
337	$fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/credmovement".$id."-".$year.".png";
338	$title = $langs->transnoentities("Credit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year;
339	$graph_datas = array();
340	for ($i = 0; $i < 12; $i++) {
341		$graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]);
342	}
343
344	$px1 = new DolGraph();
345	$px1->SetData($graph_datas);
346	$px1->SetLegend(array(($year), ($year - 1), ($year - 2)));
347	$px1->SetLegendWidthMin(180);
348	$px1->SetMaxValue($px1->GetCeilMaxValue() < 0 ? 0 : $px1->GetCeilMaxValue());
349	$px1->SetMinValue($px1->GetFloorMinValue() > 0 ? 0 : $px1->GetFloorMinValue());
350	$px1->SetTitle($title);
351	$px1->SetWidth($WIDTH);
352	$px1->SetHeight($HEIGHT);
353	$px1->SetType(array('line', 'line', 'line'));
354	$px1->SetShading(3);
355	$px1->setBgColor('onglet');
356	$px1->setBgColorGrid(array(255, 255, 255));
357	$px1->SetHorizTickIncrement(1);
358	$px1->draw($file, $fileurl);
359
360	$show1 = $px1->show();
361
362	unset($graph_datas);
363	unset($px1);
364	unset($tblyear[0]);
365	unset($tblyear[1]);
366	unset($tblyear[2]);
367
368	// DEDBT PART
369	// Chargement du tableau des années
370	$tblyear[0] = array();
371	$tblyear[1] = array();
372	$tblyear[2] = array();
373
374	for ($annee = 0; $annee < 3; $annee++) {
375		$sql = "SELECT date_format(b.datev,'%m')";
376		$sql .= ", SUM(b.amount)";
377		$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
378		$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
379		$sql .= " WHERE b.fk_account = ba.rowid";
380		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
381		$sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'";
382		$sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'";
383		$sql .= " AND b.amount < 0";
384		if ($id && $_GET["option"] != 'all') {
385			$sql .= " AND b.fk_account IN (".$db->sanitize($id).")";
386		}
387		$sql .= " GROUP BY date_format(b.datev,'%m');";
388
389		$resql = $db->query($sql);
390		if ($resql) {
391			$num = $db->num_rows($resql);
392			$i = 0;
393			while ($i < $num) {
394				$row = $db->fetch_row($resql);
395				$tblyear[$annee][$row[0]] = abs($row[1]);
396				$i++;
397			}
398			$db->free($resql);
399		} else {
400			dol_print_error($db);
401		}
402	}
403	// Chargement de labels et data_xxx pour tableau 4 Mouvements
404	$labels = array();
405	$data_year_0 = array();
406	$data_year_1 = array();
407	$data_year_2 = array();
408
409	for ($i = 0; $i < 12; $i++) {
410		$data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0;
411		$data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0;
412		$data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0;
413		$labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i + 1));
414		$datamin[$i] = 0;
415	}
416
417	$file = $conf->bank->dir_temp."/debmovement".$id."-".$year.".png";
418	$fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/debmovement".$id."-".$year.".png";
419	$title = $langs->transnoentities("Debit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year;
420	$graph_datas = array();
421	for ($i = 0; $i < 12; $i++) {
422		$graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]);
423	}
424
425	$px2 = new DolGraph();
426	$px2->SetData($graph_datas);
427	$px2->SetLegend(array(($year), ($year - 1), ($year - 2)));
428	$px2->SetLegendWidthMin(180);
429	$px2->SetMaxValue($px2->GetCeilMaxValue() < 0 ? 0 : $px2->GetCeilMaxValue());
430	$px2->SetMinValue($px2->GetFloorMinValue() > 0 ? 0 : $px2->GetFloorMinValue());
431	$px2->SetTitle($title);
432	$px2->SetWidth($WIDTH);
433	$px2->SetHeight($HEIGHT);
434	$px2->SetType(array('line', 'line', 'line'));
435	$px2->SetShading(3);
436	$px2->setBgColor('onglet');
437	$px2->setBgColorGrid(array(255, 255, 255));
438	$px2->SetHorizTickIncrement(1);
439	$px2->draw($file, $fileurl);
440
441	$show2 = $px2->show();
442
443	unset($graph_datas);
444	unset($px2);
445	unset($tblyear[0]);
446	unset($tblyear[1]);
447	unset($tblyear[2]);
448
449	print '<div class="fichecenter"><div class="fichehalfleft"><div align="center">'; // do not use class="center" here, it will have no effect for the js graph inside.
450	print $show1;
451	print '</div></div><div class="fichehalfright"><div class="ficheaddleft"><div align="center">'; // do not use class="center" here, it will have no effect for the js graph inside.
452	print $show2;
453	print '</div></div></div></div>';
454	print '<div style="clear:both"></div>';
455}
456
457
458print "\n</div><br>\n";
459
460// End of page
461llxFooter();
462$db->close();
463