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  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16  */
17 
24 require '../../main.inc.php';
25 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
26 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
28 
29 $langs->loadLangs(array("companies", "bills", "products", "margins"));
30 
31 $id = GETPOST('id', 'int');
32 $ref = GETPOST('ref', 'alpha');
33 $action = GETPOST('action', 'aZ09');
34 $confirm = GETPOST('confirm', 'alpha');
35 
36 // Security check
37 $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
38 $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
39 if (!empty($user->socid)) {
40  $socid = $user->socid;
41 }
42 
43 $object = new Product($db);
44 
45 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
46 $sortfield = GETPOST('sortfield', 'aZ09comma');
47 $sortorder = GETPOST('sortorder', 'aZ09comma');
48 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
49 if (empty($page) || $page == -1) {
50  $page = 0;
51 } // If $page is not defined, or '' or -1
52 $offset = $limit * $page;
53 $pageprev = $page - 1;
54 $pagenext = $page + 1;
55 if (!$sortorder) {
56  $sortorder = "DESC";
57 }
58 if (!$sortfield) {
59  $sortfield = "f.datef";
60 }
61 
62 $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
63 
64 if (empty($user->rights->margins->liretous)) {
66 }
67 
68 
69 /*
70  * View
71  */
72 
73 $invoicestatic = new Facture($db);
74 
75 $form = new Form($db);
76 
77 if ($id > 0 || !empty($ref)) {
78  $result = $object->fetch($id, $ref);
79 
80  $title = $langs->trans('ProductServiceCard');
81  $help_url = '';
82  $shortlabel = dol_trunc($object->label, 16);
83  if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
84  $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card');
85  $help_url = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
86  }
87  if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
88  $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card');
89  $help_url = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
90  }
91 
92  llxHeader('', $title, $help_url);
93 
94  // View mode
95  if ($result > 0) {
96  $head = product_prepare_head($object);
97  $titre = $langs->trans("CardProduct".$object->type);
98  $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
99  print dol_get_fiche_head($head, 'margin', $titre, -1, $picto);
100 
101  $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
102 
103  dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref');
104 
105 
106  print '<div class="fichecenter">';
107 
108  print '<div class="underbanner clearboth"></div>';
109  print '<table class="border tableforfield centpercent">';
110 
111  // Total Margin
112  print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td>';
113  print '<span id="totalMargin" class="amount"></span>'; // set by jquery (see below)
114  print '</td></tr>';
115 
116  // Margin Rate
117  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
118  print '<tr><td>'.$langs->trans("MarginRate").'</td><td>';
119  print '<span id="marginRate"></span>'; // set by jquery (see below)
120  print '</td></tr>';
121  }
122 
123  // Mark Rate
124  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
125  print '<tr><td>'.$langs->trans("MarkRate").'</td><td>';
126  print '<span id="markRate"></span>'; // set by jquery (see below)
127  print '</td></tr>';
128  }
129 
130  print "</table>";
131 
132  print '</div>';
133  print '<div style="clear:both"></div>';
134 
135  print dol_get_fiche_end();
136 
137 
138  if ($user->rights->facture->lire) {
139  $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,";
140  $sql .= " f.rowid as facid, f.ref, f.total_ht,";
141  $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
142  if (empty($user->rights->societe->client->voir) && !$socid) {
143  $sql .= " sc.fk_soc, sc.fk_user,";
144  }
145  $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
146  $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note
147  $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // not always positive in case of Credit note
148  $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // not always positive in case of Credit note
149  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
150  $sql .= ", ".MAIN_DB_PREFIX."facture as f";
151  $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
152  if (empty($user->rights->societe->client->voir) && !$socid) {
153  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
154  }
155  $sql .= " WHERE f.fk_soc = s.rowid";
156  $sql .= " AND f.fk_statut > 0";
157  $sql .= " AND f.entity IN (".getEntity('invoice').")";
158  $sql .= " AND d.fk_facture = f.rowid";
159  $sql .= " AND d.fk_product = ".((int) $object->id);
160  if (empty($user->rights->societe->client->voir) && !$socid) {
161  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
162  }
163  if (!empty($socid)) {
164  $sql .= " AND f.fk_soc = $socid";
165  }
166  $sql .= " AND d.buy_price_ht IS NOT NULL";
167  // 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.
168  // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
169  if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
170  $sql .= " AND d.buy_price_ht <> 0";
171  }
172  $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut, f.type";
173  if (empty($user->rights->societe->client->voir) && !$socid) {
174  $sql .= ", sc.fk_soc, sc.fk_user";
175  }
176  $sql .= $db->order($sortfield, $sortorder);
177  // TODO: calculate total to display then restore pagination
178  //$sql.= $db->plimit($conf->liste_limit +1, $offset);
179  dol_syslog('margin:tabs:productMargins.php', LOG_DEBUG);
180  $result = $db->query($sql);
181  if ($result) {
182  $num = $db->num_rows($result);
183 
184  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=$object->id", $sortfield, $sortorder, '', 0, 0, '');
185 
186  $i = 0;
187 
188  print '<div class="div-table-responsive">';
189  print '<table class="noborder centpercent">';
190 
191  print '<tr class="liste_titre">';
192  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
193  print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
194  print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
195  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'left ');
196  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
197  print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
198  print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
199  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
200  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
201  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
202  }
203  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
204  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
205  }
206  print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
207  print "</tr>\n";
208 
209  $cumul_achat = 0;
210  $cumul_vente = 0;
211  $cumul_qty = 0;
212 
213  if ($num > 0) {
214  while ($i < $num /*&& $i < $conf->liste_limit*/) {
215  $objp = $db->fetch_object($result);
216 
217  $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
218  $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
219 
220  print '<tr class="oddeven">';
221  print '<td>';
222  $invoicestatic->id = $objp->facid;
223  $invoicestatic->ref = $objp->ref;
224  print $invoicestatic->getNomUrl(1);
225  print "</td>\n";
226  print '<td><a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$objp->socid.'">'.img_object($langs->trans("ShowCompany"), "company").' '.dol_trunc($objp->name, 44).'</a></td>';
227  print "<td>".$objp->code_client."</td>\n";
228  print '<td class="center">';
229  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
230  print '<td class="right amount">'.price(price2num($objp->selling_price, 'MT'))."</td>\n";
231  print '<td class="right amount">'.price(price2num($objp->buying_price, 'MT'))."</td>\n";
232  print '<td class="right">'.price(price2num($objp->qty, 'MT'))."</td>\n";
233  print '<td class="right amount">'.price(price2num($objp->marge, 'MT'))."</td>\n";
234  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
235  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
236  }
237  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
238  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
239  }
240  print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
241  print "</tr>\n";
242  $i++;
243  $cumul_achat += $objp->buying_price;
244  $cumul_vente += $objp->selling_price;
245  $cumul_qty += $objp->qty;
246  }
247  }
248 
249  // affichage totaux marges
250 
251  $totalMargin = $cumul_vente - $cumul_achat;
252  if ($totalMargin < 0) {
253  $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
254  $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
255  } else {
256  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
257  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
258  }
259  print '<tr class="liste_total">';
260  print '<td colspan=4>'.$langs->trans('TotalMargin')."</td>";
261  print '<td class="right amount">'.price(price2num($cumul_vente, 'MT'))."</td>\n";
262  print '<td class="right amount">'.price(price2num($cumul_achat, 'MT'))."</td>\n";
263  print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n";
264  print '<td class="right amount">'.price(price2num($totalMargin, 'MT'))."</td>\n";
265  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
266  print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
267  }
268  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
269  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
270  }
271  print '<td class="right">&nbsp;</td>';
272  print "</tr>\n";
273  print "</table>";
274  print '</div>';
275  } else {
276  dol_print_error($db);
277  }
278  $db->free($result);
279  }
280  }
281 } else {
282  dol_print_error();
283 }
284 
285 print '
286  <script type="text/javascript">
287  $(document).ready(function() {
288  $("#totalMargin").html("'. price(price2num($totalMargin, 'MT')).'");
289  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
290  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
291  });
292  </script>
293 ';
294 
295 // End of page
296 llxFooter();
297 $db->close();
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:3805
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
product_prepare_head
product_prepare_head($object)
Prepare array with list of tabs.
Definition: product.lib.php:35
$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
dol_banner_tab
dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
Show tab footer of a card.
Definition: functions.lib.php:2046
$help_url
if(GETPOST('button_removefilter_x', 'alpha')||GETPOST('button_removefilter.x', 'alpha')||GETPOST('button_removefilter', 'alpha')) if(GETPOST('button_search_x', 'alpha')||GETPOST('button_search.x', 'alpha')||GETPOST('button_search', 'alpha')) if($action=="save" &&empty($cancel)) $help_url
View.
Definition: agenda.php:116
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
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
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
Product\TYPE_SERVICE
const TYPE_SERVICE
Service.
Definition: product.class.php:504
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
Product\TYPE_PRODUCT
const TYPE_PRODUCT
Regular product.
Definition: product.class.php:500
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