dolibarr 19.0.4
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// Load Dolibarr environment
25require '../../main.inc.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
27require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
28require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
29
30$langs->loadLangs(array("companies", "bills", "products", "margins"));
31
32$id = GETPOST('id', 'int');
33$ref = GETPOST('ref', 'alpha');
34$action = GETPOST('action', 'aZ09');
35$confirm = GETPOST('confirm', 'alpha');
36
37// Security check
38$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
39$fieldtype = (!empty($ref) ? 'ref' : 'rowid');
40if (!empty($user->socid)) {
41 $socid = $user->socid;
42}
43
44$object = new Product($db);
45
46$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
47$sortfield = GETPOST('sortfield', 'aZ09comma');
48$sortorder = GETPOST('sortorder', 'aZ09comma');
49$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
50if (empty($page) || $page == -1) {
51 $page = 0;
52} // If $page is not defined, or '' or -1
53$offset = $limit * $page;
54$pageprev = $page - 1;
55$pagenext = $page + 1;
56if (!$sortorder) {
57 $sortorder = "DESC";
58}
59if (!$sortfield) {
60 $sortfield = "f.datef";
61}
62
63$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
64
65if (!$user->hasRight('margins', 'liretous')) {
67}
68
69
70/*
71 * View
72 */
73
74$invoicestatic = new Facture($db);
75
76$form = new Form($db);
77$totalMargin = 0;
78$marginRate = '';
79$markRate = '';
80if ($id > 0 || !empty($ref)) {
81 $result = $object->fetch($id, $ref);
82
83 $title = $langs->trans('ProductServiceCard');
84 $help_url = '';
85 $shortlabel = dol_trunc($object->label, 16);
86 if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
87 $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card');
88 $help_url = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
89 }
90 if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
91 $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card');
92 $help_url = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
93 }
94
95 llxHeader('', $title, $help_url);
96
97 // View mode
98 if ($result > 0) {
99 $head = product_prepare_head($object);
100 $titre = $langs->trans("CardProduct".$object->type);
101 $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
102 print dol_get_fiche_head($head, 'margin', $titre, -1, $picto);
103
104 $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
105
106 dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref');
107
108
109 print '<div class="fichecenter">';
110
111 print '<div class="underbanner clearboth"></div>';
112 print '<table class="border tableforfield centpercent">';
113
114 // Total Margin
115 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td>';
116 print '<span id="totalMargin" class="amount"></span>'; // set by jquery (see below)
117 print '</td></tr>';
118
119 // Margin Rate
120 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
121 print '<tr><td>'.$langs->trans("MarginRate").'</td><td>';
122 print '<span id="marginRate"></span>'; // set by jquery (see below)
123 print '</td></tr>';
124 }
125
126 // Mark Rate
127 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
128 print '<tr><td>'.$langs->trans("MarkRate").'</td><td>';
129 print '<span id="markRate"></span>'; // set by jquery (see below)
130 print '</td></tr>';
131 }
132
133 print "</table>";
134
135 print '</div>';
136 print '<div class="clearboth"></div>';
137
138 print dol_get_fiche_end();
139
140
141 if ($user->hasRight("facture", "read")) {
142 $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,";
143 $sql .= " f.rowid as facid, f.ref, f.total_ht,";
144 $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
145 if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
146 $sql .= " sc.fk_soc, sc.fk_user,";
147 }
148 $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
149 $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note
150 $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
151 $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
152 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
153 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
154 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
155 if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
156 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
157 }
158 $sql .= " WHERE f.fk_soc = s.rowid";
159 $sql .= " AND f.fk_statut > 0";
160 $sql .= " AND f.entity IN (".getEntity('invoice').")";
161 $sql .= " AND d.fk_facture = f.rowid";
162 $sql .= " AND d.fk_product = ".((int) $object->id);
163 if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
164 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
165 }
166 if (!empty($socid)) {
167 $sql .= " AND f.fk_soc = ".((int) $socid);
168 }
169 $sql .= " AND d.buy_price_ht IS NOT NULL";
170 // 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.
171 // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
172 if (getDolGlobalInt('ForceBuyingPriceIfNull') == 2) {
173 $sql .= " AND d.buy_price_ht <> 0";
174 }
175 $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";
176 if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
177 $sql .= ", sc.fk_soc, sc.fk_user";
178 }
179 $sql .= $db->order($sortfield, $sortorder);
180 // TODO: calculate total to display then restore pagination
181 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
182 dol_syslog('margin:tabs:productMargins.php', LOG_DEBUG);
183 $result = $db->query($sql);
184 if ($result) {
185 $num = $db->num_rows($result);
186
187 print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=$object->id", $sortfield, $sortorder, '', 0, 0, '');
188
189 $i = 0;
190
191 print '<div class="div-table-responsive">';
192 print '<table class="noborder centpercent">';
193
194 print '<tr class="liste_titre">';
195 print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
196 print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
197 print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
198 print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'left ');
199 print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
200 print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
201 print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
202 print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
203 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
204 print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
205 }
206 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
207 print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
208 }
209 print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
210 print "</tr>\n";
211
212 $cumul_achat = 0;
213 $cumul_vente = 0;
214 $cumul_qty = 0;
215
216 if ($num > 0) {
217 while ($i < $num /*&& $i < $conf->liste_limit*/) {
218 $objp = $db->fetch_object($result);
219
220 $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
221 $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
222
223 print '<tr class="oddeven">';
224 print '<td>';
225 $invoicestatic->id = $objp->facid;
226 $invoicestatic->ref = $objp->ref;
227 print $invoicestatic->getNomUrl(1);
228 print "</td>\n";
229 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>';
230 print "<td>".$objp->code_client."</td>\n";
231 print '<td class="center">';
232 print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
233 print '<td class="right amount">'.price(price2num($objp->selling_price, 'MT'))."</td>\n";
234 print '<td class="right amount">'.price(price2num($objp->buying_price, 'MT'))."</td>\n";
235 print '<td class="right">'.price(price2num($objp->qty, 'MT'))."</td>\n";
236 print '<td class="right amount">'.price(price2num($objp->marge, 'MT'))."</td>\n";
237 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
238 print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
239 }
240 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
241 print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
242 }
243 print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
244 print "</tr>\n";
245 $i++;
246 $cumul_achat += $objp->buying_price;
247 $cumul_vente += $objp->selling_price;
248 $cumul_qty += $objp->qty;
249 }
250 }
251
252 // affichage totaux marges
253
254 $totalMargin = $cumul_vente - $cumul_achat;
255 if ($totalMargin < 0) {
256 $marginRate = ($cumul_achat != 0) ? -1 * (100 * $totalMargin / $cumul_achat) : '';
257 $markRate = ($cumul_vente != 0) ? -1 * (100 * $totalMargin / $cumul_vente) : '';
258 } else {
259 $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
260 $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
261 }
262 print '<tr class="liste_total">';
263 print '<td colspan=4>'.$langs->trans('TotalMargin')."</td>";
264 print '<td class="right amount">'.price(price2num($cumul_vente, 'MT'))."</td>\n";
265 print '<td class="right amount">'.price(price2num($cumul_achat, 'MT'))."</td>\n";
266 print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n";
267 print '<td class="right amount">'.price(price2num($totalMargin, 'MT'))."</td>\n";
268 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
269 print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
270 }
271 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
272 print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
273 }
274 print '<td class="right">&nbsp;</td>';
275 print "</tr>\n";
276 print "</table>";
277 print '</div>';
278 } else {
279 dol_print_error($db);
280 }
281 $db->free($result);
282 }
283 }
284} else {
286}
287
288print '
289 <script type="text/javascript">
290 $(document).ready(function() {
291 $("#totalMargin").html("'. price(price2num($totalMargin, 'MT')).'");
292 $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
293 $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
294 });
295 </script>
296';
297
298// End of page
299llxFooter();
300$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:55
llxFooter()
Empty footer.
Definition wrapper.php:69
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
const TYPE_SERVICE
Service.
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.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
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...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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).
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
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.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
product_prepare_head($object)
Prepare array with list of tabs.
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.