dolibarr  13.0.2
supplier_turnover_by_prodserv.php
Go to the documentation of this file.
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/tax.lib.php';
26 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
29 
30 // Load translation files required by the page
31 $langs->loadLangs(array("products", "categories", "errors", 'accountancy'));
32 
33 // Security pack (data & check)
34 $socid = GETPOST('socid', 'int');
35 
36 if ($user->socid > 0) $socid = $user->socid;
37 if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat');
38 if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
39 
40 // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
41 $modecompta = $conf->global->ACCOUNTING_MODE;
42 if (GETPOST("modecompta")) $modecompta = GETPOST("modecompta");
43 
44 $sortorder = isset($_GET["sortorder"]) ? $_GET["sortorder"] : $_POST["sortorder"];
45 $sortfield = isset($_GET["sortfield"]) ? $_GET["sortfield"] : $_POST["sortfield"];
46 if (!$sortorder) $sortorder = "asc";
47 if (!$sortfield) $sortfield = "ref";
48 
49 // Category
50 $selected_cat = (int) GETPOST('search_categ', 'int');
51 $selected_soc = (int) GETPOST('search_soc', 'int');
52 $subcat = false;
53 if (GETPOST('subcat', 'alpha') === 'yes') {
54  $subcat = true;
55 }
56 // product/service
57 $selected_type = GETPOST('search_type', 'int');
58 if ($selected_type == '') $selected_type = -1;
59 
60 // Hook
61 $hookmanager->initHooks(array('supplierturnoverbyprodservlist'));
62 
63 // Date range
64 $year = GETPOST("year");
65 $month = GETPOST("month");
66 $date_startyear = GETPOST("date_startyear");
67 $date_startmonth = GETPOST("date_startmonth");
68 $date_startday = GETPOST("date_startday");
69 $date_endyear = GETPOST("date_endyear");
70 $date_endmonth = GETPOST("date_endmonth");
71 $date_endday = GETPOST("date_endday");
72 if (empty($year))
73 {
74  $year_current = strftime("%Y", dol_now());
75  $month_current = strftime("%m", dol_now());
76  $year_start = $year_current;
77 } else {
78  $year_current = $year;
79  $month_current = strftime("%m", dol_now());
80  $year_start = $year;
81 }
82 $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"));
83 $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"));
84 // Quarter
85 if (empty($date_start) || empty($date_end)) // We define date_start and date_end
86 {
87  $q = GETPOST("q", "int");
88  if (empty($q))
89  {
90  // We define date_start and date_end
91  $month_start = GETPOST("month") ?GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
92  $year_end = $year_start;
93  $month_end = $month_start;
94  if (!GETPOST("month")) // If month not forced
95  {
96  if (!GETPOST('year') && $month_start > $month_current)
97  {
98  $year_start--;
99  $year_end--;
100  }
101  $month_end = $month_start - 1;
102  if ($month_end < 1) $month_end = 12;
103  else $year_end++;
104  }
105  $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false);
106  } else {
107  if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); }
108  if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); }
109  if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); }
110  if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); }
111  }
112 } else {
113  // TODO We define q
114 }
115 
116 // $date_start and $date_end are defined. We force $year_start and $nbofyear
117 $tmps = dol_getdate($date_start);
118 $year_start = $tmps['year'];
119 $tmpe = dol_getdate($date_end);
120 $year_end = $tmpe['year'];
121 $nbofyear = ($year_end - $year_start) + 1;
122 
123 $commonparams = array();
124 if (!empty($modecompta)) $commonparams['modecompta'] = $modecompta;
125 if (!empty($sortorder)) $commonparams['sortorder'] = $sortorder;
126 if (!empty($sortfield)) $commonparams['sortfield'] = $sortfield;
127 
128 $headerparams = array();
129 if (!empty($date_startyear)) $headerparams['date_startyear'] = $date_startyear;
130 if (!empty($date_startmonth)) $headerparams['date_startmonth'] = $date_startmonth;
131 if (!empty($date_startday)) $headerparams['date_startday'] = $date_startday;
132 if (!empty($date_endyear)) $headerparams['date_endyear'] = $date_endyear;
133 if (!empty($date_endmonth)) $headerparams['date_endmonth'] = $date_endmonth;
134 if (!empty($date_endday)) $headerparams['date_endday'] = $date_endday;
135 if (!empty($year)) $headerparams['year'] = $year;
136 if (!empty($month)) $headerparams['month'] = $month;
137 $headerparams['q'] = $q;
138 
139 $tableparams = array();
140 if (!empty($selected_cat)) $tableparams['search_categ'] = $selected_cat;
141 if (!empty($selected_soc)) $tableparams['search_soc'] = $selected_soc;
142 if (!empty($selected_type)) $tableparams['search_type'] = $selected_type;
143 $tableparams['subcat'] = ($subcat === true) ? 'yes' : '';
144 
145 // Adding common parameters
146 $allparams = array_merge($commonparams, $headerparams, $tableparams);
147 $headerparams = array_merge($commonparams, $headerparams);
148 $tableparams = array_merge($commonparams, $tableparams);
149 
150 foreach ($allparams as $key => $value) {
151  $paramslink .= '&'.$key.'='.$value;
152 }
153 
154 
155 /*
156  * View
157  */
158 
159 llxHeader();
160 
161 $form = new Form($db);
162 $formother = new FormOther($db);
163 
164 // TODO Report from bookkeeping not yet available, so we switch on report on business events
165 if ($modecompta == "BOOKKEEPING") $modecompta = "CREANCES-DETTES";
166 if ($modecompta == "BOOKKEEPINGCOLLECTED") $modecompta = "RECETTES-DEPENSES";
167 
168 // Show report header
169 if ($modecompta == "CREANCES-DETTES") {
170  $name = $langs->trans("PurchaseTurnover").', '.$langs->trans("ByProductsAndServices");
171  $calcmode = $langs->trans("CalcModeDebt");
172  //$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
173 
174  $description = $langs->trans("RulesPurchaseTurnoverDue");
175  $builddate = dol_now();
176 } elseif ($modecompta == "RECETTES-DEPENSES")
177 {
178  $name = $langs->trans("PurchaseTurnoverCollected").', '.$langs->trans("ByProductsAndServices");
179  $calcmode = $langs->trans("CalcModeEngagement");
180  //$calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=CREANCES-DETTES">','</a>').')';
181  $description = $langs->trans("RulesPurchaseTurnoverIn");
182 
183  $builddate = dol_now();
184 } elseif ($modecompta == "BOOKKEEPING")
185 {
186 } elseif ($modecompta == "BOOKKEEPINGCOLLECTED")
187 {
188 }
189 
190 $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
191 if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start - 1).'&modecompta='.$modecompta.'">'.img_previous().'</a> <a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start + 1).'&modecompta='.$modecompta.'">'.img_next().'</a>';
192 else $periodlink = '';
193 
194 report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $tableparams, $calcmode);
195 
196 if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING')
197 {
198  print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
199 }
200 
201 
202 
203 $name = array();
204 
205 // SQL request
206 $catotal = 0;
207 $catotal_ht = 0;
208 $qtytotal = 0;
209 
210 if ($modecompta == 'CREANCES-DETTES')
211 {
212  $sql = "SELECT DISTINCT p.rowid as rowid, p.ref as ref, p.label as label, p.fk_product_type as product_type,";
213  $sql .= " SUM(l.total_ht) as amount, SUM(l.total_ttc) as amount_ttc,";
214  $sql .= " SUM(CASE WHEN f.type = 2 THEN -l.qty ELSE l.qty END) as qty";
215  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
216  if ($selected_soc > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc ON (soc.rowid = f.fk_soc)";
217  $sql .= ",".MAIN_DB_PREFIX."facture_fourn_det as l";
218  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product = p.rowid";
219  if ($selected_cat === -2) // Without any category
220  {
221  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product";
222  } elseif ($selected_cat) // Into a specific category
223  {
224  $sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp";
225  }
226  $sql .= " WHERE l.fk_facture_fourn = f.rowid";
227  $sql .= " AND f.fk_statut in (1,2)";
228  $sql .= " AND f.type IN (0,2)";
229 
230  if ($date_start && $date_end) {
231  $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
232  }
233  if ($selected_type >= 0)
234  {
235  $sql .= " AND l.product_type = ".$selected_type;
236  }
237  if ($selected_cat === -2) // Without any category
238  {
239  $sql .= " AND cp.fk_product is null";
240  } elseif ($selected_cat) { // Into a specific category
241  $sql .= " AND (c.rowid = ".$selected_cat;
242  if ($subcat) $sql .= " OR c.fk_parent = ".$selected_cat;
243  $sql .= ")";
244  $sql .= " AND cp.fk_categorie = c.rowid AND cp.fk_product = p.rowid";
245  }
246  if ($selected_soc > 0) $sql .= " AND soc.rowid=".$selected_soc;
247  $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
248  $sql .= " GROUP BY p.rowid, p.ref, p.label, p.fk_product_type";
249  $sql .= $db->order($sortfield, $sortorder);
250 
251  dol_syslog("supplier_turnover_by_prodserv", LOG_DEBUG);
252  $result = $db->query($sql);
253  if ($result) {
254  $num = $db->num_rows($result);
255  $i = 0;
256  while ($i < $num) {
257  $obj = $db->fetch_object($result);
258  $amount_ht[$obj->rowid] = $obj->amount;
259  $amount[$obj->rowid] = $obj->amount_ttc;
260  $qty[$obj->rowid] = $obj->qty;
261  $name[$obj->rowid] = $obj->ref.'&nbsp;-&nbsp;'.$obj->label;
262  $type[$obj->rowid] = $obj->product_type;
263  $catotal_ht += $obj->amount;
264  $catotal += $obj->amount_ttc;
265  $qtytotal += $obj->qty;
266  $i++;
267  }
268  } else {
269  dol_print_error($db);
270  }
271 
272  // Show Array
273  $i = 0;
274  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
275  print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
276  // Extra parameters management
277  foreach ($headerparams as $key => $value)
278  {
279  print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
280  }
281 
282  $moreforfilter = '';
283 
284  print '<div class="div-table-responsive">';
285  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
286 
287  // Category filter
288  print '<tr class="liste_titre">';
289  print '<td>';
290  print $langs->trans("Category").': '.$formother->select_categories(Categorie::TYPE_PRODUCT, $selected_cat, 'search_categ', true);
291  print ' ';
292  print $langs->trans("SubCats").'? ';
293  print '<input type="checkbox" name="subcat" value="yes"';
294  if ($subcat) {
295  print ' checked';
296  }
297  print '>';
298  // type filter (produit/service)
299  print ' ';
300  print $langs->trans("Type").': ';
301  $form->select_type_of_lines(isset($selected_type) ? $selected_type : -1, 'search_type', 1, 1, 1);
302 
303  //select thirdparty
304  print '</br>';
305  print $langs->trans("ThirdParty").': '.$form->select_thirdparty_list($selected_soc, 'search_soc', '', 1);
306  print '</td>';
307 
308  print '<td colspan="5" class="right">';
309  print '<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"), 'search.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
310  print '</td></tr>';
311 
312  // Array header
313  print "<tr class=\"liste_titre\">";
315  $langs->trans("Product"),
316  $_SERVER["PHP_SELF"],
317  "ref",
318  "",
319  $paramslink,
320  "",
321  $sortfield,
322  $sortorder
323  );
325  $langs->trans('Quantity'),
326  $_SERVER["PHP_SELF"],
327  "qty",
328  "",
329  $paramslink,
330  'class="right"',
331  $sortfield,
332  $sortorder
333  );
335  $langs->trans("Percentage"),
336  $_SERVER["PHP_SELF"],
337  "qty",
338  "",
339  $paramslink,
340  'class="right"',
341  $sortfield,
342  $sortorder
343  );
345  $langs->trans('AmountHT'),
346  $_SERVER["PHP_SELF"],
347  "amount",
348  "",
349  $classslink,
350  'class="right"',
351  $sortfield,
352  $sortorder
353  );
355  $langs->trans("AmountTTC"),
356  $_SERVER["PHP_SELF"],
357  "amount_ttc",
358  "",
359  $paramslink,
360  'class="right"',
361  $sortfield,
362  $sortorder
363  );
365  $langs->trans("Percentage"),
366  $_SERVER["PHP_SELF"],
367  "amount_ttc",
368  "",
369  $paramslink,
370  'class="right"',
371  $sortfield,
372  $sortorder
373  );
374  print "</tr>\n";
375 
376  if (count($name)) {
377  foreach ($name as $key=>$value) {
378  print '<tr class="oddeven">';
379 
380  // Product
381  print "<td>";
382  $fullname = $name[$key];
383  if ($key > 0) {
384  $linkname = '<a href="'.DOL_URL_ROOT.'/product/card.php?id='.$key.'">'.img_object($langs->trans("ShowProduct"), $type[$key] == 0 ? 'product' : 'service').' '.$fullname.'</a>';
385  } else {
386  $linkname = $langs->trans("PaymentsNotLinkedToProduct");
387  }
388  print $linkname;
389  print "</td>\n";
390 
391  // Quantity
392  print '<td class="right">';
393  print $qty[$key];
394  print '</td>';
395 
396  // Percent;
397  print '<td class="right">'.($qtytotal > 0 ? round(100 * $qty[$key] / $qtytotal, 2).'%' : '&nbsp;').'</td>';
398 
399  // Amount w/o VAT
400  print '<td class="right">';
401  print price($amount_ht[$key]);
402  //print '</a>';
403  print '</td>';
404 
405  // Amount with VAT
406  print '<td class="right">';
407  print price($amount[$key]);
408  //print '</a>';
409  print '</td>';
410 
411  // Percent;
412  print '<td class="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal, 2).'%' : '&nbsp;').'</td>';
413 
414  // TODO: statistics?
415 
416  print "</tr>\n";
417  $i++;
418  }
419 
420  // Total
421  print '<tr class="liste_total">';
422  print '<td>'.$langs->trans("Total").'</td>';
423  print '<td class="right">'.$qtytotal.'</td>';
424  print '<td class="right">100%</td>';
425  print '<td class="right">'.price($catotal_ht).'</td>';
426  print '<td class="right">'.price($catotal).'</td>';
427  print '<td class="right">100%</td>';
428  print '</tr>';
429 
430  $db->free($result);
431  }
432  print "</table>";
433  print '</div>';
434 
435  print '</form>';
436 } else {
437  // $modecompta != 'CREANCES-DETTES'
438  // "Calculation of part of each product for accountancy in this mode is not possible. When a partial payment (for example 5 euros) is done on an
439  // invoice with 2 product (product A for 10 euros and product B for 20 euros), what is part of paiment for product A and part of paiment for product B ?
440  // Because there is no way to know this, this report is not relevant.
441  print '<br>'.$langs->trans("TurnoverPerProductInCommitmentAccountingNotRelevant").'<br>';
442 }
443 
444 // End of page
445 llxFooter();
446 $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.
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
Classe permettant la generation de composants html autre Only common components are here...
dol_getdate($timestamp, $fast=false, $forcetimezone= '')
Return an array with locale date info.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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
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
dol_time_plus_duree($time, $duration_value, $duration_unit)
Add a delay to a date.
Definition: date.lib.php:114
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin= '1', $morecss= '', $textfordropdown= '')
Show information for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...