1<?php
2/* Copyright (C) 2020       Maxime Kohlhaas         <maxime@atm-consulting.fr>
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 <https://www.gnu.org/licenses/>.
16 */
17
18/**
19 *	\file        htdocs/compta/stats/supplier_turnover.php
20 *	\brief       Page reporting purchase turnover
21 */
22
23require '../../main.inc.php';
24require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
25require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
26
27// Load translation files required by the page
28$langs->loadLangs(array('compta', 'bills'));
29
30$date_startday = GETPOST('date_startday', 'int');
31$date_startmonth = GETPOST('date_startmonth', 'int');
32$date_startyear = GETPOST('date_startyear', 'int');
33$date_endday = GETPOST('date_endday', 'int');
34$date_endmonth = GETPOST('date_endmonth', 'int');
35$date_endyear = GETPOST('date_endyear', 'int');
36
37$nbofyear = 4;
38
39// Date range
40$year = GETPOST('year', 'int');
41if (empty($year)) {
42	$year_current = strftime("%Y", dol_now());
43	$month_current = strftime("%m", dol_now());
44	$year_start = $year_current - ($nbofyear - 1);
45} else {
46	$year_current = $year;
47	$month_current = strftime("%m", dol_now());
48	$year_start = $year - ($nbofyear - 1);
49}
50$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear, 'tzserver');	// We use timezone of server so report is same from everywhere
51$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear, 'tzserver');		// We use timezone of server so report is same from everywhere
52
53// We define date_start and date_end
54if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
55	$q = GETPOST("q") ?GETPOST("q") : 0;
56	if ($q == 0) {
57		// We define date_start and date_end
58		$year_end = $year_start + ($nbofyear - 1);
59		$month_start = GETPOST("month") ? GETPOST("month", 'int') : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
60		if (!GETPOST('month')) {
61			if (!GETPOST("year") && $month_start > $month_current) {
62				$year_start--;
63				$year_end--;
64			}
65			$month_end = $month_start - 1;
66			if ($month_end < 1) {
67				$month_end = 12;
68			}
69		} else {
70			$month_end = $month_start;
71		}
72		$date_start = dol_get_first_day($year_start, $month_start, false);
73		$date_end = dol_get_last_day($year_end, $month_end, false);
74	}
75	if ($q == 1) {
76		$date_start = dol_get_first_day($year_start, 1, false);
77		$date_end = dol_get_last_day($year_start, 3, false);
78	}
79	if ($q == 2) {
80		$date_start = dol_get_first_day($year_start, 4, false);
81		$date_end = dol_get_last_day($year_start, 6, false);
82	}
83	if ($q == 3) {
84		$date_start = dol_get_first_day($year_start, 7, false);
85		$date_end = dol_get_last_day($year_start, 9, false);
86	}
87	if ($q == 4) {
88		$date_start = dol_get_first_day($year_start, 10, false);
89		$date_end = dol_get_last_day($year_start, 12, false);
90	}
91}
92
93$userid = GETPOST('userid', 'int');
94$socid = GETPOST('socid', 'int');
95
96$tmps = dol_getdate($date_start);
97$year_start = $tmps['year'];
98$tmpe = dol_getdate($date_end);
99$year_end = $tmpe['year'];
100$nbofyear = ($year_end - $year_start) + 1;
101
102// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING')
103$modecompta = $conf->global->ACCOUNTING_MODE;
104if (!empty($conf->accounting->enabled)) {
105	$modecompta = 'BOOKKEEPING';
106}
107if (GETPOST("modecompta")) {
108	$modecompta = GETPOST("modecompta", 'alpha');
109}
110
111// Security check
112if ($user->socid > 0) {
113	$socid = $user->socid;
114}
115if (!empty($conf->comptabilite->enabled)) {
116	$result = restrictedArea($user, 'compta', '', '', 'resultat');
117}
118if (!empty($conf->accounting->enabled)) {
119	$result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
120}
121
122
123/*
124 * View
125 */
126
127llxHeader();
128
129$form = new Form($db);
130
131// TODO Report from bookkeeping not yet available, so we switch on report on business events
132if ($modecompta == "BOOKKEEPING") {
133	$modecompta = "CREANCES-DETTES";
134}
135if ($modecompta == "BOOKKEEPINGCOLLECTED") {
136	$modecompta = "RECETTES-DEPENSES";
137}
138
139// Affiche en-tete du rapport
140if ($modecompta == "CREANCES-DETTES") {
141	$name = $langs->trans("PurchaseTurnover");
142	$calcmode = $langs->trans("CalcModeDebt");
143	if (!empty($conf->accounting->enabled)) {
144		$calcmode .= '<br>('.$langs->trans("SeeReportInBookkeepingMode", '{link1}', '{link2}').')';
145		$calcmode = str_replace('{link1}', '<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=BOOKKEEPING">', $calcmode);
146		$calcmode = str_replace('{link2}', '</a>', $calcmode);
147	}
148	$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>" : "");
149	$description = $langs->trans("RulesPurchaseTurnoverDue");
150	//$exportlink=$langs->trans("NotYetAvailable");
151} elseif ($modecompta == "RECETTES-DEPENSES") {
152	$name = $langs->trans("PurchaseTurnoverCollected");
153	$calcmode = $langs->trans("CalcModeEngagement");
154	$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>" : "");
155	$description = $langs->trans("RulesPurchaseTurnoverIn");
156	//$exportlink=$langs->trans("NotYetAvailable");
157} elseif ($modecompta == "BOOKKEEPING") {
158	$name = $langs->trans("PurchaseTurnover");
159	$calcmode = $langs->trans("CalcModeBookkeeping");
160	$calcmode .= '<br>('.$langs->trans("SeeReportInDueDebtMode", '{link1}', '{link2}').')';
161	$calcmode = str_replace('{link1}', '<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=CREANCES-DETTES">', $calcmode);
162	$calcmode = str_replace('{link2}', '</a>', $calcmode);
163	$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>" : "");
164	$description = $langs->trans("RulesPurchaseTurnoverOfExpenseAccounts");
165	//$exportlink=$langs->trans("NotYetAvailable");
166} elseif ($modecompta == "BOOKKEEPINGCOLLECTED") {
167	$name = $langs->trans("PurchaseTurnoverCollected");
168	$calcmode = $langs->trans("CalcModeBookkeeping");
169	$calcmode .= '<br>('.$langs->trans("SeeReportInDueDebtMode", '{link1}', '{link2}').')';
170	$calcmode = str_replace('{link1}', '<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=RECETTES-DEPENSES">', $calcmode);
171	$calcmode = str_replace('{link2}', '</a>', $calcmode);
172	$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>" : "");
173	$description = $langs->trans("RulesPurchaseTurnoverCollectedOfExpenseAccounts");
174	//$exportlink=$langs->trans("NotYetAvailable");
175}
176
177$builddate = dol_now();
178$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
179$period .= ' - ';
180$period .= $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
181
182$moreparam = array();
183if (!empty($modecompta)) {
184	$moreparam['modecompta'] = $modecompta;
185}
186report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $moreparam, $calcmode);
187
188if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') {
189	print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
190}
191
192
193if ($modecompta == 'CREANCES-DETTES') {
194	$sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_ht) as amount, sum(f.total_ttc) as amount_ttc";
195	$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
196	$sql .= " WHERE f.fk_statut in (1,2)";
197	$sql .= " AND f.type IN (0,2)";
198	$sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
199	if ($socid) {
200		$sql .= " AND f.fk_soc = ".((int) $socid);
201	}
202} elseif ($modecompta == "RECETTES-DEPENSES") {
203	$sql = "SELECT date_format(p.datep,'%Y-%m') as dm, sum(pf.amount) as amount_ttc";
204	$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
205	$sql .= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf";
206	$sql .= ", ".MAIN_DB_PREFIX."paiementfourn as p";
207	$sql .= " WHERE p.rowid = pf.fk_paiementfourn";
208	$sql .= " AND pf.fk_facturefourn = f.rowid";
209	$sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
210	if ($socid) {
211		$sql .= " AND f.fk_soc = ".((int) $socid);
212	}
213} elseif ($modecompta == "BOOKKEEPING") {
214	$pcgverid = $conf->global->CHARTOFACCOUNTS;
215	$pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version');
216	if (empty($pcgvercode)) {
217		$pcgvercode = $pcgverid;
218	}
219
220	$sql = "SELECT date_format(b.doc_date, '%Y-%m') as dm, sum(b.debit - b.credit) as amount_ttc";
221	$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b,";
222	$sql .= " ".MAIN_DB_PREFIX."accounting_account as aa";
223	$sql .= " WHERE b.entity = ".$conf->entity; // In module double party accounting, we never share entities
224	$sql .= " AND b.doc_type = 'supplier_invoice'";
225	$sql .= " AND b.numero_compte = aa.account_number";
226	$sql .= " AND aa.entity = ".$conf->entity;
227	$sql .= " AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
228	$sql .= " AND aa.pcg_type = 'EXPENSE'";		// TODO Be able to use a custom group
229}
230//print $sql;
231
232$sql .= " GROUP BY dm";
233$sql .= " ORDER BY dm";
234// TODO Add a filter on $date_start and $date_end to reduce quantity on data
235//print $sql;
236
237$minyearmonth = $maxyearmonth = 0;
238
239$result = $db->query($sql);
240if ($result) {
241	$num = $db->num_rows($result);
242	$i = 0;
243	while ($i < $num) {
244		$obj = $db->fetch_object($result);
245		$cum_ht[$obj->dm] = !empty($obj->amount) ? $obj->amount : 0;
246		$cum[$obj->dm] = $obj->amount_ttc;
247		if ($obj->amount_ttc) {
248			$minyearmonth = ($minyearmonth ? min($minyearmonth, $obj->dm) : $obj->dm);
249			$maxyearmonth = max($maxyearmonth, $obj->dm);
250		}
251		$i++;
252	}
253	$db->free($result);
254} else {
255	dol_print_error($db);
256}
257
258$moreforfilter = '';
259
260print '<div class="div-table-responsive">';
261print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
262
263print '<tr class="liste_titre"><td>&nbsp;</td>';
264
265for ($annee = $year_start; $annee <= $year_end; $annee++) {
266	if ($modecompta == 'CREANCES-DETTES') {
267		print '<td align="center" width="10%" colspan="3">';
268	} else {
269		print '<td align="center" width="10%" colspan="2" class="borderrightlight">';
270	}
271	if ($modecompta != 'BOOKKEEPING') {
272		print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee.($modecompta ? '&modecompta='.$modecompta : '').'">';
273	}
274	print $annee;
275	if ($conf->global->SOCIETE_FISCAL_MONTH_START > 1) {
276		print '-'.($annee + 1);
277	}
278	if ($modecompta != 'BOOKKEEPING') {
279		print '</a>';
280	}
281	print '</td>';
282	if ($annee != $year_end) {
283		print '<td width="15">&nbsp;</td>';
284	}
285}
286print '</tr>';
287
288print '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Month").'</td>';
289for ($annee = $year_start; $annee <= $year_end; $annee++) {
290	if ($modecompta == 'CREANCES-DETTES') {
291		print '<td class="liste_titre right">'.$langs->trans("AmountHT").'</td>';
292	}
293	print '<td class="liste_titre right">';
294	if ($modecompta == "BOOKKEEPING") {
295		print $langs->trans("Amount");
296	} else {
297		print $langs->trans("AmountTTC");
298	}
299	print '</td>';
300	print '<td class="liste_titre right borderrightlight">'.$langs->trans("Delta").'</td>';
301	if ($annee != $year_end) {
302		print '<td class="liste_titre" width="15">&nbsp;</td>';
303	}
304}
305print '</tr>';
306
307$now_show_delta = 0;
308$minyear = substr($minyearmonth, 0, 4);
309$maxyear = substr($maxyearmonth, 0, 4);
310$nowyear = strftime("%Y", dol_now());
311$nowyearmonth = strftime("%Y-%m", dol_now());
312$maxyearmonth = max($maxyearmonth, $nowyearmonth);
313$now = dol_now();
314$casenow = dol_print_date($now, "%Y-%m");
315
316// Loop on each month
317$nb_mois_decalage = $conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START - 1) : 0;
318for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) {
319	$mois_modulo = $mois; // ajout
320	if ($mois > 12) {
321		$mois_modulo = $mois - 12;
322	} // ajout
323
324	if ($year_start == $year_end) {
325		if ($mois > $date_endmonth && $year_end >= $date_endyear) {
326			break;
327		}
328	}
329
330	print '<tr class="oddeven">';
331
332	// Month
333	print "<td>".dol_print_date(dol_mktime(12, 0, 0, $mois_modulo, 1, 2000), "%B")."</td>";
334
335	for ($annee = $year_start - 1; $annee <= $year_end; $annee++) {	// We start one year before to have data to be able to make delta
336		$annee_decalage = $annee;
337		if ($mois > 12) {
338			$annee_decalage = $annee + 1;
339		}
340		$case = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage), "%Y-%m");
341		$caseprev = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage - 1), "%Y-%m");
342
343		if ($annee >= $year_start) {	// We ignore $annee < $year_start, we loop on it to be able to make delta, nothing is output.
344			if ($modecompta == 'CREANCES-DETTES') {
345				// Valeur CA du mois w/o VAT
346				print '<td class="right">';
347				if ($cum_ht[$case]) {
348					$now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
349					print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">'.price($cum_ht[$case], 1).'</a>';
350				} else {
351					if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) {
352						print '0';
353					} else {
354						print '&nbsp;';
355					}
356				}
357				print "</td>";
358			}
359
360			// Valeur CA du mois
361			print '<td class="right">';
362			if ($cum[$case]) {
363				$now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
364				if ($modecompta != 'BOOKKEEPING') {
365					print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">';
366				}
367				print price($cum[$case], 1);
368				if ($modecompta != 'BOOKKEEPING') {
369					print '</a>';
370				}
371			} else {
372				if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) {
373					print '0';
374				} else {
375					print '&nbsp;';
376				}
377			}
378			print "</td>";
379
380			// Pourcentage du mois
381			if ($annee_decalage > $minyear && $case <= $casenow) {
382				if ($cum[$caseprev] && $cum[$case]) {
383					$percent = (round(($cum[$case] - $cum[$caseprev]) / $cum[$caseprev], 4) * 100);
384					//print "X $cum[$case] - $cum[$caseprev] - $cum[$caseprev] - $percent X";
385					print '<td class="borderrightlight right">'.($percent >= 0 ? "+$percent" : "$percent").'%</td>';
386				}
387				if ($cum[$caseprev] && !$cum[$case]) {
388					print '<td class="borderrightlight right">-100%</td>';
389				}
390				if (!$cum[$caseprev] && $cum[$case]) {
391					//print '<td class="right">+Inf%</td>';
392					print '<td class="borderrightlight right">-</td>';
393				}
394				if (isset($cum[$caseprev]) && !$cum[$caseprev] && !$cum[$case]) {
395					print '<td class="borderrightlight right">+0%</td>';
396				}
397				if (!isset($cum[$caseprev]) && !$cum[$case]) {
398					print '<td class="borderrightlight right">-</td>';
399				}
400			} else {
401				print '<td class="borderrightlight right">';
402				if ($minyearmonth <= $case && $case <= $maxyearmonth) {
403					print '-';
404				} else {
405					print '&nbsp;';
406				}
407				print '</td>';
408			}
409
410			if ($annee_decalage < $year_end || ($annee_decalage == $year_end && $mois > 12 && $annee < $year_end)) {
411				print '<td width="15">&nbsp;</td>';
412			}
413		}
414
415		$total_ht[$annee] += ((!empty($cum_ht[$case])) ? $cum_ht[$case] : 0);
416		$total[$annee] += $cum[$case];
417	}
418
419	print '</tr>';
420}
421
422// Affiche total
423print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td>';
424for ($annee = $year_start; $annee <= $year_end; $annee++) {
425	if ($modecompta == 'CREANCES-DETTES') {
426		// Montant total HT
427		if ($total_ht[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) {
428			print '<td class="nowrap right">'.($total_ht[$annee] ?price($total_ht[$annee]) : "0")."</td>";
429		} else {
430			print '<td>&nbsp;</td>';
431		}
432	}
433
434	// Montant total
435	if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) {
436		print '<td class="nowrap right">'.($total[$annee] ?price($total[$annee]) : "0")."</td>";
437	} else {
438		print '<td>&nbsp;</td>';
439	}
440
441	// Pourcentage total
442	if ($annee > $minyear && $annee <= max($nowyear, $maxyear)) {
443		if ($total[$annee - 1] && $total[$annee]) {
444			$percent = (round(($total[$annee] - $total[$annee - 1]) / $total[$annee - 1], 4) * 100);
445			print '<td class="nowrap borderrightlight right">'.($percent >= 0 ? "+$percent" : "$percent").'%</td>';
446		}
447		if ($total[$annee - 1] && !$total[$annee]) {
448			print '<td class="borderrightlight right">-100%</td>';
449		}
450		if (!$total[$annee - 1] && $total[$annee]) {
451			print '<td class="borderrightlight right">+'.$langs->trans('Inf').'%</td>';
452		}
453		if (!$total[$annee - 1] && !$total[$annee]) {
454			print '<td class="borderrightlight right">+0%</td>';
455		}
456	} else {
457		print '<td class="borderrightlight right">';
458		if ($total[$annee] || ($minyear <= $annee && $annee <= max($nowyear, $maxyear))) {
459			print '-';
460		} else {
461			print '&nbsp;';
462		}
463		print '</td>';
464	}
465
466	if ($annee != $year_end) {
467		print '<td width="15">&nbsp;</td>';
468	}
469}
470print "</tr>\n";
471print "</table>";
472print '</div>';
473
474// End of page
475llxFooter();
476$db->close();
477