1<?php
2/* Copyright (C) 2001-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2020 Laurent Destailleur  <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@inodbox.com>
5 * Copyright (C) 2013      Cédric Salvador      <csalvador@gpcsolutions.fr>
6 * Copyright (C) 2014-2019 Juanjo Menent        <jmenent@2byte.es>
7 * Copyright (C) 2015	   Claudio Aschieri		<c.aschieri@19.coop>
8 * Copyright (C) 2015      Jean-François Ferry	<jfefe@aternatik.fr>
9 * Copyright (C) 2016-2018 Ferran Marcet        <fmarcet@2byte.es>
10 * Copyright (C) 2019      Nicolas ZABOURI      <info@inovea-conseil.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
26/**
27 *       \file       htdocs/contrat/list.php
28 *       \ingroup    contrat
29 *       \brief      Page to list contracts
30 */
31
32require '../main.inc.php';
33require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
36require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
37require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
38
39// Load translation files required by the page
40$langs->loadLangs(array('contracts', 'products', 'companies', 'compta'));
41
42$action = GETPOST('action', 'aZ09');
43$massaction = GETPOST('massaction', 'alpha');
44$show_files = GETPOST('show_files', 'int');
45$confirm = GETPOST('confirm', 'alpha');
46$toselect = GETPOST('toselect', 'array');
47$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'contractlist'; // To manage different context of search
48
49$search_name = GETPOST('search_name', 'alpha');
50$search_email = GETPOST('search_email', 'alpha');
51$search_town = GETPOST('search_town', 'alpha');
52$search_zip = GETPOST('search_zip', 'alpha');
53$search_state = GETPOST("search_state", 'alpha');
54$search_country = GETPOST("search_country", 'int');
55$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int');
56$search_contract = GETPOST('search_contract', 'alpha');
57$search_ref_customer = GETPOST('search_ref_customer', 'alpha');
58$search_ref_supplier = GETPOST('search_ref_supplier', 'alpha');
59$sall = (GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
60$search_status = GETPOST('search_status', 'alpha');
61$socid = GETPOST('socid', 'int');
62$search_user = GETPOST('search_user', 'int');
63$search_sale = GETPOST('search_sale', 'int');
64$search_product_category = GETPOST('search_product_category', 'int');
65$search_dfmonth = GETPOST('search_dfmonth', 'int');
66$search_dfyear = GETPOST('search_dfyear', 'int');
67$search_op2df = GETPOST('search_op2df', 'alpha');
68$day = GETPOST("day", "int");
69$year = GETPOST("year", "int");
70$month = GETPOST("month", "int");
71
72$optioncss = GETPOST('optioncss', 'alpha');
73
74$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
75$sortfield = GETPOST("sortfield", 'alpha');
76$sortorder = GETPOST("sortorder", 'alpha');
77$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
78if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
79$offset = $limit * $page;
80$pageprev = $page - 1;
81$pagenext = $page + 1;
82if (!$sortfield) $sortfield = 'c.ref';
83if (!$sortorder) $sortorder = 'DESC';
84
85// Security check
86$id = GETPOST('id', 'int');
87if ($user->socid) $socid = $user->socid;
88$result = restrictedArea($user, 'contrat', $id);
89
90$diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id;
91
92$staticcontrat = new Contrat($db);
93$staticcontratligne = new ContratLigne($db);
94
95if ($search_status == '') $search_status = 1;
96
97// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
98$object = new Contrat($db);
99$hookmanager->initHooks(array('contractlist'));
100$extrafields = new ExtraFields($db);
101
102// fetch optionals attributes and labels
103$extrafields->fetch_name_optionals_label($object->table_element);
104
105$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
106// List of fields to search into when doing a "search in all"
107$fieldstosearchall = array(
108	'c.ref'=>'Ref',
109	'c.ref_customer'=>'RefCustomer',
110	'c.ref_supplier'=>'RefSupplier',
111	's.nom'=>"ThirdParty",
112	'c.note_public'=>'NotePublic',
113);
114if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate";
115
116$arrayfields = array(
117	'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>10),
118	'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1, 'position'=>12),
119	'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'position'=>14),
120	's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>30),
121	's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0, 'position'=>30),
122	's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0, 'position'=>31),
123	's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0, 'position'=>32),
124	'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0, 'position'=>33),
125	'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0, 'position'=>34),
126	'sale_representative'=>array('label'=>$langs->trans("SaleRepresentativesOfThirdParty"), 'checked'=>1, 'position'=>80),
127	'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1, 'position'=>45),
128	'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
129	'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500),
130	'lower_planned_end_date'=>array('label'=>$langs->trans("LowerDateEndPlannedShort"), 'checked'=>1, 'position'=>900, 'help'=>$langs->trans("LowerDateEndPlannedShort")),
131	'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000),
132);
133// Extra fields
134include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
135
136$object->fields = dol_sort_array($object->fields, 'position');
137$arrayfields = dol_sort_array($arrayfields, 'position');
138
139
140/*
141 * Action
142 */
143
144if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
145if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
146
147$parameters = array('socid'=>$socid);
148$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
149if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
150
151include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
152
153// Purge search criteria
154if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
155{
156	$day = '';
157	$month = '';
158	$year = '';
159	$search_dfmonth = '';
160	$search_dfyear = '';
161	$search_op2df = '';
162	$search_name = "";
163	$search_email = "";
164	$search_town = '';
165	$search_zip = "";
166	$search_state = "";
167	$search_type = '';
168	$search_country = '';
169	$search_contract = "";
170	$search_ref_customer = "";
171	$search_ref_supplier = "";
172	$search_user = '';
173	$search_sale = '';
174	$search_product_category = '';
175	$sall = "";
176	$search_status = "";
177	$toselect = '';
178	$search_array_options = array();
179}
180
181if (empty($reshook))
182{
183	$objectclass = 'Contrat';
184	$objectlabel = 'Contracts';
185	$permissiontoread = $user->rights->contrat->lire;
186	$permissiontodelete = $user->rights->contrat->supprimer;
187	$uploaddir = $conf->contrat->dir_output;
188	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
189}
190
191
192/*
193 * View
194 */
195
196$now = dol_now();
197$form = new Form($db);
198$formfile = new FormFile($db);
199$formother = new FormOther($db);
200$socstatic = new Societe($db);
201$contracttmp = new Contrat($db);
202
203$sql = 'SELECT';
204$sql .= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public, c.entity,";
205$sql .= ' s.rowid as socid, s.nom as name, s.name_alias, s.email, s.town, s.zip, s.fk_pays as country_id, s.client, s.code_client, s.status as company_status, s.logo as company_logo,';
206$sql .= " typent.code as typent_code,";
207$sql .= " state.code_departement as state_code, state.nom as state_name,";
208$sql .= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") as lower_planned_end_date,";
209$sql .= ' SUM('.$db->ifsql("cd.statut=0", 1, 0).') as nb_initial,';
210$sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NULL OR cd.date_fin_validite >= '".$db->idate($now)."')", 1, 0).') as nb_running,';
211$sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now)."')", 1, 0).') as nb_expired,';
212$sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now - $conf->contrat->services->expires->warning_delay)."')", 1, 0).') as nb_late,';
213$sql .= ' SUM('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed';
214// Add fields from extrafields
215if (!empty($extrafields->attributes[$object->table_element]['label'])) {
216	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
217}
218// Add fields from hooks
219$parameters = array();
220$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
221$sql .= $hookmanager->resPrint;
222$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
223$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
224$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
225$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
226if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
227$sql .= ", ".MAIN_DB_PREFIX."contrat as c";
228if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)";
229$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat";
230if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
231if ($search_user > 0)
232{
233	$sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
234	$sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc";
235}
236$sql .= " WHERE c.fk_soc = s.rowid ";
237$sql .= ' AND c.entity IN ('.getEntity('contract').')';
238if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category;
239if ($socid) $sql .= " AND s.rowid = ".$db->escape($socid);
240if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
241$sql .= dolSqlDateFilter('c.date_contrat', $day, $month, $year);
242if ($search_name) $sql .= natural_search('s.nom', $search_name);
243if ($search_email) $sql .= natural_search('s.email', $search_email);
244if ($search_contract) $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract);
245if (!empty($search_ref_customer)) $sql .= natural_search(array('c.ref_customer'), $search_ref_customer);
246if (!empty($search_ref_supplier)) $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier);
247if ($search_zip) $sql .= natural_search(array('s.zip'), $search_zip);
248if ($search_town) $sql .= natural_search(array('s.town'), $search_town);
249if ($search_sale > 0)
250{
251	$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale;
252}
253if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
254if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user;
255// Add where from extra fields
256include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
257// Add where from hooks
258$parameters = array();
259$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
260$sql .= $hookmanager->resPrint;
261$sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public, c.entity,";
262$sql .= ' s.rowid, s.nom, s.name_alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, s.status, s.logo,';
263$sql .= " typent.code,";
264$sql .= " state.code_departement, state.nom";
265// Add fields from extrafields
266if (!empty($extrafields->attributes[$object->table_element]['label'])) {
267	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : '');
268}
269// Add where from hooks
270$parameters = array();
271$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook
272$sql .= $hookmanager->resPrint;
273if ($search_dfyear > 0 && $search_op2df)
274{
275	if ($search_op2df == '<=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'";
276	elseif ($search_op2df == '>=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'";
277	else $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'";
278}
279$sql .= $db->order($sortfield, $sortorder);
280//print $sql;
281
282$totalnboflines = 0;
283$result = $db->query($sql);
284if ($result)
285{
286	$totalnboflines = $db->num_rows($result);
287}
288
289$nbtotalofrecords = '';
290if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
291{
292	$result = $db->query($sql);
293	$nbtotalofrecords = $db->num_rows($result);
294	if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
295	{
296		$page = 0;
297		$offset = 0;
298	}
299}
300
301$sql .= $db->plimit($limit + 1, $offset);
302
303$resql = $db->query($sql);
304if (!$resql)
305{
306	dol_print_error($db);
307	exit;
308}
309
310$num = $db->num_rows($resql);
311
312// Direct jump if only one record found
313if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page)
314{
315	$obj = $db->fetch_object($resql);
316	$id = $obj->rowid;
317	header("Location: ".DOL_URL_ROOT.'/contrat/card.php?id='.$id);
318	exit;
319}
320
321
322// Output page
323// --------------------------------------------------------------------
324
325llxHeader('', $langs->trans("Contracts"));
326
327$i = 0;
328
329$arrayofselected = is_array($toselect) ? $toselect : array();
330
331if ($socid > 0)
332{
333	$soc = new Societe($db);
334	$soc->fetch($socid);
335	if (empty($search_name)) $search_name = $soc->name;
336}
337
338$param = '';
339if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
340if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
341if ($sall != '')                $param .= '&sall='.urlencode($sall);
342if ($search_contract != '')     $param .= '&search_contract='.urlencode($search_contract);
343if ($search_name != '')         $param .= '&search_name='.urlencode($search_name);
344if ($search_email != '')        $param .= '&search_email='.urlencode($search_email);
345if ($search_ref_customer != '') $param .= '&search_ref_customer='.urlencode($search_ref_customer);
346if ($search_ref_supplier != '') $param .= '&search_ref_supplier='.urlencode($search_ref_supplier);
347if ($search_op2df != '') 		$param .= '&search_op2df='.urlencode($search_op2df);
348if ($search_dfyear != '')       $param .= '&search_dfyear='.urlencode($search_dfyear);
349if ($search_dfmonth != '')      $param .= '&search_dfmonth='.urlencode($search_dfmonth);
350if ($search_sale != '')         $param .= '&search_sale='.urlencode($search_sale);
351if ($search_user != '')			$param .= '&search_user='.urlencode($search_user);
352if ($search_product_category != '')	$param .= '&search_product_category='.urlencode($search_product_category);
353if ($show_files)                $param .= '&show_files='.urlencode($show_files);
354if ($optioncss != '')           $param .= '&optioncss='.urlencode($optioncss);
355// Add $param from extra fields
356include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
357
358// List of mass actions available
359$arrayofmassactions = array(
360	'generate_doc'=>$langs->trans("ReGeneratePDF"),
361	'builddoc'=>$langs->trans("PDFMerge"),
362	'presend'=>$langs->trans("SendByMail"),
363);
364if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
365if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
366$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
367
368$url = DOL_URL_ROOT.'/contrat/card.php?action=create';
369if (!empty($socid)) $url .= '&socid='.$socid;
370$newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer);
371
372print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
373if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
374print '<input type="hidden" name="token" value="'.newToken().'">';
375print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
376print '<input type="hidden" name="action" value="list">';
377print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
378print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
379print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
380
381print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'contract', 0, $newcardbutton, '', $limit, 0, 0, 1);
382
383$topicmail = "SendContractRef";
384$modelmail = "contract";
385$objecttmp = new Contrat($db);
386$trackid = 'con'.$object->id;
387include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
388
389if ($sall)
390{
391	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
392	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
393}
394
395$moreforfilter = '';
396
397// If the user can view prospects other than his'
398if ($user->rights->societe->client->voir || $socid)
399{
400	$langs->load("commercial");
401	$moreforfilter .= '<div class="divsearchfield">';
402	$moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': ';
403	$moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200');
404	$moreforfilter .= '</div>';
405}
406// If the user can view other users
407if ($user->rights->user->user->lire)
408{
409	$moreforfilter .= '<div class="divsearchfield">';
410	$moreforfilter .= $langs->trans('LinkedToSpecificUsers').': ';
411	$moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
412 	$moreforfilter .= '</div>';
413}
414// If the user can view categories of products
415if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire))
416{
417	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
418	$moreforfilter .= '<div class="divsearchfield">';
419	$moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
420	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
421	$moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
422	$moreforfilter .= '</div>';
423}
424
425$parameters = array();
426$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
427if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
428else $moreforfilter = $hookmanager->resPrint;
429
430if (!empty($moreforfilter))
431{
432	print '<div class="liste_titre liste_titre_bydiv centpercent">';
433	print $moreforfilter;
434	print '</div>';
435}
436
437$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
438$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
439if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
440
441print '<div class="div-table-responsive">';
442print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
443
444print '<tr class="liste_titre_filter">';
445if (!empty($arrayfields['c.ref']['checked']))
446{
447	print '<td class="liste_titre">';
448	print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">';
449	print '</td>';
450}
451if (!empty($arrayfields['c.ref_customer']['checked']))
452{
453	print '<td class="liste_titre">';
454	print '<input type="text" class="flat" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">';
455	print '</td>';
456}
457if (!empty($arrayfields['c.ref_supplier']['checked']))
458{
459	print '<td class="liste_titre">';
460	print '<input type="text" class="flat" size="6" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'">';
461	print '</td>';
462}
463if (!empty($arrayfields['s.nom']['checked']))
464{
465	print '<td class="liste_titre">';
466	print '<input type="text" class="flat" size="8" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
467	print '</td>';
468}
469if (!empty($arrayfields['s.email']['checked']))
470{
471	print '<td class="liste_titre">';
472	print '<input type="text" class="flat" size="6" name="search_email" value="'.dol_escape_htmltag($search_email).'">';
473	print '</td>';
474}
475// Town
476if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>';
477// Zip
478if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>';
479// State
480if (!empty($arrayfields['state.nom']['checked']))
481{
482	print '<td class="liste_titre">';
483	print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
484	print '</td>';
485}
486// Country
487if (!empty($arrayfields['country.code_iso']['checked']))
488{
489	print '<td class="liste_titre center">';
490	print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
491	print '</td>';
492}
493// Company type
494if (!empty($arrayfields['typent.code']['checked']))
495{
496	print '<td class="liste_titre maxwidthonsmartphone center">';
497	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));
498	print '</td>';
499}
500if (!empty($arrayfields['sale_representative']['checked']))
501{
502	print '<td class="liste_titre"></td>';
503}
504if (!empty($arrayfields['c.date_contrat']['checked']))
505{
506	// Date contract
507	print '<td class="liste_titre center nowraponall">';
508	//print $langs->trans('Month').': ';
509	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.$day.'">';
510	print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month" value="'.$month.'">';
511	//print '&nbsp;'.$langs->trans('Year').': ';
512	$syear = $year;
513	print $formother->selectyear($syear, 'year', 1, 20, 5);
514	print '</td>';
515}
516// Extra fields
517include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
518
519// Fields from hook
520$parameters = array('arrayfields'=>$arrayfields);
521$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
522print $hookmanager->resPrint;
523// Date creation
524if (!empty($arrayfields['c.datec']['checked']))
525{
526	print '<td class="liste_titre">';
527	print '</td>';
528}
529// Date modification
530if (!empty($arrayfields['c.tms']['checked']))
531{
532	print '<td class="liste_titre">';
533	print '</td>';
534}
535// First end date
536if (!empty($arrayfields['lower_planned_end_date']['checked']))
537{
538		print '<td class="liste_titre nowraponall center">';
539		$arrayofoperators = array('0'=>'', '='=>'=', '<='=>'<=', '>='=>'>=');
540		print $form->selectarray('search_op2df', $arrayofoperators, $search_op2df, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth50imp');
541		print '</br>';
542		print $formother->select_month($search_dfmonth, 'search_dfmonth', 1, 0);
543		print ' ';
544		$formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5, 0, 0, '');
545		print '</td>';
546}
547// Status
548if (!empty($arrayfields['status']['checked']))
549{
550	print '<td class="liste_titre right" colspan="4"></td>';
551}
552print '<td class="liste_titre center">';
553$searchpicto = $form->showFilterButtons();
554print $searchpicto;
555print '</td>';
556print "</tr>\n";
557
558print '<tr class="liste_titre">';
559if (!empty($arrayfields['c.ref']['checked']))               print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder);
560if (!empty($arrayfields['c.ref_customer']['checked']))      print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder);
561if (!empty($arrayfields['c.ref_supplier']['checked']))      print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder);
562if (!empty($arrayfields['s.nom']['checked']))               print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
563if (!empty($arrayfields['s.email']['checked']))             print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder);
564if (!empty($arrayfields['s.town']['checked']))              print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
565if (!empty($arrayfields['s.zip']['checked']))               print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
566if (!empty($arrayfields['state.nom']['checked']))           print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
567if (!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 ');
568if (!empty($arrayfields['typent.code']['checked']))         print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
569if (!empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder);
570if (!empty($arrayfields['c.date_contrat']['checked']))      print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center ');
571// Extra fields
572include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
573// Hook fields
574$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
575$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
576print $hookmanager->resPrint;
577if (!empty($arrayfields['c.datec']['checked'])) {
578	print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
579}
580if (!empty($arrayfields['c.tms']['checked'])) {
581	print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
582}
583if (!empty($arrayfields['lower_planned_end_date']['checked'])) {
584	print_liste_field_titre($arrayfields['lower_planned_end_date']['label'], $_SERVER["PHP_SELF"], "lower_planned_end_date", "", $param, '', $sortfield, $sortorder, 'center ');
585}
586if (!empty($arrayfields['status']['checked'])) {
587	print_liste_field_titre($staticcontratligne->LibStatut(0, 3, -1, 'class="nochangebackground"'), '', '', '', '', 'width="16"');
588	print_liste_field_titre($staticcontratligne->LibStatut(4, 3, 0, 'class="nochangebackground"'), '', '', '', '', 'width="16"');
589	print_liste_field_titre($staticcontratligne->LibStatut(4, 3, 1, 'class="nochangebackground"'), '', '', '', '', 'width="16"');
590	print_liste_field_titre($staticcontratligne->LibStatut(5, 3, -1, 'class="nochangebackground"'), '', '', '', '', 'width="16"');
591}
592print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
593print "</tr>\n";
594
595$totalarray = array();
596$typenArray = array();
597$cacheCountryIDCode = array();
598
599while ($i < min($num, $limit))
600{
601	$obj = $db->fetch_object($resql);
602
603	$contracttmp->ref = $obj->ref;
604	$contracttmp->id = $obj->rowid;
605	$contracttmp->ref_customer = $obj->ref_customer;
606	$contracttmp->ref_supplier = $obj->ref_supplier;
607
608	if ($obj->socid > 0) {
609		$result = $socstatic->fetch($obj->socid);
610	}
611	/*$socstatic->id = $obj->socid;
612	$socstatic->name = $obj->name;
613	$socstatic->name_alias = $obj->name_alias;
614	$socstatic->email = $obj->email;
615	$socstatic->status = $obj->company_status;
616	$socstatic->logo = $obj->logo;
617	$socstatic->country_id = $obj->country_id;
618	$socstatic->country_code = '';
619	$socstatic->country = '';*/
620	if ($obj->country_id > 0) {
621		if (!isset($cacheCountryIDCode[$obj->country_id]['code'])) {
622			$tmparray = getCountry($obj->country_id, 'all');
623			$cacheCountryIDCode[$obj->country_id] = array('code'=> empty($tmparray['code']) ? '' : $tmparray['code'], 'label' => empty($tmparray['label']) ? '' : $tmparray['label']);
624		}
625		$socstatic->country_code = $cacheCountryIDCode[$obj->country_id]['code'];
626		$socstatic->country = $cacheCountryIDCode[$obj->country_id]['label'];
627	}
628
629
630	print '<tr class="oddeven">';
631
632	// Ref
633	if (!empty($arrayfields['c.ref']['checked']))
634	{
635		print '<td class="nowraponall">';
636		print $contracttmp->getNomUrl(1);
637		if ($obj->nb_late) print img_warning($langs->trans("Late"));
638		if (!empty($obj->note_private) || !empty($obj->note_public)) {
639			print ' <span class="note">';
640			print '<a href="'.DOL_URL_ROOT.'/contrat/note.php?id='.$obj->rowid.'&save_lastsearch_values=1">'.img_picto($langs->trans("ViewPrivateNote"), 'note').'</a>';
641			print '</span>';
642		}
643
644		$filename = dol_sanitizeFileName($obj->ref);
645		$filedir = $conf->contrat->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref);
646		$urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid;
647		print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir);
648		print '</td>';
649
650		print '</td>';
651	}
652
653	if (!empty($arrayfields['c.ref_customer']['checked']))
654	{
655		print '<td>'.$contracttmp->getFormatedCustomerRef($obj->ref_customer).'</td>';
656	}
657	if (!empty($arrayfields['c.ref_supplier']['checked']))
658	{
659		print '<td>'.$obj->ref_supplier.'</td>';
660	}
661	if (!empty($arrayfields['s.nom']['checked']))
662	{
663		print '<td class="tdoverflowmax150">';
664		if ($obj->socid > 0) {
665			// TODO Use a cache for this string
666			print $socstatic->getNomUrl(1, '');
667		}
668		print '</td>';
669	}
670	if (!empty($arrayfields['s.email']['checked']))
671	{
672		print '<td>'.$obj->email.'</td>';
673	}
674	// Town
675	if (!empty($arrayfields['s.town']['checked']))
676	{
677		print '<td class="nocellnopadd">';
678		print $obj->town;
679		print '</td>';
680		if (!$i) $totalarray['nbfield']++;
681	}
682	// Zip
683	if (!empty($arrayfields['s.zip']['checked']))
684	{
685		print '<td class="nocellnopadd">';
686		print $obj->zip;
687		print '</td>';
688		if (!$i) $totalarray['nbfield']++;
689	}
690	// State
691	if (!empty($arrayfields['state.nom']['checked']))
692	{
693		print "<td>".$obj->state_name."</td>\n";
694		if (!$i) $totalarray['nbfield']++;
695	}
696	// Country
697	if (!empty($arrayfields['country.code_iso']['checked']))
698	{
699		print '<td class="center">';
700		print $socstatic->country;
701		print '</td>';
702		if (!$i) $totalarray['nbfield']++;
703	}
704	// Type ent
705	if (!empty($arrayfields['typent.code']['checked']))
706	{
707		print '<td class="center">';
708		if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1);
709		print $typenArray[$obj->typent_code];
710		print '</td>';
711		if (!$i) $totalarray['nbfield']++;
712	}
713	if (!empty($arrayfields['sale_representative']['checked']))
714	{
715		// Sales representatives
716		print '<td>';
717		if ($obj->socid > 0)
718		{
719			$listsalesrepresentatives = $socstatic->getSalesRepresentatives($user);
720			if ($listsalesrepresentatives < 0) dol_print_error($db);
721			$nbofsalesrepresentative = count($listsalesrepresentatives);
722			if ($nbofsalesrepresentative > 3) {
723				// We print only number
724				print $nbofsalesrepresentative;
725			} elseif ($nbofsalesrepresentative > 0)
726			{
727				$userstatic = new User($db);
728				$j = 0;
729				foreach ($listsalesrepresentatives as $val)
730				{
731					$userstatic->id = $val['id'];
732					$userstatic->lastname = $val['lastname'];
733					$userstatic->firstname = $val['firstname'];
734					$userstatic->email = $val['email'];
735					$userstatic->statut = $val['statut'];
736					$userstatic->entity = $val['entity'];
737					$userstatic->photo = $val['photo'];
738
739					//print '<div class="float">':
740					print $userstatic->getNomUrl(-2);
741					$j++;
742					if ($j < $nbofsalesrepresentative) print ' ';
743					//print '</div>';
744				}
745			}
746			//else print $langs->trans("NoSalesRepresentativeAffected");
747		} else {
748			print '&nbsp';
749		}
750		print '</td>';
751	}
752	// Date
753	if (!empty($arrayfields['c.date_contrat']['checked']))
754	{
755		print '<td class="center">'.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').'</td>';
756	}
757	// Extra fields
758	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
759	// Fields from hook
760	$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
761	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
762	print $hookmanager->resPrint;
763	// Date creation
764	if (!empty($arrayfields['c.datec']['checked']))
765	{
766		print '<td class="center nowrap">';
767		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
768		print '</td>';
769		if (!$i) $totalarray['nbfield']++;
770	}
771	// Date modification
772	if (!empty($arrayfields['c.tms']['checked']))
773	{
774		print '<td class="center nowrap">';
775		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
776		print '</td>';
777		if (!$i) $totalarray['nbfield']++;
778	}
779	// Date lower end date
780	if (!empty($arrayfields['lower_planned_end_date']['checked']))
781	{
782		print '<td class="center nowrapforall">';
783		print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser');
784		print '</td>';
785		if (!$i) $totalarray['nbfield']++;
786	}
787	// Status
788	if (!empty($arrayfields['status']['checked']))
789	{
790		print '<td class="center">'.($obj->nb_initial > 0 ? $obj->nb_initial : '').'</td>';
791		print '<td class="center">'.($obj->nb_running > 0 ? $obj->nb_running : '').'</td>';
792		print '<td class="center">'.($obj->nb_expired > 0 ? $obj->nb_expired : '').'</td>';
793		print '<td class="center">'.($obj->nb_closed > 0 ? $obj->nb_closed : '').'</td>';
794	}
795	// Action column
796	print '<td class="nowrap center">';
797	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
798	{
799		$selected = 0;
800		if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
801		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
802	}
803	print '</td>';
804	if (!$i) $totalarray['nbfield']++;
805
806	print "</tr>\n";
807	$i++;
808}
809$db->free($resql);
810
811$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
812$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
813print $hookmanager->resPrint;
814
815print '</table>';
816print '</div>';
817
818print '</form>';
819
820$hidegeneratedfilelistifempty = 1;
821if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
822
823// Show list of available documents
824$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
825$urlsource .= str_replace('&amp;', '&', $param);
826
827$filedir = $diroutputmassaction;
828$genallowed = $user->rights->contrat->lire;
829$delallowed = $user->rights->contrat->lire;
830
831print $formfile->showdocuments('massfilesarea_contract', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
832
833
834llxFooter();
835$db->close();
836