1<?php
2/* Copyright (C) 2019 Laurent Destailleur  <eldy@users.sourceforge.net>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18/**
19 *   	\file       mo_movements.php
20 *		\ingroup    mrp
21 *		\brief      Page to show tock movements of a MO
22 */
23
24// Load Dolibarr environment
25require '../main.inc.php';
26
27require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
28require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
29require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
30require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
31require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
32require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
33require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
34require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
35dol_include_once('/mrp/class/mo.class.php');
36dol_include_once('/mrp/lib/mrp_mo.lib.php');
37
38// Load translation files required by the page
39$langs->loadLangs(array("mrp", "stocks", "other"));
40
41// Get parameters
42$id = GETPOST('id', 'int');
43$ref        = GETPOST('ref', 'alpha');
44$action = GETPOST('action', 'aZ09');
45$confirm    = GETPOST('confirm', 'alpha');
46$cancel     = GETPOST('cancel', 'aZ09');
47$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'mostockmovement'; // To manage different context of search
48$backtopage = GETPOST('backtopage', 'alpha');
49//$lineid   = GETPOST('lineid', 'int');
50
51$msid = GETPOST('msid', 'int');
52$year = GETPOST("year", 'int');
53$month = GETPOST("month", 'int');
54$search_ref = GETPOST('search_ref', 'alpha');
55$search_movement = GETPOST("search_movement", 'alpha');
56$search_product_ref = trim(GETPOST("search_product_ref", 'alpha'));
57$search_product = trim(GETPOST("search_product", 'alpha'));
58$search_warehouse = trim(GETPOST("search_warehouse", 'alpha'));
59$search_inventorycode = trim(GETPOST("search_inventorycode", 'alpha'));
60$search_user = trim(GETPOST("search_user", 'alpha'));
61$search_batch = trim(GETPOST("search_batch", 'alpha'));
62$search_qty = trim(GETPOST("search_qty", 'alpha'));
63$search_type_mouvement = GETPOST('search_type_mouvement', 'int');
64
65$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
66$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
67$sortfield = GETPOST("sortfield", 'alpha');
68$sortorder = GETPOST("sortorder", 'alpha');
69if (empty($page) || $page == -1) {
70	$page = 0;
71}     // If $page is not defined, or '' or -1
72$offset = $limit * $page;
73if (!$sortfield) {
74	$sortfield = "m.datem";
75}
76if (!$sortorder) {
77	$sortorder = "DESC";
78}
79
80// Initialize technical objects
81$object = new Mo($db);
82$extrafields = new ExtraFields($db);
83$diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id;
84$hookmanager->initHooks(array('mocard', 'globalcard')); // Note that conf->hooks_modules contains array
85
86// Fetch optionals attributes and labels
87$extrafields->fetch_name_optionals_label($object->table_element);
88
89$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
90
91// Initialize array of search criterias
92$search_all = trim(GETPOST("search_all", 'alpha'));
93$search = array();
94foreach ($object->fields as $key => $val) {
95	if (GETPOST('search_'.$key, 'alpha')) {
96		$search[$key] = GETPOST('search_'.$key, 'alpha');
97	}
98}
99
100if (empty($action) && empty($id) && empty($ref)) {
101	$action = 'view';
102}
103
104// Load object
105include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
106
107// Security check - Protection if external user
108//if ($user->socid > 0) accessforbidden();
109//if ($user->socid > 0) $socid = $user->socid;
110$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
111$result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'rowid', $isdraft);
112
113$objectlist = new MouvementStock($db);
114
115// Definition of fields for list
116$arrayfields = array(
117	'm.rowid'=>array('label'=>"Ref", 'checked'=>1, 'position'=>1),
118	'm.datem'=>array('label'=>"Date", 'checked'=>1, 'position'=>2),
119	'p.ref'=>array('label'=>"ProductRef", 'checked'=>1, 'css'=>'maxwidth100', 'position'=>3),
120	'p.label'=>array('label'=>"ProductLabel", 'checked'=>0, 'position'=>5),
121	'm.batch'=>array('label'=>"BatchNumberShort", 'checked'=>1, 'position'=>8, 'enabled'=>(!empty($conf->productbatch->enabled))),
122	'pl.eatby'=>array('label'=>"EatByDate", 'checked'=>0, 'position'=>9, 'enabled'=>(!empty($conf->productbatch->enabled))),
123	'pl.sellby'=>array('label'=>"SellByDate", 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))),
124	'e.ref'=>array('label'=>"Warehouse", 'checked'=>1, 'position'=>100, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it
125	'm.fk_user_author'=>array('label'=>"Author", 'checked'=>0, 'position'=>120),
126	'm.inventorycode'=>array('label'=>"InventoryCodeShort", 'checked'=>1, 'position'=>130),
127	'm.label'=>array('label'=>"MovementLabel", 'checked'=>1, 'position'=>140),
128	'm.type_mouvement'=>array('label'=>"TypeMovement", 'checked'=>0, 'position'=>150),
129	'origin'=>array('label'=>"Origin", 'checked'=>1, 'position'=>155),
130	'm.fk_projet'=>array('label'=>'Project', 'checked'=>0, 'position'=>180),
131	'm.value'=>array('label'=>"Qty", 'checked'=>1, 'position'=>200),
132	'm.price'=>array('label'=>"UnitPurchaseValue", 'checked'=>0, 'position'=>210)
133	//'m.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500),
134	//'m.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500)
135);
136if (!empty($conf->global->PRODUCT_DISABLE_SELLBY)) {
137	unset($arrayfields['pl.sellby']);
138}
139if (!empty($conf->global->PRODUCT_DISABLE_EATBY)) {
140	unset($arrayfields['pl.eatby']);
141}
142$objectlist->fields = dol_sort_array($objectlist->fields, 'position');
143$arrayfields = dol_sort_array($arrayfields, 'position');
144
145$permissionnote = $user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php
146$permissiondellink = $user->rights->mrp->write; // Used by the include of actions_dellink.inc.php
147$permissiontoadd = $user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
148$permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
149$upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
150
151$permissiontoproduce = $permissiontoadd;
152$permissiontoupdatecost = $user->rights->bom->write; // User who can define cost must have knowledge of pricing
153
154if ($permissiontoupdatecost) {
155	$arrayfields['m.price']['enabled'] = 1;
156}
157
158/*
159 * Actions
160 */
161
162if (GETPOST('cancel', 'alpha')) {
163	$action = 'list'; $massaction = '';
164}
165if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
166	$massaction = '';
167}
168
169$parameters = array();
170$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
171if ($reshook < 0) {
172	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
173}
174
175include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
176
177// Do we click on purge search criteria ?
178if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
179	$year = '';
180	$month = '';
181	$search_ref = '';
182	$search_movement = "";
183	$search_type_mouvement = "";
184	$search_inventorycode = "";
185	$search_product_ref = "";
186	$search_product = "";
187	$search_warehouse = "";
188	$search_user = "";
189	$search_batch = "";
190	$search_qty = '';
191	$sall = "";
192	$toselect = '';
193	$search_array_options = array();
194}
195
196if (empty($reshook)) {
197	$error = 0;
198
199	$backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
200
201	if (empty($backtopage) || ($cancel && empty($id))) {
202		//var_dump($backurlforlist);exit;
203		if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
204			$backtopage = $backurlforlist;
205		} else {
206			$backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__');
207		}
208	}
209	$triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record
210
211	// Actions cancel, add, update, delete or clone
212	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
213
214	// Actions when linking object each other
215	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
216
217	// Actions when printing a doc from card
218	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
219
220	// Actions to send emails
221	$triggersendname = 'MO_SENTBYMAIL';
222	$autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO';
223	$trackid = 'mo'.$object->id;
224	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
225
226	// Action to move up and down lines of object
227	//include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';	// Must be include, not include_once
228
229	if ($action == 'set_thirdparty' && $permissiontoadd) {
230		$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
231	}
232	if ($action == 'classin' && $permissiontoadd) {
233		$object->setProject(GETPOST('projectid', 'int'));
234	}
235
236	if ($action == 'confirm_reopen') {
237		$result = $object->setStatut($object::STATUS_INPROGRESS, 0, '', 'MRP_REOPEN');
238	}
239}
240
241
242
243/*
244 * View
245 */
246
247$form = new Form($db);
248$formproject = new FormProjets($db);
249$formproduct = new FormProduct($db);
250$productstatic = new Product($db);
251$productlot = new ProductLot($db);
252$warehousestatic = new Entrepot($db);
253$userstatic = new User($db);
254
255$help_url = 'EN:Module_Manufacturing_Orders|FR:Module_Ordres_de_Fabrication';
256
257llxHeader('', $langs->trans('Mo'), $help_url);
258
259// Part to show record
260if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
261	$res = $object->fetch_thirdparty();
262	$res = $object->fetch_optionals();
263
264	$head = moPrepareHead($object);
265
266	print dol_get_fiche_head($head, 'stockmovement', $langs->trans("ManufacturingOrder"), -1, $object->picto);
267
268	$formconfirm = '';
269
270	// Confirmation to delete
271	if ($action == 'delete') {
272		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1);
273	}
274	// Confirmation to delete line
275	if ($action == 'deleteline') {
276		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
277	}
278	// Clone confirmation
279	if ($action == 'clone') {
280		// Create an array for form
281		$formquestion = array();
282		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
283	}
284
285	// Confirmation of action xxxx
286	if ($action == 'xxx') {
287		$formquestion = array();
288		/*
289		$forcecombo=0;
290		if ($conf->browser->name == 'ie') $forcecombo = 1;	// There is a bug in IE10 that make combo inside popup crazy
291		$formquestion = array(
292			// 'text' => $langs->trans("ConfirmClone"),
293			// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
294			// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
295			// array('type' => 'other',    'name' => 'idwarehouse',   'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
296		);
297		*/
298		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
299	}
300
301	// Call Hook formConfirm
302	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
303	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
304	if (empty($reshook)) {
305		$formconfirm .= $hookmanager->resPrint;
306	} elseif ($reshook > 0) {
307		$formconfirm = $hookmanager->resPrint;
308	}
309
310	// Print form confirm
311	print $formconfirm;
312
313
314	// Object card
315	// ------------------------------------------------------------
316	$linkback = '<a href="'.dol_buildpath('/mrp/mo_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
317
318	$morehtmlref = '<div class="refidno">';
319	/*
320	// Ref bis
321	$morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', 0, 1);
322	$morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', null, null, '', 1);*/
323	// Thirdparty
324	$morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
325	// Project
326	if (!empty($conf->projet->enabled)) {
327		$langs->load("projects");
328		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
329		if ($permissiontoadd) {
330			if ($action != 'classify') {
331				$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
332			}
333			if ($action == 'classify') {
334				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
335				$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
336				$morehtmlref .= '<input type="hidden" name="action" value="classin">';
337				$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
338				$morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1);
339				$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
340				$morehtmlref .= '</form>';
341			} else {
342				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1);
343			}
344		} else {
345			if (!empty($object->fk_project)) {
346				$proj = new Project($db);
347				$proj->fetch($object->fk_project);
348				$morehtmlref .= $proj->getNomUrl();
349			} else {
350				$morehtmlref .= '';
351			}
352		}
353	}
354	$morehtmlref .= '</div>';
355
356
357	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
358
359
360	print '<div class="fichecenter">';
361	print '<div class="fichehalfleft">';
362	print '<div class="underbanner clearboth"></div>';
363	print '<table class="border centpercent tableforfield">'."\n";
364
365	// Common attributes
366	$keyforbreak = 'fk_warehouse';
367	unset($object->fields['fk_project']);
368	unset($object->fields['fk_soc']);
369	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
370
371	// Other attributes
372	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
373
374	print '</table>';
375	print '</div>';
376	print '</div>';
377
378	print '<div class="clearboth"></div>';
379
380	print dol_get_fiche_end();
381
382	/*
383		print '<div class="tabsAction">';
384
385		$parameters = array();
386		// Note that $action and $object may be modified by hook
387		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
388		if (empty($reshook)) {
389			// Cancel - Reopen
390			if ($permissiontoadd)
391			{
392				if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
393				{
394					print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n";
395				}
396
397				if ($object->status == $object::STATUS_CANCELED)
398				{
399					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("Re-Open").'</a>'."\n";
400				}
401
402				if ($object->status == $object::STATUS_PRODUCED) {
403					if ($permissiontoproduce) {
404						print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen">'.$langs->trans('ReOpen').'</a>';
405					} else {
406						print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ReOpen').'</a>';
407					}
408				}
409			}
410		}
411
412		print '</div>';
413	*/
414
415
416	$sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,";
417	$sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,";
418	$sql .= " m.rowid as mid, m.value as qty, m.datem, m.fk_user_author, m.label, m.inventorycode, m.fk_origin, m.origintype,";
419	$sql .= " m.batch, m.price,";
420	$sql .= " m.type_mouvement,";
421	$sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,";
422	$sql .= " u.login, u.photo, u.lastname, u.firstname";
423	// Add fields from extrafields
424	if (!empty($extrafields->attributes[$objectlist->table_element]['label'])) {
425		foreach ($extrafields->attributes[$objectlist->table_element]['label'] as $key => $val) {
426			$sql .= ($extrafields->attributes[$objectlist->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
427		}
428	}
429	// Add fields from hooks
430	$parameters = array();
431	$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $objectlist may have been modified by hook
432	$sql .= $hookmanager->resPrint;
433	$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
434	$sql .= " ".MAIN_DB_PREFIX."product as p,";
435	$sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m";
436	if (is_array($extrafields->attributes[$objectlist->table_element]['label']) && count($extrafields->attributes[$objectlist->table_element]['label'])) {
437		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$objectlist->table_element."_extrafields as ef on (m.rowid = ef.fk_object)";
438	}
439	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid";
440	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product";
441	$sql .= " WHERE m.fk_product = p.rowid";
442	$sql .= " AND m.origintype = 'mo' AND m.fk_origin = ".(int) $object->id;
443	if ($msid > 0) {
444		$sql .= " AND m.rowid = ".((int) $msid);
445	}
446	$sql .= " AND m.fk_entrepot = e.rowid";
447	$sql .= " AND e.entity IN (".getEntity('stock').")";
448	if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
449		$sql .= " AND p.fk_product_type = 0";
450	}
451	$sql .= dolSqlDateFilter('m.datem', 0, $month, $year);
452	if (!empty($search_ref)) {
453		$sql .= natural_search('m.rowid', $search_ref, 1);
454	}
455	if (!empty($search_movement)) {
456		$sql .= natural_search('m.label', $search_movement);
457	}
458	if (!empty($search_inventorycode)) {
459		$sql .= natural_search('m.inventorycode', $search_inventorycode);
460	}
461	if (!empty($search_product_ref)) {
462		$sql .= natural_search('p.ref', $search_product_ref);
463	}
464	if (!empty($search_product)) {
465		$sql .= natural_search('p.label', $search_product);
466	}
467	if ($search_warehouse != '' && $search_warehouse != '-1') {
468		$sql .= natural_search('e.rowid', $search_warehouse, 2);
469	}
470	if (!empty($search_user)) {
471		$sql .= natural_search('u.login', $search_user);
472	}
473	if (!empty($search_batch)) {
474		$sql .= natural_search('m.batch', $search_batch);
475	}
476	if ($search_qty != '') {
477		$sql .= natural_search('m.value', $search_qty, 1);
478	}
479	if ($search_type_mouvement != '' && $search_type_mouvement != '-1') {
480		$sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2);
481	}
482	// Add where from extra fields
483	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
484	// Add where from hooks
485	$parameters = array();
486	$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $objectlist may have been modified by hook
487	$sql .= $hookmanager->resPrint;
488	$sql .= $db->order($sortfield, $sortorder);
489
490	$nbtotalofrecords = '';
491	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
492		$result = $db->query($sql);
493		$nbtotalofrecords = $db->num_rows($result);
494		if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
495			$page = 0;
496			$offset = 0;
497		}
498	}
499	$sql .= $db->plimit($limit + 1, $offset);
500
501	$param = '';
502	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
503		$param .= '&contextpage='.urlencode($contextpage);
504	}
505	if ($limit > 0 && $limit != $conf->liste_limit) {
506		$param .= '&limit='.urlencode($limit);
507	}
508	if ($id > 0) {
509		$param .= '&id='.urlencode($id);
510	}
511	if ($search_movement) {
512		$param .= '&search_movement='.urlencode($search_movement);
513	}
514	if ($search_inventorycode) {
515		$param .= '&search_inventorycode='.urlencode($search_inventorycode);
516	}
517	if ($search_type_mouvement) {
518		$param .= '&search_type_mouvement='.urlencode($search_type_mouvement);
519	}
520	if ($search_product_ref) {
521		$param .= '&search_product_ref='.urlencode($search_product_ref);
522	}
523	if ($search_product) {
524		$param .= '&search_product='.urlencode($search_product);
525	}
526	if ($search_batch) {
527		$param .= '&search_batch='.urlencode($search_batch);
528	}
529	if ($search_warehouse > 0) {
530		$param .= '&search_warehouse='.urlencode($search_warehouse);
531	}
532	if ($search_user) {
533		$param .= '&search_user='.urlencode($search_user);
534	}
535
536	// Add $param from extra fields
537	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
538
539	// List of mass actions available
540	$arrayofmassactions = array(
541		//    'presend'=>$langs->trans("SendByMail"),
542		//    'builddoc'=>$langs->trans("PDFMerge"),
543	);
544	//if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
545	if (in_array($massaction, array('presend', 'predelete'))) {
546		$arrayofmassactions = array();
547	}
548	$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
549
550	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
551	if ($optioncss != '') {
552		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
553	}
554	print '<input type="hidden" name="token" value="'.newToken().'">';
555	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
556	print '<input type="hidden" name="action" value="list">';
557	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
558	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
559	print '<input type="hidden" name="page" value="'.$page.'">';
560	print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
561	if ($id > 0) {
562		print '<input type="hidden" name="id" value="'.$id.'">';
563	}
564
565	if ($id > 0) {
566		print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit);
567	} else {
568		print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit);
569	}
570
571	$moreforfilter = '';
572
573	$parameters = array();
574	$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
575	if (empty($reshook)) {
576		$moreforfilter .= $hookmanager->resPrint;
577	} else {
578		$moreforfilter = $hookmanager->resPrint;
579	}
580
581	if (!empty($moreforfilter)) {
582		print '<div class="liste_titre liste_titre_bydiv centpercent">';
583		print $moreforfilter;
584		print '</div>';
585	}
586
587	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
588	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
589
590	print '<div class="div-table-responsive">';
591	print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
592
593	// Fields title search
594	print '<tr class="liste_titre_filter">';
595	if (!empty($arrayfields['m.rowid']['checked'])) {
596		// Ref
597		print '<td class="liste_titre left">';
598		print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
599		print '</td>';
600	}
601	if (!empty($arrayfields['m.datem']['checked'])) {
602		print '<td class="liste_titre nowraponall">';
603		print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">';
604		if (empty($conf->productbatch->enabled)) {
605			print '&nbsp;';
606		}
607		//else print '<br>';
608		$syear = $year ? $year : -1;
609		print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">';
610		//print $formother->selectyear($syear,'year',1, 20, 5);
611		print '</td>';
612	}
613	if (!empty($arrayfields['p.ref']['checked'])) {
614		// Product Ref
615		print '<td class="liste_titre left">';
616		print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">';
617		print '</td>';
618	}
619	if (!empty($arrayfields['p.label']['checked'])) {
620		// Product label
621		print '<td class="liste_titre left">';
622		print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">';
623		print '</td>';
624	}
625	// Batch
626	if (!empty($arrayfields['m.batch']['checked'])) {
627		print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>';
628	}
629	if (!empty($arrayfields['pl.eatby']['checked'])) {
630		print '<td class="liste_titre left">';
631		print '</td>';
632	}
633	if (!empty($arrayfields['pl.sellby']['checked'])) {
634		print '<td class="liste_titre left">';
635		print '</td>';
636	}
637	// Warehouse
638	if (!empty($arrayfields['e.ref']['checked'])) {
639		print '<td class="liste_titre maxwidthonsmartphone left">';
640		//print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">';
641		print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
642		print '</td>';
643	}
644	if (!empty($arrayfields['m.fk_user_author']['checked'])) {
645		// Author
646		print '<td class="liste_titre left">';
647		print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">';
648		print '</td>';
649	}
650	if (!empty($arrayfields['m.inventorycode']['checked'])) {
651		// Inventory code
652		print '<td class="liste_titre left">';
653		print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">';
654		print '</td>';
655	}
656	if (!empty($arrayfields['m.label']['checked'])) {
657		// Label of movement
658		print '<td class="liste_titre left">';
659		print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">';
660		print '</td>';
661	}
662	if (!empty($arrayfields['m.type_mouvement']['checked'])) {
663		// Type of movement
664		print '<td class="liste_titre center">';
665		//print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">';
666		print '<select id="search_type_mouvement" name="search_type_mouvement" class="maxwidth150">';
667		print '<option value="" '.(($search_type_mouvement == "") ? 'selected="selected"' : '').'>&nbsp;</option>';
668		print '<option value="0" '.(($search_type_mouvement == "0") ? 'selected="selected"' : '').'>'.$langs->trans('StockIncreaseAfterCorrectTransfer').'</option>';
669		print '<option value="1" '.(($search_type_mouvement == "1") ? 'selected="selected"' : '').'>'.$langs->trans('StockDecreaseAfterCorrectTransfer').'</option>';
670		print '<option value="2" '.(($search_type_mouvement == "2") ? 'selected="selected"' : '').'>'.$langs->trans('StockDecrease').'</option>';
671		print '<option value="3" '.(($search_type_mouvement == "3") ? 'selected="selected"' : '').'>'.$langs->trans('StockIncrease').'</option>';
672		print '</select>';
673		print ajax_combobox('search_type_mouvement');
674		// TODO: add new function $formentrepot->selectTypeOfMovement(...) like
675		// print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
676		print '</td>';
677	}
678	if (!empty($arrayfields['origin']['checked'])) {
679		// Origin of movement
680		print '<td class="liste_titre left">';
681		print '&nbsp; ';
682		print '</td>';
683	}
684	if (!empty($arrayfields['m.fk_projet']['checked'])) {
685		// fk_project
686		print '<td class="liste_titre" align="left">';
687		print '&nbsp; ';
688		print '</td>';
689	}
690	if (!empty($arrayfields['m.value']['checked'])) {
691		// Qty
692		print '<td class="liste_titre right">';
693		print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">';
694		print '</td>';
695	}
696	if (!empty($arrayfields['m.price']['checked'])) {
697		// Price
698		print '<td class="liste_titre left">';
699		print '&nbsp; ';
700		print '</td>';
701	}
702
703
704	// Extra fields
705	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
706
707	// Fields from hook
708	$parameters = array('arrayfields'=>$arrayfields);
709	$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
710	print $hookmanager->resPrint;
711	// Date creation
712	if (!empty($arrayfields['m.datec']['checked'])) {
713		print '<td class="liste_titre">';
714		print '</td>';
715	}
716	// Date modification
717	if (!empty($arrayfields['m.tms']['checked'])) {
718		print '<td class="liste_titre">';
719		print '</td>';
720	}
721	// Actions
722	print '<td class="liste_titre maxwidthsearch">';
723	$searchpicto = $form->showFilterAndCheckAddButtons(0);
724	print $searchpicto;
725	print '</td>';
726	print "</tr>\n";
727
728	print '<tr class="liste_titre">';
729	if (!empty($arrayfields['m.rowid']['checked'])) {
730		print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder);
731	}
732	if (!empty($arrayfields['m.datem']['checked'])) {
733		print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder);
734	}
735	if (!empty($arrayfields['p.ref']['checked'])) {
736		print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder);
737	}
738	if (!empty($arrayfields['p.label']['checked'])) {
739		print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder);
740	}
741	if (!empty($arrayfields['m.batch']['checked'])) {
742		print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center ');
743	}
744	if (!empty($arrayfields['pl.eatby']['checked'])) {
745		print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center ');
746	}
747	if (!empty($arrayfields['pl.sellby']['checked'])) {
748		print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center ');
749	}
750	if (!empty($arrayfields['e.ref']['checked'])) {
751		// We are on a specific warehouse card, no filter on other should be possible
752		print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder);
753	}
754	if (!empty($arrayfields['m.fk_user_author']['checked'])) {
755		print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder);
756	}
757	if (!empty($arrayfields['m.inventorycode']['checked'])) {
758		print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder);
759	}
760	if (!empty($arrayfields['m.label']['checked'])) {
761		print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder);
762	}
763	if (!empty($arrayfields['m.type_mouvement']['checked'])) {
764		print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center ');
765	}
766	if (!empty($arrayfields['origin']['checked'])) {
767		print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder);
768	}
769	if (!empty($arrayfields['m.fk_projet']['checked'])) {
770		print_liste_field_titre($arrayfields['m.fk_projet']['label'], $_SERVER["PHP_SELF"], "m.fk_projet", "", $param, '', $sortfield, $sortorder);
771	}
772	if (!empty($arrayfields['m.value']['checked'])) {
773		print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right ');
774	}
775	if (!empty($arrayfields['m.price']['checked'])) {
776		print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right ');
777	}
778
779	// Extra fields
780	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
781
782	// Hook fields
783	$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder);
784	$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
785	print $hookmanager->resPrint;
786	if (!empty($arrayfields['m.datec']['checked'])) {
787		print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
788	}
789	if (!empty($arrayfields['m.tms']['checked'])) {
790		print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
791	}
792	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
793	print "</tr>\n";
794
795	$resql = $db->query($sql);
796	if (!$resql) {
797		dol_print_error($db);
798	}
799	$num = $db->num_rows($resql);
800
801	$i = 0;
802	while ($i < ($limit ? min($num, $limit) : $num)) {
803		$objp = $db->fetch_object($resql);
804
805		$userstatic->id = $objp->fk_user_author;
806		$userstatic->login = $objp->login;
807		$userstatic->lastname = $objp->lastname;
808		$userstatic->firstname = $objp->firstname;
809		$userstatic->photo = $objp->photo;
810
811		$productstatic->id = $objp->rowid;
812		$productstatic->ref = $objp->product_ref;
813		$productstatic->label = $objp->produit;
814		$productstatic->type = $objp->type;
815		$productstatic->entity = $objp->entity;
816		$productstatic->status_batch = $objp->tobatch;
817
818		$productlot->id = $objp->lotid;
819		$productlot->batch = $objp->batch;
820		$productlot->eatby = $objp->eatby;
821		$productlot->sellby = $objp->sellby;
822
823		$warehousestatic->id = $objp->entrepot_id;
824		$warehousestatic->libelle = $objp->warehouse_ref; // deprecated
825		$warehousestatic->label = $objp->warehouse_ref;
826		$warehousestatic->lieu = $objp->lieu;
827
828		if (!empty($objp->fk_origin)) {
829			$origin = $objectlist->get_origin($objp->fk_origin, $objp->origintype);
830		} else {
831			$origin = '';
832		}
833
834		print '<tr class="oddeven">';
835		// Id movement
836		if (!empty($arrayfields['m.rowid']['checked'])) {
837			// This is primary not movement id
838			print '<td>'.$objp->mid.'</td>';
839		}
840		if (!empty($arrayfields['m.datem']['checked'])) {
841			// Date
842			print '<td>'.dol_print_date($db->jdate($objp->datem), 'dayhour').'</td>';
843		}
844		if (!empty($arrayfields['p.ref']['checked'])) {
845			// Product ref
846			print '<td class="nowraponall">';
847			print $productstatic->getNomUrl(1, 'stock', 16);
848			print "</td>\n";
849		}
850		if (!empty($arrayfields['p.label']['checked'])) {
851			// Product label
852			print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($productstatic->label).'">';
853			print $productstatic->label;
854			print "</td>\n";
855		}
856		if (!empty($arrayfields['m.batch']['checked'])) {
857			print '<td class="center nowraponall">';
858			if ($productlot->id > 0) {
859				print $productlot->getNomUrl(1);
860			} else {
861				print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement.
862			}
863			print '</td>';
864		}
865		if (!empty($arrayfields['pl.eatby']['checked'])) {
866			print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>';
867		}
868		if (!empty($arrayfields['pl.sellby']['checked'])) {
869			print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>';
870		}
871		// Warehouse
872		if (!empty($arrayfields['e.ref']['checked'])) {
873			print '<td>';
874			print $warehousestatic->getNomUrl(1);
875			print "</td>\n";
876		}
877		// Author
878		if (!empty($arrayfields['m.fk_user_author']['checked'])) {
879			print '<td class="tdoverflowmax100">';
880			print $userstatic->getNomUrl(-1);
881			print "</td>\n";
882		}
883		if (!empty($arrayfields['m.inventorycode']['checked'])) {
884			// Inventory code
885			print '<td>';
886			//print '<a href="' . DOL_URL_ROOT . '/product/stock/movement_card.php' . '?id=' . $objp->entrepot_id . '&amp;search_inventorycode=' . $objp->inventorycode . '&amp;search_type_mouvement=' . $objp->type_mouvement . '">';
887			print $objp->inventorycode;
888			//print '</a>';
889			print '</td>';
890		}
891		if (!empty($arrayfields['m.label']['checked'])) {
892			// Label of movement
893			print '<td class="tdoverflowmax300" title="'.dol_escape_htmltag($objp->label).'">'.$objp->label.'</td>';
894		}
895		if (!empty($arrayfields['m.type_mouvement']['checked'])) {
896			// Type of movement
897			switch ($objp->type_mouvement) {
898				case "0":
899					print '<td class="center">'.$langs->trans('StockIncreaseAfterCorrectTransfer').'</td>';
900					break;
901				case "1":
902					print '<td class="center">'.$langs->trans('StockDecreaseAfterCorrectTransfer').'</td>';
903					break;
904				case "2":
905					print '<td class="center">'.$langs->trans('StockDecrease').'</td>';
906					break;
907				case "3":
908					print '<td class="center">'.$langs->trans('StockIncrease').'</td>';
909					break;
910			}
911		}
912		if (!empty($arrayfields['origin']['checked'])) {
913			// Origin of movement
914			print '<td class="nowraponall">'.$origin.'</td>';
915		}
916		if (!empty($arrayfields['m.fk_projet']['checked'])) {
917			// fk_project
918			print '<td>';
919			if ($objp->fk_project != 0) {
920				print $movement->get_origin($objp->fk_project, 'project');
921			}
922			print '</td>';
923		}
924		if (!empty($arrayfields['m.value']['checked'])) {
925			// Qty
926			print '<td class="right">';
927			if ($objp->qt > 0) {
928				print '+';
929			}
930			print $objp->qty;
931			print '</td>';
932		}
933		if (!empty($arrayfields['m.price']['checked'])) {
934			// Price
935			print '<td class="right">';
936			if ($objp->price != 0) {
937				print price($objp->price);
938			}
939			print '</td>';
940		}
941		// Action column
942		print '<td class="nowrap center">';
943		if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
944			$selected = 0;
945			if (in_array($obj->rowid, $arrayofselected)) {
946				$selected = 1;
947			}
948			print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
949		}
950		print '</td>';
951		if (!$i) {
952			$totalarray['nbfield']++;
953		}
954
955		print "</tr>\n";
956		$i++;
957	}
958	$db->free($resql);
959
960	print "</table>";
961	print '</div>';
962	print "</form>";
963}
964
965// End of page
966llxFooter();
967$db->close();
968