dolibarr  13.0.2
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 require '../main.inc.php';
26 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
27 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
30 
31 // Load translation files required by the page
32 $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
33 
34 // Security check
35 $socid = GETPOST('socid', 'int');
36 $TSelectedProducts = GETPOST('products', 'array');
37 $TSelectedCats = GETPOST('categories', 'array');
38 
39 if (!empty($user->socid)) $socid = $user->socid;
40 $result = restrictedArea($user, 'societe', '', '');
41 $result = restrictedArea($user, 'margins');
42 
43 
44 $mesg = '';
45 
46 // Load variable for pagination
47 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
48 $sortfield = GETPOST('sortfield', 'aZ09comma');
49 $sortorder = GETPOST('sortorder', 'aZ09comma');
50 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
51 if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
52 $offset = $limit * $page;
53 $pageprev = $page - 1;
54 $pagenext = $page + 1;
55 if (!$sortfield) $sortfield = "s.nom"; // Set here default search field
56 if (!$sortorder) $sortorder = "ASC";
57 
58 $startdate = $enddate = '';
59 
60 if (!empty($_POST['startdatemonth']))
61  $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
62 if (!empty($_POST['enddatemonth']))
63  $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
64 
65 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
66 $object = new Societe($db);
67 $hookmanager->initHooks(array('margincustomerlist'));
68 
69 /*
70  * View
71  */
72 
73 $companystatic = new Societe($db);
74 $invoicestatic = new Facture($db);
75 
76 $form = new Form($db);
77 
78 llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Clients"));
79 
80 $text = $langs->trans("Margins");
81 //print load_fiche_titre($text);
82 
83 // Show tabs
84 $head = marges_prepare_head($user);
85 $titre = $langs->trans("Margins");
86 $picto = 'margin';
87 
88 
89 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
90 print '<input type="hidden" name="token" value="'.newToken().'">';
91 
92 print dol_get_fiche_head($head, 'customerMargins', $titre, 0, $picto);
93 
94 print '<table class="border centpercent">';
95 
96 $client = false;
97 if ($socid > 0) {
98  $soc = new Societe($db);
99  $soc->fetch($socid);
100 
101  if ($soc->client)
102  {
103  print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
104  print '<td class="maxwidthonsmartphone" colspan="4">';
105  print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0);
106  print '</td></tr>';
107 
108  $client = true;
109  if (!$sortorder) $sortorder = "DESC";
110  if (!$sortfield) $sortfield = "f.datef";
111  }
112 } else {
113  print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
114  print '<td class="maxwidthonsmartphone" colspan="4">';
115  print img_picto('', 'company').$form->select_company(null, 'socid', '(client=1 OR client=3)', 1, 0, 0);
116  print '</td></tr>';
117 }
118 
119 $sortfield = GETPOST("sortfield", 'alpha');
120 $sortorder = GETPOST("sortorder", 'alpha');
121 if (!$sortorder) $sortorder = "ASC";
122 if (!$sortfield)
123 {
124  if ($client)
125  {
126  $sortfield = "f.datef";
127  $sortorder = "DESC";
128  } else {
129  $sortfield = "s.nom";
130  $sortorder = "ASC";
131  }
132 }
133 
134 // Products
135 $TRes = $form->select_produits_list('', '', '', '', 0, '', 1, 2, 1, 0, '', 1);
136 
137 $TProducts = array();
138 foreach ($TRes as $prod) {
139  $TProducts[$prod['key']] = $prod['label'];
140 }
141 
142 print '<tr><td class="titlefield">'.$langs->trans('ProductOrService').'</td>';
143 print '<td class="maxwidthonsmartpone" colspan="4">';
144 print img_picto('', 'product').$form->multiselectarray('products', $TProducts, $TSelectedProducts, 0, 0, 'minwidth500');
145 print '</td></tr>';
146 
147 // Categories
148 $TCats = $form->select_all_categories(0, array(), '', 64, 0, 1);
149 
150 print '<tr>';
151 print '<td class="titlefield">'.$langs->trans('Category').'</td>';
152 print '<td class="maxwidthonsmartphone" colspan="4">';
153 print img_picto('', 'category').$form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'quatrevingtpercent widthcentpercentminusx');
154 print '</td>';
155 print '</tr>';
156 
157 // Start date
158 print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
159 print '<td>';
160 print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
161 print '</td>';
162 print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
163 print '<td>';
164 print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
165 print '</td>';
166 print '<td style="text-align: center;">';
167 print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
168 print '</td></tr>';
169 
170 print "</table>";
171 
172 print '<br>';
173 
174 print '<table class="border centpercent">';
175 
176 // Total Margin
177 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
178 print '<span id="totalMargin"></span>'; // set by jquery (see below)
179 print '</td></tr>';
180 
181 // Margin Rate
182 if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
183  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
184  print '<span id="marginRate"></span>'; // set by jquery (see below)
185  print '</td></tr>';
186 }
187 
188 // Mark Rate
189 if (!empty($conf->global->DISPLAY_MARK_RATES)) {
190  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
191  print '<span id="markRate"></span>'; // set by jquery (see below)
192  print '</td></tr>';
193 }
194 
195 print "</table>";
196 
198 
199 print '</form>';
200 
201 $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
202 
203 $sql = "SELECT";
204 $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
205 if ($client) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
206 $sql .= " sum(d.total_ht) as selling_price,";
207 // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this)
208 $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,";
209 $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";
210 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
211 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
212 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
213 if (!empty($TSelectedCats)) {
214  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product';
215 }
216 
217 if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
218 $sql .= " WHERE f.fk_soc = s.rowid";
219 if ($socid > 0) $sql .= ' AND s.rowid = '.$socid;
220 if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
221 $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")";
222 $sql .= ' AND s.entity IN ('.getEntity('societe').')';
223 $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
224 $sql .= " AND d.fk_facture = f.rowid";
225 $sql .= " AND (d.product_type = 0 OR d.product_type = 1)";
226 if (!empty($TSelectedProducts)) {
227  $sql .= ' AND d.fk_product IN ('.implode(',', $TSelectedProducts).')';
228 }
229 if (!empty($TSelectedCats)) {
230  $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')';
231 }
232 if (!empty($startdate))
233 $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
234 if (!empty($enddate))
235 $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
236 $sql .= " AND d.buy_price_ht IS NOT NULL";
237 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
238 $sql .= " AND d.buy_price_ht <> 0";
239 if ($client) $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
240 else $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client";
241 $sql .= $db->order($sortfield, $sortorder);
242 // TODO: calculate total to display then restore pagination
243 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
244 
245 dol_syslog('margin::customerMargins.php', LOG_DEBUG);
246 $result = $db->query($sql);
247 if ($result)
248 {
249  $num = $db->num_rows($result);
250 
251  print '<br>';
252  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
253 
254  if ($conf->global->MARGIN_TYPE == "1")
255  $labelcostprice = 'BuyingPrice';
256  else // value is 'costprice' or 'pmp'
257  $labelcostprice = 'CostPrice';
258 
259  $moreforfilter = '';
260 
261  $i = 0;
262  print '<div class="div-table-responsive">';
263  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
264 
265  print '<tr class="liste_titre">';
266  if (!empty($client)) {
267  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$socid, '', $sortfield, $sortorder);
268  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$socid, 'align="center"', $sortfield, $sortorder);
269  } else print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;socid=".$socid, '', $sortfield, $sortorder);
270  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
271  print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
272  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
273  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
274  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
275  if (!empty($conf->global->DISPLAY_MARK_RATES))
276  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
277  print "</tr>\n";
278 
279  $cumul_achat = 0;
280  $cumul_vente = 0;
281 
282  if ($num > 0)
283  {
284  while ($i < $num /*&& $i < $conf->liste_limit*/)
285  {
286  $objp = $db->fetch_object($result);
287 
288  $pa = $objp->buying_price;
289  $pv = $objp->selling_price;
290  $marge = $objp->marge;
291 
292  if ($marge < 0)
293  {
294  $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
295  $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
296  } else {
297  $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
298  $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
299  }
300 
301  print '<tr class="oddeven">';
302  if ($client) {
303  print '<td>';
304  $invoicestatic->id = $objp->facid;
305  $invoicestatic->ref = $objp->ref;
306  print $invoicestatic->getNomUrl(1);
307  print "</td>\n";
308  print "<td class=\"center\">";
309  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
310  } else {
311  $companystatic->id = $objp->socid;
312  $companystatic->name = $objp->name;
313  $companystatic->client = $objp->client;
314  print "<td>".$companystatic->getNomUrl(1, 'margin')."</td>\n";
315  }
316 
317  print "<td class=\"right\">".price(price2num($pv, 'MT'))."</td>\n";
318  print "<td class=\"right\">".price(price2num($pa, 'MT'))."</td>\n";
319  print "<td class=\"right\">".price(price2num($marge, 'MT'))."</td>\n";
320  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
321  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
322  if (!empty($conf->global->DISPLAY_MARK_RATES))
323  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
324  print "</tr>\n";
325 
326  $i++;
327  $cumul_achat += $objp->buying_price;
328  $cumul_vente += $objp->selling_price;
329  }
330  }
331 
332  // affichage totaux marges
333 
334  $totalMargin = $cumul_vente - $cumul_achat;
335  /*if ($totalMargin < 0)
336  {
337  $marginRate = ($cumul_achat != 0)?-1*(100 * $totalMargin / $cumul_achat):'';
338  $markRate = ($cumul_vente != 0)?-1*(100 * $totalMargin / $cumul_vente):'';
339  }
340  else
341  {*/
342  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
343  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
344  //}
345 
346  print '<tr class="liste_total">';
347  if ($client)
348  print '<td colspan=2>';
349  else print '<td>';
350  print $langs->trans('TotalMargin')."</td>";
351  print "<td class=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
352  print "<td class=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
353  print "<td class=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
354  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
355  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
356  if (!empty($conf->global->DISPLAY_MARK_RATES))
357  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
358  print "</tr>\n";
359 
360  print "</table>";
361  print '</div>';
362 } else {
363  dol_print_error($db);
364 }
365 $db->free($result);
366 
367 print '<script type="text/javascript">
368 $(document).ready(function() {
369  $("#totalMargin").html("'.price($totalMargin, null, null, null, null, $rounding).'");
370  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price($marginRate, null, null, null, null, $rounding)."%").'");
371  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%").'");
372 });
373 </script>
374 ';
375 
376 // End of page
377 llxFooter();
378 $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...
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.
Class to manage third parties objects (customers, suppliers, prospects...)
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.
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.
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