dolibarr  16.0.5
productMargins.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
3  * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
4  * Copyright (C) 2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  */
19 
26 require '../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
31 
32 // Load translation files required by the page
33 $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
34 
35 $id = GETPOST('id', 'int');
36 $ref = GETPOST('ref', 'alpha');
37 $action = GETPOST('action', 'aZ09');
38 $confirm = GETPOST('confirm', 'alpha');
39 $TSelectedCats = GETPOST('categories', 'array');
40 
41 // Security check
42 $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
43 $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
44 if (!empty($user->socid)) {
45  $socid = $user->socid;
46 }
47 $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
48 if (empty($user->rights->margins->liretous)) {
50 }
51 
52 $mesg = '';
53 
54 // Load variable for pagination
55 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
56 $sortfield = GETPOST('sortfield', 'aZ09comma');
57 $sortorder = GETPOST('sortorder', 'aZ09comma');
58 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
59 if (empty($page) || $page == -1) {
60  $page = 0;
61 } // If $page is not defined, or '' or -1
62 $offset = $limit * $page;
63 $pageprev = $page - 1;
64 $pagenext = $page + 1;
65 if (!$sortfield) {
66  if ($id > 0) {
67  $sortfield = "f.datef";
68  $sortorder = "DESC";
69  } else {
70  $sortfield = "p.ref";
71  $sortorder = "ASC";
72  }
73 }
74 
75 $startdate = $enddate = '';
76 if (GETPOST('startdatemonth')) {
77  $startdate = dol_mktime(0, 0, 0, GETPOST('startdatemonth', 'int'), GETPOST('startdateday', 'int'), GETPOST('startdateyear', 'int'));
78 }
79 if (GETPOST('enddatemonth')) {
80  $enddate = dol_mktime(23, 59, 59, GETPOST('enddatemonth', 'int'), GETPOST('enddateday', 'int'), GETPOST('enddateyear'));
81 }
82 
83 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
84 $object = new Product($db);
85 $hookmanager->initHooks(array('marginproductlist'));
86 
87 
88 /*
89  * View
90  */
91 
92 $product_static = new Product($db);
93 $invoicestatic = new Facture($db);
94 
95 $form = new Form($db);
96 
97 llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Products"));
98 
99 $text = $langs->trans("Margins");
100 //print load_fiche_titre($text);
101 
102 // Show tabs
103 $head = marges_prepare_head($user);
104 $titre = $langs->trans("Margins");
105 $picto = 'margin';
106 
107 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
108 print '<input type="hidden" name="token" value="'.newToken().'">';
109 
110 print dol_get_fiche_head($head, 'productMargins', $titre, 0, $picto);
111 
112 print '<table class="border centpercent">';
113 
114 // Product
115 print '<tr><td class="titlefield">'.$langs->trans('ProductOrService').'</td>';
116 print '<td class="maxwidthonsmartphone" colspan="4">';
117 print img_picto('', 'product').$form->select_produits(($id > 0 ? $id : ''), 'id', '', 20, 0, 1, 2, '', 1, array(), 0, 'All', 0, '', 0, '', null, 1);
118 print '</td></tr>';
119 
120 // Categories
121 $TCats = $form->select_all_categories(0, array(), '', 64, 0, 1);
122 
123 print '<tr>';
124 print '<td class="titlefield">'.$langs->trans('Category').'</td>';
125 print '<td class="maxwidthonsmartphone" colspan="4">';
126 print img_picto('', 'category').$form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'quatrevingtpercent widthcentpercentminusx');
127 print '</td>';
128 print '</tr>';
129 
130 // Start date
131 print '<tr>';
132 print '<td class="titlefield">'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
133 print '<td>';
134 print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
135 print '</td>';
136 print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
137 print '<td>';
138 print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
139 print '</td>';
140 print '<td style="text-align: center;">';
141 print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
142 print '</td></tr>';
143 
144 print "</table>";
145 
146 print '<br>';
147 
148 print '<table class="border centpercent">';
149 
150 // Total Margin
151 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
152 print '<span id="totalMargin" class="amount"></span> <span class="amount">'.$langs->getCurrencySymbol($conf->currency).'</span>'; // set by jquery (see below)
153 print '</td></tr>';
154 
155 // Margin Rate
156 if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
157  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
158  print '<span id="marginRate"></span>'; // set by jquery (see below)
159  print '</td></tr>';
160 }
161 
162 // Mark Rate
163 if (!empty($conf->global->DISPLAY_MARK_RATES)) {
164  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
165  print '<span id="markRate"></span>'; // set by jquery (see below)
166  print '</td></tr>';
167 }
168 
169 print "</table>";
170 
171 print dol_get_fiche_end();
172 
173 print '</form>';
174 
175 $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
176 
177 $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
178 if ($id > 0) {
179  $sql .= " d.fk_product,";
180 }
181 if ($id > 0) {
182  $sql .= " f.rowid as facid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut as statut,";
183 }
184 $sql .= " SUM(d.total_ht) as selling_price,";
185 // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
186 $sql .= " SUM(d.qty) as product_qty,";
187 $sql .= " SUM(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1 * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,";
188 $sql .= " SUM(".$db->ifsql('d.total_ht < 0', '-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100)))', 'd.total_ht - (d.buy_price_ht * d.qty * (d.situation_percent / 100))').") as marge";
189 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
190 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
191 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
192 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product";
193 if (!empty($TSelectedCats)) {
194  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
195 }
196 $sql .= " WHERE f.fk_soc = s.rowid";
197 $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
198 $sql .= " AND f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
199 $sql .= " AND d.fk_facture = f.rowid";
200 if ($id > 0) {
201  $sql .= " AND d.fk_product =".((int) $id);
202 }
203 if (!empty($TSelectedCats)) {
204  $sql .= ' AND cp.fk_categorie IN ('.$db->sanitize(implode(',', $TSelectedCats)).')';
205 }
206 if (!empty($startdate)) {
207  $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
208 }
209 if (!empty($enddate)) {
210  $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
211 }
212 $sql .= " AND d.buy_price_ht IS NOT NULL";
213 // We should not use this here. Option ForceBuyingPriceIfNull should have effect only when inserting data. Once data is recorded, it must be used as it is for report.
214 // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
215 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
216  $sql .= " AND d.buy_price_ht <> 0";
217 }
218 if ($id > 0) {
219  $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut";
220 } else {
221  $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
222 }
223 $sql .= $db->order($sortfield, $sortorder);
224 // TODO: calculate total to display then restore pagination
225 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
226 
227 $param = '&id='.((int) $id);
228 if (GETPOST('startdatemonth', 'int')) {
229  $param .= '&startdateyear='.GETPOST('startdateyear', 'int');
230  $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int');
231  $param .= '&startdateday='.GETPOST('startdateday', 'int');
232 }
233 if (GETPOST('enddatemonth', 'int')) {
234  $param .= '&enddateyear='.GETPOST('enddateyear', 'int');
235  $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int');
236  $param .= '&enddateday='.GETPOST('enddateday', 'int');
237 }
238 $listofcateg = GETPOST('categories', 'array:int');
239 if (is_array($listofcateg)) {
240  foreach ($listofcateg as $val) {
241  $param .= '&categories[]='.$val;
242  }
243 }
244 
245 dol_syslog('margin::productMargins.php', LOG_DEBUG);
246 $result = $db->query($sql);
247 if ($result) {
248  $num = $db->num_rows($result);
249 
250  print '<br>';
251  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
252 
253  //var_dump($conf->global->MARGIN_TYPE);
254  if ($conf->global->MARGIN_TYPE == "1") {
255  $labelcostprice = 'BuyingPrice';
256  } else { // value is 'costprice' or 'pmp'
257  $labelcostprice = 'CostPrice';
258  }
259 
260  $moreforfilter = '';
261 
262  $i = 0;
263  print '<div class="div-table-responsive">';
264  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
265 
266  print '<tr class="liste_titre">';
267  if ($id > 0) {
268  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
269  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", $param, '', $sortfield, $sortorder, 'center ');
270  } else {
271  print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
272  }
273  print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "product_qty", "", $param, '', $sortfield, $sortorder, 'center ');
274  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right ');
275  print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right ');
276  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right ');
277  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
278  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
279  }
280  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
281  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
282  }
283  print "</tr>\n";
284 
285  $cumul_achat = 0;
286  $cumul_vente = 0;
287  $cumul_qty = 0;
288 
289  if ($num > 0) {
290  while ($i < $num /*&& $i < $conf->liste_limit*/) {
291  $objp = $db->fetch_object($result);
292  $qty = $objp->product_qty;
293  $pa = $objp->buying_price;
294  $pv = $objp->selling_price;
295  $marge = $objp->marge;
296 
297  if ($marge < 0) {
298  $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
299  $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
300  } else {
301  $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
302  $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
303  }
304 
305  print '<tr class="oddeven">';
306  if ($id > 0) {
307  print '<td>';
308  $invoicestatic->id = $objp->facid;
309  $invoicestatic->ref = $objp->ref;
310  print $invoicestatic->getNomUrl(1);
311  print "</td>\n";
312  print "<td class=\"center\">";
313  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
314  } else {
315  print '<td>';
316  if ($objp->rowid > 0) {
317  $product_static->type = $objp->fk_product_type;
318  $product_static->id = $objp->rowid;
319  $product_static->ref = $objp->ref;
320  $product_static->label = $objp->label;
321  $product_static->entity = $objp->pentity;
322  $text = $product_static->getNomUrl(1);
323  print $text .= ' - '.$objp->label;
324  } else {
325  print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
326  }
327  print "</td>\n";
328  //print "<td>".$product_static->getNomUrl(1)."</td>\n";
329  }
330  print '<td class="center">'.$qty.'</td>';
331  print '<td class="nowrap right"><span class="amount">'.price(price2num($pv, 'MT')).'</span></td>';
332  print '<td class="nowrap right"><span class="amount">'.price(price2num($pa, 'MT')).'</span></td>';
333  print '<td class="nowrap right"><span class="amount">'.price(price2num($marge, 'MT')).'</span></td>';
334  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
335  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
336  }
337  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
338  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
339  }
340  print "</tr>\n";
341 
342  $i++;
343  $cumul_achat += $objp->buying_price;
344  $cumul_vente += $objp->selling_price;
345  $cumul_qty += $objp->product_qty;
346  }
347  }
348 
349  // affichage totaux marges
350 
351  $totalMargin = $cumul_vente - $cumul_achat;
352 
353  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
354  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
355 
356  print '<tr class="liste_total">';
357  if ($id > 0) {
358  print '<td colspan=2>';
359  } else {
360  print '<td>';
361  }
362  print $langs->trans('TotalMargin').'</td>';
363  print '<td class="center">'.$cumul_qty.'</td>';
364  print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
365  print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
366  print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
367  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
368  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
369  }
370  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
371  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
372  }
373  print "</tr>\n";
374 
375  print "</table>";
376  print '</div>';
377 } else {
378  dol_print_error($db);
379 }
380 $db->free($result);
381 
382 
383 print '
384 <script type="text/javascript">
385 $(document).ready(function() {
386  console.log("Init some values");
387  $("#totalMargin").html("'.price(price2num($totalMargin, 'MT')).'");
388  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
389  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
390 });
391 </script>
392 ';
393 
394 // End of page
395 llxFooter();
396 $db->close();
Facture\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: facture.class.php:412
restrictedArea
restrictedArea($user, $features, $objectid=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.
Definition: security.lib.php:234
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:73
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
Facture
Class to manage invoices.
Definition: facture.class.php:60
marges_prepare_head
marges_prepare_head()
Return array of tabs to used on pages for third parties cards.
Definition: margins.lib.php:59
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
print_barre_liste
print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
Definition: functions.lib.php:5257
dol_get_fiche_head
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tabs of a record.
Definition: functions.lib.php:1822
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
print_liste_field_titre
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
Definition: functions.lib.php:5026
Product
Class to manage products or services.
Definition: product.class.php:46
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
Facture\STATUS_ABANDONED
const STATUS_ABANDONED
Classified abandoned and no payment done.
Definition: facture.class.php:435
price
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.
Definition: functions.lib.php:5541
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Definition: security.lib.php:933
dol_mktime
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...
Definition: functions.lib.php:2757
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOCSRFCHECK')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:59