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