dolibarr  13.0.2
cabyprodserv.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2013 Antoine Iauch <aiauch@gpcsolutions.fr>
3  * Copyright (C) 2013-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
5  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
26 require '../../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
32 
33 // Load translation files required by the page
34 $langs->loadLangs(array("products", "categories", "errors", 'accountancy'));
35 
36 // Security pack (data & check)
37 $socid = GETPOST('socid', 'int');
38 
39 if ($user->socid > 0) $socid = $user->socid;
40 if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat');
41 if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
42 
43 // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
44 $modecompta = $conf->global->ACCOUNTING_MODE;
45 if (GETPOST("modecompta")) $modecompta = GETPOST("modecompta");
46 
47 $sortorder = isset($_GET["sortorder"]) ? $_GET["sortorder"] : $_POST["sortorder"];
48 $sortfield = isset($_GET["sortfield"]) ? $_GET["sortfield"] : $_POST["sortfield"];
49 if (!$sortorder) $sortorder = "asc";
50 if (!$sortfield) $sortfield = "ref";
51 
52 // Category
53 $selected_cat = (int) GETPOST('search_categ', 'int');
54 $selected_soc = (int) GETPOST('search_soc', 'int');
55 $subcat = false;
56 if (GETPOST('subcat', 'alpha') === 'yes') {
57  $subcat = true;
58 }
59 $categorie = new Categorie($db);
60 
61 // product/service
62 $selected_type = GETPOST('search_type', 'int');
63 if ($selected_type == '') $selected_type = -1;
64 
65 // Hook
66 $hookmanager->initHooks(array('cabyprodservlist'));
67 
68 // Date range
69 $year = GETPOST("year");
70 $month = GETPOST("month");
71 $date_startyear = GETPOST("date_startyear");
72 $date_startmonth = GETPOST("date_startmonth");
73 $date_startday = GETPOST("date_startday");
74 $date_endyear = GETPOST("date_endyear");
75 $date_endmonth = GETPOST("date_endmonth");
76 $date_endday = GETPOST("date_endday");
77 if (empty($year))
78 {
79  $year_current = strftime("%Y", dol_now());
80  $month_current = strftime("%m", dol_now());
81  $year_start = $year_current;
82 } else {
83  $year_current = $year;
84  $month_current = strftime("%m", dol_now());
85  $year_start = $year;
86 }
87 $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"));
88 $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"));
89 // Quarter
90 if (empty($date_start) || empty($date_end)) // We define date_start and date_end
91 {
92  $q = GETPOST("q", "int");
93  if (empty($q))
94  {
95  // We define date_start and date_end
96  $month_start = GETPOST("month") ?GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
97  $year_end = $year_start;
98  $month_end = $month_start;
99  if (!GETPOST("month")) // If month not forced
100  {
101  if (!GETPOST('year') && $month_start > $month_current)
102  {
103  $year_start--;
104  $year_end--;
105  }
106  $month_end = $month_start - 1;
107  if ($month_end < 1) $month_end = 12;
108  else $year_end++;
109  }
110  $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false);
111  } else {
112  if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); }
113  if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); }
114  if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); }
115  if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); }
116  }
117 } else {
118  // TODO We define q
119 }
120 
121 // $date_start and $date_end are defined. We force $year_start and $nbofyear
122 $tmps = dol_getdate($date_start);
123 $year_start = $tmps['year'];
124 $tmpe = dol_getdate($date_end);
125 $year_end = $tmpe['year'];
126 $nbofyear = ($year_end - $year_start) + 1;
127 
128 $commonparams = array();
129 if (!empty($modecompta)) $commonparams['modecompta'] = $modecompta;
130 if (!empty($sortorder)) $commonparams['sortorder'] = $sortorder;
131 if (!empty($sortfield)) $commonparams['sortfield'] = $sortfield;
132 
133 $headerparams = array();
134 if (!empty($date_startyear)) $headerparams['date_startyear'] = $date_startyear;
135 if (!empty($date_startmonth)) $headerparams['date_startmonth'] = $date_startmonth;
136 if (!empty($date_startday)) $headerparams['date_startday'] = $date_startday;
137 if (!empty($date_endyear)) $headerparams['date_endyear'] = $date_endyear;
138 if (!empty($date_endmonth)) $headerparams['date_endmonth'] = $date_endmonth;
139 if (!empty($date_endday)) $headerparams['date_endday'] = $date_endday;
140 if (!empty($year)) $headerparams['year'] = $year;
141 if (!empty($month)) $headerparams['month'] = $month;
142 $headerparams['q'] = $q;
143 
144 $tableparams = array();
145 if (!empty($selected_cat)) $tableparams['search_categ'] = $selected_cat;
146 if (!empty($selected_soc)) $tableparams['search_soc'] = $selected_soc;
147 if (!empty($selected_type)) $tableparams['search_type'] = $selected_type;
148 $tableparams['subcat'] = ($subcat === true) ? 'yes' : '';
149 
150 // Adding common parameters
151 $allparams = array_merge($commonparams, $headerparams, $tableparams);
152 $headerparams = array_merge($commonparams, $headerparams);
153 $tableparams = array_merge($commonparams, $tableparams);
154 
155 foreach ($allparams as $key => $value) {
156  $paramslink .= '&'.$key.'='.$value;
157 }
158 
159 
160 /*
161  * View
162  */
163 
164 llxHeader();
165 
166 $form = new Form($db);
167 $formother = new FormOther($db);
168 
169 // TODO Report from bookkeeping not yet available, so we switch on report on business events
170 if ($modecompta == "BOOKKEEPING") $modecompta = "CREANCES-DETTES";
171 if ($modecompta == "BOOKKEEPINGCOLLECTED") $modecompta = "RECETTES-DEPENSES";
172 
173 // Show report header
174 if ($modecompta == "CREANCES-DETTES") {
175  $name = $langs->trans("Turnover").', '.$langs->trans("ByProductsAndServices");
176  $calcmode = $langs->trans("CalcModeDebt");
177  //$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
178 
179  $description = $langs->trans("RulesCADue");
180  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
181  $description .= $langs->trans("DepositsAreNotIncluded");
182  } else {
183  $description .= $langs->trans("DepositsAreIncluded");
184  }
185 
186  $builddate = dol_now();
187 } elseif ($modecompta == "RECETTES-DEPENSES")
188 {
189  $name = $langs->trans("TurnoverCollected").', '.$langs->trans("ByProductsAndServices");
190  $calcmode = $langs->trans("CalcModeEngagement");
191  //$calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=CREANCES-DETTES">','</a>').')';
192 
193  $description = $langs->trans("RulesCAIn");
194  $description .= $langs->trans("DepositsAreIncluded");
195 
196  $builddate = dol_now();
197 } elseif ($modecompta == "BOOKKEEPING")
198 {
199 } elseif ($modecompta == "BOOKKEEPINGCOLLECTED")
200 {
201 }
202 
203 $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
204 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>';
205 else $periodlink = '';
206 
207 report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $tableparams, $calcmode);
208 
209 if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING')
210 {
211  print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
212 }
213 
214 
215 
216 $name = array();
217 
218 // SQL request
219 $catotal = 0;
220 $catotal_ht = 0;
221 $qtytotal = 0;
222 
223 if ($modecompta == 'CREANCES-DETTES')
224 {
225  $sql = "SELECT DISTINCT p.rowid as rowid, p.ref as ref, p.label as label, p.fk_product_type as product_type,";
226  $sql .= " SUM(l.total_ht) as amount, SUM(l.total_ttc) as amount_ttc,";
227  $sql .= " SUM(CASE WHEN f.type = 2 THEN -l.qty ELSE l.qty END) as qty";
228  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
229  if ($selected_soc > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc ON (soc.rowid = f.fk_soc)";
230  $sql .= ",".MAIN_DB_PREFIX."facturedet as l";
231  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product = p.rowid";
232  if ($selected_cat === -2) { // Without any category
233  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product";
234  } elseif ($selected_cat) { // Into a specific category
235  $sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp";
236  }
237  $sql .= " WHERE l.fk_facture = f.rowid";
238  $sql .= " AND f.fk_statut in (1,2)";
239  $sql .= " AND l.product_type in (0,1)";
240  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
241  $sql .= " AND f.type IN (0,1,2,5)";
242  } else {
243  $sql .= " AND f.type IN (0,1,2,3,5)";
244  }
245  if ($date_start && $date_end) {
246  $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
247  }
248  if ($selected_type >= 0)
249  {
250  $sql .= " AND l.product_type = ".$selected_type;
251  }
252  if ($selected_cat === -2) { // Without any category
253  $sql .= " AND cp.fk_product is null";
254  } elseif ($selected_cat) { // Into a specific category
255  if ($subcat) {
256  $TListOfCats = $categorie->get_full_arbo('product', $selected_cat, 1);
257 
258  $listofcatsql = "";
259  foreach ($TListOfCats as $key => $cat)
260  {
261  if ($key !== 0) $listofcatsql .= ",";
262  $listofcatsql .= $cat['rowid'];
263  }
264  }
265 
266  $sql .= " AND (p.rowid IN ";
267  $sql .= " (SELECT fk_product FROM ".MAIN_DB_PREFIX."categorie_product cp WHERE ";
268  if ($subcat) $sql .= "cp.fk_categorie IN (".$listofcatsql.")";
269  else $sql .= "cp.fk_categorie = ".$selected_cat;
270  $sql .= "))";
271  }
272  if ($selected_soc > 0) $sql .= " AND soc.rowid=".$selected_soc;
273  $sql .= " AND f.entity IN (".getEntity('invoice').")";
274  $sql .= " GROUP BY p.rowid, p.ref, p.label, p.fk_product_type";
275  $sql .= $db->order($sortfield, $sortorder);
276 
277  dol_syslog("cabyprodserv", LOG_DEBUG);
278  $result = $db->query($sql);
279  if ($result) {
280  $num = $db->num_rows($result);
281  $i = 0;
282  while ($i < $num) {
283  $obj = $db->fetch_object($result);
284  $amount_ht[$obj->rowid] = $obj->amount;
285  $amount[$obj->rowid] = $obj->amount_ttc;
286  $qty[$obj->rowid] = $obj->qty;
287  $name[$obj->rowid] = $obj->ref.'&nbsp;-&nbsp;'.$obj->label;
288  $type[$obj->rowid] = $obj->product_type;
289  $catotal_ht += $obj->amount;
290  $catotal += $obj->amount_ttc;
291  $qtytotal += $obj->qty;
292  $i++;
293  }
294  } else {
295  dol_print_error($db);
296  }
297 
298  // Show Array
299  $i = 0;
300  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
301  print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
302  // Extra parameters management
303  foreach ($headerparams as $key => $value)
304  {
305  print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
306  }
307 
308  $moreforfilter = '';
309 
310  print '<div class="div-table-responsive">';
311  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
312 
313  // Category filter
314  print '<tr class="liste_titre">';
315  print '<td>';
316  print $langs->trans("Category").': '.$formother->select_categories(Categorie::TYPE_PRODUCT, $selected_cat, 'search_categ', true);
317  print ' ';
318  print $langs->trans("SubCats").'? ';
319  print '<input type="checkbox" name="subcat" value="yes"';
320  if ($subcat) {
321  print ' checked';
322  }
323  print '>';
324  // type filter (produit/service)
325  print ' ';
326  print $langs->trans("Type").': ';
327  $form->select_type_of_lines(isset($selected_type) ? $selected_type : -1, 'search_type', 1, 1, 1);
328 
329  //select thirdparty
330  print '</br>';
331  print $langs->trans("ThirdParty").': '.$form->select_thirdparty_list($selected_soc, 'search_soc', '', 1);
332  print '</td>';
333 
334  print '<td colspan="5" class="right">';
335  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")).'">';
336  print '</td></tr>';
337 
338  // Array header
339  print "<tr class=\"liste_titre\">";
341  $langs->trans("Product"),
342  $_SERVER["PHP_SELF"],
343  "ref",
344  "",
345  $paramslink,
346  "",
347  $sortfield,
348  $sortorder
349  );
351  $langs->trans('Quantity'),
352  $_SERVER["PHP_SELF"],
353  "qty",
354  "",
355  $paramslink,
356  'class="right"',
357  $sortfield,
358  $sortorder
359  );
361  $langs->trans("Percentage"),
362  $_SERVER["PHP_SELF"],
363  "qty",
364  "",
365  $paramslink,
366  'class="right"',
367  $sortfield,
368  $sortorder
369  );
371  $langs->trans('AmountHT'),
372  $_SERVER["PHP_SELF"],
373  "amount",
374  "",
375  $classslink,
376  'class="right"',
377  $sortfield,
378  $sortorder
379  );
381  $langs->trans("AmountTTC"),
382  $_SERVER["PHP_SELF"],
383  "amount_ttc",
384  "",
385  $paramslink,
386  'class="right"',
387  $sortfield,
388  $sortorder
389  );
391  $langs->trans("Percentage"),
392  $_SERVER["PHP_SELF"],
393  "amount_ttc",
394  "",
395  $paramslink,
396  'class="right"',
397  $sortfield,
398  $sortorder
399  );
400  print "</tr>\n";
401 
402  if (count($name)) {
403  foreach ($name as $key=>$value) {
404  print '<tr class="oddeven">';
405 
406  // Product
407  print "<td>";
408  $fullname = $name[$key];
409  if ($key > 0) {
410  $linkname = '<a href="'.DOL_URL_ROOT.'/product/card.php?id='.$key.'">'.img_object($langs->trans("ShowProduct"), $type[$key] == 0 ? 'product' : 'service').' '.$fullname.'</a>';
411  } else {
412  $linkname = $langs->trans("PaymentsNotLinkedToProduct");
413  }
414  print $linkname;
415  print "</td>\n";
416 
417  // Quantity
418  print '<td class="right">';
419  print $qty[$key];
420  print '</td>';
421 
422  // Percent;
423  print '<td class="right">'.($qtytotal > 0 ? round(100 * $qty[$key] / $qtytotal, 2).'%' : '&nbsp;').'</td>';
424 
425  // Amount w/o VAT
426  print '<td class="right">';
427  /*if ($key > 0) {
428  print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?productid='.$key.'">';
429  } else {
430  print '<a href="#">';
431  }*/
432  print price($amount_ht[$key]);
433  //print '</a>';
434  print '</td>';
435 
436  // Amount with VAT
437  print '<td class="right">';
438  /*if ($key > 0) {
439  print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?productid='.$key.'">';
440  } else {
441  print '<a href="#">';
442  }*/
443  print price($amount[$key]);
444  //print '</a>';
445  print '</td>';
446 
447  // Percent;
448  print '<td class="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal, 2).'%' : '&nbsp;').'</td>';
449 
450  // TODO: statistics?
451 
452  print "</tr>\n";
453  $i++;
454  }
455 
456  // Total
457  print '<tr class="liste_total">';
458  print '<td>'.$langs->trans("Total").'</td>';
459  print '<td class="right">'.$qtytotal.'</td>';
460  print '<td class="right">100%</td>';
461  print '<td class="right">'.price($catotal_ht).'</td>';
462  print '<td class="right">'.price($catotal).'</td>';
463  print '<td class="right">100%</td>';
464  print '</tr>';
465 
466  $db->free($result);
467  }
468  print "</table>";
469  print '</div>';
470 
471  print '</form>';
472 } else {
473  // $modecompta != 'CREANCES-DETTES'
474  // "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
475  // 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 ?
476  // Because there is no way to know this, this report is not relevant.
477  print '<br>'.$langs->trans("TurnoverPerProductInCommitmentAccountingNotRelevant").'<br>';
478 }
479 
480 // End of page
481 llxFooter();
482 $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.
Class to manage categories.
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...