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