dolibarr  13.0.2
supplier_turnover.php
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 
23 require '../../main.inc.php';
24 require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
25 require_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');
41 if (empty($year))
42 {
43  $year_current = strftime("%Y", dol_now());
44  $month_current = strftime("%m", dol_now());
45  $year_start = $year_current - ($nbofyear - 1);
46 } else {
47  $year_current = $year;
48  $month_current = strftime("%m", dol_now());
49  $year_start = $year - ($nbofyear - 1);
50 }
51 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
52 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
53 
54 // We define date_start and date_end
55 if (empty($date_start) || empty($date_end)) // We define date_start and date_end
56 {
57  $q = GETPOST("q") ?GETPOST("q") : 0;
58  if ($q == 0)
59  {
60  // We define date_start and date_end
61  $year_end = $year_start + ($nbofyear - 1);
62  $month_start = GETPOST("month") ? GETPOST("month", 'int') : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
63  if (!GETPOST('month'))
64  {
65  if (!GETPOST("year") && $month_start > $month_current)
66  {
67  $year_start--;
68  $year_end--;
69  }
70  $month_end = $month_start - 1;
71  if ($month_end < 1) $month_end = 12;
72  } else $month_end = $month_start;
73  $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false);
74  }
75  if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); }
76  if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); }
77  if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); }
78  if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); }
79 }
80 
81 $userid = GETPOST('userid', 'int');
82 $socid = GETPOST('socid', 'int');
83 
84 $tmps = dol_getdate($date_start);
85 $year_start = $tmps['year'];
86 $tmpe = dol_getdate($date_end);
87 $year_end = $tmpe['year'];
88 $nbofyear = ($year_end - $year_start) + 1;
89 
90 // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING')
91 $modecompta = $conf->global->ACCOUNTING_MODE;
92 if (!empty($conf->accounting->enabled)) $modecompta = 'BOOKKEEPING';
93 if (GETPOST("modecompta")) $modecompta = GETPOST("modecompta", 'alpha');
94 
95 // Security check
96 if ($user->socid > 0) $socid = $user->socid;
97 if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat');
98 if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
99 
100 
101 
102 
103 /*
104  * View
105  */
106 
107 llxHeader();
108 
109 $form = new Form($db);
110 
111 // Affiche en-tete du rapport
112 if ($modecompta == "CREANCES-DETTES")
113 {
114  $name = $langs->trans("PurchaseTurnover");
115  $calcmode = $langs->trans("CalcModeDebt");
116  $calcmode .= '<br>('.$langs->trans("SeeReportInBookkeepingMode", '{link1}', '{link2}').')';
117  $calcmode = str_replace('{link1}', '<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=BOOKKEEPING">', $calcmode);
118  $calcmode = str_replace('{link2}', '</a>', $calcmode);
119  $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
120  $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>" : "");
121  $description = $langs->trans("RulesPurchaseTurnoverDue");
122  $builddate = dol_now();
123  //$exportlink=$langs->trans("NotYetAvailable");
124 } elseif ($modecompta == "RECETTES-DEPENSES")
125 {
126  $name = $langs->trans("PurchaseTurnoverCollected");
127  $calcmode = $langs->trans("CalcModeEngagement");
128  $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
129  $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>" : "");
130  $description = $langs->trans("RulesPurchaseTurnoverIn");
131  $builddate = dol_now();
132  //$exportlink=$langs->trans("NotYetAvailable");
133 } elseif ($modecompta == "BOOKKEEPING")
134 {
135  $name = $langs->trans("PurchaseTurnover");
136  $calcmode = $langs->trans("CalcModeBookkeeping");
137  $calcmode .= '<br>('.$langs->trans("SeeReportInDueDebtMode", '{link1}', '{link2}').')';
138  $calcmode = str_replace('{link1}', '<a href="'.$_SERVER["PHP_SELF"].'?year_start='.$year_start.'&modecompta=CREANCES-DETTES">', $calcmode);
139  $calcmode = str_replace('{link2}', '</a>', $calcmode);
140  $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
141  $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>" : "");
142  $description = $langs->trans("RulesPurchaseTurnoverTotalPurchaseJournal");
143  $builddate = dol_now();
144  //$exportlink=$langs->trans("NotYetAvailable");
145 }
146 
147 $moreparam = array();
148 if (!empty($modecompta)) $moreparam['modecompta'] = $modecompta;
149 report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $moreparam, $calcmode);
150 
151 if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING')
152 {
153  print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
154 }
155 
156 
157 if ($modecompta == 'CREANCES-DETTES')
158 {
159  $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_ht) as amount, sum(f.total_ttc) as amount_ttc";
160  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
161  $sql .= " WHERE f.fk_statut in (1,2)";
162  $sql .= " AND f.type IN (0,2)";
163  $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
164  if ($socid) $sql .= " AND f.fk_soc = ".$socid;
165 } elseif ($modecompta == "RECETTES-DEPENSES")
166 {
167  $sql = "SELECT date_format(p.datep,'%Y-%m') as dm, sum(pf.amount) as amount_ttc";
168  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
169  $sql .= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf";
170  $sql .= ", ".MAIN_DB_PREFIX."paiementfourn as p";
171  $sql .= " WHERE p.rowid = pf.fk_paiementfourn";
172  $sql .= " AND pf.fk_facturefourn = f.rowid";
173  $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
174  if ($socid) $sql .= " AND f.fk_soc = ".$socid;
175 } elseif ($modecompta == "BOOKKEEPING")
176 {
177  $sql = "SELECT date_format(b.doc_date,'%Y-%m') as dm, sum(b.debit) as amount_ttc";
178  $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b, ".MAIN_DB_PREFIX."accounting_journal as aj";
179  $sql .= " WHERE b.entity = ".$conf->entity; // In module double party accounting, we never share entities
180  $sql .= " AND aj.entity = ".$conf->entity;
181  $sql .= " AND b.code_journal = aj.code AND aj.nature = 3"; // @todo currently count amount in sale journal, but we need to define a category group for turnover
182 }
183 
184 $sql .= " GROUP BY dm";
185 $sql .= " ORDER BY dm";
186 // TODO Add a filter on $date_start and $date_end to reduce quantity on data
187 //print $sql;
188 
189 $minyearmonth = $maxyearmonth = 0;
190 
191 $result = $db->query($sql);
192 if ($result)
193 {
194  $num = $db->num_rows($result);
195  $i = 0;
196  while ($i < $num)
197  {
198  $obj = $db->fetch_object($result);
199  $cum_ht[$obj->dm] = !empty($obj->amount) ? $obj->amount : 0;
200  $cum[$obj->dm] = $obj->amount_ttc;
201  if ($obj->amount_ttc)
202  {
203  $minyearmonth = ($minyearmonth ? min($minyearmonth, $obj->dm) : $obj->dm);
204  $maxyearmonth = max($maxyearmonth, $obj->dm);
205  }
206  $i++;
207  }
208  $db->free($result);
209 } else {
210  dol_print_error($db);
211 }
212 
213 $moreforfilter = '';
214 
215 print '<div class="div-table-responsive">';
216 print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
217 
218 print '<tr class="liste_titre"><td>&nbsp;</td>';
219 
220 for ($annee = $year_start; $annee <= $year_end; $annee++)
221 {
222  if ($modecompta == 'CREANCES-DETTES') print '<td align="center" width="10%" colspan="3">';
223  else print '<td align="center" width="10%" colspan="2" class="borderrightlight">';
224  if ($modecompta != 'BOOKKEEPING') print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee.($modecompta ? '&modecompta='.$modecompta : '').'">';
225  print $annee;
226  if ($conf->global->SOCIETE_FISCAL_MONTH_START > 1) print '-'.($annee + 1);
227  if ($modecompta != 'BOOKKEEPING') print '</a>';
228  print '</td>';
229  if ($annee != $year_end) print '<td width="15">&nbsp;</td>';
230 }
231 print '</tr>';
232 
233 print '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Month").'</td>';
234 for ($annee = $year_start; $annee <= $year_end; $annee++)
235 {
236  if ($modecompta == 'CREANCES-DETTES') print '<td class="liste_titre right">'.$langs->trans("AmountHT").'</td>';
237  print '<td class="liste_titre right">'.$langs->trans("AmountTTC").'</td>';
238  print '<td class="liste_titre right borderrightlight">'.$langs->trans("Delta").'</td>';
239  if ($annee != $year_end) print '<td class="liste_titre" width="15">&nbsp;</td>';
240 }
241 print '</tr>';
242 
243 $now_show_delta = 0;
244 $minyear = substr($minyearmonth, 0, 4);
245 $maxyear = substr($maxyearmonth, 0, 4);
246 $nowyear = strftime("%Y", dol_now());
247 $nowyearmonth = strftime("%Y-%m", dol_now());
248 $maxyearmonth = max($maxyearmonth, $nowyearmonth);
249 $now = dol_now();
250 $casenow = dol_print_date($now, "%Y-%m");
251 
252 // Loop on each month
253 $nb_mois_decalage = $conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START - 1) : 0;
254 for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++)
255 {
256  $mois_modulo = $mois; // ajout
257  if ($mois > 12) {$mois_modulo = $mois - 12; } // ajout
258 
259  if ($year_start == $year_end) {
260  if ($mois > $date_endmonth && $year_end >= $date_endyear) {
261  break;
262  }
263  }
264 
265  print '<tr class="oddeven">';
266 
267  // Month
268  print "<td>".dol_print_date(dol_mktime(12, 0, 0, $mois_modulo, 1, 2000), "%B")."</td>";
269 
270  for ($annee = $year_start - 1; $annee <= $year_end; $annee++) // We start one year before to have data to be able to make delta
271  {
272  $annee_decalage = $annee;
273  if ($mois > 12) {$annee_decalage = $annee + 1; }
274  $case = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage), "%Y-%m");
275  $caseprev = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage - 1), "%Y-%m");
276 
277  if ($annee >= $year_start) // We ignore $annee < $year_start, we loop on it to be able to make delta, nothing is output.
278  {
279  if ($modecompta == 'CREANCES-DETTES') {
280  // Valeur CA du mois w/o VAT
281  print '<td class="right">';
282  if ($cum_ht[$case])
283  {
284  $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
285  print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">'.price($cum_ht[$case], 1).'</a>';
286  } else {
287  if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print '&nbsp;'; }
288  }
289  print "</td>";
290  }
291 
292  // Valeur CA du mois
293  print '<td class="right">';
294  if ($cum[$case])
295  {
296  $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre.
297  if ($modecompta != 'BOOKKEEPING') print '<a href="supplier_turnover_by_thirdparty.php?year='.$annee_decalage.'&month='.$mois_modulo.($modecompta ? '&modecompta='.$modecompta : '').'">';
298  print price($cum[$case], 1);
299  if ($modecompta != 'BOOKKEEPING') print '</a>';
300  } else {
301  if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print '&nbsp;'; }
302  }
303  print "</td>";
304 
305  // Pourcentage du mois
306  if ($annee_decalage > $minyear && $case <= $casenow)
307  {
308  if ($cum[$caseprev] && $cum[$case])
309  {
310  $percent = (round(($cum[$case] - $cum[$caseprev]) / $cum[$caseprev], 4) * 100);
311  //print "X $cum[$case] - $cum[$caseprev] - $cum[$caseprev] - $percent X";
312  print '<td class="borderrightlight right">'.($percent >= 0 ? "+$percent" : "$percent").'%</td>';
313  }
314  if ($cum[$caseprev] && !$cum[$case])
315  {
316  print '<td class="borderrightlight right">-100%</td>';
317  }
318  if (!$cum[$caseprev] && $cum[$case])
319  {
320  //print '<td class="right">+Inf%</td>';
321  print '<td class="borderrightlight right">-</td>';
322  }
323  if (isset($cum[$caseprev]) && !$cum[$caseprev] && !$cum[$case])
324  {
325  print '<td class="borderrightlight right">+0%</td>';
326  }
327  if (!isset($cum[$caseprev]) && !$cum[$case])
328  {
329  print '<td class="borderrightlight right">-</td>';
330  }
331  } else {
332  print '<td class="borderrightlight right">';
333  if ($minyearmonth <= $case && $case <= $maxyearmonth) { print '-'; } else { print '&nbsp;'; }
334  print '</td>';
335  }
336 
337  if ($annee_decalage < $year_end || ($annee_decalage == $year_end && $mois > 12 && $annee < $year_end)) print '<td width="15">&nbsp;</td>';
338  }
339 
340  $total_ht[$annee] += ((!empty($cum_ht[$case])) ? $cum_ht[$case] : 0);
341  $total[$annee] += $cum[$case];
342  }
343 
344  print '</tr>';
345 }
346 
347 // Affiche total
348 print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td>';
349 for ($annee = $year_start; $annee <= $year_end; $annee++)
350 {
351  if ($modecompta == 'CREANCES-DETTES') {
352  // Montant total HT
353  if ($total_ht[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear)))
354  {
355  print '<td class="nowrap right">'.($total_ht[$annee] ?price($total_ht[$annee]) : "0")."</td>";
356  } else {
357  print '<td>&nbsp;</td>';
358  }
359  }
360 
361  // Montant total
362  if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear)))
363  {
364  print '<td class="nowrap right">'.($total[$annee] ?price($total[$annee]) : "0")."</td>";
365  } else {
366  print '<td>&nbsp;</td>';
367  }
368 
369  // Pourcentage total
370  if ($annee > $minyear && $annee <= max($nowyear, $maxyear))
371  {
372  if ($total[$annee - 1] && $total[$annee]) {
373  $percent = (round(($total[$annee] - $total[$annee - 1]) / $total[$annee - 1], 4) * 100);
374  print '<td class="nowrap borderrightlight right">'.($percent >= 0 ? "+$percent" : "$percent").'%</td>';
375  }
376  if ($total[$annee - 1] && !$total[$annee])
377  {
378  print '<td class="borderrightlight right">-100%</td>';
379  }
380  if (!$total[$annee - 1] && $total[$annee])
381  {
382  print '<td class="borderrightlight right">+'.$langs->trans('Inf').'%</td>';
383  }
384  if (!$total[$annee - 1] && !$total[$annee])
385  {
386  print '<td class="borderrightlight right">+0%</td>';
387  }
388  } else {
389  print '<td class="borderrightlight right">';
390  if ($total[$annee] || ($minyear <= $annee && $annee <= max($nowyear, $maxyear))) { print '-'; } else { print '&nbsp;'; }
391  print '</td>';
392  }
393 
394  if ($annee != $year_end) print '<td width="15">&nbsp;</td>';
395 }
396 print "</tr>\n";
397 print "</table>";
398 print '</div>';
399 
400 // End of page
401 llxFooter();
402 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_now($mode= 'auto')
Return date for now.
report_header($reportname, $notused, $period, $periodlink, $description, $builddate, $exportlink= '', $moreparam=array(), $calcmode= '', $varlink= '')
Show header of a report.
Definition: report.lib.php:41
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:481
price($amount, $form=0, $outlangs= '', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code= '')
Function to format a value into an amount for visual output Function used into PDF and HTML pages...
llxHeader()
Empty header.
Definition: wrapper.php:45
Class to manage generation of HTML components Only common components must be here.
dol_getdate($timestamp, $fast=false, $forcetimezone= '')
Return an array with locale date info.
restrictedArea($user, $features, $objectid=0, $tableandshare= '', $feature2= '', $dbt_keyfield= 'fk_soc', $dbt_select= 'rowid', $isdraft=0)
Check permissions of a user to show a page and an object.
print $_SERVER["PHP_SELF"]
Edit parameters.
img_next($titlealt= 'default', $moreatt= '')
Show next logo.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:498
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
img_previous($titlealt= 'default', $moreatt= '')
Show previous logo.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
llxFooter()
Empty footer.
Definition: wrapper.php:59
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin= '1', $morecss= '', $textfordropdown= '')
Show information for admin users or standard users.