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-2021  Ferran Marcet           <fmarcet@2byte.es>
13 * Copyright (C) 2018       Charlene Benke	        <charlie@patas-monkey.com>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
29/**
30 *	\file       htdocs/commande/list.php
31 *	\ingroup    commande
32 *	\brief      Page to list orders
33 */
34
35
36require '../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
40require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
43require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
44require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
45require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
46require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
47
48// Load translation files required by the page
49$langs->loadLangs(array("orders", 'sendings', 'deliveries', 'companies', 'compta', 'bills', 'stocks', 'products'));
50
51$action = GETPOST('action', 'aZ09');
52$massaction = GETPOST('massaction', 'alpha');
53$show_files = GETPOST('show_files', 'int');
54$confirm = GETPOST('confirm', 'alpha');
55$toselect = GETPOST('toselect', 'array');
56$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'orderlist';
57
58$search_datecloture_start = dol_mktime(0, 0, 0, GETPOST('search_datecloture_startmonth', 'int'), GETPOST('search_datecloture_startday', 'int'), GETPOST('search_datecloture_startyear', 'int'));
59$search_datecloture_end = dol_mktime(23, 59, 59, GETPOST('search_datecloture_endmonth', 'int'), GETPOST('search_datecloture_endday', 'int'), GETPOST('search_datecloture_endyear', 'int'));
60$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'));
61$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'));
62$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'));
63$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'));
64$search_product_category = GETPOST('search_product_category', 'int');
65$search_ref = GETPOST('search_ref', 'alpha') != '' ?GETPOST('search_ref', 'alpha') : GETPOST('sref', 'alpha');
66$search_ref_customer = GETPOST('search_ref_customer', 'alpha');
67$search_company = GETPOST('search_company', 'alpha');
68$search_town = GETPOST('search_town', 'alpha');
69$search_zip = GETPOST('search_zip', 'alpha');
70$search_state = GETPOST("search_state", 'alpha');
71$search_country = GETPOST("search_country", 'int');
72$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int');
73$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
74$socid = GETPOST('socid', 'int');
75$search_user = GETPOST('search_user', 'int');
76$search_sale = GETPOST('search_sale', 'int');
77$search_total_ht = GETPOST('search_total_ht', 'alpha');
78$search_total_vat = GETPOST('search_total_vat', 'alpha');
79$search_total_ttc = GETPOST('search_total_ttc', 'alpha');
80$search_warehouse = GETPOST('search_warehouse', 'int');
81$search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha');
82$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha');
83$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha');
84$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha');
85$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha');
86$search_login = GETPOST('search_login', 'alpha');
87$search_categ_cus = GETPOST("search_categ_cus", 'int');
88$optioncss = GETPOST('optioncss', 'alpha');
89$search_billed = GETPOSTISSET('search_billed') ? GETPOST('search_billed', 'int') : GETPOST('billed', 'int');
90$search_status = GETPOST('search_status', 'int');
91$search_btn = GETPOST('button_search', 'alpha');
92$search_remove_btn = GETPOST('button_removefilter', 'alpha');
93$search_project_ref = GETPOST('search_project_ref', 'alpha');
94$search_project = GETPOST('search_project', 'alpha');
95$search_shippable = GETPOST('search_shippable', 'aZ09');
96
97
98// Security check
99$id = (GETPOST('orderid') ?GETPOST('orderid', 'int') : GETPOST('id', 'int'));
100if ($user->socid) $socid = $user->socid;
101$result = restrictedArea($user, 'commande', $id, '');
102
103$diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id;
104
105// Load variable for pagination
106$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
107$sortfield = GETPOST("sortfield", 'alpha');
108$sortorder = GETPOST("sortorder", 'alpha');
109$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
110if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters
111$offset = $limit * $page;
112$pageprev = $page - 1;
113$pagenext = $page + 1;
114if (!$sortfield) $sortfield = 'c.ref';
115if (!$sortorder) $sortorder = 'DESC';
116
117$show_shippable_command = GETPOST('show_shippable_command', 'aZ09');
118
119// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
120$object = new Commande($db);
121$hookmanager->initHooks(array('orderlist'));
122$extrafields = new ExtraFields($db);
123
124// fetch optionals attributes and labels
125$extrafields->fetch_name_optionals_label($object->table_element);
126$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
127
128// List of fields to search into when doing a "search in all"
129$fieldstosearchall = array(
130	'c.ref'=>'Ref',
131	'c.ref_client'=>'RefCustomerOrder',
132	'pd.description'=>'Description',
133	's.nom'=>"ThirdParty",
134	's.name_alias'=>"AliasNameShort",
135	's.zip'=>"Zip",
136	's.town'=>"Town",
137	'c.note_public'=>'NotePublic',
138);
139if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate";
140
141$checkedtypetiers = 0;
142$arrayfields = array(
143	'c.ref'=>array('label'=>"Ref", 'checked'=>1, 'position'=>5),
144	'c.ref_client'=>array('label'=>"RefCustomerOrder", 'checked'=>-1, 'position'=>10),
145	'p.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1), 'position'=>20),
146	'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1), 'position'=>25),
147	's.nom'=>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30),
148	's.town'=>array('label'=>"Town", 'checked'=>1, 'position'=>35),
149	's.zip'=>array('label'=>"Zip", 'checked'=>1, 'position'=>40),
150	'state.nom'=>array('label'=>"StateShort", 'checked'=>0, 'position'=>45),
151	'country.code_iso'=>array('label'=>"Country", 'checked'=>0, 'position'=>50),
152	'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers, 'position'=>55),
153	'c.date_commande'=>array('label'=>"OrderDateShort", 'checked'=>1, 'position'=>60),
154	'c.date_delivery'=>array('label'=>"DateDeliveryPlanned", 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE), 'position'=>65),
155	'c.total_ht'=>array('label'=>"AmountHT", 'checked'=>1, 'position'=>75),
156	'c.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0, 'position'=>80),
157	'c.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0, 'position'=>85),
158	'c.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>90),
159	'c.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>95),
160	'c.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>100),
161	'c.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>105),
162	'c.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>110),
163	'u.login'=>array('label'=>"Author", 'checked'=>1, 'position'=>10, 'position'=>115),
164	'c.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500, 'position'=>120),
165	'c.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500, 'position'=>125),
166	'c.date_cloture'=>array('label'=>"DateClosing", 'checked'=>0, 'position'=>500, 'position'=>130),
167	'c.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'position'=>510, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PUBLIC_NOTES)), 'position'=>135),
168	'c.note_private'=>array('label'=>'NotePrivate', 'checked'=>0, 'position'=>511, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PRIVATE_NOTES)), 'position'=>140),
169	'c.facture'=>array('label'=>"Billed", 'checked'=>1, 'position'=>990, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)), 'position'=>145),
170	'shippable'=>array('label'=>"Shippable", 'checked'=>1, 'position'=>995, 'enabled'=>(!empty($conf->expedition->enabled)), 'position'=>150),
171	'c.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000, 'position'=>155)
172);
173// Extra fields
174include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
175
176$object->fields = dol_sort_array($object->fields, 'position');
177$arrayfields = dol_sort_array($arrayfields, 'position');
178
179
180
181/*
182 * Actions
183 */
184
185if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
186if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; }
187
188$parameters = array('socid'=>$socid);
189$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
190if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
191
192if (empty($reshook))
193{
194	// Selection of new fields
195	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
196
197	// Purge search criteria
198	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
199	{
200		$search_categ = '';
201		$search_user = '';
202		$search_sale = '';
203		$search_product_category = '';
204		$search_ref = '';
205		$search_ref_customer = '';
206		$search_company = '';
207		$search_town = '';
208		$search_zip = "";
209		$search_state = "";
210		$search_type = '';
211		$search_country = '';
212		$search_type_thirdparty = '';
213		$search_total_ht = '';
214		$search_total_vat = '';
215		$search_total_ttc = '';
216		$search_warehouse = '';
217		$search_multicurrency_code = '';
218		$search_multicurrency_tx = '';
219		$search_multicurrency_montant_ht = '';
220		$search_multicurrency_montant_vat = '';
221		$search_multicurrency_montant_ttc = '';
222		$search_login = '';
223		$search_dateorder_start = '';
224		$search_dateorder_end = '';
225		$search_datedelivery_start = '';
226		$search_datedelivery_end = '';
227		$search_project_ref = '';
228		$search_project = '';
229		$search_status = '';
230		$search_billed = '';
231		$toselect = '';
232		$search_array_options = array();
233		$search_categ_cus = 0;
234		$search_datecloture_start = '';
235		$search_datecloture_end = '';
236	}
237	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
238	 || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha'))
239	{
240		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
241	}
242
243	// Mass actions
244	$objectclass = 'Commande';
245	$objectlabel = 'Orders';
246	$permissiontoread = $user->rights->commande->lire;
247	$permissiontodelete = $user->rights->commande->supprimer;
248	$uploaddir = $conf->commande->multidir_output[$conf->entity];
249	$triggersendname = 'ORDER_SENTBYMAIL';
250	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
251}
252
253
254/*
255 * View
256 */
257
258$now = dol_now();
259
260$form = new Form($db);
261$formother = new FormOther($db);
262$formfile = new FormFile($db);
263$companystatic = new Societe($db);
264$formcompany = new FormCompany($db);
265$projectstatic = new Project($db);
266
267$title = $langs->trans("Orders");
268$help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes";
269// llxHeader('',$title,$help_url);
270
271$sql = 'SELECT';
272if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT';
273$sql .= ' s.rowid as socid, s.nom as name, s.name_alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,';
274$sql .= " typent.code as typent_code,";
275$sql .= " state.code_departement as state_code, state.nom as state_name,";
276$sql .= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client, c.fk_user_author,';
277$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,';
278$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,';
279$sql .= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,';
280$sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,";
281$sql .= " u.login";
282if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc";
283// Add fields from extrafields
284if (!empty($extrafields->attributes[$object->table_element]['label']))
285	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
286// Add fields from hooks
287$parameters = array();
288$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
289$sql .= $hookmanager->resPrint;
290$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
291$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
292$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
293$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
294if (!empty($search_categ_cus)) $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
295$sql .= ', '.MAIN_DB_PREFIX.'commande as c';
296if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)";
297if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande';
298if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product';
299$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet";
300$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid';
301
302// We'll need this table joined to the select in order to filter by sale
303if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
304if ($search_user > 0)
305{
306	$sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
307	$sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc";
308}
309$sql .= ' WHERE c.fk_soc = s.rowid';
310$sql .= ' AND c.entity IN ('.getEntity('commande').')';
311if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category;
312if ($socid > 0) $sql .= ' AND s.rowid = '.$socid;
313if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
314if ($search_ref) $sql .= natural_search('c.ref', $search_ref);
315if ($search_ref_customer) $sql .= natural_search('c.ref_client', $search_ref_customer);
316if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
317if ($search_billed != '' && $search_billed >= 0) $sql .= ' AND c.facture = '.$search_billed;
318if ($search_status <> '')
319{
320	if ($search_status < 4 && $search_status > -3)
321	{
322		if ($search_status == 1 && empty($conf->expedition->enabled)) $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated'
323		else $sql .= ' AND c.fk_statut = '.$search_status; // brouillon, validee, en cours, annulee
324	}
325	if ($search_status == 4)
326	{
327		$sql .= ' AND c.facture = 1'; // invoice created
328	}
329	if ($search_status == -2)	// To process
330	{
331		//$sql.= ' AND c.fk_statut IN (1,2,3) AND c.facture = 0';
332		$sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected
333	}
334	if ($search_status == -3)	// To bill
335	{
336		//$sql.= ' AND c.fk_statut in (1,2,3)';
337		//$sql.= ' AND c.facture = 0'; // invoice not created
338		$sql .= ' AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))'; // validated, in process or closed but not billed
339	}
340}
341
342if ($search_datecloture_start)               $sql .= " AND c.date_cloture >= '".$db->idate($search_datecloture_start)."'";
343if ($search_datecloture_end)                 $sql .= " AND c.date_cloture <= '".$db->idate($search_datecloture_end)."'";
344if ($search_dateorder_start)                 $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'";
345if ($search_dateorder_end)                   $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'";
346if ($search_datedelivery_start)              $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'";
347if ($search_datedelivery_end)                $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'";
348if ($search_town)                            $sql .= natural_search('s.town', $search_town);
349if ($search_zip)                             $sql .= natural_search("s.zip", $search_zip);
350if ($search_state)                           $sql .= natural_search("state.nom", $search_state);
351if ($search_country)                         $sql .= " AND s.fk_pays IN (".$search_country.')';
352if ($search_type_thirdparty)                 $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')';
353if ($search_company)                         $sql .= natural_search('s.nom', $search_company);
354if ($search_sale > 0)                        $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale;
355if ($search_user > 0)                        $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 = ".$search_user;
356if ($search_total_ht != '')                  $sql .= natural_search('c.total_ht', $search_total_ht, 1);
357if ($search_total_vat != '')                 $sql .= natural_search('c.tva', $search_total_vat, 1);
358if ($search_total_ttc != '')                 $sql .= natural_search('c.total_ttc', $search_total_ttc, 1);
359if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('c.fk_warehouse', $search_warehouse, 1);
360if ($search_multicurrency_code != '')        $sql .= ' AND c.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"';
361if ($search_multicurrency_tx != '')          $sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1);
362if ($search_multicurrency_montant_ht != '')  $sql .= natural_search('c.multicurrency_total_ht', $search_multicurrency_montant_ht, 1);
363if ($search_multicurrency_montant_vat != '') $sql .= natural_search('c.multicurrency_total_tva', $search_multicurrency_montant_vat, 1);
364if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('c.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1);
365if ($search_login)                           $sql .= natural_search("u.login", $search_login);
366if ($search_project_ref != '')               $sql .= natural_search("p.ref", $search_project_ref);
367if ($search_project != '')                   $sql .= natural_search("p.title", $search_project);
368if ($search_categ_cus > 0)                   $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus);
369if ($search_categ_cus == -2)                 $sql .= " AND cc.fk_categorie IS NULL";
370
371// Add where from extra fields
372include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
373// Add where from hooks
374$parameters = array();
375$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
376$sql .= $hookmanager->resPrint;
377
378$sql .= $db->order($sortfield, $sortorder);
379
380// Count total nb of records
381$nbtotalofrecords = '';
382if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
383{
384	$result = $db->query($sql);
385	$nbtotalofrecords = $db->num_rows($result);
386
387	if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
388	{
389		$page = 0;
390		$offset = 0;
391	}
392}
393
394$sql .= $db->plimit($limit + 1, $offset);
395//print $sql;
396
397$resql = $db->query($sql);
398if ($resql)
399{
400	if ($socid > 0)
401	{
402		$soc = new Societe($db);
403		$soc->fetch($socid);
404		$title = $langs->trans('ListOfOrders').' - '.$soc->name;
405		if (empty($search_company)) $search_company = $soc->name;
406	} else {
407		$title = $langs->trans('ListOfOrders');
408	}
409	if (strval($search_status) == '0')
410	$title .= ' - '.$langs->trans('StatusOrderDraftShort');
411	if ($search_status == 1)
412	$title .= ' - '.$langs->trans('StatusOrderValidatedShort');
413	if ($search_status == 2)
414	$title .= ' - '.$langs->trans('StatusOrderSentShort');
415	if ($search_status == 3)
416	$title .= ' - '.$langs->trans('StatusOrderToBillShort');
417	if ($search_status == 4)
418	$title .= ' - '.$langs->trans('StatusOrderProcessedShort');
419	if ($search_status == -1)
420	$title .= ' - '.$langs->trans('StatusOrderCanceledShort');
421	if ($search_status == -2)
422	$title .= ' - '.$langs->trans('StatusOrderToProcessShort');
423	if ($search_status == -3)
424	$title .= ' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled) ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill');
425
426	$num = $db->num_rows($resql);
427
428	$arrayofselected = is_array($toselect) ? $toselect : array();
429
430	if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall)
431	{
432		$obj = $db->fetch_object($resql);
433		$id = $obj->rowid;
434		header("Location: ".DOL_URL_ROOT.'/commande/card.php?id='.$id);
435		exit;
436	}
437
438	llxHeader('', $title, $help_url);
439
440	$param = '';
441
442	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
443	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
444	if ($sall)						$param .= '&sall='.urlencode($sall);
445	if ($socid > 0)					$param .= '&socid='.urlencode($socid);
446	if ($search_status != '')		$param .= '&search_status='.urlencode($search_status);
447	if ($search_datecloture_start)  $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');
448	if ($search_datecloture_end)    $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');
449	if ($search_dateorder_start) 	$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');
450	if ($search_dateorder_end) 		$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');
451	if ($search_datedelivery_start) $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');
452	if ($search_datedelivery_end) 	$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');
453	if ($search_ref)      			$param .= '&search_ref='.urlencode($search_ref);
454	if ($search_company)  			$param .= '&search_company='.urlencode($search_company);
455	if ($search_ref_customer)		$param .= '&search_ref_customer='.urlencode($search_ref_customer);
456	if ($search_user > 0) 			$param .= '&search_user='.urlencode($search_user);
457	if ($search_sale > 0) 			$param .= '&search_sale='.urlencode($search_sale);
458	if ($search_total_ht != '') 	$param .= '&search_total_ht='.urlencode($search_total_ht);
459	if ($search_total_vat != '')  	$param .= '&search_total_vat='.urlencode($search_total_vat);
460	if ($search_total_ttc != '')  	$param .= '&search_total_ttc='.urlencode($search_total_ttc);
461	if ($search_warehouse != '')	$param .= '&search_warehouse='.urlencode($search_warehouse);
462	if ($search_login)				$param .= '&search_login='.urlencode($search_login);
463	if ($search_multicurrency_code != '')  $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code);
464	if ($search_multicurrency_tx != '')  $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx);
465	if ($search_multicurrency_montant_ht != '')  $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht);
466	if ($search_multicurrency_montant_vat != '')  $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat);
467	if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc);
468	if ($search_project_ref >= 0) 	$param .= "&search_project_ref=".urlencode($search_project_ref);
469	if ($search_town != '')       	$param .= '&search_town='.urlencode($search_town);
470	if ($search_zip != '')        	$param .= '&search_zip='.urlencode($search_zip);
471	if ($search_state != '')      	$param .= '&search_state='.urlencode($search_state);
472	if ($search_country != '')    	$param .= '&search_country='.urlencode($search_country);
473	if ($search_type_thirdparty != '')  $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty);
474	if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category);
475	if ($search_categ_cus > 0)      $param .= '&search_categ_cus='.urlencode($search_categ_cus);
476	if ($show_files)            	$param .= '&show_files='.urlencode($show_files);
477	if ($optioncss != '')       	$param .= '&optioncss='.urlencode($optioncss);
478	if ($search_billed != '')		$param .= '&search_billed='.urlencode($search_billed);
479
480	// Add $param from extra fields
481	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
482
483	// List of mass actions available
484	$arrayofmassactions = array(
485		'generate_doc'=>$langs->trans("ReGeneratePDF"),
486		'builddoc'=>$langs->trans("PDFMerge"),
487		'cancelorders'=>$langs->trans("Cancel"),
488		'presend'=>$langs->trans("SendByMail"),
489	);
490	if ($user->rights->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisCustomer");
491	if ($user->rights->commande->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
492	if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array();
493	$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
494
495	$url = DOL_URL_ROOT.'/commande/card.php?action=create';
496	if (!empty($socid)) $url .= '&socid='.$socid;
497	$newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $contextpage == 'orderlist' && $user->rights->commande->creer);
498
499	// Lines of title fields
500	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
501	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
502	print '<input type="hidden" name="token" value="'.newToken().'">';
503	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
504	print '<input type="hidden" name="action" value="list">';
505	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
506	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
507	print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
508	print '<input type="hidden" name="search_status" value="'.$search_status.'">';
509	print '<input type="hidden" name="socid" value="'.$socid.'">';
510
511	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'order', 0, $newcardbutton, '', $limit, 0, 0, 1);
512
513	$topicmail = "SendOrderRef";
514	$modelmail = "order_send";
515	$objecttmp = new Commande($db);
516	$trackid = 'ord'.$object->id;
517	include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
518
519	if ($massaction == 'createbills')
520	{
521		//var_dump($_REQUEST);
522		print '<input type="hidden" name="massaction" value="confirm_createbills">';
523
524		print '<table class="noborder" width="100%" >';
525		print '<tr>';
526		print '<td class="titlefield">';
527		print $langs->trans('DateInvoice');
528		print '</td>';
529		print '<td>';
530		print $form->selectDate('', '', '', '', '', '', 1, 1);
531		print '</td>';
532		print '</tr>';
533		print '<tr>';
534		print '<td>';
535		print $langs->trans('CreateOneBillByThird');
536		print '</td>';
537		print '<td>';
538		print $form->selectyesno('createbills_onebythird', '', 1);
539		print '</td>';
540		print '</tr>';
541		print '<tr>';
542		print '<td>';
543		print $langs->trans('ValidateInvoices');
544		print '</td>';
545		print '<td>';
546		if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
547		{
548			print $form->selectyesno('validate_invoices', 0, 1, 1);
549			print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')';
550		} else {
551			print $form->selectyesno('validate_invoices', 0, 1);
552		}
553		if (!empty($conf->workflow->enabled) && !empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").'</span>';
554		else print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("OptionToSetOrderBilledNotEnabled").'</span>';
555		print '</td>';
556		print '</tr>';
557		print '</table>';
558
559		print '<br>';
560		print '<div class="center">';
561		print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisCustomer').'">  ';
562		print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
563		print '</div>';
564		print '<br>';
565	}
566
567	if ($sall)
568	{
569		foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
570		print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
571	}
572
573	$moreforfilter = '';
574
575 	// If the user can view prospects other than his'
576 	if ($user->rights->societe->client->voir || $socid)
577 	{
578 		$langs->load("commercial");
579		$moreforfilter .= '<div class="divsearchfield">';
580 		$moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': ';
581		$moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200');
582	 	$moreforfilter .= '</div>';
583 	}
584	// If the user can view other users
585	if ($user->rights->user->user->lire)
586	{
587		$moreforfilter .= '<div class="divsearchfield">';
588		$moreforfilter .= $langs->trans('LinkedToSpecificUsers').': ';
589		$moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
590	 	$moreforfilter .= '</div>';
591	}
592	// If the user can view prospects other than his'
593	if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire))
594	{
595		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
596		$moreforfilter .= '<div class="divsearchfield">';
597		$moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
598		$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
599		$moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
600		$moreforfilter .= '</div>';
601	}
602	if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire)
603	{
604		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
605		$moreforfilter .= '<div class="divsearchfield">';
606	 	$moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': ';
607		$moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1);
608	 	$moreforfilter .= '</div>';
609	}
610	if (!empty($conf->expedition->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
611		require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
612		$formproduct = new FormProduct($db);
613		$moreforfilter .= '<div class="divsearchfield">';
614	 	$moreforfilter .= $langs->trans('Warehouse').': ';
615		$moreforfilter .= $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1);
616	 	$moreforfilter .= '</div>';
617	}
618	$parameters = array();
619	$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
620	if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
621	else $moreforfilter = $hookmanager->resPrint;
622
623	if (!empty($moreforfilter))
624	{
625		print '<div class="liste_titre liste_titre_bydiv centpercent">';
626		print $moreforfilter;
627		print '</div>';
628	}
629
630	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
631	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
632	$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
633
634	if (GETPOST('autoselectall', 'int')) {
635		$selectedfields .= '<script>';
636		$selectedfields .= '   $(document).ready(function() {';
637		$selectedfields .= '        console.log("Autoclick on checkforselects");';
638		$selectedfields .= '   		$("#checkforselects").click();';
639		$selectedfields .= '        $("#massaction").val("createbills").change();';
640		$selectedfields .= '   });';
641		$selectedfields .= '</script>';
642	}
643
644	print '<div class="div-table-responsive">';
645	print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
646
647	print '<tr class="liste_titre_filter">';
648	// Ref
649	if (!empty($arrayfields['c.ref']['checked']))
650	{
651		print '<td class="liste_titre">';
652		print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
653		print '</td>';
654	}
655	// Ref customer
656	if (!empty($arrayfields['c.ref_client']['checked']))
657	{
658		print '<td class="liste_titre" align="left">';
659		print '<input class="flat" type="text" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">';
660		print '</td>';
661	}
662	// Project ref
663	if (!empty($arrayfields['p.ref']['checked']))
664	{
665		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
666	}
667	// Project title
668	if (!empty($arrayfields['p.title']['checked']))
669	{
670		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project" value="'.dol_escape_htmltag($search_project).'"></td>';
671	}
672	// Thirpdarty
673	if (!empty($arrayfields['s.nom']['checked']))
674	{
675		print '<td class="liste_titre" align="left">';
676		print '<input class="flat maxwidth100" type="text" name="search_company" value="'.dol_escape_htmltag($search_company).'">';
677		print '</td>';
678	}
679	// Town
680	if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>';
681	// Zip
682	if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>';
683	// State
684	if (!empty($arrayfields['state.nom']['checked']))
685	{
686		print '<td class="liste_titre">';
687		print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
688		print '</td>';
689	}
690	// Country
691	if (!empty($arrayfields['country.code_iso']['checked']))
692	{
693		print '<td class="liste_titre" align="center">';
694		print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
695		print '</td>';
696	}
697	// Company type
698	if (!empty($arrayfields['typent.code']['checked']))
699	{
700		print '<td class="liste_titre maxwidthonsmartphone" align="center">';
701		print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT));
702		print '</td>';
703	}
704	// Date order
705	if (!empty($arrayfields['c.date_commande']['checked']))
706	{
707		print '<td class="liste_titre center">';
708		print '<div class="nowrap">';
709		print $form->selectDate($search_dateorder_start ? $search_dateorder_start : -1, 'search_dateorder_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
710		print '</div>';
711		print '<div class="nowrap">';
712		print $form->selectDate($search_dateorder_end ? $search_dateorder_end : -1, 'search_dateorder_end_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
713		print '</div>';
714		print '</td>';
715	}
716	if (!empty($arrayfields['c.date_delivery']['checked']))
717	{
718		print '<td class="liste_titre center">';
719		print '<div class="nowrap">';
720		print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
721		print '</div>';
722		print '<div class="nowrap">';
723		print $form->selectDate($search_datedelivery_end ? $search_datedelivery_end : -1, 'search_datedelivery_end_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
724		print '</div>';
725		print '</td>';
726	}
727	if (!empty($arrayfields['c.total_ht']['checked']))
728	{
729		// Amount
730		print '<td class="liste_titre right">';
731		print '<input class="flat" type="text" size="4" name="search_total_ht" value="'.dol_escape_htmltag($search_total_ht).'">';
732		print '</td>';
733	}
734	if (!empty($arrayfields['c.total_vat']['checked']))
735	{
736		// Amount
737		print '<td class="liste_titre right">';
738		print '<input class="flat" type="text" size="4" name="search_total_vat" value="'.dol_escape_htmltag($search_total_vat).'">';
739		print '</td>';
740	}
741	if (!empty($arrayfields['c.total_ttc']['checked']))
742	{
743		// Amount
744		print '<td class="liste_titre right">';
745		print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">';
746		print '</td>';
747	}
748	if (!empty($arrayfields['c.multicurrency_code']['checked']))
749	{
750		// Currency
751		print '<td class="liste_titre">';
752		print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1);
753		print '</td>';
754	}
755	if (!empty($arrayfields['c.multicurrency_tx']['checked']))
756	{
757		// Currency rate
758		print '<td class="liste_titre">';
759		print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">';
760		print '</td>';
761	}
762	if (!empty($arrayfields['c.multicurrency_total_ht']['checked']))
763	{
764		// Amount
765		print '<td class="liste_titre right">';
766		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">';
767		print '</td>';
768	}
769	if (!empty($arrayfields['c.multicurrency_total_vat']['checked']))
770	{
771		// Amount VAT
772		print '<td class="liste_titre right">';
773		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">';
774		print '</td>';
775	}
776	if (!empty($arrayfields['c.multicurrency_total_ttc']['checked']))
777	{
778		// Amount
779		print '<td class="liste_titre right">';
780		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">';
781		print '</td>';
782	}
783	if (!empty($arrayfields['u.login']['checked']))
784	{
785		// Author
786		print '<td class="liste_titre" align="center">';
787		print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">';
788		print '</td>';
789	}
790	// Extra fields
791	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
792	// Fields from hook
793	$parameters = array('arrayfields'=>$arrayfields);
794	$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
795	print $hookmanager->resPrint;
796	// Date creation
797	if (!empty($arrayfields['c.datec']['checked']))
798	{
799		print '<td class="liste_titre">';
800		print '</td>';
801	}
802	// Date modification
803	if (!empty($arrayfields['c.tms']['checked']))
804	{
805		print '<td class="liste_titre">';
806		print '</td>';
807	}
808	// Date cloture
809	if (!empty($arrayfields['c.date_cloture']['checked']))
810	{
811		print '<td class="liste_titre center">';
812		print '<div class="nowrap">';
813		print $form->selectDate($search_datecloture_start ? $search_datecloture_start : -1, 'search_datecloture_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
814		print '</div>';
815		print '<div class="nowrap">';
816		print $form->selectDate($search_datecloture_end ? $search_datecloture_end : -1, 'search_datecloture_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
817		print '</div>';
818		print '</td>';
819	}
820	// Note public
821	if (!empty($arrayfields['c.note_public']['checked']))
822	{
823		print '<td class="liste_titre">';
824		print '</td>';
825	}
826	// Note private
827	if (!empty($arrayfields['c.note_private']['checked']))
828	{
829		print '<td class="liste_titre">';
830		print '</td>';
831	}
832	// Shippable
833	if (!empty($arrayfields['shippable']['checked']))
834	{
835		print '<td class="liste_titre maxwidthonsmartphone" align="center">';
836		//print $form->selectyesno('search_shippable', $search_shippable, 1, 0, 1, 1);
837		if (!empty($conf->global->ORDER_SHIPABLE_STATUS_DISABLED_BY_DEFAULT)) {
838			print '<input type="checkbox" name="show_shippable_command" value="1"'.($show_shippable_command ? ' checked' : '').'>';
839			print $langs->trans('ShowShippableStatus');
840		} else {
841			$show_shippable_command = 1;
842		}
843		print '</td>';
844	}
845	// Status billed
846	if (!empty($arrayfields['c.facture']['checked']))
847	{
848		print '<td class="liste_titre maxwidthonsmartphone" align="center">';
849		print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1);
850		print '</td>';
851	}
852	// Status
853	if (!empty($arrayfields['c.fk_statut']['checked']))
854	{
855		print '<td class="liste_titre maxwidthonsmartphone center">';
856		$liststatus = array(
857			Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"),
858			Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"),
859			Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"),
860			Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"),
861			-3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"),
862			Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort")
863		);
864		print $form->selectarray('search_status', $liststatus, $search_status, -4, 0, 0, '', 0, 0, 0, '', 'maxwidth100', 1);
865		print '</td>';
866	}
867	// Action column
868	print '<td class="liste_titre" align="middle">';
869	$searchpicto = $form->showFilterButtons();
870	print $searchpicto;
871	print '</td>';
872
873	print "</tr>\n";
874
875	// Fields title
876	print '<tr class="liste_titre">';
877	if (!empty($arrayfields['c.ref']['checked']))            print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], 'c.ref', '', $param, '', $sortfield, $sortorder);
878	if (!empty($arrayfields['c.ref_client']['checked']))     print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $sortfield, $sortorder);
879	if (!empty($arrayfields['p.ref']['checked'])) 	         print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
880	if (!empty($arrayfields['p.title']['checked'])) 	     print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, '', $sortfield, $sortorder);
881	if (!empty($arrayfields['s.nom']['checked']))            print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder);
882	if (!empty($arrayfields['s.town']['checked']))           print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
883	if (!empty($arrayfields['s.zip']['checked']))            print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
884	if (!empty($arrayfields['state.nom']['checked']))        print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
885	if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
886	if (!empty($arrayfields['typent.code']['checked']))      print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
887	if (!empty($arrayfields['c.date_commande']['checked']))  print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center ');
888	if (!empty($arrayfields['c.date_delivery']['checked']))  print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center ');
889	if (!empty($arrayfields['c.total_ht']['checked']))       print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
890	if (!empty($arrayfields['c.total_vat']['checked']))      print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right ');
891	if (!empty($arrayfields['c.total_ttc']['checked']))      print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
892	if (!empty($arrayfields['c.multicurrency_code']['checked']))          print_liste_field_titre($arrayfields['c.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_code', '', $param, '', $sortfield, $sortorder);
893	if (!empty($arrayfields['c.multicurrency_tx']['checked']))            print_liste_field_titre($arrayfields['c.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_tx', '', $param, '', $sortfield, $sortorder);
894	if (!empty($arrayfields['c.multicurrency_total_ht']['checked']))      print_liste_field_titre($arrayfields['c.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder);
895	if (!empty($arrayfields['c.multicurrency_total_vat']['checked']))     print_liste_field_titre($arrayfields['c.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder);
896	if (!empty($arrayfields['c.multicurrency_total_ttc']['checked']))     print_liste_field_titre($arrayfields['c.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder);
897	if (!empty($arrayfields['u.login']['checked']))       	  print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder);
898
899	// Extra fields
900	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
901	// Hook fields
902	$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
903	$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
904	print $hookmanager->resPrint;
905	if (!empty($arrayfields['c.datec']['checked']))     print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
906	if (!empty($arrayfields['c.tms']['checked']))       print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
907	if (!empty($arrayfields['c.date_cloture']['checked']))       print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
908	if (!empty($arrayfields['c.note_public']['checked'])) print_liste_field_titre($arrayfields['c.note_public']['label'], $_SERVER["PHP_SELF"], "c.note_public", "", $param, '', $sortfield, $sortorder, 'right ');
909	if (!empty($arrayfields['c.note_private']['checked'])) print_liste_field_titre($arrayfields['c.note_private']['label'], $_SERVER["PHP_SELF"], "c.note_private", "", $param, '', $sortfield, $sortorder, 'right ');
910	if (!empty($arrayfields['shippable']['checked']))   print_liste_field_titre($arrayfields['shippable']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center ');
911	if (!empty($arrayfields['c.facture']['checked']))   print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center ');
912	if (!empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'center ');
913	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
914	print '</tr>'."\n";
915
916	$total = 0;
917	$subtotal = 0;
918	$productstat_cache = array();
919	$productstat_cachevirtual = array();
920	$getNomUrl_cache = array();
921
922	$generic_commande = new Commande($db);
923	$generic_product = new Product($db);
924	$userstatic = new User($db);
925	$i = 0;
926	$totalarray = array();
927	while ($i < min($num, $limit))
928	{
929		$obj = $db->fetch_object($resql);
930
931		$notshippable = 0;
932		$warning = 0;
933		$text_info = '';
934		$text_warning = '';
935		$nbprod = 0;
936
937		$companystatic->id = $obj->socid;
938		$companystatic->code_client = $obj->code_client;
939		$companystatic->name = $obj->name;
940		$companystatic->name_alias = $obj->name_alias;
941		$companystatic->client = $obj->client;
942		$companystatic->email = $obj->email;
943		if (!isset($getNomUrl_cache[$obj->socid])) {
944			$getNomUrl_cache[$obj->socid] = $companystatic->getNomUrl(1, 'customer');
945		}
946
947		$generic_commande->id = $obj->rowid;
948		$generic_commande->ref = $obj->ref;
949		$generic_commande->statut = $obj->fk_statut;
950		$generic_commande->billed = $obj->billed;
951		$generic_commande->date = $db->jdate($obj->date_commande);
952		$generic_commande->date_livraison = $db->jdate($obj->date_delivery); // deprecated
953		$generic_commande->delivery_date = $db->jdate($obj->date_delivery);
954		$generic_commande->ref_client = $obj->ref_client;
955		$generic_commande->total_ht = $obj->total_ht;
956		$generic_commande->total_tva = $obj->total_tva;
957		$generic_commande->total_ttc = $obj->total_ttc;
958		$generic_commande->note_public = $obj->note_public;
959		$generic_commande->note_private = $obj->note_private;
960
961		$projectstatic->id = $obj->project_id;
962		$projectstatic->ref = $obj->project_ref;
963		$projectstatic->title = $obj->project_label;
964
965		print '<tr class="oddeven">';
966
967		// Ref
968		if (!empty($arrayfields['c.ref']['checked']))
969		{
970			print '<td class="nowraponall">';
971			print $generic_commande->getNomUrl(1, ($search_status != 2 ? 0 : $obj->fk_statut), 0, 0, 0, 1, 1);
972
973			// Warning late icon and note
974			if ($generic_commande->hasDelay()) {
975				print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning");
976			}
977
978			$filename = dol_sanitizeFileName($obj->ref);
979			$filedir = $conf->commande->multidir_output[$conf->entity].'/'.dol_sanitizeFileName($obj->ref);
980			$urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid;
981			print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir);
982
983			print '</td>';
984			if (!$i) $totalarray['nbfield']++;
985		}
986
987		// Ref customer
988		if (!empty($arrayfields['c.ref_client']['checked']))
989		{
990			print '<td class="nowrap tdoverflowmax200">'.$obj->ref_client.'</td>';
991			if (!$i) $totalarray['nbfield']++;
992		}
993
994		// Project ref
995		if (!empty($arrayfields['p.ref']['checked']))
996		{
997			print '<td class="nowrap">';
998			if ($obj->project_id > 0)
999			{
1000				print $projectstatic->getNomUrl(1);
1001			}
1002			print '</td>';
1003			if (!$i) $totalarray['nbfield']++;
1004		}
1005
1006		// Project label
1007		if (!empty($arrayfields['p.title']['checked']))
1008		{
1009			print '<td class="nowrap">';
1010			if ($obj->project_id > 0)
1011			{
1012				print $projectstatic->title;
1013			}
1014			print '</td>';
1015			if (!$i) $totalarray['nbfield']++;
1016		}
1017
1018		// Third party
1019		if (!empty($arrayfields['s.nom']['checked']))
1020		{
1021			print '<td class="tdoverflowmax200">';
1022			print $getNomUrl_cache[$obj->socid];
1023
1024			// If module invoices enabled and user with invoice creation permissions
1025			if (!empty($conf->facture->enabled) && !empty($conf->global->ORDER_BILLING_ALL_CUSTOMER))
1026			{
1027				if ($user->rights->facture->creer)
1028				{
1029					if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0))
1030					{
1031						print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$companystatic->id.'&search_billed=0&autoselectall=1">';
1032						print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').'</a>';
1033					}
1034				}
1035			}
1036			print '</td>';
1037			if (!$i) $totalarray['nbfield']++;
1038		}
1039		// Town
1040		if (!empty($arrayfields['s.town']['checked']))
1041		{
1042			print '<td class="nocellnopadd">';
1043			print $obj->town;
1044			print '</td>';
1045			if (!$i) $totalarray['nbfield']++;
1046		}
1047		// Zip
1048		if (!empty($arrayfields['s.zip']['checked']))
1049		{
1050			print '<td class="nocellnopadd">';
1051			print $obj->zip;
1052			print '</td>';
1053			if (!$i) $totalarray['nbfield']++;
1054		}
1055		// State
1056		if (!empty($arrayfields['state.nom']['checked']))
1057		{
1058			print "<td>".$obj->state_name."</td>\n";
1059			if (!$i) $totalarray['nbfield']++;
1060		}
1061		// Country
1062		if (!empty($arrayfields['country.code_iso']['checked']))
1063		{
1064			print '<td class="center">';
1065			$tmparray = getCountry($obj->fk_pays, 'all');
1066			print $tmparray['label'];
1067			print '</td>';
1068			if (!$i) $totalarray['nbfield']++;
1069		}
1070		// Type ent
1071		if (!empty($arrayfields['typent.code']['checked']))
1072		{
1073			print '<td class="center">';
1074			if (empty($typenArray)) $typenArray = $formcompany->typent_array(1);
1075			print $typenArray[$obj->typent_code];
1076			print '</td>';
1077			if (!$i) $totalarray['nbfield']++;
1078		}
1079
1080		// Order date
1081		if (!empty($arrayfields['c.date_commande']['checked']))
1082		{
1083			print '<td class="center">';
1084			print dol_print_date($db->jdate($obj->date_commande), 'day');
1085			print '</td>';
1086			if (!$i) $totalarray['nbfield']++;
1087		}
1088		// Plannned date of delivery
1089		if (!empty($arrayfields['c.date_delivery']['checked']))
1090		{
1091			print '<td class="center">';
1092			print dol_print_date($db->jdate($obj->date_delivery), 'dayhour');
1093			print '</td>';
1094			if (!$i) $totalarray['nbfield']++;
1095		}
1096		// Amount HT
1097		if (!empty($arrayfields['c.total_ht']['checked']))
1098		{
1099			  print '<td class="nowrap right">'.price($obj->total_ht)."</td>\n";
1100			  if (!$i) $totalarray['nbfield']++;
1101			  if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ht';
1102			  $totalarray['val']['c.total_ht'] += $obj->total_ht;
1103		}
1104		// Amount VAT
1105		if (!empty($arrayfields['c.total_vat']['checked']))
1106		{
1107			print '<td class="nowrap right">'.price($obj->total_tva)."</td>\n";
1108			if (!$i) $totalarray['nbfield']++;
1109			if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_tva';
1110			$totalarray['val']['c.total_tva'] += $obj->total_tva;
1111		}
1112		// Amount TTC
1113		if (!empty($arrayfields['c.total_ttc']['checked']))
1114		{
1115			print '<td class="nowrap right">'.price($obj->total_ttc)."</td>\n";
1116			if (!$i) $totalarray['nbfield']++;
1117			if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ttc';
1118			$totalarray['val']['c.total_ttc'] += $obj->total_ttc;
1119		}
1120
1121		// Currency
1122		if (!empty($arrayfields['c.multicurrency_code']['checked']))
1123		{
1124			  print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n";
1125			  if (!$i) $totalarray['nbfield']++;
1126		}
1127
1128		// Currency rate
1129		if (!empty($arrayfields['c.multicurrency_tx']['checked']))
1130		{
1131			  print '<td class="nowrap">';
1132			  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
1133			  print "</td>\n";
1134			  if (!$i) $totalarray['nbfield']++;
1135		}
1136		// Amount HT
1137		if (!empty($arrayfields['c.multicurrency_total_ht']['checked']))
1138		{
1139			  print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n";
1140			  if (!$i) $totalarray['nbfield']++;
1141		}
1142		// Amount VAT
1143		if (!empty($arrayfields['c.multicurrency_total_vat']['checked']))
1144		{
1145			print '<td class="right nowrap">'.price($obj->multicurrency_total_vat)."</td>\n";
1146			if (!$i) $totalarray['nbfield']++;
1147		}
1148		// Amount TTC
1149		if (!empty($arrayfields['c.multicurrency_total_ttc']['checked']))
1150		{
1151			print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n";
1152			if (!$i) $totalarray['nbfield']++;
1153		}
1154
1155		$userstatic->id = $obj->fk_user_author;
1156		$userstatic->login = $obj->login;
1157
1158		// Author
1159		if (!empty($arrayfields['u.login']['checked']))
1160		{
1161			print '<td align="center">';
1162			if ($userstatic->id) print $userstatic->getLoginUrl(1);
1163			else print '&nbsp;';
1164			print "</td>\n";
1165			if (!$i) $totalarray['nbfield']++;
1166		}
1167
1168		// Extra fields
1169		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
1170		// Fields from hook
1171		$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
1172		$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
1173		print $hookmanager->resPrint;
1174
1175		// Date creation
1176		if (!empty($arrayfields['c.datec']['checked']))
1177		{
1178			print '<td align="center" class="nowrap">';
1179			print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
1180			print '</td>';
1181			if (!$i) $totalarray['nbfield']++;
1182		}
1183
1184		// Date modification
1185		if (!empty($arrayfields['c.tms']['checked']))
1186		{
1187			print '<td align="center" class="nowrap">';
1188			print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
1189			print '</td>';
1190			if (!$i) $totalarray['nbfield']++;
1191		}
1192
1193		// Date cloture
1194		if (!empty($arrayfields['c.date_cloture']['checked']))
1195		{
1196			print '<td align="center" class="nowrap">';
1197			print dol_print_date($db->jdate($obj->date_cloture), 'dayhour', 'tzuser');
1198			print '</td>';
1199			if (!$i) $totalarray['nbfield']++;
1200		}
1201
1202		// Note public
1203		if (!empty($arrayfields['c.note_public']['checked']))
1204		{
1205			print '<td align="center" class="nowrap">';
1206			print dol_escape_htmltag($obj->note_public);
1207			print '</td>';
1208			if (!$i) $totalarray['nbfield']++;
1209		}
1210
1211		// Note private
1212		if (!empty($arrayfields['c.note_private']['checked']))
1213		{
1214			print '<td align="center" class="nowrap">';
1215			print dol_escape_htmltag($obj->note_private);
1216			print '</td>';
1217			if (!$i) $totalarray['nbfield']++;
1218		}
1219
1220		// Show shippable Icon (this creates subloops, so may be slow)
1221		if (!empty($arrayfields['shippable']['checked']))
1222		{
1223			print '<td class="center">';
1224			if (!empty($show_shippable_command) && !empty($conf->stock->enabled)) {
1225				if (($obj->fk_statut > $generic_commande::STATUS_DRAFT) && ($obj->fk_statut < $generic_commande::STATUS_CLOSED)) {
1226					$generic_commande->getLinesArray(); // This set ->lines
1227
1228					$numlines = count($generic_commande->lines); // Loop on each line of order
1229					for ($lig = 0; $lig < $numlines; $lig++) {
1230						if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0)  // If line is a product and not a service
1231						{
1232							$nbprod++; // order contains real products
1233							$generic_product->id = $generic_commande->lines[$lig]->fk_product;
1234
1235							// Get local and virtual stock and store it into cache
1236							if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) {
1237								$generic_product->load_stock('nobatch'); // ->load_virtual_stock() is already included into load_stock()
1238								$productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel;
1239								$productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique;
1240							} else {
1241								$generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'];
1242								$generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique;
1243							}
1244
1245							if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST))  // Default code. Default should be this case.
1246							{
1247								$text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->product_ref.'&nbsp;'.dol_trunc($generic_commande->lines[$lig]->product_label, 25);
1248								$text_info .= ' - '.$langs->trans("Stock").': <span class="'.($generic_product->stock_reel > 0 ? 'ok' : 'error').'">'.$generic_product->stock_reel.'</span>';
1249								$text_info .= ' - '.$langs->trans("VirtualStock").': <span class="'.($generic_product->stock_theorique > 0 ? 'ok' : 'error').'">'.$generic_product->stock_theorique.'</span>';
1250								$text_info .= '<br>';
1251
1252								if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) {
1253									$notshippable++;
1254								}
1255							} else {  // BUGGED CODE.
1256								// DOES NOT TAKE INTO ACCOUNT MANUFACTURING. THIS CODE SHOULD BE USELESS. PREVIOUS CODE SEEMS COMPLETE.
1257								// COUNT STOCK WHEN WE SHOULD ALREADY HAVE VALUE
1258								// Detailed virtual stock, looks bugged, uncomplete and need heavy load.
1259								// stock order and stock order_supplier
1260								$stock_order = 0;
1261								$stock_order_supplier = 0;
1262								if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))    // What about other options ?
1263								{
1264									if (!empty($conf->commande->enabled)) {
1265										if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) {
1266											$generic_product->load_stats_commande(0, '1,2');
1267											$productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty'];
1268										} else {
1269											$generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'];
1270										}
1271										$stock_order = $generic_product->stats_commande['qty'];
1272									}
1273									if (!empty($conf->fournisseur->enabled)) {
1274										if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) {
1275											$generic_product->load_stats_commande_fournisseur(0, '3');
1276											$productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty'];
1277										} else {
1278											$generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'];
1279										}
1280										$stock_order_supplier = $generic_product->stats_commande_fournisseur['qty'];
1281									}
1282								}
1283								$text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.'&nbsp;'.dol_trunc($generic_commande->lines[$lig]->product_label, 25);
1284								$text_stock_reel = $generic_product->stock_reel.'/'.$stock_order;
1285								if ($stock_order > $generic_product->stock_reel && !($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) {
1286									$warning++;
1287									$text_warning .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
1288								}
1289								if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) {
1290									$notshippable++;
1291									$text_info .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
1292								} else {
1293									$text_info .= '<span class="ok">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
1294								}
1295								if (!empty($conf->fournisseur->enabled)) {
1296									$text_info .= '&nbsp;'.$langs->trans('SupplierOrder').'&nbsp;:&nbsp;'.$stock_order_supplier.'<br>';
1297								} else {
1298									$text_info .= '<br>';
1299								}
1300							}
1301						}
1302					}
1303					if ($notshippable == 0) {
1304						$text_icon = img_picto('', 'dolly', '', false, 0, 0, '', 'green paddingleft');
1305						$text_info = $langs->trans('Shippable').'<br>'.$text_info;
1306					} else {
1307						$text_icon = img_picto('', 'dolly', '', false, 0, 0, '', 'error paddingleft');
1308						$text_info = $langs->trans('NonShippable').'<br>'.$text_info;
1309					}
1310				}
1311
1312				if ($nbprod) {
1313					print $form->textwithtooltip('', $text_info, 2, 1, $text_icon, '', 2);
1314				}
1315				if ($warning) {     // Always false in default mode
1316					print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'<br>'.$text_warning, 2, 1, img_picto('', 'error'), '', 2);
1317				}
1318			}
1319			print '</td>';
1320		}
1321
1322		// Billed
1323		if (!empty($arrayfields['c.facture']['checked']))
1324		{
1325			print '<td class="center">'.yn($obj->billed).'</td>';
1326			if (!$i) $totalarray['nbfield']++;
1327		}
1328
1329		// Status
1330		if (!empty($arrayfields['c.fk_statut']['checked']))
1331		{
1332			print '<td class="nowrap center">'.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).'</td>';
1333			if (!$i) $totalarray['nbfield']++;
1334		}
1335
1336		// Action column
1337		print '<td class="nowrap center">';
1338		if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
1339		{
1340			$selected = 0;
1341			if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
1342			print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
1343		}
1344		print '</td>';
1345		if (!$i) $totalarray['nbfield']++;
1346
1347		print "</tr>\n";
1348
1349		$total += $obj->total_ht;
1350		$subtotal += $obj->total_ht;
1351		$i++;
1352	}
1353
1354	// Show total line
1355	include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
1356
1357	$db->free($resql);
1358
1359	$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
1360	$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
1361	print $hookmanager->resPrint;
1362
1363	print '</table>'."\n";
1364	print '</div>';
1365
1366	print '</form>'."\n";
1367
1368	$hidegeneratedfilelistifempty = 1;
1369	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
1370
1371	// Show list of available documents
1372	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
1373	$urlsource .= str_replace('&amp;', '&', $param);
1374
1375	$filedir = $diroutputmassaction;
1376	$genallowed = $user->rights->commande->lire;
1377	$delallowed = $user->rights->commande->creer;
1378
1379	print $formfile->showdocuments('massfilesarea_orders', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
1380} else {
1381	dol_print_error($db);
1382}
1383
1384// End of page
1385llxFooter();
1386$db->close();
1387