dolibarr  17.0.4
customerMargins.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  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
25 // Load Dolibarr environment
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 // Load variable for pagination
36 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
37 $sortfield = GETPOST('sortfield', 'aZ09comma');
38 $sortorder = GETPOST('sortorder', 'aZ09comma');
39 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
40 if (empty($page) || $page == -1) {
41  $page = 0;
42 } // If $page is not defined, or '' or -1
43 $offset = $limit * $page;
44 $pageprev = $page - 1;
45 $pagenext = $page + 1;
46 if (!$sortfield) {
47  $sortfield = "s.nom"; // Set here default search field
48 }
49 if (!$sortorder) {
50  $sortorder = "ASC";
51 }
52 
53 $startdate = $enddate = '';
54 if (GETPOST('startdatemonth')) {
55  $startdate = dol_mktime(0, 0, 0, GETPOST('startdatemonth', 'int'), GETPOST('startdateday', 'int'), GETPOST('startdateyear', 'int'));
56 }
57 if (GETPOST('enddatemonth')) {
58  $enddate = dol_mktime(23, 59, 59, GETPOST('enddatemonth', 'int'), GETPOST('enddateday', 'int'), GETPOST('enddateyear'));
59 }
60 
61 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
62 $object = new Societe($db);
63 $hookmanager->initHooks(array('margincustomerlist'));
64 
65 // Security check
66 $socid = GETPOST('socid', 'int');
67 $TSelectedProducts = GETPOST('products', 'array');
68 $TSelectedCats = GETPOST('categories', 'array');
69 
70 if (!empty($user->socid)) {
71  $socid = $user->socid;
72 }
73 $result = restrictedArea($user, 'societe', '', '');
74 $result = restrictedArea($user, 'margins');
75 
76 
77 /*
78  * View
79  */
80 
81 $companystatic = new Societe($db);
82 $invoicestatic = new Facture($db);
83 
84 $form = new Form($db);
85 
86 llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Clients"));
87 
88 $text = $langs->trans("Margins");
89 //print load_fiche_titre($text);
90 
91 // Show tabs
92 $head = marges_prepare_head();
93 
94 $titre = $langs->trans("Margins");
95 $picto = 'margin';
96 
97 
98 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
99 print '<input type="hidden" name="token" value="'.newToken().'">';
100 
101 print dol_get_fiche_head($head, 'customerMargins', $titre, 0, $picto);
102 
103 print '<table class="border centpercent">';
104 
105 $client = false;
106 if ($socid > 0) {
107  $soc = new Societe($db);
108  $soc->fetch($socid);
109 
110  if ($soc->client) {
111  print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
112  print '<td class="maxwidthonsmartphone" colspan="4">';
113  print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0);
114  print '</td></tr>';
115 
116  $client = true;
117  if (!$sortorder) {
118  $sortorder = "DESC";
119  }
120  if (!$sortfield) {
121  $sortfield = "f.datef";
122  }
123  }
124 } else {
125  print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
126  print '<td class="maxwidthonsmartphone" colspan="4">';
127  print img_picto('', 'company').$form->select_company(null, 'socid', '(client=1 OR client=3)', 1, 0, 0);
128  print '</td></tr>';
129 }
130 
131 $sortfield = GETPOST('sortfield', 'aZ09comma');
132 $sortorder = GETPOST('sortorder', 'aZ09comma');
133 if (!$sortorder) {
134  $sortorder = "ASC";
135 }
136 if (!$sortfield) {
137  if ($client) {
138  $sortfield = "f.datef";
139  $sortorder = "DESC";
140  } else {
141  $sortfield = "s.nom";
142  $sortorder = "ASC";
143  }
144 }
145 
146 // Products
147 $TRes = $form->select_produits_list('', '', '', '', 0, '', 1, 2, 1, 0, '', 1);
148 
149 $TProducts = array();
150 foreach ($TRes as $prod) {
151  $TProducts[$prod['key']] = $prod['label'];
152 }
153 
154 print '<tr><td class="titlefield">'.$langs->trans('ProductOrService').'</td>';
155 print '<td class="maxwidthonsmartpone" colspan="4">';
156 print img_picto('', 'product').$form->multiselectarray('products', $TProducts, $TSelectedProducts, 0, 0, 'minwidth500');
157 print '</td></tr>';
158 
159 // Categories
160 $TCats = $form->select_all_categories('product', array(), '', 64, 0, 1);
161 
162 print '<tr>';
163 print '<td class="titlefield">'.$langs->trans('Category').'</td>';
164 print '<td class="maxwidthonsmartphone" colspan="4">';
165 print img_picto('', 'category').$form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'quatrevingtpercent widthcentpercentminusx');
166 print '</td>';
167 print '</tr>';
168 
169 // Start date
170 print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
171 print '<td>';
172 print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
173 print '</td>';
174 print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
175 print '<td>';
176 print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
177 print '</td>';
178 print '<td style="text-align: center;">';
179 print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
180 print '</td></tr>';
181 
182 print "</table>";
183 
184 print '<br>';
185 
186 print '<table class="border centpercent">';
187 
188 // Total Margin
189 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
190 print '<span id="totalMargin" class="amount"></span> <span class="amount">'.$langs->getCurrencySymbol($conf->currency).'</span>'; // set by jquery (see below)
191 print '</td></tr>';
192 
193 // Margin Rate
194 if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
195  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
196  print '<span id="marginRate"></span>'; // set by jquery (see below)
197  print '</td></tr>';
198 }
199 
200 // Mark Rate
201 if (!empty($conf->global->DISPLAY_MARK_RATES)) {
202  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
203  print '<span id="markRate"></span>'; // set by jquery (see below)
204  print '</td></tr>';
205 }
206 
207 print "</table>";
208 
209 print dol_get_fiche_end();
210 
211 print '</form>';
212 
213 $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
214 
215 $sql = "SELECT";
216 $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
217 if ($client) {
218  $sql .= " f.rowid as facid, f.ref, f.total_ht, f.datef, f.paye, f.type, f.fk_statut as statut,";
219 }
220 $sql .= " sum(d.total_ht) as selling_price,";
221 // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this)
222 
223 $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,";
224 $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";
225 
226 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
227 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
228 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
229 if (!empty($TSelectedCats)) {
230  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product';
231 }
232 
233 if (empty($user->rights->societe->client->voir) && !$socid) {
234  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
235 }
236 $sql .= " WHERE f.fk_soc = s.rowid";
237 if ($socid > 0) {
238  $sql .= ' AND s.rowid = '.((int) $socid);
239 }
240 if (empty($user->rights->societe->client->voir) && !$socid) {
241  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
242 }
243 $sql .= " AND f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
244 $sql .= ' AND s.entity IN ('.getEntity('societe').')';
245 $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
246 $sql .= " AND d.fk_facture = f.rowid";
247 $sql .= " AND (d.product_type = 0 OR d.product_type = 1)";
248 if (!empty($TSelectedProducts)) {
249  $sql .= ' AND d.fk_product IN ('.$db->sanitize(implode(',', $TSelectedProducts)).')';
250 }
251 if (!empty($TSelectedCats)) {
252  $sql .= ' AND cp.fk_categorie IN ('.$db->sanitize(implode(',', $TSelectedCats)).')';
253 }
254 if (!empty($startdate)) {
255  $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
256 }
257 if (!empty($enddate)) {
258  $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
259 }
260 $sql .= " AND d.buy_price_ht IS NOT NULL";
261 // 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.
262 // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
263 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
264  $sql .= " AND d.buy_price_ht <> 0";
265 }
266 if ($client) {
267  $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total_ht, f.datef, f.paye, f.type, f.fk_statut";
268 } else {
269  $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client";
270 }
271 $sql .= $db->order($sortfield, $sortorder);
272 // TODO: calculate total to display then restore pagination
273 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
274 
275 $param = '&socid='.((int) $socid);
276 if (GETPOST('startdatemonth', 'int')) {
277  $param .= '&startdateyear='.GETPOST('startdateyear', 'int');
278  $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int');
279  $param .= '&startdateday='.GETPOST('startdateday', 'int');
280 }
281 if (GETPOST('enddatemonth', 'int')) {
282  $param .= '&enddateyear='.GETPOST('enddateyear', 'int');
283  $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int');
284  $param .= '&enddateday='.GETPOST('enddateday', 'int');
285 }
286 $listofproducts = GETPOST('products', 'array:int');
287 if (is_array($listofproducts)) {
288  foreach ($listofproducts as $val) {
289  $param .= '&products[]='.$val;
290  }
291 }
292 $listofcateg = GETPOST('categories', 'array:int');
293 if (is_array($listofcateg)) {
294  foreach ($listofcateg as $val) {
295  $param .= '&categories[]='.$val;
296  }
297 }
298 
299 dol_syslog('margin::customerMargins.php', LOG_DEBUG);
300 $result = $db->query($sql);
301 if ($result) {
302  $num = $db->num_rows($result);
303 
304  print '<br>';
305  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
306 
307  if ($conf->global->MARGIN_TYPE == "1") {
308  $labelcostprice = 'BuyingPrice';
309  } else { // value is 'costprice' or 'pmp'
310  $labelcostprice = 'CostPrice';
311  }
312 
313  $moreforfilter = '';
314 
315  $i = 0;
316  print '<div class="div-table-responsive">';
317  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
318 
319  print '<tr class="liste_titre">';
320  if (!empty($client)) {
321  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
322  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", $param, 'align="center"', $sortfield, $sortorder);
323  } else {
324  print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
325  }
326  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, 'align="right"', $sortfield, $sortorder);
327  print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, 'align="right"', $sortfield, $sortorder);
328  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, 'align="right"', $sortfield, $sortorder);
329  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
330  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, 'align="right"', $sortfield, $sortorder);
331  }
332  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
333  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, 'align="right"', $sortfield, $sortorder);
334  }
335  print "</tr>\n";
336 
337  $cumul_achat = 0;
338  $cumul_vente = 0;
339 
340  if ($num > 0) {
341  while ($i < $num /*&& $i < $conf->liste_limit*/) {
342  $objp = $db->fetch_object($result);
343 
344  $pa = $objp->buying_price;
345  $pv = $objp->selling_price;
346  $marge = $objp->marge;
347 
348  if ($marge < 0) {
349  $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
350  $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
351  } else {
352  $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
353  $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
354  }
355 
356  print '<tr class="oddeven">';
357  if ($client) {
358  $invoicestatic->id = $objp->facid;
359  $invoicestatic->ref = $objp->ref;
360  $invoicestatic->statut = $objp->statut;
361  $invoicestatic->type = $objp->type;
362 
363  print '<td>';
364  print $invoicestatic->getNomUrl(1);
365  print '</td>';
366  print '<td class="center">';
367  print dol_print_date($db->jdate($objp->datef), 'day').'</td>';
368  } else {
369  $companystatic->id = $objp->socid;
370  $companystatic->name = $objp->name;
371  $companystatic->client = $objp->client;
372 
373  print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>';
374  }
375 
376  print '<td class="nowrap right"><span class="amount">'.price(price2num($pv, 'MT')).'</span></td>';
377  print '<td class="nowrap right"><span class="amount">'.price(price2num($pa, 'MT')).'</span></td>';
378  print '<td class="nowrap right"><span class="amount">'.price(price2num($marge, 'MT')).'</span></td>';
379  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
380  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
381  }
382  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
383  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
384  }
385  print "</tr>\n";
386 
387  $i++;
388  $cumul_achat += $objp->buying_price;
389  $cumul_vente += $objp->selling_price;
390  }
391  }
392 
393  // affichage totaux marges
394 
395  $totalMargin = $cumul_vente - $cumul_achat;
396  /*if ($totalMargin < 0)
397  {
398  $marginRate = ($cumul_achat != 0)?-1*(100 * $totalMargin / $cumul_achat):'';
399  $markRate = ($cumul_vente != 0)?-1*(100 * $totalMargin / $cumul_vente):'';
400  }
401  else
402  {*/
403  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
404  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
405  //}
406 
407  print '<tr class="liste_total">';
408  if ($client) {
409  print '<td colspan="2">';
410  } else {
411  print '<td>';
412  }
413  print $langs->trans('TotalMargin')."</td>";
414  print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
415  print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
416  print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
417  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
418  print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
419  }
420  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
421  print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
422  }
423  print '</tr>';
424 
425  print '</table>';
426  print '</div>';
427 } else {
428  dol_print_error($db);
429 }
430 $db->free($result);
431 
432 print '<script type="text/javascript">
433 $(document).ready(function() {
434  console.log("Init some values");
435  $("#totalMargin").html("'.price(price2num($totalMargin, 'MT')).'");
436  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
437  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
438 });
439 </script>
440 ';
441 
442 // End of page
443 llxFooter();
444 $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 third parties objects (customers, suppliers, prospects...)
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='')
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...
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.