dolibarr  19.0.0-dev
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 // Load Dolibarr environment
27 require '../main.inc.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
29 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
32 
33 // Load translation files required by the page
34 $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
35 
36 $id = GETPOST('id', 'int');
37 $ref = GETPOST('ref', 'alpha');
38 $action = GETPOST('action', 'aZ09');
39 $confirm = GETPOST('confirm', 'alpha');
40 $TSelectedCats = GETPOST('categories', 'array');
41 $socid = 0;
42 
43 $mesg = '';
44 
45 // Load variable for pagination
46 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
47 $sortfield = GETPOST('sortfield', 'aZ09comma');
48 $sortorder = GETPOST('sortorder', 'aZ09comma');
49 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
50 if (empty($page) || $page == -1) {
51  $page = 0;
52 } // If $page is not defined, or '' or -1
53 $offset = $limit * $page;
54 $pageprev = $page - 1;
55 $pagenext = $page + 1;
56 if (!$sortfield) {
57  if ($id > 0) {
58  $sortfield = "f.datef";
59  $sortorder = "DESC";
60  } else {
61  $sortfield = "p.ref";
62  $sortorder = "ASC";
63  }
64 }
65 
66 $startdate = $enddate = '';
67 if (GETPOST('startdatemonth')) {
68  $startdate = dol_mktime(0, 0, 0, GETPOST('startdatemonth', 'int'), GETPOST('startdateday', 'int'), GETPOST('startdateyear', 'int'));
69 }
70 if (GETPOST('enddatemonth')) {
71  $enddate = dol_mktime(23, 59, 59, GETPOST('enddatemonth', 'int'), GETPOST('enddateday', 'int'), GETPOST('enddateyear'));
72 }
73 
74 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
75 $object = new Product($db);
76 $hookmanager->initHooks(array('marginproductlist'));
77 
78 // Security check
79 $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
80 $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
81 if (!empty($user->socid)) {
82  $socid = $user->socid;
83 }
84 $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
85 if (empty($user->rights->margins->liretous)) {
87 }
88 
89 
90 /*
91  * View
92  */
93 
94 $product_static = new Product($db);
95 $invoicestatic = new Facture($db);
96 
97 $form = new Form($db);
98 
99 llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Products"));
100 
101 $text = $langs->trans("Margins");
102 //print load_fiche_titre($text);
103 
104 // Show tabs
105 $head = marges_prepare_head();
106 
107 $titre = $langs->trans("Margins");
108 $picto = 'margin';
109 
110 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
111 print '<input type="hidden" name="token" value="'.newToken().'">';
112 
113 print dol_get_fiche_head($head, 'productMargins', $titre, 0, $picto);
114 
115 print '<table class="border centpercent">';
116 
117 // Product
118 print '<tr><td class="titlefield">'.$langs->trans('ProductOrService').'</td>';
119 print '<td class="maxwidthonsmartphone" colspan="4">';
120 print img_picto('', 'product').$form->select_produits(($id > 0 ? $id : ''), 'id', '', 20, 0, 1, 2, '', 1, array(), 0, 'All', 0, '', 0, '', null, 1);
121 print '</td></tr>';
122 
123 // Categories
124 $TCats = $form->select_all_categories('product', array(), '', 64, 0, 1);
125 
126 print '<tr>';
127 print '<td class="titlefield">'.$langs->trans('Category').'</td>';
128 print '<td class="maxwidthonsmartphone" colspan="4">';
129 print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'quatrevingtpercent widthcentpercentminusx');
130 print '</td>';
131 print '</tr>';
132 
133 // Start date
134 print '<tr>';
135 print '<td class="titlefield">'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
136 print '<td>';
137 print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
138 print '</td>';
139 print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
140 print '<td>';
141 print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
142 print '</td>';
143 print '<td style="text-align: center;">';
144 print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
145 print '</td></tr>';
146 
147 print "</table>";
148 
149 print '<br>';
150 
151 print '<table class="border centpercent">';
152 
153 // Total Margin
154 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
155 print '<span id="totalMargin" class="amount"></span> <span class="amount">'.$langs->getCurrencySymbol($conf->currency).'</span>'; // set by jquery (see below)
156 print '</td></tr>';
157 
158 // Margin Rate
159 if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
160  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
161  print '<span id="marginRate"></span>'; // set by jquery (see below)
162  print '</td></tr>';
163 }
164 
165 // Mark Rate
166 if (!empty($conf->global->DISPLAY_MARK_RATES)) {
167  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
168  print '<span id="markRate"></span>'; // set by jquery (see below)
169  print '</td></tr>';
170 }
171 
172 print "</table>";
173 
174 print dol_get_fiche_end();
175 
176 print '</form>';
177 
178 $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
179 
180 $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
181 if ($id > 0) {
182  $sql .= " d.fk_product,";
183 }
184 if ($id > 0) {
185  $sql .= " f.rowid as facid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut as statut,";
186 }
187 $sql .= " SUM(d.total_ht) as selling_price,";
188 $sql .= " SUM(d.qty) as product_qty,";
189 
190 // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
191 $sql .= " SUM(".$db->ifsql('(d.total_ht < 0 OR (d.total_ht = 0 AND f.type = 2))', '-1 * d.qty * d.buy_price_ht * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,";
192 $sql .= " SUM(".$db->ifsql('(d.total_ht < 0 OR (d.total_ht = 0 AND f.type = 2))', '-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";
193 
194 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
195 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
196 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
197 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product";
198 if (!empty($TSelectedCats)) {
199  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
200 }
201 $sql .= " WHERE f.fk_soc = s.rowid";
202 $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
203 $sql .= " AND f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
204 $sql .= " AND d.fk_facture = f.rowid";
205 if ($id > 0) {
206  $sql .= " AND d.fk_product =".((int) $id);
207 }
208 if (!empty($TSelectedCats)) {
209  $sql .= ' AND cp.fk_categorie IN ('.$db->sanitize(implode(',', $TSelectedCats)).')';
210 }
211 if (!empty($startdate)) {
212  $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
213 }
214 if (!empty($enddate)) {
215  $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
216 }
217 $sql .= " AND d.buy_price_ht IS NOT NULL";
218 // 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.
219 // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
220 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
221  $sql .= " AND d.buy_price_ht <> 0";
222 }
223 if ($id > 0) {
224  $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";
225 } else {
226  $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
227 }
228 $sql .= $db->order($sortfield, $sortorder);
229 // TODO: calculate total to display then restore pagination
230 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
231 
232 $param = '&id='.((int) $id);
233 if (GETPOST('startdatemonth', 'int')) {
234  $param .= '&startdateyear='.GETPOST('startdateyear', 'int');
235  $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int');
236  $param .= '&startdateday='.GETPOST('startdateday', 'int');
237 }
238 if (GETPOST('enddatemonth', 'int')) {
239  $param .= '&enddateyear='.GETPOST('enddateyear', 'int');
240  $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int');
241  $param .= '&enddateday='.GETPOST('enddateday', 'int');
242 }
243 $listofcateg = GETPOST('categories', 'array:int');
244 if (is_array($listofcateg)) {
245  foreach ($listofcateg as $val) {
246  $param .= '&categories[]='.$val;
247  }
248 }
249 
250 dol_syslog('margin::productMargins.php', LOG_DEBUG);
251 $result = $db->query($sql);
252 if ($result) {
253  $num = $db->num_rows($result);
254 
255  print '<br>';
256  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
257 
258  //var_dump($conf->global->MARGIN_TYPE);
259  if ($conf->global->MARGIN_TYPE == "1") {
260  $labelcostprice = 'BuyingPrice';
261  } else { // value is 'costprice' or 'pmp'
262  $labelcostprice = 'CostPrice';
263  }
264 
265  $moreforfilter = '';
266 
267  $i = 0;
268  print '<div class="div-table-responsive">';
269  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
270 
271  print '<tr class="liste_titre">';
272  if ($id > 0) {
273  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
274  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", $param, '', $sortfield, $sortorder, 'center ');
275  } else {
276  print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
277  }
278  print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "product_qty", "", $param, '', $sortfield, $sortorder, 'center ');
279  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right ');
280  print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right ');
281  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right ');
282  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
283  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
284  }
285  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
286  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
287  }
288  print "</tr>\n";
289 
290  $cumul_achat = 0;
291  $cumul_vente = 0;
292  $cumul_qty = 0;
293 
294  if ($num > 0) {
295  while ($i < $num /*&& $i < $conf->liste_limit*/) {
296  $objp = $db->fetch_object($result);
297  $qty = $objp->product_qty;
298  $pa = $objp->buying_price;
299  $pv = $objp->selling_price;
300  $marge = $objp->marge;
301 
302  if ($marge < 0) {
303  $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
304  $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
305  } else {
306  $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
307  $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
308  }
309 
310  print '<tr class="oddeven">';
311  if ($id > 0) {
312  print '<td>';
313  $invoicestatic->id = $objp->facid;
314  $invoicestatic->ref = $objp->ref;
315  print $invoicestatic->getNomUrl(1);
316  print "</td>\n";
317  print "<td class=\"center\">";
318  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
319  } else {
320  print '<td>';
321  if ($objp->rowid > 0) {
322  $product_static->type = $objp->fk_product_type;
323  $product_static->id = $objp->rowid;
324  $product_static->ref = $objp->ref;
325  $product_static->label = $objp->label;
326  $product_static->entity = $objp->pentity;
327  $text = $product_static->getNomUrl(1);
328  print $text .= ' - '.$objp->label;
329  } else {
330  print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
331  }
332  print "</td>\n";
333  //print "<td>".$product_static->getNomUrl(1)."</td>\n";
334  }
335  print '<td class="center">'.$qty.'</td>';
336  print '<td class="nowrap right"><span class="amount">'.price(price2num($pv, 'MT')).'</span></td>';
337  print '<td class="nowrap right"><span class="amount">'.price(price2num($pa, 'MT')).'</span></td>';
338  print '<td class="nowrap right"><span class="amount">'.price(price2num($marge, 'MT')).'</span></td>';
339  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
340  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
341  }
342  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
343  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
344  }
345  print "</tr>\n";
346 
347  $i++;
348  $cumul_achat += $objp->buying_price;
349  $cumul_vente += $objp->selling_price;
350  $cumul_qty += $objp->product_qty;
351  }
352  }
353 
354  // affichage totaux marges
355 
356  $totalMargin = $cumul_vente - $cumul_achat;
357 
358  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
359  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
360 
361  print '<tr class="liste_total">';
362  if ($id > 0) {
363  print '<td colspan=2>';
364  } else {
365  print '<td>';
366  }
367  print $langs->trans('TotalMargin').'</td>';
368  print '<td class="center">'.$cumul_qty.'</td>';
369  print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
370  print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
371  print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
372  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
373  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
374  }
375  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
376  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
377  }
378  print "</tr>\n";
379 
380  print "</table>";
381  print '</div>';
382 } else {
383  dol_print_error($db);
384 }
385 $db->free($result);
386 
387 
388 print '
389 <script type="text/javascript">
390 $(document).ready(function() {
391  console.log("Init some values");
392  $("#totalMargin").html("'.price(price2num($totalMargin, 'MT')).'");
393  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
394  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
395 });
396 </script>
397 ';
398 
399 // End of page
400 llxFooter();
401 $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:56
llxFooter()
Empty footer.
Definition: wrapper.php:70
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const STATUS_ABANDONED
Classified abandoned and no payment done.
Class to manage generation of HTML components Only common components must be here.
Class to manage products or services.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
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_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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)
dol_get_fiche_end($notab=0)
Return tab footer of a card.
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).
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
marges_prepare_head()
Return array of tabs to used on pages for third parties cards.
Definition: margins.lib.php:59
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.