1<?php
2/* Copyright (C) 2001-2004  Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012  Laurent Destailleur     <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2009  Regis Houssin           <regis.houssin@inodbox.com>
5 * Copyright (C) 2017       Olivier Geffroy         <jeff@jeffinfo.com>
6 * Copyright (C) 2018-2020  Frédéric France         <frederic.france@netlogic.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22/**
23 *	\file        htdocs/compta/stats/index.php
24 *	\brief       Page reporting CA
25 */
26
27require '../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
30
31// Load translation files required by the page
32$langs->loadLangs(array('compta', 'bills', 'donation', 'salaries'));
33
34$date_startday = GETPOST('date_startday', 'int');
35$date_startmonth = GETPOST('date_startmonth', 'int');
36$date_startyear = GETPOST('date_startyear', 'int');
37$date_endday = GETPOST('date_endday', 'int');
38$date_endmonth = GETPOST('date_endmonth', 'int');
39$date_endyear = GETPOST('date_endyear', 'int');
40
41$nbofyear = 4;
42
43// Date range
44$year = GETPOST('year', 'int');
45if (empty($year)) {
46	$year_current = dol_print_date(dol_now(), "%Y");
47	$month_current = dol_print_date(dol_now(), "%m");
48	$year_start = $year_current - ($nbofyear - 1);
49} else {
50	$year_current = $year;
51	$month_current = dol_print_date(dol_now(), "%m");
52	$year_start = $year - ($nbofyear - 1);
53}
54$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear, 'tzserver');
55$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear, 'tzserver');
56
57// We define date_start and date_end
58if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
59	$q = GETPOST("q") ? GETPOST("q") : 0;
60	if ($q == 0) {
61		// We define date_start and date_end
62		$year_end = $year_start + ($nbofyear - 1);
63		$month_start = GETPOSTISSET("month") ? GETPOST("month", 'int') : ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1);
64		if (!GETPOST('month')) {
65			if (!GETPOST("year") && $month_start > $month_current) {
66				$year_start--;
67				$year_end--;
68			}
69			$month_end = $month_start - 1;
70			if ($month_end < 1) {
71				$month_end = 12;
72			}
73		} else {
74			$month_end = $month_start;
75		}
76		$date_start = dol_get_first_day($year_start, $month_start, false);
77		$date_end = dol_get_last_day($year_end, $month_end, false);
78	}
79	if ($q == 1) {
80		$date_start = dol_get_first_day($year_start, 1, false);
81		$date_end = dol_get_last_day($year_start, 3, false);
82	}
83	if ($q == 2) {
84		$date_start = dol_get_first_day($year_start, 4, false);
85		$date_end = dol_get_last_day($year_start, 6, false);
86	}
87	if ($q == 3) {
88		$date_start = dol_get_first_day($year_start, 7, false);
89		$date_end = dol_get_last_day($year_start, 9, false);
90	}
91	if ($q == 4) {
92		$date_start = dol_get_first_day($year_start, 10, false);
93		$date_end = dol_get_last_day($year_start, 12, false);
94	}
95}
96
97$userid = GETPOST('userid', 'int');
98$socid = GETPOST('socid', 'int');
99
100$tmps = dol_getdate($date_start);
101$mothn_start = $tmps['mon'];
102$year_start = $tmps['year'];
103$tmpe = dol_getdate($date_end);
104$month_end = $tmpe['mon'];
105$year_end = $tmpe['year'];
106$nbofyear = ($year_end - $year_start) + 1;
107
108// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING')
109$modecompta = $conf->global->ACCOUNTING_MODE;
110if (!empty($conf->accounting->enabled)) {
111	$modecompta = 'BOOKKEEPING';
112}
113if (GETPOST("modecompta")) {
114	$modecompta = GETPOST("modecompta", 'alpha');
115}
116
117// Security check
118if ($user->socid > 0) {
119	$socid = $user->socid;
120}
121if (!empty($conf->comptabilite->enabled)) {
122	$result = restrictedArea($user, 'compta', '', '', 'resultat');
123}
124if (!empty($conf->accounting->enabled)) {
125	$result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
126}
127
128
129
130
131/*
132 * View
133 */
134
135$param = '';
136if ($date_startday && $date_startmonth && $date_startyear) {
137	$param .= '&date_startday='.$date_startday.'&date_startmonth='.$date_startmonth.'&date_startyear='.$date_startyear;
138}
139if ($date_endday && $date_endmonth && $date_endyear) {
140	$param .= '&date_endday='.$date_endday.'&date_endmonth='.$date_endmonth.'&date_endyear='.$date_endyear;
141}
142
143llxHeader();
144
145$form = new Form($db);
146
147// Affiche en-tete du rapport
148if ($modecompta == "CREANCES-DETTES") {
149	$name = $langs->trans("Turnover");
150	$calcmode = $langs->trans("CalcModeDebt");
151	//$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
152	if (!empty($conf->accounting->enabled)) {
153		$calcmode .= '<br>('.$langs->trans("SeeReportInBookkeepingMode", '{link1}', '{link2}').')';
154		$calcmode = str_replace('{link1}', '<a class="bold" href="'.$_SERVER["PHP_SELF"].'?'.($param ? $param : 'year_start='.$year_start).'&modecompta=BOOKKEEPING">', $calcmode);
155		$calcmode = str_replace('{link2}', '</a>', $calcmode);
156	}
157	$periodlink = ($year_start ? "<a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear - 2)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear)."&modecompta=".$modecompta."'>".img_next()."</a>" : "");
158	$description = $langs->trans("RulesCADue");
159	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
160		$description .= $langs->trans("DepositsAreNotIncluded");
161	} else {
162		$description .= $langs->trans("DepositsAreIncluded");
163	}
164	$builddate = dol_now();
165	//$exportlink=$langs->trans("NotYetAvailable");
166} elseif ($modecompta == "RECETTES-DEPENSES") {
167	$name = $langs->trans("TurnoverCollected");
168	$calcmode = $langs->trans("CalcModeEngagement");
169	//$calcmode .= '<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=CREANCES-DETTES">','</a>').')';
170	//if (!empty($conf->accounting->enabled)) {
171	//$calcmode.='<br>('.$langs->trans("SeeReportInBookkeepingMode",'<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=BOOKKEEPINGCOLLECTED">','</a>').')';
172	//}
173	$periodlink = ($year_start ? "<a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear - 2)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear)."&modecompta=".$modecompta."'>".img_next()."</a>" : "");
174	$description = $langs->trans("RulesCAIn");
175	$description .= $langs->trans("DepositsAreIncluded");
176	$builddate = dol_now();
177	//$exportlink=$langs->trans("NotYetAvailable");
178} elseif ($modecompta == "BOOKKEEPING") {
179	$name = $langs->trans("Turnover");
180	$calcmode = $langs->trans("CalcModeBookkeeping");
181	$calcmode .= '<br>('.$langs->trans("SeeReportInDueDebtMode", '{link1}', '{link2}').')';
182	$calcmode = str_replace('{link1}', '<a class="bold" href="'.$_SERVER["PHP_SELF"].'?'.($param ? $param : 'year_start='.$year_start).'&modecompta=CREANCES-DETTES">', $calcmode);
183	$calcmode = str_replace('{link2}', '</a>', $calcmode);
184	//$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
185	$periodlink = ($year_start ? "<a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear - 2)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year_start + $nbofyear)."&modecompta=".$modecompta."'>".img_next()."</a>" : "");
186	$description = $langs->trans("RulesSalesTurnoverOfIncomeAccounts");
187	$builddate = dol_now();
188	//$exportlink=$langs->trans("NotYetAvailable");
189}
190$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
191$period .= ' - ';
192$period .= $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
193
194$moreparam = array();
195if (!empty($modecompta)) {
196	$moreparam['modecompta'] = $modecompta;
197}
198report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $moreparam, $calcmode);
199
200if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') {
201	print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
202}
203
204
205if ($modecompta == 'CREANCES-DETTES') {
206	$sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_ht) as amount, sum(f.total_ttc) as amount_ttc";
207	$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
208	$sql .= " WHERE f.fk_statut in (1,2)";
209	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
210		$sql .= " AND f.type IN (0,1,2,5)";
211	} else {
212		$sql .= " AND f.type IN (0,1,2,3,5)";
213	}
214	$sql .= " AND f.entity IN (".getEntity('invoice').")";
215	if ($socid) {
216		$sql .= " AND f.fk_soc = ".((int) $socid);
217	}
218} elseif ($modecompta == "RECETTES-DEPENSES") {
219	/*
220	 * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les
221	 * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin)
222	 */
223	$sql = "SELECT date_format(p.datep, '%Y-%m') as dm, sum(pf.amount) as amount_ttc";
224	$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
225	$sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf";
226	$sql .= ", ".MAIN_DB_PREFIX."paiement as p";
227	$sql .= " WHERE p.rowid = pf.fk_paiement";
228	$sql .= " AND pf.fk_facture = f.rowid";
229	$sql .= " AND f.entity IN (".getEntity('invoice').")";
230	if ($socid) {
231		$sql .= " AND f.fk_soc = ".((int) $socid);
232	}
233} elseif ($modecompta == "BOOKKEEPING") {
234	$pcgverid = $conf->global->CHARTOFACCOUNTS;
235	$pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version');
236	if (empty($pcgvercode)) {
237		$pcgvercode = $pcgverid;
238	}
239
240	$sql = "SELECT date_format(b.doc_date, '%Y-%m') as dm, sum(b.credit - b.debit) as amount_ttc";
241	$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b,";
242	$sql .= " ".MAIN_DB_PREFIX."accounting_account as aa";
243	$sql .= " WHERE b.entity = ".$conf->entity; // In module double party accounting, we never share entities
244	$sql .= " AND b.numero_compte = aa.account_number";
245	$sql .= " AND b.doc_type = 'customer_invoice'";
246	$sql .= " AND aa.entity = ".$conf->entity;
247	$sql .= " AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
248	$sql .= " AND aa.pcg_type = 'INCOME'";		// TODO Be able to use a custom group
249}
250$sql .= " GROUP BY dm";
251$sql .= " ORDER BY dm";
252// TODO Add a filter on $date_start and $date_end to reduce quantity on data
253//print $sql;
254
255$minyearmonth = $maxyearmonth = 0;
256
257$result = $db->query($sql);
258if ($result) {
259	$num = $db->num_rows($result);
260	$i = 0;
261	while ($i < $num) {
262		$obj = $db->fetch_object($result);
263		$cum_ht[$obj->dm] = !empty($obj->amount) ? $obj->amount : 0;
264		$cum[$obj->dm] = $obj->amount_ttc;
265		if ($obj->amount_ttc) {
266			$minyearmonth = ($minyearmonth ? min($minyearmonth, $obj->dm) : $obj->dm);
267			$maxyearmonth = max($maxyearmonth, $obj->dm);
268		}
269		$i++;
270	}
271	$db->free($result);
272} else {
273	dol_print_error($db);
274}
275
276// On ajoute les paiements anciennes version, non lies par paiement_facture (very old versions)
277if ($modecompta == 'RECETTES-DEPENSES') {
278	$sql = "SELECT date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount_ttc";
279	$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
280	$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
281	$sql .= ", ".MAIN_DB_PREFIX."paiement as p";
282	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement";
283	$sql .= " WHERE pf.rowid IS NULL";
284	$sql .= " AND p.fk_bank = b.rowid";
285	$sql .= " AND b.fk_account = ba.rowid";
286	$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
287	$sql .= " GROUP BY dm";
288	$sql .= " ORDER BY dm";
289
290	$result = $db->query($sql);
291	if ($result) {
292		$num = $db->num_rows($result);
293		$i = 0;
294		while ($i < $num) {
295			$obj = $db->fetch_object($result);
296			$cum[$obj->dm] += $obj->amount_ttc;
297			if ($obj->amount_ttc) {
298				$minyearmonth = ($minyearmonth ?min($minyearmonth, $obj->dm) : $obj->dm);
299				$maxyearmonth = max($maxyearmonth, $obj->dm);
300			}
301			$i++;
302		}
303	} else {
304		dol_print_error($db);
305	}
306}
307
308$moreforfilter = '';
309
310print '<div class="div-table-responsive">';
311print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
312
313print '<tr class="liste_titre"><td>&nbsp;</td>';
314
315for ($annee = $year_start; $annee <= $year_end; $annee++) {
316	if ($modecompta == 'CREANCES-DETTES') {
317		print '<td align="center" width="10%" colspan="3">';
318	} else {
319		print '<td align="center" width="10%" colspan="2" class="borderrightlight">';
320	}
321	if ($modecompta != 'BOOKKEEPING') {
322		print '<a href="casoc.php?year='.$annee.'">';
323	}
324	print $annee;
325	if ($conf->global->SOCIETE_FISCAL_MONTH_START > 1) {
326		print '-'.($annee + 1);
327	}
328	if ($modecompta != 'BOOKKEEPING') {
329		print '</a>';
330	}
331	print '</td>';
332	if ($annee != $year_end) {
333		print '<td width="15">&nbsp;</td>';
334	}
335}
336print '</tr>';
337
338print '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Month").'</td>';
339for ($annee = $year_start; $annee <= $year_end; $annee++) {
340	if ($modecompta == 'CREANCES-DETTES') {
341		print '<td class="liste_titre right">'.$langs->trans("AmountHT").'</td>';
342	}
343	print '<td class="liste_titre right">';
344	if ($modecompta == "BOOKKEEPING") {
345		print $langs->trans("Amount");
346	} else {
347		print $langs->trans("AmountTTC");
348	}
349	print '</td>';
350	print '<td class="liste_titre right borderrightlight">'.$langs->trans("Delta").'</td>';
351	if ($annee != $year_end) {
352		print '<td class="liste_titre" width="15">&nbsp;</td>';
353	}
354}
355print '</tr>';
356
357$now_show_delta = 0;
358$minyear = substr($minyearmonth, 0, 4);
359$maxyear = substr($maxyearmonth, 0, 4);
360$nowyear = strftime("%Y", dol_now());
361$nowyearmonth = strftime("%Y-%m", dol_now());
362$maxyearmonth = max($maxyearmonth, $nowyearmonth);
363$now = dol_now();
364$casenow = dol_print_date($now, "%Y-%m");
365
366// Loop on each month
367$nb_mois_decalage = GETPOSTISSET('date_startmonth') ? (GETPOST('date_startmonth', 'int') - 1) : (empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 0 : ($conf->global->SOCIETE_FISCAL_MONTH_START - 1));
368for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) {
369	$mois_modulo = $mois; // ajout
370	if ($mois > 12) {
371		$mois_modulo = $mois - 12;
372	} // ajout
373
374	if ($year_start == $year_end) {
375		// If we show only one year or one month, we do not show month before the selected month
376		if ($mois < $date_startmonth && $year_start <= $date_startyear) {
377			continue;
378		}
379		// If we show only one year or one month, we do not show month after the selected month
380		if ($mois > $date_endmonth && $year_end >= $date_endyear) {
381			break;
382		}
383	}
384
385	print '<tr class="oddeven">';
386
387	// Month
388	print "<td>".dol_print_date(dol_mktime(12, 0, 0, $mois_modulo, 1, 2000), "%B")."</td>";
389
390	for ($annee = $year_start - 1; $annee <= $year_end; $annee++) {	// We start one year before to have data to be able to make delta
391		$annee_decalage = $annee;
392		if ($mois > 12) {
393			$annee_decalage = $annee + 1;
394		}
395		$case = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage), "%Y-%m");
396		$caseprev = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage - 1), "%Y-%m");
397
398		if ($annee >= $year_start) {	// We ignore $annee < $year_start, we loop on it to be able to make delta, nothing is output.
399			if ($modecompta == 'CREANCES-DETTES') {
400				// Value turnover of month w/o VAT
401				print '<td class="right">';
402				if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) {
403					if ($cum_ht[$case]) {
404						$now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
405						print '<a href="casoc.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">'.price($cum_ht[$case], 1).'</a>';
406					} else {
407						if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) {
408							print '0';
409						} else {
410							print '&nbsp;';
411						}
412					}
413				}
414				print "</td>";
415			}
416
417			// Value turnover of month
418			print '<td class="right">';
419			if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) {
420				if ($cum[$case]) {
421					$now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
422					if ($modecompta != 'BOOKKEEPING') {
423						print '<a href="casoc.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">';
424					}
425					print price($cum[$case], 1);
426					if ($modecompta != 'BOOKKEEPING') {
427						print '</a>';
428					}
429				} else {
430					if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) {
431						print '0';
432					} else {
433						print '&nbsp;';
434					}
435				}
436			}
437			print "</td>";
438
439			// Percentage of month
440			print '<td class="borderrightlight right">';
441			//var_dump($annee.' '.$year_end.' '.$mois.' '.$month_end);
442			if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) {
443				if ($annee_decalage > $minyear && $case <= $casenow) {
444					if ($cum[$caseprev] && $cum[$case]) {
445						$percent = (round(($cum[$case] - $cum[$caseprev]) / $cum[$caseprev], 4) * 100);
446						//print "X $cum[$case] - $cum[$caseprev] - $cum[$caseprev] - $percent X";
447						print ($percent >= 0 ? "+$percent" : "$percent").'%';
448					}
449					if ($cum[$caseprev] && !$cum[$case]) {
450						print '-100%';
451					}
452					if (!$cum[$caseprev] && $cum[$case]) {
453						//print '<td class="right">+Inf%</td>';
454						print '-';
455					}
456					if (isset($cum[$caseprev]) && !$cum[$caseprev] && !$cum[$case]) {
457						print '+0%';
458					}
459					if (!isset($cum[$caseprev]) && !$cum[$case]) {
460						print '-';
461					}
462				} else {
463					if ($minyearmonth <= $case && $case <= $maxyearmonth) {
464						print '-';
465					} else {
466						print '&nbsp;';
467					}
468				}
469			}
470			print '</td>';
471
472			if ($annee_decalage < $year_end || ($annee_decalage == $year_end && $mois > 12 && $annee < $year_end)) {
473				print '<td width="15">&nbsp;</td>';
474			}
475		}
476
477		if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) {
478			$total_ht[$annee] += ((!empty($cum_ht[$case])) ? $cum_ht[$case] : 0);
479			$total[$annee] += $cum[$case];
480		}
481	}
482
483	print '</tr>';
484}
485
486/*
487 for ($mois = 1 ; $mois < 13 ; $mois++)
488 {
489
490 print '<tr class="oddeven">';
491
492 print "<td>".dol_print_date(dol_mktime(12,0,0,$mois,1,2000),"%B")."</td>";
493 for ($annee = $year_start ; $annee <= $year_end ; $annee++)
494 {
495 $casenow = dol_print_date(dol_now(),"%Y-%m");
496 $case = dol_print_date(dol_mktime(1,1,1,$mois,1,$annee),"%Y-%m");
497 $caseprev = dol_print_date(dol_mktime(1,1,1,$mois,1,$annee-1),"%Y-%m");
498
499 // Valeur CA du mois
500 print '<td class="right">';
501 if ($cum[$case])
502 {
503 $now_show_delta=1;  // On a trouve le premier mois de la premiere annee generant du chiffre.
504 print '<a href="casoc.php?year='.$annee.'&month='.$mois.'">'.price($cum[$case],1).'</a>';
505 }
506 else
507 {
508 if ($minyearmonth < $case && $case <= max($maxyearmonth,$nowyearmonth)) { print '0'; }
509 else { print '&nbsp;'; }
510 }
511 print "</td>";
512
513 // Pourcentage du mois
514 if ($annee > $minyear && $case <= $casenow) {
515 if ($cum[$caseprev] && $cum[$case])
516 {
517 $percent=(round(($cum[$case]-$cum[$caseprev])/$cum[$caseprev],4)*100);
518 //print "X $cum[$case] - $cum[$caseprev] - $cum[$caseprev] - $percent X";
519 print '<td class="right">'.($percent>=0?"+$percent":"$percent").'%</td>';
520
521 }
522 if ($cum[$caseprev] && ! $cum[$case])
523 {
524 print '<td class="right">-100%</td>';
525 }
526 if (! $cum[$caseprev] && $cum[$case])
527 {
528 print '<td class="right">+Inf%</td>';
529 }
530 if (! $cum[$caseprev] && ! $cum[$case])
531 {
532 print '<td class="right">+0%</td>';
533 }
534 }
535 else
536 {
537 print '<td class="right">';
538 if ($minyearmonth <= $case && $case <= $maxyearmonth) { print '-'; }
539 else { print '&nbsp;'; }
540 print '</td>';
541 }
542
543 $total[$annee]+=$cum[$case];
544 if ($annee != $year_end) print '<td width="15">&nbsp;</td>';
545 }
546
547 print '</tr>';
548 }
549 */
550
551// Show total
552print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td>';
553for ($annee = $year_start; $annee <= $year_end; $annee++) {
554	if ($modecompta == 'CREANCES-DETTES') {
555		// Montant total HT
556		if ($total_ht[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) {
557			print '<td class="nowrap right">';
558			print ($total_ht[$annee] ?price($total_ht[$annee]) : "0");
559			print "</td>";
560		} else {
561			print '<td>&nbsp;</td>';
562		}
563	}
564
565	// Total amount
566	if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) {
567		print '<td class="nowrap right">';
568		print ($total[$annee] ?price($total[$annee]) : "0");
569		print "</td>";
570	} else {
571		print '<td>&nbsp;</td>';
572	}
573
574	// Pourcentage total
575	if ($annee > $minyear && $annee <= max($nowyear, $maxyear)) {
576		if ($total[$annee - 1] && $total[$annee]) {
577			$percent = (round(($total[$annee] - $total[$annee - 1]) / $total[$annee - 1], 4) * 100);
578			print '<td class="nowrap borderrightlight right">';
579			print ($percent >= 0 ? "+$percent" : "$percent").'%';
580			print '</td>';
581		}
582		if ($total[$annee - 1] && !$total[$annee]) {
583			print '<td class="borderrightlight right">-100%</td>';
584		}
585		if (!$total[$annee - 1] && $total[$annee]) {
586			print '<td class="borderrightlight right">+'.$langs->trans('Inf').'%</td>';
587		}
588		if (!$total[$annee - 1] && !$total[$annee]) {
589			print '<td class="borderrightlight right">+0%</td>';
590		}
591	} else {
592		print '<td class="borderrightlight right">';
593		if ($total[$annee] || ($minyear <= $annee && $annee <= max($nowyear, $maxyear))) {
594			print '-';
595		} else {
596			print '&nbsp;';
597		}
598		print '</td>';
599	}
600
601	if ($annee != $year_end) {
602		print '<td width="15">&nbsp;</td>';
603	}
604}
605print "</tr>\n";
606print "</table>";
607print '</div>';
608
609
610/*
611 * En mode recettes/depenses, on complete avec les montants factures non regles
612 * et les propales signees mais pas facturees. En effet, en recettes-depenses,
613 * on comptabilise lorsque le montant est sur le compte donc il est interessant
614 * d'avoir une vision de ce qui va arriver.
615 */
616
617/*
618 Je commente toute cette partie car les chiffres affichees sont faux - Eldy.
619 En attendant correction.
620
621 if ($modecompta != 'CREANCES-DETTES')
622 {
623
624 print '<br><table width="100%" class="noborder">';
625
626 // Factures non reglees
627 // Y a bug ici. Il faut prendre le reste a payer et non le total des factures non reglees !
628
629 $sql = "SELECT f.ref, f.rowid, s.nom, s.rowid as socid, f.total_ttc, sum(pf.amount) as am";
630 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f left join ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture";
631 $sql .= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = 1";
632 if ($socid)
633 {
634 $sql .= " AND f.fk_soc = $socid";
635 }
636 $sql .= " GROUP BY f.ref,f.rowid,s.nom, s.rowid, f.total_ttc";
637
638 $resql=$db->query($sql);
639 if ($resql)
640 {
641 $num = $db->num_rows($resql);
642 $i = 0;
643
644 if ($num)
645 {
646 $total_ttc_Rac = $totalam_Rac = $total_Rac = 0;
647 while ($i < $num)
648 {
649 $obj = $db->fetch_object($resql);
650 $total_ttc_Rac +=  $obj->total_ttc;
651 $totalam_Rac +=  $obj->am;
652 $i++;
653 }
654
655 print "<tr class="oddeven"><td class=\"right\" colspan=\"5\"><i>Facture a encaisser : </i></td><td class=\"right\"><i>".price($total_ttc_Rac)."</i></td><td colspan=\"5\"><-- bug ici car n'exclut pas le deja r?gl? des factures partiellement r?gl?es</td></tr>";
656 }
657 $db->free($resql);
658 }
659 else
660 {
661 dol_print_error($db);
662 }
663 */
664
665/*
666 *
667 * Propales signees, et non facturees
668 *
669 */
670
671/*
672 Je commente toute cette partie car les chiffres affichees sont faux - Eldy.
673 En attendant correction.
674
675 $sql = "SELECT sum(f.total_ht) as tot_fht,sum(f.total_ttc) as tot_fttc, p.rowid, p.ref, s.nom, s.rowid as socid, p.total_ht, p.total_ttc
676 FROM ".MAIN_DB_PREFIX."commande AS p, ".MAIN_DB_PREFIX."societe AS s
677 LEFT JOIN ".MAIN_DB_PREFIX."co_fa AS co_fa ON co_fa.fk_commande = p.rowid
678 LEFT JOIN ".MAIN_DB_PREFIX."facture AS f ON co_fa.fk_facture = f.rowid
679 WHERE p.fk_soc = s.rowid
680 AND p.fk_statut >=1
681 AND p.facture =0";
682 if ($socid)
683 {
684 $sql .= " AND f.fk_soc = ".((int) $socid);
685 }
686 $sql .= " GROUP BY p.rowid";
687
688 $resql=$db->query($sql);
689 if ($resql)
690 {
691 $num = $db->num_rows($resql);
692 $i = 0;
693
694 if ($num)
695 {
696 $total_pr = 0;
697 while ($i < $num)
698 {
699 $obj = $db->fetch_object($resql);
700 $total_pr +=  $obj->total_ttc-$obj->tot_fttc;
701 $i++;
702 }
703
704 print "<tr class="oddeven"><td class=\"right\" colspan=\"5\"><i>Signe et non facture:</i></td><td class=\"right\"><i>".price($total_pr)."</i></td><td colspan=\"5\"><-- bug ici, ca devrait exclure le deja facture</td></tr>";
705 }
706 $db->free($resql);
707 }
708 else
709 {
710 dol_print_error($db);
711 }
712 print "<tr class="oddeven"><td class=\"right\" colspan=\"5\"><i>Total CA previsionnel : </i></td><td class=\"right\"><i>".price($total_CA)."</i></td><td colspan=\"3\"><-- bug ici car bug sur les 2 precedents</td></tr>";
713 }
714 print "</table>";
715
716 */
717
718// End of page
719llxFooter();
720$db->close();
721