dolibarr 20.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// 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 = GETPOSTINT('id');
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 = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
47$sortfield = GETPOST('sortfield', 'aZ09comma');
48$sortorder = GETPOST('sortorder', 'aZ09comma');
49$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
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 $object->next_prev_filter = "(te.fk_product_type:=:".((int) $object->type).")";
106
107 dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref');
108
109
110 print '<div class="fichecenter">';
111
112 print '<div class="underbanner clearboth"></div>';
113 print '<table class="border tableforfield centpercent">';
114
115 // Total Margin
116 print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td>';
117 print '<span id="totalMargin" class="amount"></span>'; // set by jquery (see below)
118 print '</td></tr>';
119
120 // Margin Rate
121 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
122 print '<tr><td>'.$langs->trans("MarginRate").'</td><td>';
123 print '<span id="marginRate"></span>'; // set by jquery (see below)
124 print '</td></tr>';
125 }
126
127 // Mark Rate
128 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
129 print '<tr><td>'.$langs->trans("MarkRate").'</td><td>';
130 print '<span id="markRate"></span>'; // set by jquery (see below)
131 print '</td></tr>';
132 }
133
134 print "</table>";
135
136 print '</div>';
137 print '<div class="clearboth"></div>';
138
139 print dol_get_fiche_end();
140
141
142 if ($user->hasRight("facture", "read")) {
143 $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,";
144 $sql .= " f.rowid as facid, f.ref, f.total_ht,";
145 $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
146 if (!$user->hasRight('societe', 'client', 'voir')) {
147 $sql .= " sc.fk_soc, sc.fk_user,";
148 }
149 $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
150 $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note
151 $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
152 $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
153 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
154 $sql .= ", ".MAIN_DB_PREFIX."facture as f";
155 $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
156 if (!$user->hasRight('societe', 'client', 'voir')) {
157 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
158 }
159 $sql .= " WHERE f.fk_soc = s.rowid";
160 $sql .= " AND f.fk_statut > 0";
161 $sql .= " AND f.entity IN (".getEntity('invoice').")";
162 $sql .= " AND d.fk_facture = f.rowid";
163 $sql .= " AND d.fk_product = ".((int) $object->id);
164 if (!$user->hasRight('societe', 'client', 'voir')) {
165 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
166 }
167 if (!empty($socid)) {
168 $sql .= " AND f.fk_soc = ".((int) $socid);
169 }
170 $sql .= " AND d.buy_price_ht IS NOT NULL";
171 // 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.
172 // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredictable.
173 if (getDolGlobalInt('ForceBuyingPriceIfNull') == 2) {
174 $sql .= " AND d.buy_price_ht <> 0";
175 }
176 $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";
177 if (!$user->hasRight('societe', 'client', 'voir')) {
178 $sql .= ", sc.fk_soc, sc.fk_user";
179 }
180 $sql .= $db->order($sortfield, $sortorder);
181 // TODO: calculate total to display then restore pagination
182 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
183 dol_syslog('margin:tabs:productMargins.php', LOG_DEBUG);
184 $result = $db->query($sql);
185 if ($result) {
186 $num = $db->num_rows($result);
187
188 print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=$object->id", $sortfield, $sortorder, '', 0, 0, '');
189
190 $i = 0;
191
192 print '<div class="div-table-responsive">';
193 print '<table class="noborder centpercent">';
194
195 print '<tr class="liste_titre">';
196 print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
197 print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
198 print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", "&amp;id=".$object->id, '', $sortfield, $sortorder);
199 print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'left ');
200 print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
201 print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
202 print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
203 print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
204 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
205 print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
206 }
207 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
208 print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
209 }
210 print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
211 print "</tr>\n";
212
213 $cumul_achat = 0;
214 $cumul_vente = 0;
215 $cumul_qty = 0;
216
217 if ($num > 0) {
218 while ($i < $num /*&& $i < $conf->liste_limit*/) {
219 $objp = $db->fetch_object($result);
220
221 $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
222 $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
223
224 print '<tr class="oddeven">';
225 print '<td>';
226 $invoicestatic->id = $objp->facid;
227 $invoicestatic->ref = $objp->ref;
228 print $invoicestatic->getNomUrl(1);
229 print "</td>\n";
230 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>';
231 print "<td>".$objp->code_client."</td>\n";
232 print '<td class="center">';
233 print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
234 print '<td class="right amount">'.price(price2num($objp->selling_price, 'MT'))."</td>\n";
235 print '<td class="right amount">'.price(price2num($objp->buying_price, 'MT'))."</td>\n";
236 print '<td class="right">'.price(price2num($objp->qty, 'MT'))."</td>\n";
237 print '<td class="right amount">'.price(price2num($objp->marge, 'MT'))."</td>\n";
238 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
239 print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
240 }
241 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
242 print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
243 }
244 print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
245 print "</tr>\n";
246 $i++;
247 $cumul_achat += $objp->buying_price;
248 $cumul_vente += $objp->selling_price;
249 $cumul_qty += $objp->qty;
250 }
251 }
252
253 // affichage totaux marges
254
255 $totalMargin = $cumul_vente - $cumul_achat;
256 if ($totalMargin < 0) {
257 $marginRate = ($cumul_achat != 0) ? -1 * (100 * $totalMargin / $cumul_achat) : '';
258 $markRate = ($cumul_vente != 0) ? -1 * (100 * $totalMargin / $cumul_vente) : '';
259 } else {
260 $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
261 $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
262 }
263 print '<tr class="liste_total">';
264 print '<td colspan=4>'.$langs->trans('TotalMargin')."</td>";
265 print '<td class="right amount">'.price(price2num($cumul_vente, 'MT'))."</td>\n";
266 print '<td class="right amount">'.price(price2num($cumul_achat, 'MT'))."</td>\n";
267 print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n";
268 print '<td class="right amount">'.price(price2num($totalMargin, 'MT'))."</td>\n";
269 if (getDolGlobalString('DISPLAY_MARGIN_RATES')) {
270 print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
271 }
272 if (getDolGlobalString('DISPLAY_MARK_RATES')) {
273 print '<td class="right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
274 }
275 print '<td class="right">&nbsp;</td>';
276 print "</tr>\n";
277 print "</table>";
278 print '</div>';
279 } else {
280 dol_print_error($db);
281 }
282 $db->free($result);
283 }
284 }
285} else {
287}
288
289print '
290 <script type="text/javascript">
291 $(document).ready(function() {
292 $("#totalMargin").html("'. price(price2num($totalMargin, 'MT'), 1, $langs, 1, -1, -1, $conf->currency).'");
293 $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
294 $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
295 });
296 </script>
297';
298
299// End of page
300llxFooter();
301$db->close();
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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_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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
print_barre_liste($title, $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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.