dolibarr  16.0.5
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  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
26 require '../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
31 
32 // Load translation files required by the page
33 $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
34 
35 $action = GETPOST('action', 'alpha');
36 $massaction = GETPOST('massaction', 'alpha');
37 $toselect = GETPOST('toselect', 'array');
38 $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'margindetail'; // To manage different context of search
39 $backtopage = GETPOST('backtopage', 'alpha');
40 $optioncss = GETPOST('optioncss', 'alpha');
41 
42 // Load variable for pagination
43 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
44 $sortfield = GETPOST('sortfield', 'aZ09comma');
45 $sortorder = GETPOST('sortorder', 'aZ09comma');
46 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
47 if (empty($page) || $page == -1) {
48  $page = 0;
49 } // If $page is not defined, or '' or -1
50 $offset = $limit * $page;
51 $pageprev = $page - 1;
52 $pagenext = $page + 1;
53 if (!$sortorder) {
54  $sortorder = "DESC";
55 }
56 if (!$sortfield) {
57  $sortfield = 'f.ref';
58 }
59 
60 $startdate = $enddate = '';
61 
62 $startdate = dol_mktime(0, 0, 0, GETPOST('startdatemonth', 'int'), GETPOST('startdateday', 'int'), GETPOST('startdateyear', 'int'));
63 $enddate = dol_mktime(23, 59, 59, GETPOST('enddatemonth', 'int'), GETPOST('enddateday', 'int'), GETPOST('enddateyear', 'int'));
64 
65 $search_ref = GETPOST('search_ref', 'alpha');
66 
67 // Security check
68 $result = restrictedArea($user, 'margins');
69 
70 // Both test are required to be compatible with all browsers
71 if (GETPOST("button_search_x") || GETPOST("button_search")) {
72  $action = 'search';
73 } elseif (GETPOST("button_updatemagins_x") || GETPOST("button_updatemagins")) {
74  $action = 'update';
75 }
76 
77 
78 /*
79  * Actions
80  */
81 
82 if (GETPOST('cancel', 'alpha')) {
83  $action = 'list'; $massaction = '';
84 }
85 if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
86  $massaction = '';
87 }
88 
89 $parameters = array();
90 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
91 if ($reshook < 0) {
92  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
93 }
94 
95 if (empty($reshook)) {
96  // Selection of new fields
97  include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
98 
99  if ($action == 'update') {
100  $datapost = $_POST;
101 
102  foreach ($datapost as $key => $value) {
103  if (strpos($key, 'buyingprice_') !== false) {
104  $tmp_array = explode('_', $key);
105  if (count($tmp_array) > 0) {
106  $invoicedet_id = $tmp_array[1];
107  if (!empty($invoicedet_id)) {
108  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facturedet';
109  $sql .= " SET buy_price_ht = ".((float) price2num($value));
110  $sql .= ' WHERE rowid = '.((int) $invoicedet_id);
111  $result = $db->query($sql);
112  if (!$result) {
113  setEventMessages($db->lasterror, null, 'errors');
114  }
115  }
116  }
117  }
118  }
119  }
120 
121  // Purge search criteria
122  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
123  $search_ref = '';
124  $search_array_options = array();
125  }
126 
127  // Mass actions
128  /*
129  $objectclass='Product';
130  if ((string) $type == '1') { $objectlabel='Services'; }
131  if ((string) $type == '0') { $objectlabel='Products'; }
132 
133  $permissiontoread = $user->rights->produit->lire;
134  $permissiontodelete = $user->rights->produit->supprimer;
135  $uploaddir = $conf->product->dir_output;
136  include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
137  */
138 }
139 
140 
141 /*
142  * View
143  */
144 
145 $userstatic = new User($db);
146 $companystatic = new Societe($db);
147 $invoicestatic = new Facture($db);
148 $productstatic = new Product($db);
149 
150 $form = new Form($db);
151 
152 $title = $langs->trans("Margins");
153 
154 llxHeader('', $title);
155 
156 // print load_fiche_titre($text);
157 
158 $param = '';
159 if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
160  $param .= '&contextpage='.$contextpage;
161 }
162 if ($limit > 0 && $limit != $conf->liste_limit) {
163  $param .= '&limit='.$limit;
164 }
165 if ($search_ref != '') {
166  $param .= '&search_ref='.urlencode($search_ref);
167 }
168 if (!empty($startdate)) {
169  $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int').'&startdateday='.GETPOST('startdateday', 'int').'&startdateyear='.GETPOST('startdateyear', 'int');
170 }
171 if (!empty($enddate)) {
172  $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int').'&enddateday='.GETPOST('enddateday', 'int').'&enddateyear='.GETPOST('enddateyear', 'int');
173 }
174 if ($optioncss != '') {
175  $param .= '&optioncss='.$optioncss;
176 }
177 
178 // Show tabs
179 $head = marges_prepare_head($user);
180 $picto = 'margin';
181 
182 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
183 print '<input type="hidden" name="token" value="'.newToken().'">';
184 
185 print dol_get_fiche_head($head, $langs->trans('checkMargins'), $title, 0, $picto);
186 
187 print '<table class="border centpercent">';
188 
189 print '<tr><td class="titlefield">'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
190 print '<td>';
191 print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
192 print '</td>';
193 print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
194 print '<td>';
195 print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
196 print '</td>';
197 print '<td style="text-align: center;">';
198 print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" name="button_search" />';
199 print '</td>';
200 print '</tr>';
201 print "</table>";
202 
203 print dol_get_fiche_end();
204 
205 
206 $arrayfields = array();
207 $massactionbutton = '';
208 
209 $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
210 
211 $sql = "SELECT";
212 $sql .= " f.ref, f.rowid as invoiceid,";
213 $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";
214 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f ";
215 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as d ON d.fk_facture = f.rowid";
216 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
217 $sql .= " WHERE f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
218 $sql .= " AND f.entity IN (".getEntity('invoice').") ";
219 if (!empty($startdate)) {
220  $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
221 }
222 if (!empty($enddate)) {
223  $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
224 }
225 if ($search_ref) {
226  $sql .= natural_search('f.ref', $search_ref);
227 }
228 $sql .= " AND d.buy_price_ht IS NOT NULL";
229 $sql .= $db->order($sortfield, $sortorder);
230 
231 $nbtotalofrecords = '';
232 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
233  dol_syslog(__FILE__, LOG_DEBUG);
234  $result = $db->query($sql);
235  $nbtotalofrecords = $db->num_rows($result);
236  if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
237  $page = 0;
238  $offset = 0;
239  }
240 }
241 
242 $sql .= $db->plimit($limit + 1, $offset);
243 
244 $result = $db->query($sql);
245 if ($result) {
246  $num = $db->num_rows($result);
247 
248  print '<br>';
249  print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
250 
251  if ($conf->global->MARGIN_TYPE == "1") {
252  $labelcostprice = 'BuyingPrice';
253  } else { // value is 'costprice' or 'pmp'
254  $labelcostprice = 'CostPrice';
255  }
256 
257  $moreforfilter = '';
258 
259  $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
260  //$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
261  //if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
262  $selectedfields = '';
263 
264  print '<div class="div-table-responsive">';
265  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
266 
267  print '<tr class="liste_titre liste_titre_search">';
268  print '<td><input type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
269  print '<td></td>';
270  print '<td></td>';
271  print '<td></td>';
272  print '<td></td>';
273  print '<td></td>';
274  print '<td class="liste_titre" align="middle">';
275  $searchpitco = $form->showFilterButtons();
276  print $searchpitco;
277  print '</td>';
278  print "</tr>\n";
279 
280  print '<tr class="liste_titre">';
281  print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
282  print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder);
283  print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "d.subprice", "", $param, '', $sortfield, $sortorder, 'right ');
284  print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "d.buy_price_ht", "", $param, '', $sortfield, $sortorder, 'right ');
285  print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $param, '', $sortfield, $sortorder, 'right ');
286  print_liste_field_titre("AmountTTC", $_SERVER["PHP_SELF"], "d.total_ht", "", $param, '', $sortfield, $sortorder, 'right ');
287  print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
288  print "</tr>\n";
289 
290  $i = 0;
291  while ($i < min($num, $limit)) {
292  $objp = $db->fetch_object($result);
293 
294  print '<tr class="oddeven">';
295  print '<td>';
296  $result_inner = $invoicestatic->fetch($objp->invoiceid);
297  if ($result_inner < 0) {
298  setEventMessages($invoicestatic->error, null, 'errors');
299  } else {
300  print $invoicestatic->getNomUrl(1);
301  }
302  print '</td>';
303  print '<td>';
304  if (!empty($objp->fk_product)) {
305  $result_inner = $productstatic->fetch($objp->fk_product);
306  if ($result_inner < 0) {
307  setEventMessages($productstatic->error, null, 'errors');
308  } else {
309  print $productstatic->getNomUrl(1);
310  }
311  } else {
312  if ($objp->product_type == $productstatic::TYPE_PRODUCT) {
313  print img_picto('', 'product');
314  }
315  if ($objp->product_type == $productstatic::TYPE_SERVICE) {
316  print img_picto('', 'service');
317  }
318  print $objp->label;
319  print '&nbsp;';
320  print $objp->description;
321  }
322  print '</td>';
323  print '<td class="right">';
324  print price($objp->subprice);
325  print '</td>';
326  print '<td class="right">';
327  print '<input type="text" name="buyingprice_'.$objp->invoicedetid.'" id="buyingprice_'.$objp->invoicedetid.'" size="6" value="'.price($objp->buy_price_ht).'" class="right flat">';
328  print '</td>';
329  print '<td class="right">';
330  print $objp->qty;
331  print '</td>';
332  print '<td class="right">';
333  print '<span class="amount">'.price($objp->total_ht).'</span>';
334  print '</td>';
335  print '<td></td>';
336 
337  print "</tr>\n";
338 
339  $i++;
340  }
341 
342  print "</table>";
343 
344  print "</div>";
345 } else {
346  dol_print_error($db);
347 }
348 
349 
350 print '<div class="center">'."\n";
351 print '<input type="submit" class="button" name="button_updatemagins" id="button_updatemagins" value="'.$langs->trans("Update").'">';
352 print '</div>';
353 
354 print '</form>';
355 
356 $db->free($result);
357 
358 // End of page
359 llxFooter();
360 $db->close();
Facture\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: facture.class.php:412
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
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
marges_prepare_head
marges_prepare_head()
Return array of tabs to used on pages for third parties cards.
Definition: margins.lib.php:59
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
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
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
User
Class to manage Dolibarr users.
Definition: user.class.php:44
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
natural_search
natural_search($fields, $value, $mode=0, $nofirstand=0)
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
Definition: functions.lib.php:9420
Product
Class to manage products or services.
Definition: product.class.php:46
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
Facture\STATUS_ABANDONED
const STATUS_ABANDONED
Classified abandoned and no payment done.
Definition: facture.class.php:435
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
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2757
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