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