dolibarr  16.0.5
thirdpartyMargins.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/company.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 // Security check
32 $socid = GETPOST('socid', 'int');
33 if (!empty($user->socid)) {
34  $socid = $user->socid;
35 }
36 
37 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
38 $sortfield = GETPOST('sortfield', 'aZ09comma');
39 $sortorder = GETPOST('sortorder', 'aZ09comma');
40 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
41 if (empty($page) || $page == -1) {
42  $page = 0;
43 } // If $page is not defined, or '' or -1
44 $offset = $limit * $page;
45 $pageprev = $page - 1;
46 $pagenext = $page + 1;
47 if (!$sortorder) {
48  $sortorder = "DESC";
49 }
50 if (!$sortfield) {
51  $sortfield = "f.datef";
52 }
53 
54 $object = new Societe($db);
55 if ($socid > 0) {
56  $object->fetch($socid);
57 }
58 
59 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
60 $hookmanager->initHooks(array('thirdpartymargins', 'globalcard'));
61 
62 $result = restrictedArea($user, 'societe', $object->id, '');
63 
64 if (empty($user->rights->margins->liretous)) {
66 }
67 
68 
69 /*
70  * Actions
71  */
72 
73 $parameters = array('id'=>$socid);
74 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
75 if ($reshook < 0) {
76  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
77 }
78 
79 
80 
81 /*
82  * View
83  */
84 
85 $invoicestatic = new Facture($db);
86 $form = new Form($db);
87 
88 $title = $langs->trans("ThirdParty").' - '.$langs->trans("Margins");
89 if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
90  $title = $object->name.' - '.$langs->trans("Files");
91 }
92 $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
93 llxHeader('', $title, $help_url);
94 
95 if ($socid > 0) {
96  $object = new Societe($db);
97  $object->fetch($socid);
98 
99  /*
100  * Affichage onglets
101  */
102 
103  $head = societe_prepare_head($object);
104 
105  print dol_get_fiche_head($head, 'margin', $langs->trans("ThirdParty"), -1, 'company');
106 
107  $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
108 
109  dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
110 
111  print '<div class="fichecenter">';
112 
113  print '<div class="underbanner clearboth"></div>';
114  print '<table class="border tableforfield" width="100%">';
115 
116  // Type Prospect/Customer/Supplier
117  print '<tr><td class="titlefield">'.$langs->trans('NatureOfThirdParty').'</td><td>';
118  print $object->getTypeUrl(1);
119  print '</td></tr>';
120 
121  if ($object->client) {
122  print '<tr><td class="titlefield">';
123  print $langs->trans('CustomerCode').'</td><td colspan="3">';
124  print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client));
125  $tmpcheck = $object->check_codeclient();
126  if ($tmpcheck != 0 && $tmpcheck != -5) {
127  print ' <span class="error">('.$langs->trans("WrongCustomerCode").')</span>';
128  }
129  print '</td></tr>';
130  }
131 
132  if (((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || (!empty($conf->supplier_order->enabled) && !empty($user->rights->supplier_order->lire)) || (!empty($conf->supplier_invoice->enabled) && !empty($user->rights->supplier_invoice->lire))) && $object->fournisseur) {
133  print '<tr><td class="titlefield">';
134  print $langs->trans('SupplierCode').'</td><td colspan="3">';
135  print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur));
136  $tmpcheck = $object->check_codefournisseur();
137  if ($tmpcheck != 0 && $tmpcheck != -5) {
138  print ' <span class="error">('.$langs->trans("WrongSupplierCode").')</span>';
139  }
140  print '</td></tr>';
141  }
142 
143  // Total Margin
144  print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="3">';
145  print '<span id="totalMargin" class="amount"></span>'; // set by jquery (see below)
146  print '</td></tr>';
147 
148  // Margin Rate
149  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
150  print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="3">';
151  print '<span id="marginRate"></span>'; // set by jquery (see below)
152  print '</td></tr>';
153  }
154 
155  // Mark Rate
156  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
157  print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="3">';
158  print '<span id="markRate"></span>'; // set by jquery (see below)
159  print '</td></tr>';
160  }
161 
162  print "</table>";
163 
164  print '</div>';
165  print '<div style="clear:both"></div>';
166 
167  print dol_get_fiche_end();
168 
169  print '<br>';
170 
171  $sql = "SELECT distinct s.nom, s.rowid as socid, s.code_client,";
172  $sql .= " f.rowid as facid, f.ref, f.total_ht,";
173  $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
174  $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
175  $sql .= " sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // always positive
176  $sql .= " sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // always positive
177  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
178  $sql .= ", ".MAIN_DB_PREFIX."facture as f";
179  $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
180  $sql .= " WHERE f.fk_soc = s.rowid";
181  $sql .= " AND f.fk_statut > 0";
182  $sql .= " AND f.entity IN (".getEntity('invoice').")";
183  $sql .= " AND d.fk_facture = f.rowid";
184  $sql .= " AND f.fk_soc = $socid";
185  $sql .= " AND d.buy_price_ht IS NOT NULL";
186  // 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.
187  // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
188  if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
189  $sql .= " AND d.buy_price_ht <> 0";
190  }
191  $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";
192  $sql .= $db->order($sortfield, $sortorder);
193  // TODO: calculate total to display then restore pagination
194  //$sql.= $db->plimit($conf->liste_limit +1, $offset);
195 
196  dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG);
197  $result = $db->query($sql);
198  if ($result) {
199  $num = $db->num_rows($result);
200 
201  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, '');
202 
203  $i = 0;
204  print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
205  print "<table class=\"noborder\" width=\"100%\">";
206 
207  print '<tr class="liste_titre">';
208  print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder);
209  print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'center ');
210  print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
211  print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
212  print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
213  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
214  print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
215  }
216  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
217  print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
218  }
219  print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
220  print "</tr>\n";
221 
222  $cumul_achat = 0;
223  $cumul_vente = 0;
224 
225  if ($num > 0) {
226  while ($i < $num /*&& $i < $conf->liste_limit*/) {
227  $objp = $db->fetch_object($result);
228 
229  $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
230  $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
231 
232  $sign = '';
233  if ($objp->type == Facture::TYPE_CREDIT_NOTE) {
234  $sign = '-';
235  }
236 
237  print '<tr class="oddeven">';
238  print '<td>';
239  $invoicestatic->id = $objp->facid;
240  $invoicestatic->ref = $objp->ref;
241  print $invoicestatic->getNomUrl(1);
242  print "</td>\n";
243  print "<td class=\"center\">";
244  print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
245  print "<td class=\"right amount\">".price(price2num($objp->selling_price, 'MT'))."</td>\n";
246  print "<td class=\"right amount\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n";
247  print "<td class=\"right amount\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n";
248  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
249  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n";
250  }
251  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
252  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
253  }
254  print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
255  print "</tr>\n";
256  $i++;
257  $cumul_vente += $objp->selling_price;
258  $cumul_achat += ($objp->type == 2 ? -1 : 1) * $objp->buying_price;
259  }
260  }
261 
262  // affichage totaux marges
263 
264  $totalMargin = $cumul_vente - $cumul_achat;
265  if ($totalMargin < 0) {
266  $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
267  $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
268  } else {
269  $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
270  $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
271  }
272 
273  // Total
274  print '<tr class="liste_total">';
275  print '<td colspan=2>'.$langs->trans('TotalMargin')."</td>";
276  print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n";
277  print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n";
278  print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n";
279  if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
280  print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
281  }
282  if (!empty($conf->global->DISPLAY_MARK_RATES)) {
283  print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
284  }
285  print '<td class="right">&nbsp;</td>';
286  print "</tr>\n";
287  } else {
288  dol_print_error($db);
289  }
290  print "</table>";
291  print '</div>';
292 
293  print '<br>';
294  $db->free($result);
295 } else {
296  dol_print_error('', 'Parameter socid not defined');
297 }
298 
299 
300 print '
301  <script type="text/javascript">
302  $(document).ready(function() {
303  $("#totalMargin").html("'. price(price2num($totalMargin, 'MT')).'");
304  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
305  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
306  });
307  </script>
308 ';
309 
310 // End of page
311 llxFooter();
312 $db->close();
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
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
$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
showValueWithClipboardCPButton
showValueWithClipboardCPButton($valuetocopy, $showonlyonhover=1, $texttoshow='')
Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
Definition: functions.lib.php:11087
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
societe_prepare_head
societe_prepare_head(Societe $object)
Return array of tabs to used on pages for third parties cards.
Definition: company.lib.php:42
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
Facture\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: facture.class.php:392
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
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
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
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
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
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