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  *
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)) $socid = $user->socid;
40 $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
41 if (empty($user->rights->margins->liretous)) accessforbidden();
42 
43 $object = new Product($db);
44 
45 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
46 $sortfield = GETPOST("sortfield", 'alpha');
47 $sortorder = GETPOST("sortorder", 'alpha');
48 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
49 if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
50 $offset = $limit * $page;
51 $pageprev = $page - 1;
52 $pagenext = $page + 1;
53 if (!$sortorder) $sortorder = "DESC";
54 if (!$sortfield) $sortfield = "f.datef";
55 
56 
57 /*
58  * View
59  */
60 
61 $invoicestatic = new Facture($db);
62 
63 $form = new Form($db);
64 
65 if ($id > 0 || !empty($ref))
66 {
67  $result = $object->fetch($id, $ref);
68 
69  $title = $langs->trans('ProductServiceCard');
70  $helpurl = '';
71  $shortlabel = dol_trunc($object->label, 16);
72  if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT))
73  {
74  $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card');
75  $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
76  }
77  if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE))
78  {
79  $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card');
80  $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
81  }
82 
83  llxHeader('', $title, $helpurl);
84 
85  /*
86  * En mode visu
87  */
88  if ($result > 0)
89  {
90  $head = product_prepare_head($object);
91  $titre = $langs->trans("CardProduct".$object->type);
92  $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
93  print dol_get_fiche_head($head, 'margin', $titre, -1, $picto);
94 
95  $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
96 
97  dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref');
98 
99 
100  print '<div class="fichecenter">';
101 
102  print '<div class="underbanner clearboth"></div>';
103  print '<table class="border tableforfield" width="100%">';
104 
105  // Total Margin
106  print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="3">';
107  print '<span id="totalMargin"></span>'; // set by jquery (see below)
108  print '</td></tr>';
109 
110  // Margin Rate
111  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
112  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="3">';
113  print '<span id="marginRate"></span>'; // set by jquery (see below)
114  print '</td></tr>';
115  }
116 
117  // Mark Rate
118  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
119  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="3">';
120  print '<span id="markRate"></span>'; // set by jquery (see below)
121  print '</td></tr>';
122  }
123 
124  print "</table>";
125 
126  print '</div>';
127  print '<div style="clear:both"></div>';
128 
130 
131 
132  if ($user->rights->facture->lire) {
133  $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,";
134  $sql .= " f.rowid as facid, f.ref, f.total as total_ht,";
135  $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
136  if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,";
137  $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
138  $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note
139  $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
140  $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
141  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
142  $sql .= ", ".MAIN_DB_PREFIX."facture as f";
143  $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
144  if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
145  $sql .= " WHERE f.fk_soc = s.rowid";
146  $sql .= " AND f.fk_statut > 0";
147  $sql .= " AND f.entity IN (".getEntity('invoice').")";
148  $sql .= " AND d.fk_facture = f.rowid";
149  $sql .= " AND d.fk_product =".$object->id;
150  if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
151  if (!empty($socid)) $sql .= " AND f.fk_soc = $socid";
152  $sql .= " AND d.buy_price_ht IS NOT NULL";
153  if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0";
154  $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type";
155  if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
156  $sql .= $db->order($sortfield, $sortorder);
157  // TODO: calculate total to display then restore pagination
158  //$sql.= $db->plimit($conf->liste_limit +1, $offset);
159  dol_syslog('margin:tabs:productMargins.php', LOG_DEBUG);
160  $result = $db->query($sql);
161  if ($result) {
162  $num = $db->num_rows($result);
163 
164  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=$object->id", $sortfield, $sortorder, '', 0, 0, '');
165 
166  $i = 0;
167 
168  print '<div class="div-table-responsive">';
169  print '<table class="noborder centpercent">';
170 
171  print '<tr class="liste_titre">';
172  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
173  print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
174  print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
175  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'left ');
176  print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
177  print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
178  print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
179  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
180  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
181  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
182  if (!empty($conf->global->DISPLAY_MARK_RATES))
183  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
184  print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
185  print "</tr>\n";
186 
187  $cumul_achat = 0;
188  $cumul_vente = 0;
189  $cumul_qty = 0;
190 
191  if ($num > 0) {
192  while ($i < $num /*&& $i < $conf->liste_limit*/) {
193  $objp = $db->fetch_object($result);
194 
195  $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
196  $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
197 
198  print '<tr class="oddeven">';
199  print '<td>';
200  $invoicestatic->id = $objp->facid;
201  $invoicestatic->ref = $objp->ref;
202  print $invoicestatic->getNomUrl(1);
203  print "</td>\n";
204  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>';
205  print "<td>".$objp->code_client."</td>\n";
206  print "<td class=\"center\">";
207  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
208  print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n";
209  print "<td class=\"right\">".price(price2num($objp->buying_price, 'MT'))."</td>\n";
210  print "<td class=\"right\">".price(price2num($objp->qty, 'MT'))."</td>\n";
211  print "<td class=\"right\">".price(price2num($objp->marge, 'MT'))."</td>\n";
212  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
213  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
214  if (!empty($conf->global->DISPLAY_MARK_RATES))
215  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
216  print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
217  print "</tr>\n";
218  $i++;
219  $cumul_achat += $objp->buying_price;
220  $cumul_vente += $objp->selling_price;
221  $cumul_qty += $objp->qty;
222  }
223  }
224 
225  // affichage totaux marges
226 
227  $totalMargin = $cumul_vente - $cumul_achat;
228  if ($totalMargin < 0)
229  {
230  $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
231  $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
232  } else {
233  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
234  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
235  }
236  print '<tr class="liste_total">';
237  print '<td colspan=4>'.$langs->trans('TotalMargin')."</td>";
238  print '<td class="right">'.price(price2num($cumul_vente, 'MT'))."</td>\n";
239  print '<td class="right">'.price(price2num($cumul_achat, 'MT'))."</td>\n";
240  print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n";
241  print '<td class="right">'.price(price2num($totalMargin, 'MT'))."</td>\n";
242  if (!empty($conf->global->DISPLAY_MARGIN_RATES))
243  print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
244  if (!empty($conf->global->DISPLAY_MARK_RATES))
245  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
246  print '<td class="right">&nbsp;</td>';
247  print "</tr>\n";
248  print "</table>";
249  print '</div>';
250  } else {
251  dol_print_error($db);
252  }
253  $db->free($result);
254  }
255  }
256 } else {
257  dol_print_error();
258 }
259 
260 print '
261  <script type="text/javascript">
262  $(document).ready(function() {
263  $("#totalMargin").html("'. price(price2num($totalMargin, 'MT')).'");
264  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
265  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
266  });
267  </script>
268 ';
269 
270 // End of page
271 llxFooter();
272 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Class to manage products or services.
const TYPE_SERVICE
Service.
const TYPE_PRODUCT
Regular product.
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.
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;...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
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 ...
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.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
Class to manage invoices.
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.
llxFooter()
Empty footer.
Definition: wrapper.php:59
product_prepare_head($object)
Prepare array with list of tabs.
Definition: product.lib.php:35