dolibarr 24.0.0-beta
checkMargins.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
3 * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
4 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
5 * Copyright (C) 2016 Florian Henry <florian.henry@open-concept.pro>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28require '../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
31require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
32require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
33
42// Load translation files required by the page
43$langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
44
45$action = GETPOST('action', 'alpha');
46$massaction = GETPOST('massaction', 'alpha');
47$toselect = GETPOST('toselect', 'array:int');
48$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'margindetail'; // To manage different context of search
49$backtopage = GETPOST('backtopage', 'alpha');
50$optioncss = GETPOST('optioncss', 'alpha');
51
52// Load variable for pagination
53$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
54$sortfield = GETPOST('sortfield', 'aZ09comma');
55$sortorder = GETPOST('sortorder', 'aZ09comma');
56$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
57if (empty($page) || $page == -1) {
58 $page = 0;
59} // If $page is not defined, or '' or -1
60$offset = $limit * $page;
61$pageprev = $page - 1;
62$pagenext = $page + 1;
63if (!$sortorder) {
64 $sortorder = "DESC";
65}
66if (!$sortfield) {
67 $sortfield = 'f.ref';
68}
69
70$startdate = $enddate = '';
71
72$startdate = dol_mktime(0, 0, 0, GETPOSTINT('startdatemonth'), GETPOSTINT('startdateday'), GETPOSTINT('startdateyear'));
73$enddate = dol_mktime(23, 59, 59, GETPOSTINT('enddatemonth'), GETPOSTINT('enddateday'), GETPOSTINT('enddateyear'));
74
75$search_ref = GETPOST('search_ref', 'alpha');
76
77$hookmanager->initHooks(array('checkmarginlist'));
78
79// Security check
80$result = restrictedArea($user, 'margins');
81
82// Both test are required to be compatible with all browsers
83if (GETPOST("button_search_x") || GETPOST("button_search")) {
84 $action = 'search';
85} elseif (GETPOST("button_updatemagins_x") || GETPOST("button_updatemagins")) {
86 $action = 'update';
87}
88
89$permissiontocreate = $user->hasRight('facture', 'creer');
90
91
92/*
93 * Actions
94 */
95
96if (GETPOST('cancel', 'alpha')) {
97 $action = 'list';
98 $massaction = '';
99}
100if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
101 $massaction = '';
102}
103
104$parameters = array();
105$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
106if ($reshook < 0) {
107 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
108}
109
110if (empty($reshook)) {
111 // Selection of new fields
112 include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
113
114 if ($action == 'update' && $permissiontocreate) {
115 $datapost = $_POST;
116
117 foreach ($datapost as $key => $value) {
118 if (strpos($key, 'buyingprice_') !== false) {
119 $tmp_array = explode('_', $key);
120 if (count($tmp_array) > 0) {
121 $invoicedet_id = $tmp_array[1];
122 if (!empty($invoicedet_id)) {
123 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facturedet';
124 $sql .= " SET buy_price_ht = ".((float) price2num($value));
125 $sql .= ' WHERE rowid = '.((int) $invoicedet_id);
126 $result = $db->query($sql);
127 if (!$result) {
128 setEventMessages($db->lasterror, null, 'errors');
129 }
130 }
131 }
132 }
133 }
134 }
135
136 // Purge search criteria
137 if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
138 $search_ref = '';
139 $search_array_options = array();
140 }
141
142 // Mass actions
143 /*
144 $objectclass='Product';
145 if ((string) $type == '1') { $objectlabel='Services'; }
146 if ((string) $type == '0') { $objectlabel='Products'; }
147
148 $permissiontoread = $user->rights->produit->lire;
149 $permissiontodelete = $user->rights->produit->supprimer;
150 $uploaddir = $conf->product->dir_output;
151 include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
152 */
153}
154
155
156/*
157 * View
158 */
159
160$userstatic = new User($db);
161$companystatic = new Societe($db);
162$invoicestatic = new Facture($db);
163$productstatic = new Product($db);
164
165$form = new Form($db);
166
167$title = $langs->trans("MarginDetails");
168
169llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-margin page-checkmargins');
170
171// print load_fiche_titre($text);
172
173$param = '';
174if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
175 $param .= '&contextpage='.$contextpage;
176}
177if ($limit > 0 && $limit != $conf->liste_limit) {
178 $param .= '&limit='.$limit;
179}
180if ($search_ref != '') {
181 $param .= '&search_ref='.urlencode($search_ref);
182}
183if (!empty($startdate)) {
184 $param .= '&startdatemonth='.GETPOSTINT('startdatemonth').'&startdateday='.GETPOSTINT('startdateday').'&startdateyear='.GETPOSTINT('startdateyear');
185}
186if (!empty($enddate)) {
187 $param .= '&enddatemonth='.GETPOSTINT('enddatemonth').'&enddateday='.GETPOSTINT('enddateday').'&enddateyear='.GETPOSTINT('enddateyear');
188}
189if ($optioncss != '') {
190 $param .= '&optioncss='.$optioncss;
191}
192
193// Show tabs
194$head = marges_prepare_head();
195
196$picto = 'margin';
197
198print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
199print '<input type="hidden" name="token" value="'.newToken().'">';
200
201print dol_get_fiche_head($head, $langs->trans('checkMargins'), $title, 0, $picto);
202
203print '<table class="border centpercent">';
204
205print '<tr><td class="titlefield">'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
206print '<td>';
207print $form->selectDate($startdate, 'startdate', 0, 0, 1, "sel", 1, 1);
208print '</td>';
209print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
210print '<td>';
211print $form->selectDate($enddate, 'enddate', 0, 0, 1, "sel", 1, 1);
212print '</td>';
213print '<td style="text-align: center;">';
214print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" name="button_search" />';
215print '</td>';
216print '</tr>';
217print "</table>";
218
219print dol_get_fiche_end();
220
221
222$arrayfields = array();
223$massactionbutton = '';
224
225$invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
226
227$sql = "SELECT";
228$sql .= " f.ref, f.rowid as invoiceid,";
229$sql .= " d.rowid as invoicedetid, d.product_type, d.buy_price_ht, d.total_ht, d.subprice, d.label, d.description, d.qty, d.fk_product";
230$sql .= " FROM ".MAIN_DB_PREFIX."facture as f ";
231$sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as d ON d.fk_facture = f.rowid";
232$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
233$sql .= " WHERE f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
234
235$sql .= " AND f.entity IN (".getEntity('invoice').") ";
236if (!empty($startdate)) {
237 $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
238}
239if (!empty($enddate)) {
240 $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
241}
242if ($search_ref) {
243 $sql .= natural_search('f.ref', $search_ref);
244}
245$sql .= " AND d.buy_price_ht IS NOT NULL";
246
247
248$parameters = array();
249$hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action);
250$sql .= $hookmanager->resPrint;
251
252
253$sql .= $db->order($sortfield, $sortorder);
254
255$nbtotalofrecords = '';
256if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
257 dol_syslog(__FILE__, LOG_DEBUG);
258 $result = $db->query($sql);
259 $nbtotalofrecords = $db->num_rows($result);
260 if (($page * $limit) > (int) $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
261 $page = 0;
262 $offset = 0;
263 }
264}
265
266$sql .= $db->plimit($limit + 1, $offset);
267
268$result = $db->query($sql);
269if ($result) {
270 $num = $db->num_rows($result);
271
272 print '<br>';
273 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
274 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1);
275
276 if (getDolGlobalString('MARGIN_TYPE') == "1") {
277 $labelcostprice = 'BuyingPrice';
278 } else { // value is 'costprice' or 'pmp'
279 $labelcostprice = 'CostPrice';
280 }
281
282 $moreforfilter = '';
283
284 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
285 //$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
286 //if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
287 $selectedfields = '';
288
289 print '<div class="div-table-responsive">';
290 print '<table class="tagtable noborder nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
291
292 print '<tr class="liste_titre liste_titre_search">';
293 if ($conf->main_checkbox_left_column) {
294 print '<td class="liste_titre center">';
295 $searchpitco = $form->showFilterButtons();
296 print $searchpitco;
297 print '</td>';
298 }
299 print '<td><input type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
300 print '<td></td>';
301 print '<td></td>';
302 print '<td></td>';
303 print '<td></td>';
304 print '<td></td>';
305 if (!$conf->main_checkbox_left_column) {
306 print '<td class="liste_titre center">';
307 $searchpitco = $form->showFilterButtons();
308 print $searchpitco;
309 print '</td>';
310 }
311 print "</tr>\n";
312
313 print '<tr class="liste_titre">';
314 if ($conf->main_checkbox_left_column) {
315 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
316 }
317 print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
318 print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder);
319 print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "d.subprice", "", $param, '', $sortfield, $sortorder, 'right ');
320 print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "d.buy_price_ht", "", $param, '', $sortfield, $sortorder, 'right ');
321 print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $param, '', $sortfield, $sortorder, 'right ');
322 print_liste_field_titre("AmountTTC", $_SERVER["PHP_SELF"], "d.total_ht", "", $param, '', $sortfield, $sortorder, 'right ');
323 if (!$conf->main_checkbox_left_column) {
324 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
325 }
326 print "</tr>\n";
327
328 $i = 0;
329 while ($i < min($num, $limit)) {
330 $objp = $db->fetch_object($result);
331
332 print '<tr class="oddeven">';
333
334 if ($conf->main_checkbox_left_column) {
335 print '<td></td>';
336 }
337
338 print '<td>';
339 $result_inner = $invoicestatic->fetch($objp->invoiceid);
340 if ($result_inner < 0) {
341 setEventMessages($invoicestatic->error, null, 'errors');
342 } else {
343 print $invoicestatic->getNomUrl(1);
344 }
345 print '</td>';
346 print '<td>';
347 if (!empty($objp->fk_product)) {
348 $result_inner = $productstatic->fetch($objp->fk_product);
349 if ($result_inner < 0) {
350 setEventMessages($productstatic->error, null, 'errors');
351 } else {
352 print $productstatic->getNomUrl(1);
353 }
354 } else {
355 if ($objp->product_type == $productstatic::TYPE_PRODUCT) {
356 print img_picto('', 'product');
357 }
358 if ($objp->product_type == $productstatic::TYPE_SERVICE) {
359 print img_picto('', 'service');
360 }
361 print $objp->label;
362 print '&nbsp;';
363 print $objp->description;
364 }
365 print '</td>';
366 print '<td class="right">';
367 print price($objp->subprice);
368 print '</td>';
369 print '<td class="right">';
370 print '<input type="text" name="buyingprice_'.$objp->invoicedetid.'" id="buyingprice_'.$objp->invoicedetid.'" size="6" value="'.price($objp->buy_price_ht).'" class="right flat">';
371 print '</td>';
372 print '<td class="right">';
373 print $objp->qty;
374 print '</td>';
375 print '<td class="right">';
376 print '<span class="amount">'.price($objp->total_ht).'</span>';
377 print '</td>';
378
379 if (!$conf->main_checkbox_left_column) {
380 print '<td></td>';
381 }
382
383 print "</tr>\n";
384
385 $i++;
386 }
387
388 if ($num == 0) {
389 print '<tr class=""><td colspan="7">';
390 print '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
391 print '</td></tr>';
392 }
393
394 print "</table>";
395
396 print "</div>";
397} else {
399}
400
401
402print '<div class="center">'."\n";
403print '<input type="submit" class="button" name="button_updatemagins" id="button_updatemagins" value="'.$langs->trans("Update").'">';
404print '</div>';
405
406print '</form>';
407
408$db->free($result);
409
410// End of page
411llxFooter();
412$db->close();
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const STATUS_ABANDONED
Classified abandoned and no payment done.
Class to manage generation of HTML components Only common components must be here.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
print_liste_field_titre($name, $file="", $field="", $begin="", $param="", $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, $selectlimitsuffix=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (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, $morecssdiv='')
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.
natural_search($fields, $value, $mode=0, $nofirstand=0, $sqltoadd='')
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
marges_prepare_head()
Return array of tabs to used on pages for third parties cards.
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.