dolibarr  17.0.3
list.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2001-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
5  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
6  * Copyright (C) 2012 Juanjo Menent <jmenent@2byte.es>
7  * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
8  * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
9  * Copyright (C) 2015-2018 Frédéric France <frederic.france@netlogic.fr>
10  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
11  * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
12  * Copyright (C) 2016-2023 Ferran Marcet <fmarcet@2byte.es>
13  * Copyright (C) 2018 Charlene Benke <charlie@patas-monkey.com>
14  * Copyright (C) 2021 Anthony Berton <anthony.berton@bb2a.fr>
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program. If not, see <https://www.gnu.org/licenses/>.
28  */
29 
37 // Load Dolibarr environment
38 require '../main.inc.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
45 if (isModEnabled('margin')) {
46  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
47 }
48 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
49 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
50 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
51 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
52 
53 // Load translation files required by the page
54 $langs->loadLangs(array('orders', 'sendings', 'deliveries', 'companies', 'compta', 'bills', 'stocks', 'products'));
55 
56 // Get Parameters
57 $action = GETPOST('action', 'aZ09');
58 $massaction = GETPOST('massaction', 'alpha');
59 $show_files = GETPOST('show_files', 'int');
60 $confirm = GETPOST('confirm', 'alpha');
61 $toselect = GETPOST('toselect', 'array');
62 $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'orderlist';
63 
64 // Search Parameters
65 $search_datecloture_start = GETPOST('search_datecloture_start', 'int');
66 if (empty($search_datecloture_start)) {
67  $search_datecloture_start = dol_mktime(0, 0, 0, GETPOST('search_datecloture_startmonth', 'int'), GETPOST('search_datecloture_startday', 'int'), GETPOST('search_datecloture_startyear', 'int'));
68 }
69 $search_datecloture_end = GETPOST('search_datecloture_end', 'int');
70 if (empty($search_datecloture_end)) {
71  $search_datecloture_end = dol_mktime(23, 59, 59, GETPOST('search_datecloture_endmonth', 'int'), GETPOST('search_datecloture_endday', 'int'), GETPOST('search_datecloture_endyear', 'int'));
72 }
73 $search_dateorder_start = dol_mktime(0, 0, 0, GETPOST('search_dateorder_start_month', 'int'), GETPOST('search_dateorder_start_day', 'int'), GETPOST('search_dateorder_start_year', 'int'));
74 $search_dateorder_end = dol_mktime(23, 59, 59, GETPOST('search_dateorder_end_month', 'int'), GETPOST('search_dateorder_end_day', 'int'), GETPOST('search_dateorder_end_year', 'int'));
75 $search_datedelivery_start = dol_mktime(0, 0, 0, GETPOST('search_datedelivery_start_month', 'int'), GETPOST('search_datedelivery_start_day', 'int'), GETPOST('search_datedelivery_start_year', 'int'));
76 $search_datedelivery_end = dol_mktime(23, 59, 59, GETPOST('search_datedelivery_end_month', 'int'), GETPOST('search_datedelivery_end_day', 'int'), GETPOST('search_datedelivery_end_year', 'int'));
77 
78 $search_product_category = GETPOST('search_product_category', 'int');
79 $search_ref = GETPOST('search_ref', 'alpha') != '' ?GETPOST('search_ref', 'alpha') : GETPOST('sref', 'alpha');
80 $search_ref_customer = GETPOST('search_ref_customer', 'alpha');
81 $search_company = GETPOST('search_company', 'alpha');
82 $search_company_alias = GETPOST('search_company_alias', 'alpha');
83 $search_parent_name = trim(GETPOST('search_parent_name', 'alphanohtml'));
84 $search_town = GETPOST('search_town', 'alpha');
85 $search_zip = GETPOST('search_zip', 'alpha');
86 $search_state = GETPOST('search_state', 'alpha');
87 $search_country = GETPOST('search_country', 'int');
88 $search_type_thirdparty = GETPOST('search_type_thirdparty', 'int');
89 $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
90 $socid = GETPOST('socid', 'int');
91 $search_user = GETPOST('search_user', 'int');
92 $search_sale = GETPOST('search_sale', 'int');
93 
94 $search_total_ht = GETPOST('search_total_ht', 'alpha');
95 $search_total_vat = GETPOST('search_total_vat', 'alpha');
96 $search_total_ttc = GETPOST('search_total_ttc', 'alpha');
97 $search_warehouse = GETPOST('search_warehouse', 'int');
98 
99 $search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha');
100 $search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha');
101 $search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha');
102 $search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha');
103 $search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha');
104 
105 $search_login = GETPOST('search_login', 'alpha');
106 $search_categ_cus = GETPOST("search_categ_cus", 'int');
107 $optioncss = GETPOST('optioncss', 'alpha');
108 $search_billed = GETPOST('search_billed', 'int');
109 $search_status = GETPOST('search_status', 'int');
110 $search_btn = GETPOST('button_search', 'alpha');
111 $search_remove_btn = GETPOST('button_removefilter', 'alpha');
112 $search_project_ref = GETPOST('search_project_ref', 'alpha');
113 $search_project = GETPOST('search_project', 'alpha');
114 $search_shippable = GETPOST('search_shippable', 'aZ09');
115 
116 $search_fk_cond_reglement = GETPOST('search_fk_cond_reglement', 'int');
117 $search_fk_shipping_method = GETPOST('search_fk_shipping_method', 'int');
118 $search_fk_mode_reglement = GETPOST('search_fk_mode_reglement', 'int');
119 $search_fk_input_reason = GETPOST('search_fk_input_reason', 'int');
120 
121 // Security check
122 $id = (GETPOST('orderid') ?GETPOST('orderid', 'int') : GETPOST('id', 'int'));
123 if ($user->socid) {
124  $socid = $user->socid;
125 }
126 $result = restrictedArea($user, 'commande', $id, '');
127 
128 $diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id;
129 
130 // Load variable for pagination
131 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
132 $sortfield = GETPOST('sortfield', 'aZ09comma');
133 $sortorder = GETPOST('sortorder', 'aZ09comma');
134 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
135 if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
136  $page = 0;
137 } // If $page is not defined, or '' or -1 or if we click on clear filters
138 $offset = $limit * $page;
139 $pageprev = $page - 1;
140 $pagenext = $page + 1;
141 if (!$sortfield) {
142  $sortfield = 'c.ref';
143 }
144 if (!$sortorder) {
145  $sortorder = 'DESC';
146 }
147 
148 $show_shippable_command = GETPOST('show_shippable_command', 'aZ09');
149 
150 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
151 $object = new Commande($db);
152 $hookmanager->initHooks(array('orderlist'));
153 $extrafields = new ExtraFields($db);
154 
155 // fetch optionals attributes and labels
156 $extrafields->fetch_name_optionals_label($object->table_element);
157 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
158 
159 // List of fields to search into when doing a "search in all"
160 $fieldstosearchall = array(
161  'c.ref'=>'Ref',
162  'c.ref_client'=>'RefCustomerOrder',
163  'pd.description'=>'Description',
164  's.nom'=>"ThirdParty",
165  's.name_alias'=>"AliasNameShort",
166  's.zip'=>"Zip",
167  's.town'=>"Town",
168  'c.note_public'=>'NotePublic',
169 );
170 if (empty($user->socid)) {
171  $fieldstosearchall["c.note_private"] = "NotePrivate";
172 }
173 
174 $checkedtypetiers = 0;
175 $arrayfields = array(
176  'c.ref'=>array('label'=>"Ref", 'checked'=>1, 'position'=>5),
177  'c.ref_client'=>array('label'=>"RefCustomerOrder", 'checked'=>-1, 'position'=>10),
178  'p.ref'=>array('label'=>"ProjectRef", 'checked'=>-1, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>20),
179  'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>25),
180  's.nom'=>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30),
181  's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>-1, 'position'=>31),
182  's2.nom'=>array('label'=>'ParentCompany', 'position'=>32, 'checked'=>0),
183  's.town'=>array('label'=>"Town", 'checked'=>-1, 'position'=>35),
184  's.zip'=>array('label'=>"Zip", 'checked'=>-1, 'position'=>40),
185  'state.nom'=>array('label'=>"StateShort", 'checked'=>0, 'position'=>45),
186  'country.code_iso'=>array('label'=>"Country", 'checked'=>0, 'position'=>50),
187  'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers, 'position'=>55),
188  'c.date_commande'=>array('label'=>"OrderDateShort", 'checked'=>1, 'position'=>60),
189  'c.date_delivery'=>array('label'=>"DateDeliveryPlanned", 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE), 'position'=>65),
190  'c.fk_shipping_method'=>array('label'=>"SendingMethod", 'checked'=>-1, 'position'=>66 , 'enabled'=>isModEnabled("expedition")),
191  'c.fk_cond_reglement'=>array('label'=>"PaymentConditionsShort", 'checked'=>-1, 'position'=>67),
192  'c.fk_mode_reglement'=>array('label'=>"PaymentMode", 'checked'=>-1, 'position'=>68),
193  'c.fk_input_reason'=>array('label'=>"Channel", 'checked'=>-1, 'position'=>69),
194  'c.total_ht'=>array('label'=>"AmountHT", 'checked'=>1, 'position'=>75),
195  'c.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0, 'position'=>80),
196  'c.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0, 'position'=>85),
197  'c.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(!isModEnabled("multicurrency") ? 0 : 1), 'position'=>90),
198  'c.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(!isModEnabled("multicurrency") ? 0 : 1), 'position'=>95),
199  'c.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(!isModEnabled("multicurrency") ? 0 : 1), 'position'=>100),
200  'c.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(!isModEnabled("multicurrency") ? 0 : 1), 'position'=>105),
201  'c.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(!isModEnabled("multicurrency") ? 0 : 1), 'position'=>110),
202  'u.login'=>array('label'=>"Author", 'checked'=>1, 'position'=>115),
203  'sale_representative'=>array('label'=>"SaleRepresentativesOfThirdParty", 'checked'=>0, 'position'=>116),
204  'total_pa' => array('label' => (getDolGlobalString('MARGIN_TYPE') == '1' ? 'BuyingPrice' : 'CostPrice'), 'checked' => 0, 'position' => 300, 'enabled' => (!isModEnabled('margin') || !$user->hasRight("margins", "liretous") ? 0 : 1)),
205  'total_margin' => array('label' => 'Margin', 'checked' => 0, 'position' => 301, 'enabled' => (!isModEnabled('margin') || !$user->hasRight("margins", "liretous") ? 0 : 1)),
206  'total_margin_rate' => array('label' => 'MarginRate', 'checked' => 0, 'position' => 302, 'enabled' => (!isModEnabled('margin') || !$user->hasRight("margins", "liretous") || empty($conf->global->DISPLAY_MARGIN_RATES) ? 0 : 1)),
207  'total_mark_rate' => array('label' => 'MarkRate', 'checked' => 0, 'position' => 303, 'enabled' => (!isModEnabled('margin') || !$user->hasRight("margins", "liretous") || empty($conf->global->DISPLAY_MARK_RATES) ? 0 : 1)),
208  'c.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>120),
209  'c.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>125),
210  'c.date_cloture'=>array('label'=>"DateClosing", 'checked'=>0, 'position'=>130),
211  'c.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'enabled'=>(!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES')), 'position'=>135),
212  'c.note_private'=>array('label'=>'NotePrivate', 'checked'=>0, 'enabled'=>(!getDolGlobalInt('MAIN_LIST_HIDE_PRIVATE_NOTES')), 'position'=>140),
213  'shippable'=>array('label'=>"Shippable", 'checked'=>1,'enabled'=>(isModEnabled("expedition")), 'position'=>990),
214  'c.facture'=>array('label'=>"Billed", 'checked'=>1, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)), 'position'=>995),
215  'c.import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>999),
216  'c.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000)
217 );
218 
219 // Extra fields
220 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
221 
222 $object->fields = dol_sort_array($object->fields, 'position');
223 $arrayfields = dol_sort_array($arrayfields, 'position');
224 
225 $error = 0;
226 
227 
228 /*
229  * Actions
230  */
231 
232 if (GETPOST('cancel', 'alpha')) {
233  $action = 'list'; $massaction = '';
234 }
235 if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') {
236  $massaction = '';
237 }
238 
239 $parameters = array('socid'=>$socid, 'arrayfields'=>&$arrayfields);
240 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
241 if ($reshook < 0) {
242  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
243 }
244 
245 if (empty($reshook)) {
246  // Selection of new fields
247  include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
248 
249  // Purge search criteria
250  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
251  $search_categ = '';
252  $search_user = '';
253  $search_sale = '';
254  $search_product_category = '';
255  $search_ref = '';
256  $search_ref_customer = '';
257  $search_company = '';
258  $search_company_alias = '';
259  $search_parent_name = '';
260  $search_town = '';
261  $search_zip = "";
262  $search_state = "";
263  $search_type = '';
264  $search_country = '';
265  $search_type_thirdparty = '';
266  $search_total_ht = '';
267  $search_total_vat = '';
268  $search_total_ttc = '';
269  $search_warehouse = '';
270  $search_multicurrency_code = '';
271  $search_multicurrency_tx = '';
272  $search_multicurrency_montant_ht = '';
273  $search_multicurrency_montant_vat = '';
274  $search_multicurrency_montant_ttc = '';
275  $search_login = '';
276  $search_dateorder_start = '';
277  $search_dateorder_end = '';
278  $search_datedelivery_start = '';
279  $search_datedelivery_end = '';
280  $search_project_ref = '';
281  $search_project = '';
282  $search_status = '';
283  $search_billed = '';
284  $toselect = array();
285  $search_array_options = array();
286  $search_categ_cus = 0;
287  $search_datecloture_start = '';
288  $search_datecloture_end = '';
289  $search_fk_cond_reglement = '';
290  $search_fk_shipping_method = '';
291  $search_fk_mode_reglement = '';
292  $search_fk_input_reason = '';
293  }
294  if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
295  || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
296  $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
297  }
298 
299  // Mass actions
300  $objectclass = 'Commande';
301  $objectlabel = 'Orders';
302  $permissiontoread = $user->hasRight("commande", "lire");
303  $permissiontoadd = $user->hasRight("commande", "creer");
304  $permissiontodelete = $user->hasRight("commande", "supprimer");
305  if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
306  $permissiontovalidate = $user->hasRight("commande", "order_advance", "validate");
307  $permissiontoclose = $user->hasRight("commande", "order_advance", "close");
308  $permissiontocancel = $user->hasRight("commande", "order_advance", "annuler");
309  $permissiontosendbymail = $user->hasRight("commande", "order_advance", "send");
310  } else {
311  $permissiontovalidate = $user->hasRight("commande", "creer");
312  $permissiontoclose = $user->hasRight("commande", "creer");
313  $permissiontocancel = $user->hasRight("commande", "creer");
314  $permissiontosendbymail = $user->hasRight("commande", "creer");
315  }
316  $uploaddir = $conf->commande->multidir_output[$conf->entity];
317  $triggersendname = 'ORDER_SENTBYMAIL';
318  include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
319 
320  if ($massaction == 'confirm_createbills') { // Create bills from orders.
321  $orders = GETPOST('toselect', 'array');
322  $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
323  $validate_invoices = GETPOST('validate_invoices', 'int');
324 
325  $errors = array();
326 
327  $TFact = array();
328  $TFactThird = array();
329  $TFactThirdNbLines = array();
330 
331  $nb_bills_created = 0;
332  $lastid= 0;
333  $lastref = '';
334 
335  $db->begin();
336 
337  $nbOrders = is_array($orders) ? count($orders) : 1;
338 
339  foreach ($orders as $id_order) {
340  $cmd = new Commande($db);
341  if ($cmd->fetch($id_order) <= 0) {
342  continue;
343  }
344  $cmd->fetch_thirdparty();
345 
346  $objecttmp = new Facture($db);
347  if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) {
348  // If option "one bill per third" is set, and an invoice for this thirdparty was already created, we re-use it.
349  $objecttmp = $TFactThird[$cmd->socid];
350  } else {
351  // If we want one invoice per order or if there is no first invoice yet for this thirdparty.
352  $objecttmp->socid = $cmd->socid;
353  $objecttmp->thirdparty = $cmd->thirdparty;
354 
355  $objecttmp->type = $objecttmp::TYPE_STANDARD;
356  $objecttmp->cond_reglement_id = !empty($cmd->cond_reglement_id) ? $cmd->cond_reglement_id : $cmd->thirdparty->cond_reglement_id;
357  $objecttmp->mode_reglement_id = !empty($cmd->mode_reglement_id) ? $cmd->mode_reglement_id : $cmd->thirdparty->mode_reglement_id;
358 
359  $objecttmp->fk_project = $cmd->fk_project;
360  $objecttmp->multicurrency_code = $cmd->multicurrency_code;
361  if (empty($createbills_onebythird)) {
362  $objecttmp->ref_client = $cmd->ref_client;
363  }
364 
365  $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
366  if (empty($datefacture)) {
367  $datefacture = dol_now();
368  }
369 
370  $objecttmp->date = $datefacture;
371  $objecttmp->origin = 'commande';
372  $objecttmp->origin_id = $id_order;
373 
374  $objecttmp->array_options = $cmd->array_options; // Copy extrafields
375 
376  $res = $objecttmp->create($user);
377 
378  if ($res > 0) {
379  $nb_bills_created++;
380  $lastref = $objecttmp->ref;
381  $lastid = $objecttmp->id;
382 
383  $TFactThird[$cmd->socid] = $objecttmp;
384  $TFactThirdNbLines[$cmd->socid] = 0; //init nblines to have lines ordered by expedition and rang
385  } else {
386  $langs->load("errors");
387  $errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->errors[0]);
388  $error++;
389  }
390  }
391 
392  if ($objecttmp->id > 0) {
393  $res = $objecttmp->add_object_linked($objecttmp->origin, $id_order);
394 
395  if ($res == 0) {
396  $errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->errors[0]);
397  $error++;
398  }
399 
400  if (!$error) {
401  $lines = $cmd->lines;
402  if (empty($lines) && method_exists($cmd, 'fetch_lines')) {
403  $cmd->fetch_lines();
404  $lines = $cmd->lines;
405  }
406 
407  $fk_parent_line = 0;
408  $num = count($lines);
409 
410  for ($i = 0; $i < $num; $i++) {
411  $desc = ($lines[$i]->desc ? $lines[$i]->desc : '');
412  // If we build one invoice for several orders, we must put the ref of order on the invoice line
413  if (!empty($createbills_onebythird)) {
414  $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day'));
415  }
416 
417  if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
418  // Negative line, we create a discount line
419  $discount = new DiscountAbsolute($db);
420  $discount->fk_soc = $objecttmp->socid;
421  $discount->amount_ht = abs($lines[$i]->total_ht);
422  $discount->amount_tva = abs($lines[$i]->total_tva);
423  $discount->amount_ttc = abs($lines[$i]->total_ttc);
424  $discount->tva_tx = $lines[$i]->tva_tx;
425  $discount->fk_user = $user->id;
426  $discount->description = $desc;
427  $discountid = $discount->create($user);
428  if ($discountid > 0) {
429  $result = $objecttmp->insert_discount($discountid);
430  //$result=$discount->link_to_invoice($lineid,$id);
431  } else {
432  setEventMessages($discount->error, $discount->errors, 'errors');
433  $error++;
434  break;
435  }
436  } else {
437  // Positive line
438  $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
439  // Date start
440  $date_start = false;
441  if ($lines[$i]->date_debut_prevue) {
442  $date_start = $lines[$i]->date_debut_prevue;
443  }
444  if ($lines[$i]->date_debut_reel) {
445  $date_start = $lines[$i]->date_debut_reel;
446  }
447  if ($lines[$i]->date_start) {
448  $date_start = $lines[$i]->date_start;
449  }
450  //Date end
451  $date_end = false;
452  if ($lines[$i]->date_fin_prevue) {
453  $date_end = $lines[$i]->date_fin_prevue;
454  }
455  if ($lines[$i]->date_fin_reel) {
456  $date_end = $lines[$i]->date_fin_reel;
457  }
458  if ($lines[$i]->date_end) {
459  $date_end = $lines[$i]->date_end;
460  }
461  // Reset fk_parent_line for no child products and special product
462  if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
463  $fk_parent_line = 0;
464  }
465 
466  // Extrafields
467  if (method_exists($lines[$i], 'fetch_optionals')) {
468  $lines[$i]->fetch_optionals();
469  $array_options = $lines[$i]->array_options;
470  }
471 
472  $objecttmp->context['createfromclone'];
473 
474  $rang = ($nbOrders > 1) ? -1 : $lines[$i]->rang;
475  //there may already be rows from previous orders
476  if (!empty($createbills_onebythird)) {
477  $rang = $TFactThirdNbLines[$cmd->socid];
478  }
479 
480  $result = $objecttmp->addline(
481  $desc,
482  $lines[$i]->subprice,
483  $lines[$i]->qty,
484  $lines[$i]->tva_tx,
485  $lines[$i]->localtax1_tx,
486  $lines[$i]->localtax2_tx,
487  $lines[$i]->fk_product,
488  $lines[$i]->remise_percent,
489  $date_start,
490  $date_end,
491  0,
492  $lines[$i]->info_bits,
493  $lines[$i]->fk_remise_except,
494  'HT',
495  0,
496  $product_type,
497  $rang,
498  $lines[$i]->special_code,
499  $objecttmp->origin,
500  $lines[$i]->rowid,
501  $fk_parent_line,
502  $lines[$i]->fk_fournprice,
503  $lines[$i]->pa_ht,
504  $lines[$i]->label,
505  $array_options,
506  100,
507  0,
508  $lines[$i]->fk_unit
509  );
510  if ($result > 0) {
511  $lineid = $result;
512  if (!empty($createbills_onebythird)) //increment rang to keep order
513  $TFactThirdNbLines[$rcp->socid]++;
514  } else {
515  $lineid = 0;
516  $error++;
517  $errors[] = $objecttmp->error;
518  break;
519  }
520  // Defined the new fk_parent_line
521  if ($result > 0 && $lines[$i]->product_type == 9) {
522  $fk_parent_line = $result;
523  }
524  }
525  }
526  }
527  }
528 
529  //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
530 
531  if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) {
532  $TFactThird[$cmd->socid] = $objecttmp;
533  } else {
534  $TFact[$objecttmp->id] = $objecttmp;
535  }
536  }
537 
538  // Build doc with all invoices
539  $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
540  $toselect = array();
541 
542  if (!$error && $validate_invoices) {
543  $massaction = $action = 'builddoc';
544 
545  foreach ($TAllFact as &$objecttmp) {
546  $result = $objecttmp->validate($user);
547  if ($result <= 0) {
548  $error++;
549  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
550  break;
551  }
552 
553  $id = $objecttmp->id; // For builddoc action
554 
555  // Builddoc
556  $donotredirect = 1;
557  $upload_dir = $conf->facture->dir_output;
558  $permissiontoadd = $user->rights->facture->creer;
559 
560  // Call action to build doc
561  $savobject = $object;
562  $object = $objecttmp;
563  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
564  $object = $savobject;
565  }
566 
567  $massaction = $action = 'confirm_createbills';
568  }
569 
570  if (!$error) {
571  $db->commit();
572 
573  if ($nb_bills_created == 1) {
574  $texttoshow = $langs->trans('BillXCreated', '{s1}');
575  $texttoshow = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?id='.urlencode($lastid).'">'.$lastref.'</a>', $texttoshow);
576  setEventMessages($texttoshow, null, 'mesgs');
577  } else {
578  setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
579  }
580 
581  // Make a redirect to avoid to bill twice if we make a refresh or back
582  $param = '';
583  if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
584  $param .= '&contextpage='.urlencode($contextpage);
585  }
586  if ($limit > 0 && $limit != $conf->liste_limit) {
587  $param .= '&limit='.urlencode($limit);
588  }
589  if ($sall) {
590  $param .= '&sall='.urlencode($sall);
591  }
592  if ($socid > 0) {
593  $param .= '&socid='.urlencode($socid);
594  }
595  if ($search_status != '') {
596  $param .= '&search_status='.urlencode($search_status);
597  }
598  if ($search_orderday) {
599  $param .= '&search_orderday='.urlencode($search_orderday);
600  }
601  if ($search_ordermonth) {
602  $param .= '&search_ordermonth='.urlencode($search_ordermonth);
603  }
604  if ($search_orderyear) {
605  $param .= '&search_orderyear='.urlencode($search_orderyear);
606  }
607  if ($search_deliveryday) {
608  $param .= '&search_deliveryday='.urlencode($search_deliveryday);
609  }
610  if ($search_deliverymonth) {
611  $param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
612  }
613  if ($search_deliveryyear) {
614  $param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
615  }
616  if ($search_ref) {
617  $param .= '&search_ref='.urlencode($search_ref);
618  }
619  if ($search_company) {
620  $param .= '&search_company='.urlencode($search_company);
621  }
622  if ($search_ref_customer) {
623  $param .= '&search_ref_customer='.urlencode($search_ref_customer);
624  }
625  if ($search_user > 0) {
626  $param .= '&search_user='.urlencode($search_user);
627  }
628  if ($search_sale > 0) {
629  $param .= '&search_sale='.urlencode($search_sale);
630  }
631  if ($search_total_ht != '') {
632  $param .= '&search_total_ht='.urlencode($search_total_ht);
633  }
634  if ($search_total_vat != '') {
635  $param .= '&search_total_vat='.urlencode($search_total_vat);
636  }
637  if ($search_total_ttc != '') {
638  $param .= '&search_total_ttc='.urlencode($search_total_ttc);
639  }
640  if ($search_project_ref >= 0) {
641  $param .= "&search_project_ref=".urlencode($search_project_ref);
642  }
643  if ($show_files) {
644  $param .= '&show_files='.urlencode($show_files);
645  }
646  if ($optioncss != '') {
647  $param .= '&optioncss='.urlencode($optioncss);
648  }
649  if ($billed != '') {
650  $param .= '&billed='.urlencode($billed);
651  }
652 
653  header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
654  exit;
655  } else {
656  $db->rollback();
657 
658  $action = 'create';
659  $_GET["origin"] = $_POST["origin"];
660  $_GET["originid"] = $_POST["originid"];
661  if (!empty($errors)) {
662  setEventMessages(null, $errors, 'errors');
663  } else {
664  setEventMessages("Error", null, 'errors');
665  }
666  $error++;
667  }
668  }
669 }
670 if ($action == 'validate' && $permissiontoadd) {
671  if (GETPOST('confirm') == 'yes') {
672  $objecttmp = new $objectclass($db);
673  $db->begin();
674  $error = 0;
675  foreach ($toselect as $checked) {
676  if ($objecttmp->fetch($checked)) {
677  if ($objecttmp->statut == 0) {
678  if (!empty($objecttmp->fk_warehouse)) {
679  $idwarehouse = $objecttmp->fk_warehouse;
680  } else {
681  $idwarehouse = 0;
682  }
683  if ($objecttmp->valid($user, $idwarehouse)) {
684  setEventMessages($langs->trans('hasBeenValidated', $objecttmp->ref), null, 'mesgs');
685  } else {
686  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
687  $error++;
688  }
689  } else {
690  $langs->load("errors");
691  setEventMessages($langs->trans('ErrorIsNotADraft', $objecttmp->ref), null, 'errors');
692  $error++;
693  }
694  } else {
695  dol_print_error($db);
696  $error++;
697  }
698  }
699  if ($error) {
700  $db->rollback();
701  } else {
702  $db->commit();
703  }
704  }
705 }
706 if ($action == 'shipped' && $permissiontoadd) {
707  if (GETPOST('confirm') == 'yes') {
708  $objecttmp = new $objectclass($db);
709  $db->begin();
710  $error = 0;
711  foreach ($toselect as $checked) {
712  if ($objecttmp->fetch($checked)) {
713  if ($objecttmp->statut == 1 || $objecttmp->statut == 2) {
714  if ($objecttmp->cloture($user)) {
715  setEventMessages($langs->trans('PassedInClosedStatus', $objecttmp->ref), null, 'mesgs');
716  } else {
717  setEventMessages($langs->trans('CantBeClosed'), null, 'errors');
718  $error++;
719  }
720  } else {
721  $langs->load("errors");
722  setEventMessages($langs->trans('ErrorIsNotADraft', $objecttmp->ref), null, 'errors');
723  $error++;
724  }
725  } else {
726  dol_print_error($db);
727  $error++;
728  }
729  }
730  if ($error) {
731  $db->rollback();
732  } else {
733  $db->commit();
734  }
735  }
736 }
737 
738 // Closed records
739 if (!$error && $massaction === 'setbilled' && $permissiontoclose) {
740  $db->begin();
741 
742  $objecttmp = new $objectclass($db);
743  $nbok = 0;
744  foreach ($toselect as $toselectid) {
745  $result = $objecttmp->fetch($toselectid);
746  if ($result > 0) {
747  $result = $objecttmp->classifyBilled($user, 0);
748  if ($result <= 0) {
749  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
750  $error++;
751  break;
752  } else {
753  $nbok++;
754  }
755  } else {
756  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
757  $error++;
758  break;
759  }
760  }
761 
762  if (!$error) {
763  if ($nbok > 1) {
764  setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
765  } else {
766  setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
767  }
768  $db->commit();
769  } else {
770  $db->rollback();
771  }
772 }
773 
774 
775 /*
776  * View
777  */
778 
779 
780 $now = dol_now();
781 
782 $form = new Form($db);
783 $formother = new FormOther($db);
784 $formfile = new FormFile($db);
785 $formmargin = null;
786 if (isModEnabled('margin')) {
787  $formmargin = new FormMargin($db);
788 }
789 $companystatic = new Societe($db);
790 $company_url_list = array();
791 $formcompany = new FormCompany($db);
792 $projectstatic = new Project($db);
793 
794 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
795 $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
796 
797 $title = $langs->trans("Orders");
798 $help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes";
799 
800 $sql = 'SELECT';
801 if ($sall || $search_user > 0) {
802  $sql = 'SELECT DISTINCT';
803 }
804 $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client,';
805 $sql .= " s.parent as fk_parent,";
806 $sql .= " s2.nom as name2,";
807 $sql .= " typent.code as typent_code,";
808 $sql .= " state.code_departement as state_code, state.nom as state_name,";
809 $sql .= " country.code as country_code,";
810 $sql .= ' c.rowid, c.ref, c.total_ht, c.total_tva, c.total_ttc, c.ref_client, c.fk_user_author,';
811 $sql .= ' c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva as multicurrency_total_vat, c.multicurrency_total_ttc,';
812 $sql .= ' c.date_valid, c.date_commande, c.note_public, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,';
813 $sql .= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,';
814 $sql .= ' p.rowid as project_id, p.ref as project_ref, p.title as project_label,';
815 $sql .= ' u.login, u.lastname, u.firstname, u.email as user_email, u.statut as user_statut, u.entity, u.photo, u.office_phone, u.office_fax, u.user_mobile, u.job, u.gender,';
816 $sql .= ' c.fk_cond_reglement,c.deposit_percent,c.fk_mode_reglement,c.fk_shipping_method,';
817 $sql .= ' c.fk_input_reason, c.import_key';
818 if (($search_categ_cus > 0) || ($search_categ_cus == -2)) {
819  $sql .= ", cc.fk_categorie, cc.fk_soc";
820 }
821 
822 // Add fields from extrafields
823 if (!empty($extrafields->attributes[$object->table_element]['label'])) {
824  foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
825  $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
826  }
827 }
828 
829 // Add fields from hooks
830 $parameters = array();
831 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
832 $sql .= $hookmanager->resPrint;
833 
834 $sqlfields = $sql; // $sql fields to remove for count total
835 
836 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
837 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s2 ON s2.rowid = s.parent";
838 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
839 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
840 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
841 if (($search_categ_cus > 0) || ($search_categ_cus == -2)) {
842  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ
843 }
844 $sql .= ', '.MAIN_DB_PREFIX.'commande as c';
845 if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
846  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)";
847 }
848 if ($sall) {
849  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande';
850 }
851 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet";
852 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid';
853 
854 // We'll need this table joined to the select in order to filter by sale
855 if ($search_sale > 0 || (empty($user->rights->societe->client->voir) && !$socid)) {
856  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
857 }
858 if ($search_user > 0) {
859  $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
860  $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc";
861 }
862 
863 // Add table from hooks
864 $parameters = array();
865 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
866 $sql .= $hookmanager->resPrint;
867 
868 $sql .= ' WHERE c.fk_soc = s.rowid';
869 $sql .= ' AND c.entity IN ('.getEntity('commande').')';
870 if ($socid > 0) {
871  $sql .= ' AND s.rowid = '.((int) $socid);
872 }
873 if (empty($user->rights->societe->client->voir) && !$socid) {
874  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
875 }
876 if ($search_ref) {
877  $sql .= natural_search('c.ref', $search_ref);
878 }
879 if ($search_ref_customer) {
880  $sql .= natural_search('c.ref_client', $search_ref_customer);
881 }
882 if ($sall) {
883  $sql .= natural_search(array_keys($fieldstosearchall), $sall);
884 }
885 if ($search_billed != '' && $search_billed >= 0) {
886  $sql .= ' AND c.facture = '.((int) $search_billed);
887 }
888 if ($search_status <> '') {
889  if ($search_status <= 3 && $search_status >= -1) { // status from -1 to 3 are real status (other are virtual combination)
890  if ($search_status == 1 && empty($conf->expedition->enabled)) {
891  $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated'
892  } else {
893  $sql .= ' AND c.fk_statut = '.((int) $search_status); // draft, validated, in process or canceled
894  }
895  }
896  if ($search_status == -2) { // "validated + in process"
897  //$sql.= ' AND c.fk_statut IN (1,2,3) AND c.facture = 0';
898  $sql .= " AND (c.fk_statut IN (1,2))";
899  }
900  if ($search_status == -3) { // "validated + in process + delivered"
901  //$sql.= ' AND c.fk_statut in (1,2,3)';
902  //$sql.= ' AND c.facture = 0'; // invoice not created
903  $sql .= ' AND (c.fk_statut IN (1,2,3))'; // validated, in process or closed
904  }
905  if ($search_status == -4) { // "validate + in progress"
906  $sql .= ' AND (c.fk_statut IN (1,2))'; // validated, in process
907  }
908 }
909 
910 if ($search_datecloture_start) {
911  $sql .= " AND c.date_cloture >= '".$db->idate($search_datecloture_start)."'";
912 }
913 if ($search_datecloture_end) {
914  $sql .= " AND c.date_cloture <= '".$db->idate($search_datecloture_end)."'";
915 }
916 if ($search_dateorder_start) {
917  $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'";
918 }
919 if ($search_dateorder_end) {
920  $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'";
921 }
922 if ($search_datedelivery_start) {
923  $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'";
924 }
925 if ($search_datedelivery_end) {
926  $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'";
927 }
928 if ($search_town) {
929  $sql .= natural_search('s.town', $search_town);
930 }
931 if ($search_zip) {
932  $sql .= natural_search("s.zip", $search_zip);
933 }
934 if ($search_state) {
935  $sql .= natural_search("state.nom", $search_state);
936 }
937 if ($search_country) {
938  $sql .= " AND s.fk_pays IN (".$db->sanitize($search_country).')';
939 }
940 if ($search_type_thirdparty && $search_type_thirdparty != '-1') {
941  $sql .= " AND s.fk_typent IN (".$db->sanitize($search_type_thirdparty).')';
942 }
943 if (empty($arrayfields['s.name_alias']['checked']) && $search_company) {
944  $sql .= natural_search(array("s.nom", "s.name_alias"), $search_company);
945 } else {
946  if ($search_company) {
947  $sql .= natural_search('s.nom', $search_company);
948  }
949  if ($search_company_alias) {
950  $sql .= natural_search('s.name_alias', $search_company_alias);
951  }
952 }
953 if ($search_parent_name) {
954  $sql .= natural_search('s2.nom', $search_parent_name);
955 }
956 if ($search_sale > 0) {
957  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale);
958 }
959 if ($search_user > 0) {
960  $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".((int) $search_user);
961 }
962 if ($search_total_ht != '') {
963  $sql .= natural_search('c.total_ht', $search_total_ht, 1);
964 }
965 if ($search_total_vat != '') {
966  $sql .= natural_search('c.total_tva', $search_total_vat, 1);
967 }
968 if ($search_total_ttc != '') {
969  $sql .= natural_search('c.total_ttc', $search_total_ttc, 1);
970 }
971 if ($search_warehouse != '' && $search_warehouse > 0) {
972  $sql .= natural_search('c.fk_warehouse', $search_warehouse, 1);
973 }
974 if ($search_multicurrency_code != '') {
975  $sql .= " AND c.multicurrency_code = '".$db->escape($search_multicurrency_code)."'";
976 }
977 if ($search_multicurrency_tx != '') {
978  $sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1);
979 }
980 if ($search_multicurrency_montant_ht != '') {
981  $sql .= natural_search('c.multicurrency_total_ht', $search_multicurrency_montant_ht, 1);
982 }
983 if ($search_multicurrency_montant_vat != '') {
984  $sql .= natural_search('c.multicurrency_total_tva', $search_multicurrency_montant_vat, 1);
985 }
986 if ($search_multicurrency_montant_ttc != '') {
987  $sql .= natural_search('c.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1);
988 }
989 if ($search_login) {
990  $sql .= natural_search(array("u.login", "u.firstname", "u.lastname"), $search_login);
991 }
992 if ($search_project_ref != '') {
993  $sql .= natural_search("p.ref", $search_project_ref);
994 }
995 if ($search_project != '') {
996  $sql .= natural_search("p.title", $search_project);
997 }
998 if ($search_categ_cus > 0) {
999  $sql .= " AND cc.fk_categorie = ".((int) $search_categ_cus);
1000 }
1001 if ($search_categ_cus == -2) {
1002  $sql .= " AND cc.fk_categorie IS NULL";
1003 }
1004 if ($search_fk_cond_reglement > 0) {
1005  $sql .= " AND c.fk_cond_reglement = ".((int) $search_fk_cond_reglement);
1006 }
1007 if ($search_fk_shipping_method > 0) {
1008  $sql .= " AND c.fk_shipping_method = ".((int) $search_fk_shipping_method);
1009 }
1010 if ($search_fk_mode_reglement > 0) {
1011  $sql .= " AND c.fk_mode_reglement = ".((int) $search_fk_mode_reglement);
1012 }
1013 if ($search_fk_input_reason > 0) {
1014  $sql .= " AND c.fk_input_reason = ".((int) $search_fk_input_reason);
1015 }
1016 // Search for tag/category ($searchCategoryProductList is an array of ID)
1017 $searchCategoryProductOperator = -1;
1018 $searchCategoryProductList = array($search_product_category);
1019 if (!empty($searchCategoryProductList)) {
1020  $searchCategoryProductSqlList = array();
1021  $listofcategoryid = '';
1022  foreach ($searchCategoryProductList as $searchCategoryProduct) {
1023  if (intval($searchCategoryProduct) == -2) {
1024  $searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product)";
1025  } elseif (intval($searchCategoryProduct) > 0) {
1026  if ($searchCategoryProductOperator == 0) {
1027  $searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie = ".((int) $searchCategoryProduct).")";
1028  } else {
1029  $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryProduct);
1030  }
1031  }
1032  }
1033  if ($listofcategoryid) {
1034  $searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
1035  }
1036  if ($searchCategoryProductOperator == 1) {
1037  if (!empty($searchCategoryProductSqlList)) {
1038  $sql .= " AND (".implode(' OR ', $searchCategoryProductSqlList).")";
1039  }
1040  } else {
1041  if (!empty($searchCategoryProductSqlList)) {
1042  $sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")";
1043  }
1044  }
1045 }
1046 // Add where from extra fields
1047 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
1048 // Add where from hooks
1049 $parameters = array();
1050 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1051 $sql .= $hookmanager->resPrint;
1052 
1053 // Add HAVING from hooks
1054 $parameters = array();
1055 $reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1056 $sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
1057 
1058 // Count total nb of records
1059 $nbtotalofrecords = '';
1060 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
1061  /* The fast and low memory method to get and count full list converts the sql into a sql count */
1062  $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
1063  $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
1064  $resql = $db->query($sqlforcount);
1065  if ($resql) {
1066  $objforcount = $db->fetch_object($resql);
1067  $nbtotalofrecords = $objforcount->nbtotalofrecords;
1068  } else {
1069  dol_print_error($db);
1070  }
1071 
1072  if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
1073  $page = 0;
1074  $offset = 0;
1075  }
1076  $db->free($resql);
1077 }
1078 
1079 $sql .= $db->order($sortfield, $sortorder);
1080 if ($limit) {
1081  $sql .= $db->plimit($limit + 1, $offset);
1082 }
1083 //print $sql;
1084 
1085 $resql = $db->query($sql);
1086 if ($resql) {
1087  if ($socid > 0) {
1088  $soc = new Societe($db);
1089  $soc->fetch($socid);
1090  $title = $langs->trans('CustomersOrders').' - '.$soc->name;
1091  if (empty($search_company)) {
1092  $search_company = $soc->name;
1093  }
1094  } else {
1095  $title = $langs->trans('CustomersOrders');
1096  }
1097  if (strval($search_status) == '0') {
1098  $title .= ' - '.$langs->trans('StatusOrderDraftShort');
1099  }
1100  if ($search_status == 1) {
1101  $title .= ' - '.$langs->trans('StatusOrderValidatedShort');
1102  }
1103  if ($search_status == 2) {
1104  $title .= ' - '.$langs->trans('StatusOrderSentShort');
1105  }
1106  if ($search_status == 3) {
1107  $title .= ' - '.$langs->trans('StatusOrderToBillShort');
1108  }
1109  if ($search_status == -1) {
1110  $title .= ' - '.$langs->trans('StatusOrderCanceledShort');
1111  }
1112  if ($search_status == -2) {
1113  $title .= ' - '.$langs->trans('StatusOrderToProcessShort');
1114  }
1115  if ($search_status == -3) {
1116  $title .= ' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled) ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill');
1117  }
1118  if ($search_status == -4) {
1119  $title .= ' - '.$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort");
1120  }
1121 
1122  $num = $db->num_rows($resql);
1123 
1124  $arrayofselected = is_array($toselect) ? $toselect : array();
1125 
1126  if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) {
1127  $obj = $db->fetch_object($resql);
1128  $id = $obj->rowid;
1129  header("Location: ".DOL_URL_ROOT.'/commande/card.php?id='.$id);
1130  exit;
1131  }
1132 
1133  llxHeader('', $title, $help_url);
1134 
1135  $param = '';
1136 
1137  if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
1138  $param .= '&contextpage='.urlencode($contextpage);
1139  }
1140  if ($limit > 0 && $limit != $conf->liste_limit) {
1141  $param .= '&limit='.urlencode($limit);
1142  }
1143  if ($sall) {
1144  $param .= '&sall='.urlencode($sall);
1145  }
1146  if ($socid > 0) {
1147  $param .= '&socid='.urlencode($socid);
1148  }
1149  if ($search_status != '') {
1150  $param .= '&search_status='.urlencode($search_status);
1151  }
1152  if ($search_datecloture_start) {
1153  $param .= '&search_datecloture_startday='.dol_print_date($search_datecloture_start, '%d').'&search_datecloture_startmonth='.dol_print_date($search_datecloture_start, '%m').'&search_datecloture_startyear='.dol_print_date($search_datecloture_start, '%Y');
1154  }
1155  if ($search_datecloture_end) {
1156  $param .= '&search_datecloture_endday='.dol_print_date($search_datecloture_end, '%d').'&search_datecloture_endmonth='.dol_print_date($search_datecloture_end, '%m').'&search_datecloture_endyear='.dol_print_date($search_datecloture_end, '%Y');
1157  }
1158  if ($search_dateorder_start) {
1159  $param .= '&search_dateorder_start_day='.dol_print_date($search_dateorder_start, '%d').'&search_dateorder_start_month='.dol_print_date($search_dateorder_start, '%m').'&search_dateorder_start_year='.dol_print_date($search_dateorder_start, '%Y');
1160  }
1161  if ($search_dateorder_end) {
1162  $param .= '&search_dateorder_end_day='.dol_print_date($search_dateorder_end, '%d').'&search_dateorder_end_month='.dol_print_date($search_dateorder_end, '%m').'&search_dateorder_end_year='.dol_print_date($search_dateorder_end, '%Y');
1163  }
1164  if ($search_datedelivery_start) {
1165  $param .= '&search_datedelivery_start_day='.dol_print_date($search_datedelivery_start, '%d').'&search_datedelivery_start_month='.dol_print_date($search_datedelivery_start, '%m').'&search_datedelivery_start_year='.dol_print_date($search_datedelivery_start, '%Y');
1166  }
1167  if ($search_datedelivery_end) {
1168  $param .= '&search_datedelivery_end_day='.dol_print_date($search_datedelivery_end, '%d').'&search_datedelivery_end_month='.dol_print_date($search_datedelivery_end, '%m').'&search_datedelivery_end_year='.dol_print_date($search_datedelivery_end, '%Y');
1169  }
1170  if ($search_ref) {
1171  $param .= '&search_ref='.urlencode($search_ref);
1172  }
1173  if ($search_company) {
1174  $param .= '&search_company='.urlencode($search_company);
1175  }
1176  if ($search_company_alias) {
1177  $param .= '&search_company_alias='.urlencode($search_company_alias);
1178  }
1179  if ($search_parent_name != '') {
1180  $param .= '&search_parent_name='.urlencode($search_parent_name);
1181  }
1182  if ($search_ref_customer) {
1183  $param .= '&search_ref_customer='.urlencode($search_ref_customer);
1184  }
1185  if ($search_user > 0) {
1186  $param .= '&search_user='.urlencode($search_user);
1187  }
1188  if ($search_sale > 0) {
1189  $param .= '&search_sale='.urlencode($search_sale);
1190  }
1191  if ($search_total_ht != '') {
1192  $param .= '&search_total_ht='.urlencode($search_total_ht);
1193  }
1194  if ($search_total_vat != '') {
1195  $param .= '&search_total_vat='.urlencode($search_total_vat);
1196  }
1197  if ($search_total_ttc != '') {
1198  $param .= '&search_total_ttc='.urlencode($search_total_ttc);
1199  }
1200  if ($search_warehouse != '') {
1201  $param .= '&search_warehouse='.urlencode($search_warehouse);
1202  }
1203  if ($search_login) {
1204  $param .= '&search_login='.urlencode($search_login);
1205  }
1206  if ($search_multicurrency_code != '') {
1207  $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code);
1208  }
1209  if ($search_multicurrency_tx != '') {
1210  $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx);
1211  }
1212  if ($search_multicurrency_montant_ht != '') {
1213  $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht);
1214  }
1215  if ($search_multicurrency_montant_vat != '') {
1216  $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat);
1217  }
1218  if ($search_multicurrency_montant_ttc != '') {
1219  $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc);
1220  }
1221  if ($search_project_ref >= 0) {
1222  $param .= "&search_project_ref=".urlencode($search_project_ref);
1223  }
1224  if ($search_town != '') {
1225  $param .= '&search_town='.urlencode($search_town);
1226  }
1227  if ($search_zip != '') {
1228  $param .= '&search_zip='.urlencode($search_zip);
1229  }
1230  if ($search_state != '') {
1231  $param .= '&search_state='.urlencode($search_state);
1232  }
1233  if ($search_country != '') {
1234  $param .= '&search_country='.urlencode($search_country);
1235  }
1236  if ($search_type_thirdparty && $search_type_thirdparty != '-1') {
1237  $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty);
1238  }
1239  if ($search_product_category != '') {
1240  $param .= '&search_product_category='.urlencode($search_product_category);
1241  }
1242  if (($search_categ_cus > 0) || ($search_categ_cus == -2)) {
1243  $param .= '&search_categ_cus='.urlencode($search_categ_cus);
1244  }
1245  if ($show_files) {
1246  $param .= '&show_files='.urlencode($show_files);
1247  }
1248  if ($optioncss != '') {
1249  $param .= '&optioncss='.urlencode($optioncss);
1250  }
1251  if ($search_billed != '') {
1252  $param .= '&search_billed='.urlencode($search_billed);
1253  }
1254  if ($search_fk_cond_reglement > 0) {
1255  $param .= '&search_fk_cond_reglement='.urlencode($search_fk_cond_reglement);
1256  }
1257  if ($search_fk_shipping_method > 0) {
1258  $param .= '&search_fk_shipping_method='.urlencode($search_fk_shipping_method);
1259  }
1260  if ($search_fk_mode_reglement > 0) {
1261  $param .= '&search_fk_mode_reglement='.urlencode($search_fk_mode_reglement);
1262  }
1263  if ($search_fk_input_reason > 0) {
1264  $param .= '&search_fk_input_reason='.urlencode($search_fk_input_reason);
1265  }
1266 
1267  // Add $param from extra fields
1268  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
1269 
1270  // Add $param from hooks
1271  $parameters = array();
1272  $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1273  $param .= $hookmanager->resPrint;
1274 
1275  // List of mass actions available
1276  $arrayofmassactions = array(
1277  'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
1278  'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
1279  );
1280  if ($permissiontovalidate) {
1281  $arrayofmassactions['prevalidate'] = img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate");
1282  }
1283  if ($permissiontosendbymail) {
1284  $arrayofmassactions['presend'] = img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail");
1285  }
1286  if ($permissiontoclose) {
1287  $arrayofmassactions['preshipped'] = img_picto('', 'dollyrevert', 'class="pictofixedwidth"').$langs->trans("ClassifyShipped");
1288  }
1289  if ($permissiontocancel) {
1290  $arrayofmassactions['cancelorders'] = img_picto('', 'close_title', 'class="pictofixedwidth"').$langs->trans("Cancel");
1291  }
1292  if (isModEnabled('facture') && $user->hasRight("facture", "creer")) {
1293  $arrayofmassactions['createbills'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("CreateInvoiceForThisCustomer");
1294  }
1295  if ($permissiontoclose) {
1296  $arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("ClassifyBilled");
1297  }
1298  if ($permissiontodelete) {
1299  $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
1300  }
1301  if (in_array($massaction, array('presend', 'predelete', 'createbills'))) {
1302  $arrayofmassactions = array();
1303  }
1304  $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
1305 
1306  $url = DOL_URL_ROOT.'/commande/card.php?action=create';
1307  if (!empty($socid)) {
1308  $url .= '&socid='.$socid;
1309  }
1310  $newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $contextpage == 'orderlist' && $permissiontoadd);
1311 
1312  // Lines of title fields
1313  print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
1314  if ($optioncss != '') {
1315  print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
1316  }
1317  print '<input type="hidden" name="token" value="'.newToken().'">';
1318  print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
1319  print '<input type="hidden" name="action" value="list">';
1320  print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
1321  print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
1322  print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
1323  print '<input type="hidden" name="search_status" value="'.$search_status.'">';
1324  print '<input type="hidden" name="socid" value="'.$socid.'">';
1325 
1326  print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'order', 0, $newcardbutton, '', $limit, 0, 0, 1);
1327 
1328  $topicmail = "SendOrderRef";
1329  $modelmail = "order_send";
1330  $objecttmp = new Commande($db);
1331  $trackid = 'ord'.$object->id;
1332  include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
1333 
1334  if ($massaction == 'prevalidate') {
1335  print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassValidation"), $langs->trans("ConfirmMassValidationQuestion"), "validate", null, '', 0, 200, 500, 1);
1336  }
1337  if ($massaction == 'preshipped') {
1338  print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("CloseOrder"), $langs->trans("ConfirmCloseOrder"), "shipped", null, '', 0, 200, 500, 1);
1339  }
1340 
1341  if ($massaction == 'createbills') {
1342  print '<input type="hidden" name="massaction" value="confirm_createbills">';
1343 
1344  print '<table class="noborder centpercent">';
1345  print '<tr>';
1346  print '<td>';
1347  print $langs->trans('DateInvoice');
1348  print '</td>';
1349  print '<td>';
1350  print $form->selectDate('', '', '', '', '', '', 1, 1);
1351  print '</td>';
1352  print '</tr>';
1353  print '<tr>';
1354  print '<td>';
1355  print $langs->trans('CreateOneBillByThird');
1356  print '</td>';
1357  print '<td>';
1358  print $form->selectyesno('createbills_onebythird', '', 1);
1359  print '</td>';
1360  print '</tr>';
1361  print '<tr>';
1362  print '<td>';
1363  print $langs->trans('ValidateInvoices');
1364  print '</td>';
1365  print '<td>';
1366  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
1367  print $form->selectyesno('validate_invoices', 0, 1, 1);
1368  $langs->load("errors");
1369  print ' ('.$langs->trans("WarningAutoValNotPossibleWhenStockIsDecreasedOnInvoiceVal").')';
1370  } else {
1371  print $form->selectyesno('validate_invoices', 0, 1);
1372  }
1373  if (!empty($conf->workflow->enabled) && !empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) {
1374  print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").'</span>';
1375  } else {
1376  print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("OptionToSetOrderBilledNotEnabled").'</span>';
1377  }
1378  print '</td>';
1379  print '</tr>';
1380  print '</table>';
1381 
1382  print '<div class="center">';
1383  print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisCustomer').'"> ';
1384  print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
1385  print '</div>';
1386  print '<br><br>';
1387  }
1388 
1389  if ($sall) {
1390  foreach ($fieldstosearchall as $key => $val) {
1391  $fieldstosearchall[$key] = $langs->trans($val);
1392  }
1393  print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
1394  }
1395 
1396  $moreforfilter = '';
1397 
1398  // If the user can view prospects? sales other than his own
1399  if ($user->hasRight("user", "user", "lire")) {
1400  $langs->load("commercial");
1401  $moreforfilter .= '<div class="divsearchfield">';
1402  $tmptitle = $langs->trans('ThirdPartiesOfSaleRepresentative');
1403  $moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth250 widthcentpercentminusx');
1404  $moreforfilter .= '</div>';
1405  }
1406  // If the user can view other users
1407  if ($user->hasRight("user", "user", "lire")) {
1408  $moreforfilter .= '<div class="divsearchfield">';
1409  $tmptitle = $langs->trans('LinkedToSpecificUsers');
1410  $moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$form->select_dolusers($search_user, 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250 widthcentpercentminusx');
1411  $moreforfilter .= '</div>';
1412  }
1413 
1414  // If the user can view other products/services than his own
1415  if (isModEnabled('categorie') && $user->hasRight("categorie", "lire") && ($user->hasRight("produit", "lire") || $user->hasRight("service", "lire"))) {
1416  include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1417  $moreforfilter .= '<div class="divsearchfield">';
1418  $tmptitle = $langs->trans('IncludingProductWithTag');
1419  $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
1420  $moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$form->selectarray('search_product_category', $cate_arbo, $search_product_category, $tmptitle, 0, 0, '', 0, 0, 0, 0, 'maxwidth300 widthcentpercentminusx', 1);
1421  $moreforfilter .= '</div>';
1422  }
1423  // If Categories are enabled & user has rights to see
1424  if (isModEnabled('categorie') && $user->hasRight("categorie", "lire")) {
1425  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1426  $moreforfilter .= '<div class="divsearchfield">';
1427  $tmptitle = $langs->trans('CustomersProspectsCategoriesShort');
1428  $moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle, 'maxwidth300 widthcentpercentminusx');
1429  $moreforfilter .= '</div>';
1430  }
1431  // If Stock is enabled
1432  if (isModEnabled('stock') && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
1433  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
1434  $formproduct = new FormProduct($db);
1435  $moreforfilter .= '<div class="divsearchfield">';
1436  $tmptitle = $langs->trans('Warehouse');
1437  $moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1, 0, 0, $tmptitle, 0, 0, array(), 'maxwidth250 widthcentpercentminusx');
1438  $moreforfilter .= '</div>';
1439  }
1440  $parameters = array();
1441  $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1442  if (empty($reshook)) {
1443  $moreforfilter .= $hookmanager->resPrint;
1444  } else {
1445  $moreforfilter = $hookmanager->resPrint;
1446  }
1447 
1448  if (!empty($moreforfilter)) {
1449  print '<div class="liste_titre liste_titre_bydiv centpercent">';
1450  print $moreforfilter;
1451  print '</div>';
1452  }
1453 
1454  $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
1455  $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')); // This also change content of $arrayfields
1456  $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
1457 
1458  if (GETPOST('autoselectall', 'int')) {
1459  $selectedfields .= '<script>';
1460  $selectedfields .= ' $(document).ready(function() {';
1461  $selectedfields .= ' console.log("Autoclick on checkforselects");';
1462  $selectedfields .= ' $("#checkforselects").click();';
1463  $selectedfields .= ' $("#massaction").val("createbills").change();';
1464  $selectedfields .= ' });';
1465  $selectedfields .= '</script>';
1466  }
1467 
1468  print '<div class="div-table-responsive">';
1469  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
1470 
1471  print '<tr class="liste_titre_filter">';
1472  // Action column
1473  if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
1474  print '<td class="liste_titre" align="middle">';
1475  $searchpicto = $form->showFilterButtons('left');
1476  print $searchpicto;
1477  print '</td>';
1478  }
1479 
1480  // Ref
1481  if (!empty($arrayfields['c.ref']['checked'])) {
1482  print '<td class="liste_titre">';
1483  print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
1484  print '</td>';
1485  }
1486  // Ref customer
1487  if (!empty($arrayfields['c.ref_client']['checked'])) {
1488  print '<td class="liste_titre" align="left">';
1489  print '<input class="flat" type="text" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">';
1490  print '</td>';
1491  }
1492  // Project ref
1493  if (!empty($arrayfields['p.ref']['checked'])) {
1494  print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
1495  }
1496  // Project title
1497  if (!empty($arrayfields['p.title']['checked'])) {
1498  print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project" value="'.dol_escape_htmltag($search_project).'"></td>';
1499  }
1500  // Thirpdarty
1501  if (!empty($arrayfields['s.nom']['checked'])) {
1502  print '<td class="liste_titre" align="left">';
1503  print '<input class="flat maxwidth100" type="text" name="search_company" value="'.dol_escape_htmltag($search_company).'">';
1504  print '</td>';
1505  }
1506  // Alias
1507  if (!empty($arrayfields['s.name_alias']['checked'])) {
1508  print '<td class="liste_titre" align="left">';
1509  print '<input class="flat maxwidth100" type="text" name="search_company_alias" value="'.dol_escape_htmltag($search_company_alias).'">';
1510  print '</td>';
1511  }
1512  // Parent company
1513  if (!empty($arrayfields['s2.nom']['checked'])) {
1514  print '<td class="liste_titre">';
1515  print '<input class="flat maxwidth100" type="text" name="search_parent_name" value="'.dol_escape_htmltag($search_parent_name).'">';
1516  print '</td>';
1517  }
1518  // Town
1519  if (!empty($arrayfields['s.town']['checked'])) {
1520  print '<td class="liste_titre"><input class="flat width50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>';
1521  }
1522  // Zip
1523  if (!empty($arrayfields['s.zip']['checked'])) {
1524  print '<td class="liste_titre"><input class="flat width50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>';
1525  }
1526  // State
1527  if (!empty($arrayfields['state.nom']['checked'])) {
1528  print '<td class="liste_titre">';
1529  print '<input class="flat width50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
1530  print '</td>';
1531  }
1532  // Country
1533  if (!empty($arrayfields['country.code_iso']['checked'])) {
1534  print '<td class="liste_titre" align="center">';
1535  print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
1536  print '</td>';
1537  }
1538  // Company type
1539  if (!empty($arrayfields['typent.code']['checked'])) {
1540  print '<td class="liste_titre maxwidthonsmartphone" align="center">';
1541  print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1);
1542  print '</td>';
1543  }
1544  // Date order
1545  if (!empty($arrayfields['c.date_commande']['checked'])) {
1546  print '<td class="liste_titre center">';
1547  print '<div class="nowrap">';
1548  print $form->selectDate($search_dateorder_start ? $search_dateorder_start : -1, 'search_dateorder_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
1549  print '</div>';
1550  print '<div class="nowrap">';
1551  print $form->selectDate($search_dateorder_end ? $search_dateorder_end : -1, 'search_dateorder_end_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
1552  print '</div>';
1553  print '</td>';
1554  }
1555  if (!empty($arrayfields['c.date_delivery']['checked'])) {
1556  print '<td class="liste_titre center">';
1557  print '<div class="nowrap">';
1558  print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
1559  print '</div>';
1560  print '<div class="nowrap">';
1561  print $form->selectDate($search_datedelivery_end ? $search_datedelivery_end : -1, 'search_datedelivery_end_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
1562  print '</div>';
1563  print '</td>';
1564  }
1565  // Shipping Method
1566  if (!empty($arrayfields['c.fk_shipping_method']['checked'])) {
1567  print '<td class="liste_titre">';
1568  $form->selectShippingMethod($search_fk_shipping_method, 'search_fk_shipping_method', '', 1, '', 1);
1569  print '</td>';
1570  }
1571  // Payment term
1572  if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) {
1573  print '<td class="liste_titre">';
1574  print $form->getSelectConditionsPaiements($search_fk_cond_reglement, 'search_fk_cond_reglement', 1, 1, 1);
1575  print '</td>';
1576  }
1577  // Payment mode
1578  if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) {
1579  print '<td class="liste_titre">';
1580  print $form->select_types_paiements($search_fk_mode_reglement, 'search_fk_mode_reglement', '', 0, 1, 1, 0, -1, '', 1);
1581  print '</td>';
1582  }
1583  // Channel
1584  if (!empty($arrayfields['c.fk_input_reason']['checked'])) {
1585  print '<td class="liste_titre">';
1586  $form->selectInputReason($search_fk_input_reason, 'search_fk_input_reason', '', 1, '', 1);
1587  print '</td>';
1588  }
1589  // Amount HT / net
1590  if (!empty($arrayfields['c.total_ht']['checked'])) {
1591  print '<td class="liste_titre right">';
1592  print '<input class="flat" type="text" size="4" name="search_total_ht" value="'.dol_escape_htmltag($search_total_ht).'">';
1593  print '</td>';
1594  }
1595  // Amount of VAT
1596  if (!empty($arrayfields['c.total_vat']['checked'])) {
1597  print '<td class="liste_titre right">';
1598  print '<input class="flat" type="text" size="4" name="search_total_vat" value="'.dol_escape_htmltag($search_total_vat).'">';
1599  print '</td>';
1600  }
1601  // Total Amount (TTC / gross)
1602  if (!empty($arrayfields['c.total_ttc']['checked'])) {
1603  print '<td class="liste_titre right">';
1604  print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">';
1605  print '</td>';
1606  }
1607  // Currency
1608  if (!empty($arrayfields['c.multicurrency_code']['checked'])) {
1609  print '<td class="liste_titre">';
1610  print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1);
1611  print '</td>';
1612  }
1613  // Currency rate
1614  if (!empty($arrayfields['c.multicurrency_tx']['checked'])) {
1615  print '<td class="liste_titre">';
1616  print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">';
1617  print '</td>';
1618  }
1619  // Amount HT/net in foreign currency
1620  if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) {
1621  print '<td class="liste_titre right">';
1622  print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">';
1623  print '</td>';
1624  }
1625  // VAT in foreign currency
1626  if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) {
1627  print '<td class="liste_titre right">';
1628  print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">';
1629  print '</td>';
1630  }
1631  // Amount/Total (TTC / gross) in foreign currency
1632  if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) {
1633  print '<td class="liste_titre right">';
1634  print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">';
1635  print '</td>';
1636  }
1637  // Author
1638  if (!empty($arrayfields['u.login']['checked'])) {
1639  print '<td class="liste_titre" align="center">';
1640  print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">';
1641  print '</td>';
1642  }
1643  // Sales Representative
1644  if (!empty($arrayfields['sale_representative']['checked'])) {
1645  print '<td class="liste_titre"></td>';
1646  }
1647  if (!empty($arrayfields['total_pa']['checked'])) {
1648  print '<td class="liste_titre right">';
1649  print '</td>';
1650  }
1651  if (!empty($arrayfields['total_margin']['checked'])) {
1652  print '<td class="liste_titre right">';
1653  print '</td>';
1654  }
1655  if (!empty($arrayfields['total_margin_rate']['checked'])) {
1656  print '<td class="liste_titre right">';
1657  print '</td>';
1658  }
1659  if (!empty($arrayfields['total_mark_rate']['checked'])) {
1660  print '<td class="liste_titre right">';
1661  print '</td>';
1662  }
1663 
1664  // Extra fields
1665  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
1666 
1667  // Fields from hook
1668  $parameters = array('arrayfields'=>$arrayfields);
1669  $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1670  print $hookmanager->resPrint;
1671 
1672  // Date creation
1673  if (!empty($arrayfields['c.datec']['checked'])) {
1674  print '<td class="liste_titre">';
1675  print '</td>';
1676  }
1677  // Date modification
1678  if (!empty($arrayfields['c.tms']['checked'])) {
1679  print '<td class="liste_titre">';
1680  print '</td>';
1681  }
1682  // Date cloture
1683  if (!empty($arrayfields['c.date_cloture']['checked'])) {
1684  print '<td class="liste_titre center">';
1685  print '<div class="nowrap">';
1686  print $form->selectDate($search_datecloture_start ? $search_datecloture_start : -1, 'search_datecloture_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
1687  print '</div>';
1688  print '<div class="nowrap">';
1689  print $form->selectDate($search_datecloture_end ? $search_datecloture_end : -1, 'search_datecloture_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
1690  print '</div>';
1691  print '</td>';
1692  }
1693  // Note public
1694  if (!empty($arrayfields['c.note_public']['checked'])) {
1695  print '<td class="liste_titre">';
1696  print '</td>';
1697  }
1698  // Note private
1699  if (!empty($arrayfields['c.note_private']['checked'])) {
1700  print '<td class="liste_titre">';
1701  print '</td>';
1702  }
1703  // Shippable
1704  if (!empty($arrayfields['shippable']['checked'])) {
1705  print '<td class="liste_titre maxwidthonsmartphone" align="center">';
1706  //print $form->selectyesno('search_shippable', $search_shippable, 1, 0, 1, 1);
1707  if (!empty($conf->global->ORDER_SHIPABLE_STATUS_DISABLED_BY_DEFAULT)) {
1708  print '<input type="checkbox" name="show_shippable_command" value="1"'.($show_shippable_command ? ' checked' : '').'>';
1709  print $langs->trans('ShowShippableStatus');
1710  } else {
1711  $show_shippable_command = 1;
1712  }
1713  print '</td>';
1714  }
1715  // Status billed
1716  if (!empty($arrayfields['c.facture']['checked'])) {
1717  print '<td class="liste_titre maxwidthonsmartphone center">';
1718  print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1);
1719  print '</td>';
1720  }
1721  // Import key
1722  if (!empty($arrayfields['c.import_key']['checked'])) {
1723  print '<td class="liste_titre maxwidthonsmartphone center">';
1724  print '</td>';
1725  }
1726  // Status
1727  if (!empty($arrayfields['c.fk_statut']['checked'])) {
1728  print '<td class="liste_titre right parentonrightofpage">';
1729  $liststatus = array(
1730  Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"),
1731  Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"),
1732  Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"),
1733  Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"),
1734  -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"),
1735  -2=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort"),
1736  Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort")
1737  );
1738  print $form->selectarray('search_status', $liststatus, $search_status, -5, 0, 0, '', 0, 0, 0, '', 'maxwidth125 onrightofpage', 1);
1739  print '</td>';
1740  }
1741  // Action column
1742  if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
1743  print '<td class="liste_titre" align="middle">';
1744  $searchpicto = $form->showFilterButtons();
1745  print $searchpicto;
1746  print '</td>';
1747  }
1748  print "</tr>\n";
1749 
1750  // Fields title
1751  print '<tr class="liste_titre">';
1752 
1753  if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
1754  print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
1755  }
1756  if (!empty($arrayfields['c.ref']['checked'])) {
1757  print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], 'c.ref', '', $param, '', $sortfield, $sortorder);
1758  }
1759  if (!empty($arrayfields['c.ref_client']['checked'])) {
1760  print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $sortfield, $sortorder);
1761  }
1762  if (!empty($arrayfields['p.ref']['checked'])) {
1763  print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
1764  }
1765  if (!empty($arrayfields['p.title']['checked'])) {
1766  print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, '', $sortfield, $sortorder);
1767  }
1768  if (!empty($arrayfields['s.nom']['checked'])) {
1769  print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder);
1770  }
1771  if (!empty($arrayfields['s.name_alias']['checked'])) {
1772  print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], 's.name_alias', '', $param, '', $sortfield, $sortorder);
1773  }
1774  if (!empty($arrayfields['s2.nom']['checked'])) {
1775  print_liste_field_titre($arrayfields['s2.nom']['label'], $_SERVER['PHP_SELF'], 's2.nom', '', $param, '', $sortfield, $sortorder);
1776  }
1777  if (!empty($arrayfields['s.town']['checked'])) {
1778  print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
1779  }
1780  if (!empty($arrayfields['s.zip']['checked'])) {
1781  print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
1782  }
1783  if (!empty($arrayfields['state.nom']['checked'])) {
1784  print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
1785  }
1786  if (!empty($arrayfields['country.code_iso']['checked'])) {
1787  print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
1788  }
1789  if (!empty($arrayfields['typent.code']['checked'])) {
1790  print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
1791  }
1792  if (!empty($arrayfields['c.date_commande']['checked'])) {
1793  print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center ');
1794  }
1795  if (!empty($arrayfields['c.date_delivery']['checked'])) {
1796  print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center ');
1797  }
1798  if (!empty($arrayfields['c.fk_shipping_method']['checked'])) {
1799  print_liste_field_titre($arrayfields['c.fk_shipping_method']['label'], $_SERVER["PHP_SELF"], "c.fk_shipping_method", "", $param, '', $sortfield, $sortorder);
1800  }
1801  if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) {
1802  print_liste_field_titre($arrayfields['c.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_cond_reglement", "", $param, '', $sortfield, $sortorder);
1803  }
1804  if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) {
1805  print_liste_field_titre($arrayfields['c.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_mode_reglement", "", $param, '', $sortfield, $sortorder);
1806  }
1807  if (!empty($arrayfields['c.fk_input_reason']['checked'])) {
1808  print_liste_field_titre($arrayfields['c.fk_input_reason']['label'], $_SERVER["PHP_SELF"], "c.fk_input_reason", "", $param, '', $sortfield, $sortorder);
1809  }
1810  if (!empty($arrayfields['c.total_ht']['checked'])) {
1811  print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
1812  }
1813  if (!empty($arrayfields['c.total_vat']['checked'])) {
1814  print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.total_tva', '', $param, '', $sortfield, $sortorder, 'right ');
1815  }
1816  if (!empty($arrayfields['c.total_ttc']['checked'])) {
1817  print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
1818  }
1819  if (!empty($arrayfields['c.multicurrency_code']['checked'])) {
1820  print_liste_field_titre($arrayfields['c.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_code', '', $param, '', $sortfield, $sortorder);
1821  }
1822  if (!empty($arrayfields['c.multicurrency_tx']['checked'])) {
1823  print_liste_field_titre($arrayfields['c.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_tx', '', $param, '', $sortfield, $sortorder);
1824  }
1825  if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) {
1826  print_liste_field_titre($arrayfields['c.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder);
1827  }
1828  if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) {
1829  print_liste_field_titre($arrayfields['c.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder);
1830  }
1831  if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) {
1832  print_liste_field_titre($arrayfields['c.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder);
1833  }
1834  if (!empty($arrayfields['u.login']['checked'])) {
1835  print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder);
1836  }
1837  if (!empty($arrayfields['sale_representative']['checked'])) {
1838  print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $sortfield, $sortorder);
1839  }
1840  if (!empty($arrayfields['total_pa']['checked'])) {
1841  print_liste_field_titre($arrayfields['total_pa']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder);
1842  }
1843  if (!empty($arrayfields['total_margin']['checked'])) {
1844  print_liste_field_titre($arrayfields['total_margin']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder);
1845  }
1846  if (!empty($arrayfields['total_margin_rate']['checked'])) {
1847  print_liste_field_titre($arrayfields['total_margin_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder);
1848  }
1849  if (!empty($arrayfields['total_mark_rate']['checked'])) {
1850  print_liste_field_titre($arrayfields['total_mark_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder);
1851  }
1852 
1853  $totalarray = array(
1854  'nbfield' => 0,
1855  'val' => array(
1856  'c.total_ht' => 0,
1857  'c.total_tva' => 0,
1858  'c.total_ttc' => 0,
1859  ),
1860  'pos' => array(),
1861  );
1862 
1863  // Extra fields
1864  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
1865 
1866  // Hook fields
1867  $parameters = array(
1868  'arrayfields' => $arrayfields,
1869  'param' => $param,
1870  'sortfield' => $sortfield,
1871  'sortorder' => $sortorder,
1872  'totalarray' => &$totalarray,
1873  );
1874  $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1875  print $hookmanager->resPrint;
1876  if (!empty($arrayfields['c.datec']['checked'])) {
1877  print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
1878  }
1879  if (!empty($arrayfields['c.tms']['checked'])) {
1880  print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
1881  }
1882  if (!empty($arrayfields['c.date_cloture']['checked'])) {
1883  print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
1884  }
1885  if (!empty($arrayfields['c.note_public']['checked'])) {
1886  print_liste_field_titre($arrayfields['c.note_public']['label'], $_SERVER["PHP_SELF"], "c.note_public", "", $param, '', $sortfield, $sortorder, 'right ');
1887  }
1888  if (!empty($arrayfields['c.note_private']['checked'])) {
1889  print_liste_field_titre($arrayfields['c.note_private']['label'], $_SERVER["PHP_SELF"], "c.note_private", "", $param, '', $sortfield, $sortorder, 'right ');
1890  }
1891  if (!empty($arrayfields['shippable']['checked'])) {
1892  print_liste_field_titre($arrayfields['shippable']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center ');
1893  }
1894  if (!empty($arrayfields['c.facture']['checked'])) {
1895  print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center ');
1896  }
1897  if (!empty($arrayfields['c.import_key']['checked'])) {
1898  print_liste_field_titre($arrayfields['c.import_key']['label'], $_SERVER["PHP_SELF"], "c.import_key", "", $param, '', $sortfield, $sortorder, 'center ');
1899  }
1900  if (!empty($arrayfields['c.fk_statut']['checked'])) {
1901  print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'right ');
1902  }
1903  if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
1904  print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
1905  }
1906  print '</tr>'."\n";
1907 
1908  $total = 0;
1909  $subtotal = 0;
1910  $productstat_cache = array();
1911  $productstat_cachevirtual = array();
1912  $getNomUrl_cache = array();
1913 
1914  $generic_commande = new Commande($db);
1915  $generic_product = new Product($db);
1916  $userstatic = new User($db);
1917  $i = 0;
1918 
1919  $with_margin_info = false;
1920  if (isModEnabled('margin') && (
1921  !empty($arrayfields['total_pa']['checked'])
1922  || !empty($arrayfields['total_margin']['checked'])
1923  || !empty($arrayfields['total_margin_rate']['checked'])
1924  || !empty($arrayfields['total_mark_rate']['checked'])
1925  )
1926  ) {
1927  $with_margin_info = true;
1928  }
1929  $total_ht = 0;
1930  $total_margin = 0;
1931 
1932  $savnbfield = $totalarray['nbfield'];
1933  $totalarray = array();
1934  $totalarray['nbfield'] = 0;
1935  $imaxinloop = ($limit ? min($num, $limit) : $num);
1936  while ($i < $imaxinloop) {
1937  $obj = $db->fetch_object($resql);
1938 
1939  $notshippable = 0;
1940  $warning = 0;
1941  $text_info = '';
1942  $text_warning = '';
1943  $nbprod = 0;
1944 
1945  $companystatic->id = $obj->socid;
1946  $companystatic->name = $obj->name;
1947  $companystatic->name_alias = $obj->alias;
1948  $companystatic->client = $obj->client;
1949  $companystatic->fournisseur = $obj->fournisseur;
1950  $companystatic->code_client = $obj->code_client;
1951  $companystatic->email = $obj->email;
1952  $companystatic->phone = $obj->phone;
1953  $companystatic->address = $obj->address;
1954  $companystatic->zip = $obj->zip;
1955  $companystatic->town = $obj->town;
1956  $companystatic->country_code = $obj->country_code;
1957  if (!isset($getNomUrl_cache[$obj->socid])) {
1958  $getNomUrl_cache[$obj->socid] = $companystatic->getNomUrl(1, 'customer', 100, 0, 1, empty($arrayfields['s.name_alias']['checked']) ? 0 : 1);
1959  }
1960 
1961  $generic_commande->id = $obj->rowid;
1962  $generic_commande->ref = $obj->ref;
1963  $generic_commande->statut = $obj->fk_statut;
1964  $generic_commande->billed = $obj->billed;
1965  $generic_commande->date = $db->jdate($obj->date_commande);
1966  $generic_commande->delivery_date = $db->jdate($obj->date_delivery);
1967  $generic_commande->ref_client = $obj->ref_client;
1968  $generic_commande->total_ht = $obj->total_ht;
1969  $generic_commande->total_tva = $obj->total_tva;
1970  $generic_commande->total_ttc = $obj->total_ttc;
1971  $generic_commande->note_public = $obj->note_public;
1972  $generic_commande->note_private = $obj->note_private;
1973 
1974  $projectstatic->id = $obj->project_id;
1975  $projectstatic->ref = $obj->project_ref;
1976  $projectstatic->title = $obj->project_label;
1977 
1978  $marginInfo = array();
1979  if ($with_margin_info === true) {
1980  $generic_commande->fetch_lines();
1981  $marginInfo = $formmargin->getMarginInfosArray($generic_commande);
1982  $total_ht += $obj->total_ht;
1983  $total_margin += $marginInfo['total_margin'];
1984  }
1985 
1986  print '<tr class="oddeven">';
1987 
1988  // Action column
1989  if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
1990  print '<td class="nowrap center">';
1991  if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
1992  $selected = 0;
1993  if (in_array($obj->rowid, $arrayofselected)) {
1994  $selected = 1;
1995  }
1996  print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
1997  }
1998  if (!$i) {
1999  $totalarray['nbfield']++;
2000  }
2001  print '</td>';
2002  }
2003 
2004  // Ref
2005  if (!empty($arrayfields['c.ref']['checked'])) {
2006  print '<td class="nowraponall">';
2007  print $generic_commande->getNomUrl(1, ($search_status != 2 ? 0 : $obj->fk_statut), 0, 0, 0, 1, 1);
2008 
2009  $filename = dol_sanitizeFileName($obj->ref);
2010  $filedir = $conf->commande->multidir_output[$conf->entity].'/'.dol_sanitizeFileName($obj->ref);
2011  $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid;
2012  print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir);
2013 
2014  print '</td>';
2015  if (!$i) {
2016  $totalarray['nbfield']++;
2017  }
2018  }
2019 
2020  // Ref customer
2021  if (!empty($arrayfields['c.ref_client']['checked'])) {
2022  print '<td class="nowrap tdoverflowmax200">'.$obj->ref_client.'</td>';
2023  if (!$i) {
2024  $totalarray['nbfield']++;
2025  }
2026  }
2027 
2028  // Project ref
2029  if (!empty($arrayfields['p.ref']['checked'])) {
2030  print '<td class="nowrap">';
2031  if ($obj->project_id > 0) {
2032  print $projectstatic->getNomUrl(1);
2033  }
2034  print '</td>';
2035  if (!$i) {
2036  $totalarray['nbfield']++;
2037  }
2038  }
2039 
2040  // Project label
2041  if (!empty($arrayfields['p.title']['checked'])) {
2042  print '<td class="nowrap">';
2043  if ($obj->project_id > 0) {
2044  print $projectstatic->title;
2045  }
2046  print '</td>';
2047  if (!$i) {
2048  $totalarray['nbfield']++;
2049  }
2050  }
2051 
2052  // Third party
2053  if (!empty($arrayfields['s.nom']['checked'])) {
2054  print '<td class="tdoverflowmax150">';
2055  print $getNomUrl_cache[$obj->socid];
2056 
2057  // If module invoices enabled and user with invoice creation permissions
2058  if (isModEnabled('facture') && !empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) {
2059  if ($user->rights->facture->creer) {
2060  if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) {
2061  print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$companystatic->id.'&search_billed=0&autoselectall=1">';
2062  print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').'</a>';
2063  }
2064  }
2065  }
2066  print '</td>';
2067  if (!$i) {
2068  $totalarray['nbfield']++;
2069  }
2070  }
2071 
2072  // Alias name
2073  if (!empty($arrayfields['s.name_alias']['checked'])) {
2074  print '<td class="nocellnopadd">';
2075  print $obj->alias;
2076  print '</td>';
2077  if (!$i) {
2078  $totalarray['nbfield']++;
2079  }
2080  }
2081 
2082  // Parent company
2083  if (!empty($arrayfields['s2.nom']['checked'])) {
2084  print '<td class="tdoverflowmax200">';
2085  if ($obj->fk_parent > 0) {
2086  if (!isset($company_url_list[$obj->fk_parent])) {
2087  $companyparent = new Societe($db);
2088  $res = $companyparent->fetch($obj->fk_parent);
2089  if ($res > 0) {
2090  $company_url_list[$obj->fk_parent] = $companyparent->getNomUrl(1);
2091  }
2092  }
2093  if (isset($company_url_list[$obj->fk_parent])) {
2094  print $company_url_list[$obj->fk_parent];
2095  }
2096  }
2097  print "</td>";
2098  if (!$i) {
2099  $totalarray['nbfield']++;
2100  }
2101  }
2102 
2103  // Town
2104  if (!empty($arrayfields['s.town']['checked'])) {
2105  print '<td class="nocellnopadd">';
2106  print $obj->town;
2107  print '</td>';
2108  if (!$i) {
2109  $totalarray['nbfield']++;
2110  }
2111  }
2112 
2113  // Zip
2114  if (!empty($arrayfields['s.zip']['checked'])) {
2115  print '<td class="nocellnopadd">';
2116  print $obj->zip;
2117  print '</td>';
2118  if (!$i) {
2119  $totalarray['nbfield']++;
2120  }
2121  }
2122 
2123  // State
2124  if (!empty($arrayfields['state.nom']['checked'])) {
2125  print "<td>".$obj->state_name."</td>\n";
2126  if (!$i) {
2127  $totalarray['nbfield']++;
2128  }
2129  }
2130 
2131  // Country
2132  if (!empty($arrayfields['country.code_iso']['checked'])) {
2133  print '<td class="center">';
2134  $tmparray = getCountry($obj->fk_pays, 'all');
2135  print $tmparray['label'];
2136  print '</td>';
2137  if (!$i) {
2138  $totalarray['nbfield']++;
2139  }
2140  }
2141 
2142  // Type ent
2143  if (!empty($arrayfields['typent.code']['checked'])) {
2144  print '<td class="center">';
2145  if (empty($typenArray)) {
2146  $typenArray = $formcompany->typent_array(1);
2147  }
2148  print $typenArray[$obj->typent_code];
2149  print '</td>';
2150  if (!$i) {
2151  $totalarray['nbfield']++;
2152  }
2153  }
2154 
2155  // Order date
2156  if (!empty($arrayfields['c.date_commande']['checked'])) {
2157  print '<td class="center">';
2158  print dol_print_date($db->jdate($obj->date_commande), 'day');
2159  // Warning late icon and note
2160  if ($generic_commande->hasDelay()) {
2161  print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning");
2162  }
2163  print '</td>';
2164  if (!$i) {
2165  $totalarray['nbfield']++;
2166  }
2167  }
2168 
2169  // Plannned date of delivery
2170  if (!empty($arrayfields['c.date_delivery']['checked'])) {
2171  print '<td class="center">';
2172  print dol_print_date($db->jdate($obj->date_delivery), 'dayhour');
2173  print '</td>';
2174  if (!$i) {
2175  $totalarray['nbfield']++;
2176  }
2177  }
2178 
2179  // Shipping Method
2180  if (!empty($arrayfields['c.fk_shipping_method']['checked'])) {
2181  print '<td>';
2182  $form->formSelectShippingMethod('', $obj->fk_shipping_method, 'none', 1);
2183  print '</td>';
2184  if (!$i) {
2185  $totalarray['nbfield']++;
2186  }
2187  }
2188 
2189  // Payment terms
2190  if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) {
2191  print '<td>';
2192  $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', 0, '', 1, $obj->deposit_percent);
2193  print '</td>';
2194  if (!$i) {
2195  $totalarray['nbfield']++;
2196  }
2197  }
2198 
2199  // Payment mode
2200  if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) {
2201  print '<td>';
2202  $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1);
2203  print '</td>';
2204  if (!$i) {
2205  $totalarray['nbfield']++;
2206  }
2207  }
2208 
2209  // Channel
2210  if (!empty($arrayfields['c.fk_input_reason']['checked'])) {
2211  print '<td>';
2212  $form->formInputReason($_SERVER['PHP_SELF'], $obj->fk_input_reason, 'none', '');
2213  print '</td>';
2214  if (!$i) {
2215  $totalarray['nbfield']++;
2216  }
2217  }
2218 
2219  // Amount HT/net
2220  if (!empty($arrayfields['c.total_ht']['checked'])) {
2221  print '<td class="nowrap right"><span class="amount">'.price($obj->total_ht)."</span></td>\n";
2222  if (!$i) {
2223  $totalarray['nbfield']++;
2224  }
2225  if (!$i) {
2226  $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ht';
2227  }
2228  if (isset($totalarray['val']['c.total_ht'])) {
2229  $totalarray['val']['c.total_ht'] += $obj->total_ht;
2230  } else {
2231  $totalarray['val']['c.total_ht'] = $obj->total_ht;
2232  }
2233  }
2234 
2235  // Amount VAT
2236  if (!empty($arrayfields['c.total_vat']['checked'])) {
2237  print '<td class="nowrap right"><span class="amount">'.price($obj->total_tva)."</span></td>\n";
2238  if (!$i) {
2239  $totalarray['nbfield']++;
2240  }
2241  if (!$i) {
2242  $totalarray['pos'][$totalarray['nbfield']] = 'c.total_tva';
2243  }
2244  if (isset($totalarray['val']['c.total_tva'])) {
2245  $totalarray['val']['c.total_tva'] += $obj->total_tva;
2246  } else {
2247  $totalarray['val']['c.total_tva'] = $obj->total_tva;
2248  }
2249  }
2250 
2251  // Amount TTC / gross
2252  if (!empty($arrayfields['c.total_ttc']['checked'])) {
2253  print '<td class="nowrap right"><span class="amount">'.price($obj->total_ttc)."</span></td>\n";
2254  if (!$i) {
2255  $totalarray['nbfield']++;
2256  }
2257  if (!$i) {
2258  $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ttc';
2259  }
2260  if (isset($totalarray['val']['c.total_ttc'])) {
2261  $totalarray['val']['c.total_ttc'] += $obj->total_ttc;
2262  } else {
2263  $totalarray['val']['c.total_ttc'] = $obj->total_ttc;
2264  }
2265  }
2266 
2267  // Currency
2268  if (!empty($arrayfields['c.multicurrency_code']['checked'])) {
2269  print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n";
2270  if (!$i) {
2271  $totalarray['nbfield']++;
2272  }
2273  }
2274 
2275  // Currency rate
2276  if (!empty($arrayfields['c.multicurrency_tx']['checked'])) {
2277  print '<td class="nowrap">';
2278  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
2279  print "</td>\n";
2280  if (!$i) {
2281  $totalarray['nbfield']++;
2282  }
2283  }
2284 
2285  // Amount HT/net in foreign currency
2286  if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) {
2287  print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ht)."</span></td>\n";
2288  if (!$i) {
2289  $totalarray['nbfield']++;
2290  }
2291  }
2292  // Amount VAT in foreign currency
2293  if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) {
2294  print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_vat)."</span></td>\n";
2295  if (!$i) {
2296  $totalarray['nbfield']++;
2297  }
2298  }
2299  // Amount TTC / gross in foreign currency
2300  if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) {
2301  print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ttc)."</span></td>\n";
2302  if (!$i) {
2303  $totalarray['nbfield']++;
2304  }
2305  }
2306 
2307  $userstatic->id = $obj->fk_user_author;
2308  $userstatic->login = $obj->login;
2309  $userstatic->lastname = $obj->lastname;
2310  $userstatic->firstname = $obj->firstname;
2311  $userstatic->email = $obj->user_email;
2312  $userstatic->statut = $obj->user_statut;
2313  $userstatic->entity = $obj->entity;
2314  $userstatic->photo = $obj->photo;
2315  $userstatic->office_phone = $obj->office_phone;
2316  $userstatic->office_fax = $obj->office_fax;
2317  $userstatic->user_mobile = $obj->user_mobile;
2318  $userstatic->job = $obj->job;
2319  $userstatic->gender = $obj->gender;
2320 
2321  // Author
2322  if (!empty($arrayfields['u.login']['checked'])) {
2323  print '<td class="tdoverflowmax200">';
2324  if ($userstatic->id) {
2325  print $userstatic->getNomUrl(-1);
2326  } else {
2327  print '&nbsp;';
2328  }
2329  print "</td>\n";
2330  if (!$i) {
2331  $totalarray['nbfield']++;
2332  }
2333  }
2334 
2335  // Sales representatives
2336  if (!empty($arrayfields['sale_representative']['checked'])) {
2337  print '<td>';
2338  if ($obj->socid > 0) {
2339  $listsalesrepresentatives = $companystatic->getSalesRepresentatives($user);
2340  if ($listsalesrepresentatives < 0) {
2341  dol_print_error($db);
2342  }
2343  $nbofsalesrepresentative = count($listsalesrepresentatives);
2344  if ($nbofsalesrepresentative > 6) {
2345  // We print only number
2346  print $nbofsalesrepresentative;
2347  } elseif ($nbofsalesrepresentative > 0) {
2348  $j = 0;
2349  foreach ($listsalesrepresentatives as $val) {
2350  $userstatic->id = $val['id'];
2351  $userstatic->lastname = $val['lastname'];
2352  $userstatic->firstname = $val['firstname'];
2353  $userstatic->email = $val['email'];
2354  $userstatic->statut = $val['statut'];
2355  $userstatic->entity = $val['entity'];
2356  $userstatic->photo = $val['photo'];
2357  $userstatic->login = $val['login'];
2358  $userstatic->office_phone = $val['office_phone'];
2359  $userstatic->office_fax = $val['office_fax'];
2360  $userstatic->user_mobile = $val['user_mobile'];
2361  $userstatic->job = $val['job'];
2362  $userstatic->gender = $val['gender'];
2363  //print '<div class="float">':
2364  print ($nbofsalesrepresentative < 2) ? $userstatic->getNomUrl(-1, '', 0, 0, 12) : $userstatic->getNomUrl(-2);
2365  $j++;
2366  if ($j < $nbofsalesrepresentative) {
2367  print ' ';
2368  }
2369  //print '</div>';
2370  }
2371  }
2372  //else print $langs->trans("NoSalesRepresentativeAffected");
2373  } else {
2374  print '&nbsp;';
2375  }
2376  print '</td>';
2377  if (!$i) {
2378  $totalarray['nbfield']++;
2379  }
2380  }
2381 
2382  // Total buying or cost price
2383  if (!empty($arrayfields['total_pa']['checked'])) {
2384  print '<td class="right nowrap">'.price($marginInfo['pa_total']).'</td>';
2385  if (!$i) {
2386  $totalarray['nbfield']++;
2387  }
2388  }
2389 
2390  // Total margin
2391  if (!empty($arrayfields['total_margin']['checked'])) {
2392  print '<td class="right nowrap">'.price($marginInfo['total_margin']).'</td>';
2393  if (!$i) {
2394  $totalarray['nbfield']++;
2395  }
2396  if (!$i) {
2397  $totalarray['pos'][$totalarray['nbfield']] = 'total_margin';
2398  }
2399  $totalarray['val']['total_margin'] += $marginInfo['total_margin'];
2400  }
2401 
2402  // Total margin rate
2403  if (!empty($arrayfields['total_margin_rate']['checked'])) {
2404  print '<td class="right nowrap">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, 2).'%').'</td>';
2405  if (!$i) {
2406  $totalarray['nbfield']++;
2407  }
2408  }
2409 
2410  // Total mark rate
2411  if (!empty($arrayfields['total_mark_rate']['checked'])) {
2412  print '<td class="right nowrap">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, 2).'%').'</td>';
2413  if (!$i) {
2414  $totalarray['nbfield']++;
2415  }
2416  if (!$i) {
2417  $totalarray['pos'][$totalarray['nbfield']] = 'total_mark_rate';
2418  }
2419  if ($i >= $imaxinloop - 1) {
2420  if (!empty($total_ht)) {
2421  $totalarray['val']['total_mark_rate'] = price2num($total_margin * 100 / $total_ht, 'MT');
2422  } else {
2423  $totalarray['val']['total_mark_rate'] = '';
2424  }
2425  }
2426  }
2427 
2428  // Extra fields
2429  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
2430  // Fields from hook
2431  $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
2432  $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2433  print $hookmanager->resPrint;
2434 
2435  // Date creation
2436  if (!empty($arrayfields['c.datec']['checked'])) {
2437  print '<td align="center" class="nowrap">';
2438  print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
2439  print '</td>';
2440  if (!$i) {
2441  $totalarray['nbfield']++;
2442  }
2443  }
2444 
2445  // Date modification
2446  if (!empty($arrayfields['c.tms']['checked'])) {
2447  print '<td align="center" class="nowrap">';
2448  print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
2449  print '</td>';
2450  if (!$i) {
2451  $totalarray['nbfield']++;
2452  }
2453  }
2454 
2455  // Date cloture
2456  if (!empty($arrayfields['c.date_cloture']['checked'])) {
2457  print '<td align="center" class="nowrap">';
2458  print dol_print_date($db->jdate($obj->date_cloture), 'dayhour', 'tzuser');
2459  print '</td>';
2460  if (!$i) {
2461  $totalarray['nbfield']++;
2462  }
2463  }
2464 
2465  // Note public
2466  if (!empty($arrayfields['c.note_public']['checked'])) {
2467  print '<td class="center">';
2468  print dol_string_nohtmltag($obj->note_public);
2469  print '</td>';
2470  if (!$i) {
2471  $totalarray['nbfield']++;
2472  }
2473  }
2474 
2475  // Note private
2476  if (!empty($arrayfields['c.note_private']['checked'])) {
2477  print '<td class="center">';
2478  print dol_string_nohtmltag($obj->note_private);
2479  print '</td>';
2480  if (!$i) {
2481  $totalarray['nbfield']++;
2482  }
2483  }
2484 
2485  // Show shippable Icon (this creates subloops, so may be slow)
2486  if (!empty($arrayfields['shippable']['checked'])) {
2487  print '<td class="center">';
2488  if (!empty($show_shippable_command) && isModEnabled('stock')) {
2489  if (($obj->fk_statut > $generic_commande::STATUS_DRAFT) && ($obj->fk_statut < $generic_commande::STATUS_CLOSED)) {
2490  $generic_commande->getLinesArray(); // Load array ->lines
2491  $generic_commande->loadExpeditions(); // Load array ->expeditions
2492 
2493  $numlines = count($generic_commande->lines); // Loop on each line of order
2494  for ($lig = 0; $lig < $numlines; $lig++) {
2495  if (isset($generic_commande->expeditions[$generic_commande->lines[$lig]->id])) {
2496  $reliquat = $generic_commande->lines[$lig]->qty - $generic_commande->expeditions[$generic_commande->lines[$lig]->id];
2497  } else {
2498  $reliquat = $generic_commande->lines[$lig]->qty;
2499  }
2500  if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) { // If line is a product and not a service
2501  $nbprod++; // order contains real products
2502  $generic_product->id = $generic_commande->lines[$lig]->fk_product;
2503 
2504  // Get local and virtual stock and store it into cache
2505  if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) {
2506  $generic_product->load_stock('nobatch,warehouseopen'); // ->load_virtual_stock() is already included into load_stock()
2507  $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel;
2508  $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique;
2509  } else {
2510  $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'];
2511  $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique;
2512  }
2513 
2514  if ($reliquat > $generic_product->stock_reel) {
2515  $notshippable++;
2516  }
2517  if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) { // Default code. Default should be this case.
2518  $text_info .= $reliquat.' x '.$generic_commande->lines[$lig]->product_ref.'&nbsp;'.dol_trunc($generic_commande->lines[$lig]->product_label, 20);
2519  $text_info .= ' - '.$langs->trans("Stock").': <span class="'.($generic_product->stock_reel > 0 ? 'ok' : 'error').'">'.$generic_product->stock_reel.'</span>';
2520  $text_info .= ' - '.$langs->trans("VirtualStock").': <span class="'.($generic_product->stock_theorique > 0 ? 'ok' : 'error').'">'.$generic_product->stock_theorique.'</span>';
2521  $text_info .= ($reliquat != $generic_commande->lines[$lig]->qty ? ' <span class="opacitymedium">('.$langs->trans("QtyInOtherShipments").' '.($generic_commande->lines[$lig]->qty - $reliquat).')</span>' : '');
2522  $text_info .= '<br>';
2523  } else { // BUGGED CODE.
2524  // DOES NOT TAKE INTO ACCOUNT MANUFACTURING. THIS CODE SHOULD BE USELESS. PREVIOUS CODE SEEMS COMPLETE.
2525  // COUNT STOCK WHEN WE SHOULD ALREADY HAVE VALUE
2526  // Detailed virtual stock, looks bugged, uncomplete and need heavy load.
2527  // stock order and stock order_supplier
2528  $stock_order = 0;
2529  $stock_order_supplier = 0;
2530  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { // What about other options ?
2531  if (isModEnabled('commande')) {
2532  if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) {
2533  $generic_product->load_stats_commande(0, '1,2');
2534  $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty'];
2535  } else {
2536  $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'];
2537  }
2538  $stock_order = $generic_product->stats_commande['qty'];
2539  }
2540  if ((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order")) {
2541  if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) {
2542  $generic_product->load_stats_commande_fournisseur(0, '3');
2543  $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty'];
2544  } else {
2545  $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'];
2546  }
2547  $stock_order_supplier = $generic_product->stats_commande_fournisseur['qty'];
2548  }
2549  }
2550  $text_info .= $reliquat.' x '.$generic_commande->lines[$lig]->ref.'&nbsp;'.dol_trunc($generic_commande->lines[$lig]->product_label, 20);
2551  $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order;
2552  if ($stock_order > $generic_product->stock_reel && !($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) {
2553  $warning++;
2554  $text_warning .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
2555  }
2556  if ($reliquat > $generic_product->stock_reel) {
2557  $text_info .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
2558  } else {
2559  $text_info .= '<span class="ok">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
2560  }
2561  if ((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order")) {
2562  $text_info .= '&nbsp;'.$langs->trans('SupplierOrder').'&nbsp;:&nbsp;'.$stock_order_supplier;
2563  }
2564  $text_info .= ($reliquat != $generic_commande->lines[$lig]->qty ? ' <span class="opacitymedium">('.$langs->trans("QtyInOtherShipments").' '.($generic_commande->lines[$lig]->qty - $reliquat).')</span>' : '');
2565  $text_info .= '<br>';
2566  }
2567  }
2568  }
2569  if ($notshippable == 0) {
2570  $text_icon = img_picto('', 'dolly', '', false, 0, 0, '', 'green paddingleft');
2571  $text_info = $text_icon.' '.$langs->trans('Shippable').'<br>'.$text_info;
2572  } else {
2573  $text_icon = img_picto('', 'dolly', '', false, 0, 0, '', 'error paddingleft');
2574  $text_info = $text_icon.' '.$langs->trans('NonShippable').'<br>'.$text_info;
2575  }
2576  }
2577 
2578  if ($nbprod) {
2579  print $form->textwithtooltip('', $text_info, 2, 1, $text_icon, '', 2);
2580  }
2581  if ($warning) { // Always false in default mode
2582  print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'<br>'.$text_warning, 2, 1, img_picto('', 'error'), '', 2);
2583  }
2584  }
2585  print '</td>';
2586  if (!$i) {
2587  $totalarray['nbfield']++;
2588  }
2589  }
2590 
2591  // Billed
2592  if (!empty($arrayfields['c.facture']['checked'])) {
2593  print '<td class="center">'.yn($obj->billed).'</td>';
2594  if (!$i) {
2595  $totalarray['nbfield']++;
2596  }
2597  }
2598 
2599  // Import key
2600  if (!empty($arrayfields['c.import_key']['checked'])) {
2601  print '<td class="nowrap center">'.$obj->import_key.'</td>';
2602  if (!$i) {
2603  $totalarray['nbfield']++;
2604  }
2605  }
2606 
2607  // Status
2608  if (!empty($arrayfields['c.fk_statut']['checked'])) {
2609  print '<td class="nowrap right">'.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).'</td>';
2610  if (!$i) {
2611  $totalarray['nbfield']++;
2612  }
2613  }
2614 
2615  // Action column
2616  if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
2617  print '<td class="nowrap center">';
2618  if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
2619  $selected = 0;
2620  if (in_array($obj->rowid, $arrayofselected)) {
2621  $selected = 1;
2622  }
2623  print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
2624  }
2625  print '</td>';
2626  if (!$i) {
2627  $totalarray['nbfield']++;
2628  }
2629  }
2630 
2631  print "</tr>\n";
2632 
2633  $total += $obj->total_ht;
2634  $subtotal += $obj->total_ht;
2635  $i++;
2636  }
2637 
2638  // Show total line
2639  include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
2640 
2641  // If no record found
2642  if ($num == 0) {
2643  $colspan = 1;
2644  foreach ($arrayfields as $key => $val) {
2645  if (!empty($val['checked'])) {
2646  $colspan++;
2647  }
2648  }
2649  print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
2650  }
2651 
2652  $db->free($resql);
2653 
2654  $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
2655  $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2656  print $hookmanager->resPrint;
2657 
2658  print '</table>'."\n";
2659  print '</div>';
2660 
2661  print '</form>'."\n";
2662 
2663  $hidegeneratedfilelistifempty = 1;
2664  if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
2665  $hidegeneratedfilelistifempty = 0;
2666  }
2667 
2668  // Show list of available documents
2669  $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
2670  $urlsource .= str_replace('&amp;', '&', $param);
2671 
2672  $filedir = $diroutputmassaction;
2673  $genallowed = $permissiontoread;
2674  $delallowed = $permissiontoadd;
2675 
2676  print $formfile->showdocuments('massfilesarea_orders', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
2677 } else {
2678  dol_print_error($db);
2679 }
2680 
2681 // End of page
2682 llxFooter();
2683 $db->close();
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:49
dol_trunc
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.
Definition: functions.lib.php:3949
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1225
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:70
Project
Class to manage projects.
Definition: project.class.php:35
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:520
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:4993
dol_sort_array
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
Definition: functions.lib.php:8713
Commande\STATUS_CLOSED
const STATUS_CLOSED
Closed (Sent, billed or not)
Definition: commande.class.php:388
Commande\STATUS_SHIPMENTONPROCESS
const STATUS_SHIPMENTONPROCESS
Shipment on process.
Definition: commande.class.php:382
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
FormMargin
Classe permettant la generation de composants html autre Only common components are here.
Definition: html.formmargin.class.php:29
FormOther
Classe permettant la generation de composants html autre Only common components are here.
Definition: html.formother.class.php:39
Facture
Class to manage invoices.
Definition: facture.class.php:60
Commande\STATUS_CANCELED
const STATUS_CANCELED
Canceled status.
Definition: commande.class.php:370
$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:118
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5823
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:2550
dol_concatdesc
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
Definition: functions.lib.php:7542
FormCompany
Class to build HTML component for third parties management Only common components are here.
Definition: html.formcompany.class.php:40
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:4024
Commande\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: commande.class.php:378
llxHeader
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
FormFile
Class to offer components to list and upload files.
Definition: html.formfile.class.php:36
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dolGetButtonTitle
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
Definition: functions.lib.php:11021
Commande
Class to manage customers orders.
Definition: commande.class.php:46
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6880
DiscountAbsolute
Class to manage absolute discounts.
Definition: discount.class.php:29
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:5413
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:82
restrictedArea
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.
Definition: security.lib.php:346
FormProduct
Class with static methods for building HTML components related to products Only components common to ...
Definition: html.formproduct.class.php:30
Commande\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: commande.class.php:374
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:137
User
Class to manage Dolibarr users.
Definition: user.class.php:46
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:421
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:5178
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:9801
ExtraFields
Class to manage standard extra fields.
Definition: extrafields.class.php:39
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:53
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2951
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:5697
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:515
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8465
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:2863
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:96
$nbtotalofrecords
$nbtotalofrecords
Count total nb of records.
Definition: list.php:329