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