dolibarr 23.0.4
inventory.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2019 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Load Dolibarr environment
27require '../../main.inc.php';
28include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
29include_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
30include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
31include_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
32include_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
33include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
34include_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
35
44// Load translation files required by the page
45$langs->loadLangs(array("stocks", "other", "productbatch"));
46
47// Get parameters
48$id = GETPOSTINT('id');
49$ref = GETPOST('ref', 'alpha');
50$action = GETPOST('action', 'aZ09');
51$confirm = GETPOST('confirm', 'alpha');
52$cancel = GETPOST('cancel');
53$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search
54$backtopage = GETPOST('backtopage', 'alpha');
55$listoffset = GETPOST('listoffset', 'alpha');
56$sortfield = GETPOST('sortfield', 'aZ09comma');
57$sortorder = GETPOST('sortorder', 'aZ09comma');
58$limit = GETPOSTINT('limit') > 0 ? GETPOSTINT('limit') : $conf->liste_limit;
59$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
60if (empty($page) || $page == -1) {
61 $page = 0;
62}
63$offset = $limit * $page;
64$pageprev = $page - 1;
65$pagenext = $page + 1;
66
67$fk_warehouse = GETPOSTINT('fk_warehouse');
68$fk_product = GETPOSTINT('fk_product');
69$lineid = GETPOSTINT('lineid');
70$batch = GETPOST('batch', 'alphanohtml');
71$totalExpectedValuation = 0;
72$totalRealValuation = 0;
73$hookmanager->initHooks(array('inventorycard')); // Note that conf->hooks_modules contains array
74if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
75 $result = restrictedArea($user, 'stock', $id, 'inventory&stock');
76} else {
77 $result = restrictedArea($user, 'stock', $id, 'inventory&stock', 'inventory_advance');
78}
79
80// Initialize a technical objects
81$object = new Inventory($db);
82$extrafields = new ExtraFields($db);
83$diroutputmassaction = $conf->stock->dir_output.'/temp/massgeneration/'.$user->id;
84
85// Default sort order (if not yet defined by previous GETPOST)
86if (!$sortfield) {
87 $sortfield = "e.ref";
88}
89if (!$sortorder) {
90 $sortorder = "ASC";
91}
92
93// Fetch optionals attributes and labels
94$extrafields->fetch_name_optionals_label($object->table_element);
95
96$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
97
98// Initialize array of search criteria
99$search_all = GETPOST("search_all", 'alpha');
100$search = array();
101foreach ($object->fields as $key => $val) {
102 if (GETPOST('search_'.$key, 'alpha')) {
103 $search[$key] = GETPOST('search_'.$key, 'alpha');
104 }
105}
106
107if (empty($action) && empty($id) && empty($ref)) {
108 $action = 'view';
109}
110
111// Load object
112include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'.
113
114// Security check - Protection if external user
115//if ($user->socid > 0) accessforbidden();
116//if ($user->socid > 0) $socid = $user->socid;
117//restrictedArea($user, 'mymodule', $id);
118
119//Parameters Page
120$paramwithsearch = '&sortfield=' . urlencode($sortfield);
121$paramwithsearch .= '&sortorder=' . urlencode($sortorder);
122if ($limit > 0 && $limit != $conf->liste_limit) {
123 $paramwithsearch .= '&limit='.((int) $limit);
124}
125
126// Sort by warehouse/product or product/warehouse, in the SQL requests only: the form sends back $sortfield and $sortorder,
127// so adding the secondary sort to them would add it again at each submit.
128$sortfieldforsql = $sortfield . ',' . ($sortfield == 'e.ref' ? 'p.ref' : 'e.ref') . ',id.batch,id.rowid';
129$sortorderforsql = $sortorder . ',' . $sortorder.",ASC,ASC";
130
131if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
132 $permissiontoadd = $user->hasRight('stock', 'creer');
133 $permissiontodelete = $user->hasRight('stock', 'supprimer');
134 $permissiontoupdatestock = $user->hasRight('stock', 'mouvement', 'creer');
135} else {
136 $permissiontoadd = $user->hasRight('stock', 'inventory_advance', 'write');
137 $permissiontodelete = $user->hasRight('stock', 'inventory_advance', 'write');
138 $permissiontoupdatestock = $user->hasRight('stock', 'inventory_advance', 'write');
139}
140
141$now = dol_now();
142
143
144
145/*
146 * Actions
147 */
148
149if ($cancel) {
150 $action = '';
151}
152
153
154$parameters = array();
155$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
156if ($reshook < 0) {
157 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
158}
159
160if (empty($reshook)) {
161 $error = 0;
162
163 if ($action == 'cancel_record' && $confirm == 'yes' && $permissiontoupdatestock && $object->status == $object::STATUS_VALIDATED) {
164 $object->setCanceled($user);
165 }
166
167 // Close inventory by recording the stock movements
168 if ($action == 'update' && $confirm == 'yes' && $permissiontoupdatestock && $object->status == $object::STATUS_VALIDATED) {
169 $stockmovment = new MouvementStock($db);
170 $stockmovment->setOrigin($object->element, $object->id);
171
172 $cacheOfProducts = array();
173
174 $db->begin();
175
176 $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
177 $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.pmp_real';
178 $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
179 $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
180 $sql .= ' ORDER BY id.rowid';
181
182 $resql = $db->query($sql);
183 if ($resql) {
184 $num = $db->num_rows($resql);
185 $i = 0;
186 $totalarray = array();
187 $option = '';
188
189 while ($i < $num) {
190 $line = $db->fetch_object($resql);
191
192 $qty_stock = $line->qty_stock;
193 $qty_view = $line->qty_view; // The quantity viewed by inventorier, the qty we target
194
195
196 // Load real stock we have now.
197 if (isset($cacheOfProducts[$line->fk_product])) {
198 $product_static = $cacheOfProducts[$line->fk_product];
199 } else {
200 $product_static = new Product($db);
201 $result = $product_static->fetch($line->fk_product, '', '', '', 1, 1, 1);
202
203 //$option = 'nobatch';
204 $option .= ',novirtual';
205 $product_static->load_stock($option); // Load stock_reel + stock_warehouse.
206
207 $cacheOfProducts[$product_static->id] = $product_static;
208 }
209
210 // Get the real quantity in stock now, but before the stock move for inventory.
211 $realqtynow = $product_static->stock_warehouse[$line->fk_warehouse]->real;
212 if (isModEnabled('productbatch') && $product_static->hasbatch()) {
213 // Search the lot without case sensitivity, like the database (and the stock movement) does,
214 // otherwise a lot typed with another case is seen as empty and the full counted qty is added.
215 $realqtynow = 0;
216 if (!empty($product_static->stock_warehouse[$line->fk_warehouse]->detail_batch)) {
217 foreach ($product_static->stock_warehouse[$line->fk_warehouse]->detail_batch as $tmpbatchnumber => $tmpdetailbatch) {
218 if (dol_strtolower((string) $tmpbatchnumber) == dol_strtolower((string) $line->batch)) {
219 $realqtynow = $tmpdetailbatch->qty;
220 break;
221 }
222 }
223 }
224 }
225
226 if (!is_null($qty_view)) {
227 $stock_movement_qty = price2num($qty_view - $realqtynow, 'MS');
228 //print "Process inventory line ".$line->rowid." product=".$product_static->id." realqty=".$realqtynow." qty_stock=".$qty_stock." qty_view=".$qty_view." warehouse=".$line->fk_warehouse." qty to move=".$stock_movement_qty."<br>\n";
229
230 if ($stock_movement_qty != 0) {
231 if ($stock_movement_qty < 0) {
232 $movement_type = 1;
233 } else {
234 $movement_type = 0;
235 }
236
237 $datemovement = '';
238 //$inventorycode = 'INV'.$object->id;
239 $inventorycode = 'INV-'.$object->ref;
240 $price = 0;
241 if (!empty($line->pmp_real) && getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
242 $price = $line->pmp_real;
243 }
244
245 $idstockmove = $stockmovment->_create($user, $line->fk_product, $line->fk_warehouse, (float) $stock_movement_qty, $movement_type, $price, $langs->trans('LabelOfInventoryMovemement', $object->ref), $inventorycode, $datemovement, '', '', $line->batch);
246 if ($idstockmove < 0) {
247 $error++;
248 setEventMessages($stockmovment->error, $stockmovment->errors, 'errors');
249 break;
250 }
251
252 // Update line with id of stock movement (and the start quantity if it has changed this last recording)
253 $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."inventorydet";
254 $sqlupdate .= " SET fk_movement = ".((int) $idstockmove);
255 if ($qty_stock != $realqtynow) {
256 $sqlupdate .= ", qty_stock = ".((float) $realqtynow);
257 }
258 $sqlupdate .= " WHERE rowid = ".((int) $line->rowid);
259 $resqlupdate = $db->query($sqlupdate);
260 if (! $resqlupdate) {
261 $error++;
262 setEventMessages($db->lasterror(), null, 'errors');
263 break;
264 }
265 }
266
267 if (!empty($line->pmp_real) && getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
268 $sqlpmp = 'UPDATE '.MAIN_DB_PREFIX.'product SET pmp = '.((float) $line->pmp_real).' WHERE rowid = '.((int) $line->fk_product);
269 $resqlpmp = $db->query($sqlpmp);
270 if (! $resqlpmp) {
271 $error++;
272 setEventMessages($db->lasterror(), null, 'errors');
273 break;
274 }
275 // Mirror Product::fetch (product.class.php:2995-2997) which reads pmp from
276 // llx_product_perentity only when MULTICOMPANY_PRODUCT_SHARING_ENABLED and
277 // MULTICOMPANY_PMP_PER_ENTITY_ENABLED are both set. MAIN_PRODUCT_PERENTITY_SHARED
278 // is the accountancy-codes flag; using it to gate the pmp write here means we
279 // silently write into a row that fetch never looks at (#37773).
280 if (getDolGlobalString('MULTICOMPANY_PRODUCT_SHARING_ENABLED') && getDolGlobalString('MULTICOMPANY_PMP_PER_ENTITY_ENABLED')) {
281 $sqlpmp = 'UPDATE '.MAIN_DB_PREFIX.'product_perentity SET pmp = '.((float) $line->pmp_real).' WHERE fk_product = '.((int) $line->fk_product).' AND entity='.$conf->entity;
282 $resqlpmp = $db->query($sqlpmp);
283 if (! $resqlpmp) {
284 $error++;
285 setEventMessages($db->lasterror(), null, 'errors');
286 break;
287 }
288 }
289 }
290 }
291 $i++;
292 }
293
294 if (!$error) {
295 $object->setRecorded($user);
296 }
297 } else {
298 setEventMessages($db->lasterror, null, 'errors');
299 $error++;
300 }
301
302 if (! $error) {
303 $db->commit();
304 } else {
305 $db->rollback();
306 }
307 $action = '';
308 }
309
310 // Save quantity found during inventory (when we click on Save button on inventory page)
311 if ($action == 'updateinventorylines' && $permissiontoupdatestock) {
312 $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
313 $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
314 $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
315 $sql .= ' LEFT JOIN ' . $db->prefix() . 'product as p ON id.fk_product = p.rowid';
316 $sql .= ' LEFT JOIN ' . $db->prefix() . 'entrepot as e ON id.fk_warehouse = e.rowid';
317 $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
318 $sql .= $db->order($sortfieldforsql, $sortorderforsql);
319 $sql .= $db->plimit($limit, $offset);
320
321 $db->begin();
322
323 $resql = $db->query($sql);
324 if ($resql) {
325 $num = $db->num_rows($resql);
326 $i = 0;
327 $totalarray = array();
328 $inventoryline = new InventoryLine($db);
329
330 while ($i < $num) {
331 $line = $db->fetch_object($resql);
332 $lineid = $line->rowid;
333
334 $result = 0;
335 $resultupdate = 0;
336
337 if (GETPOST("id_".$lineid, 'alpha') != '') { // If a value was set ('0' or something else)
338 $qtytoupdate = (float) price2num(GETPOST("id_".$lineid, 'alpha'), 'MS');
339 $result = $inventoryline->fetch($lineid);
340 if ($qtytoupdate < 0) {
341 $result = -1;
342 setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
343 }
344 if ($result > 0) {
345 $inventoryline->qty_stock = (float) price2num(GETPOST('stock_qty_'.$lineid, 'alpha'), 'MS'); // The new value that was set in as hidden field
346 $inventoryline->qty_view = $qtytoupdate; // The new value we want
347 $inventoryline->pmp_real = price2num(GETPOST('realpmp_'.$lineid, 'alpha'), 'MS');
348 $inventoryline->pmp_expected = price2num(GETPOST('expectedpmp_'.$lineid, 'alpha'), 'MS');
349 $resultupdate = $inventoryline->update($user);
350 }
351 } elseif (GETPOSTISSET('id_' . $lineid)) {
352 // Delete record
353 $result = $inventoryline->fetch($lineid);
354 if ($result > 0) {
355 $inventoryline->qty_view = null; // The new value we want
356 $inventoryline->pmp_real = price2num(GETPOST('realpmp_'.$lineid, 'alpha'), 'MS');
357 $inventoryline->pmp_expected = price2num(GETPOST('expectedpmp_'.$lineid, 'alpha'), 'MS');
358 $resultupdate = $inventoryline->update($user);
359 }
360 }
361
362 if ($result < 0 || $resultupdate < 0) {
363 $error++;
364 }
365
366 $i++;
367 }
368 }
369
370 // Update line with id of stock movement (and the start quantity if it has changed this last recording)
371 if (! $error) {
372 $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."inventory";
373 $sqlupdate .= " SET fk_user_modif = ".((int) $user->id);
374 $sqlupdate .= " WHERE rowid = ".((int) $object->id);
375 $resqlupdate = $db->query($sqlupdate);
376 if (! $resqlupdate) {
377 $error++;
378 setEventMessages($db->lasterror(), null, 'errors');
379 }
380 }
381
382 if (!$error) {
383 $db->commit();
384 } else {
385 $db->rollback();
386 }
387 }
388
389 $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php';
390 $backtopage = DOL_URL_ROOT.'/product/inventory/inventory.php?id='.$object->id.'&page='.$page.$paramwithsearch;
391
392 // Action 'update' of this page is the recording of the inventory (done above or refused), never the
393 // generic update of the object: it would overwrite the fields of the inventory with empty values.
394 if ($action == 'update') { // Test on permission not required here
395 $action = '';
396 }
397
398 // Actions cancel, add, update, delete or clone
399 include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
400
401 // Actions when linking object each other
402 include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
403
404 // Actions when printing a doc from card
405 include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
406
407 // Actions to send emails
408 /*$triggersendname = 'MYOBJECT_SENTBYMAIL';
409 $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
410 $trackid='stockinv'.$object->id;
411 include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';*/
412
413 if (GETPOST('addline', 'alpha')) {
414 $qty = (GETPOST('qtytoadd') != '' ? ((float) price2num(GETPOST('qtytoadd'), 'MS')) : null);
415 if ($fk_warehouse <= 0) {
416 $error++;
417 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
418 }
419 if ($fk_product <= 0) {
420 $error++;
421 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
422 }
423 if (price2num(GETPOST('qtytoadd'), 'MS') < 0) {
424 $error++;
425 setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
426 }
427 if (!$error && isModEnabled('productbatch')) {
428 $tmpproduct = new Product($db);
429 $result = $tmpproduct->fetch($fk_product);
430
431 if (empty($error) && $tmpproduct->status_batch > 0 && empty($batch)) {
432 $error++;
433 $langs->load("errors");
434 setEventMessages($langs->trans("ErrorProductNeedBatchNumber", $tmpproduct->ref), null, 'errors');
435 }
436 if (empty($error) && $tmpproduct->status_batch == 2 && !empty($batch) && $qty > 1) {
437 $error++;
438 $langs->load("errors");
439 setEventMessages($langs->trans("TooManyQtyForSerialNumber", $tmpproduct->ref, $batch), null, 'errors');
440 }
441 if (empty($error) && empty($tmpproduct->status_batch) && !empty($batch)) {
442 $error++;
443 $langs->load("errors");
444 setEventMessages($langs->trans("ErrorProductDoesNotNeedBatchNumber", $tmpproduct->ref), null, 'errors');
445 }
446 }
447 if (!$error) {
448 $tmp = new InventoryLine($db);
449 $tmp->fk_inventory = $object->id;
450 $tmp->fk_warehouse = $fk_warehouse;
451 $tmp->fk_product = $fk_product;
452 $tmp->batch = $batch;
453 $tmp->datec = $now;
454 $tmp->qty_view = $qty;
455
456 $result = $tmp->create($user);
457 if ($result < 0) {
458 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
459 $langs->load("errors");
460 setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
461 } else {
462 dol_print_error($db, $tmp->error, $tmp->errors);
463 }
464 } else {
465 // Clear var
466 $_POST['batch'] = ''; // TODO Replace this with a var
467 $_POST['qtytoadd'] = '';
468 }
469 }
470 }
471}
472
473
474
475/*
476 * View
477 */
478
479$form = new Form($db);
480$formproduct = new FormProduct($db);
481
482$help_url = '';
483
484llxHeader('', $langs->trans('Inventory'), $help_url, '', 0, 0, '', '', '', 'mod-product page-inventory_inventory');
485
486// Part to show record
487if ($object->id <= 0) {
488 dol_print_error(null, 'Bad value for object id');
489 exit;
490}
491
492$param = '';
493if ($limit > 0 && $limit != $conf->liste_limit) {
494 $param .= '&limit=' . ((int) $limit);
495}
496
497
498$res = $object->fetch_optionals();
499
500$head = inventoryPrepareHead($object);
501print dol_get_fiche_head($head, 'inventory', $langs->trans("Inventory"), -1, 'stock');
502
503$formconfirm = '';
504
505// Confirmation to delete
506if ($action == 'delete') {
507 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
508}
509// Confirmation to delete line
510if ($action == 'deleteline') {
511 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid.'&page='.$page.$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
512}
513
514// Clone confirmation
515if ($action == 'clone') {
516 // Create an array for form
517 $formquestion = array();
518 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
519}
520
521// Confirmation to close
522if ($action == 'record') {
523 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&page='.$page.$paramwithsearch, $langs->trans('Close'), $langs->trans('ConfirmFinish'), 'update', '', 0, 1);
524 $action = 'view';
525}
526
527// Confirmation to close
528if ($action == 'confirm_cancel') {
529 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Cancel'), $langs->trans('ConfirmCancel'), 'cancel_record', '', 0, 1);
530 $action = 'view';
531}
532
533if ($action == 'validate') {
534 $form = new Form($db);
535 $formquestion = '';
536 if (getDolGlobalInt('INVENTORY_INCLUDE_SUB_WAREHOUSE') && !empty($object->fk_warehouse)) {
537 $formquestion = array(
538 array('type' => 'checkbox', 'name' => 'include_sub_warehouse', 'label' => $langs->trans("IncludeSubWarehouse"), 'value' => 1, 'size' => '10'),
539 );
540 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateInventory'), $langs->trans('IncludeSubWarehouseExplanation'), 'confirm_validate', $formquestion, '', 1);
541 }
542}
543
544// Call Hook formConfirm
545$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
546$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
547if (empty($reshook)) {
548 $formconfirm .= $hookmanager->resPrint;
549} elseif ($reshook > 0) {
550 $formconfirm = $hookmanager->resPrint;
551}
552
553// Print form confirm
554print $formconfirm;
555
556
557// Object card
558// ------------------------------------------------------------
559$linkback = '<a href="'.DOL_URL_ROOT.'/product/inventory/list.php">'.$langs->trans("BackToList").'</a>';
560
561$morehtmlref = '<div class="refidno">';
562/*
563// Ref bis
564$morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', 0, 1);
565$morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', null, null, '', 1);
566// Thirdparty
567$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1);
568// Project
569if (isModEnabled('project'))
570{
571 $langs->load("projects");
572 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
573 if ($user->rights->inventory->creer)
574 {
575 if ($action != 'classify')
576 {
577 $morehtmlref.='<a class="editfielda" href="' . dolBuildUrl($_SERVER['PHP_SELF'], ['action' => 'classify', 'id' => $object->id], true) . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
578 if ($action == 'classify') {
579 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
580 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
581 $morehtmlref.='<input type="hidden" name="action" value="classin">';
582 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
583 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
584 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
585 $morehtmlref.='</form>';
586 } else {
587 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
588 }
589 }
590 } else {
591 if (!empty($object->fk_project)) {
592 $proj = new Project($db);
593 $proj->fetch($object->fk_project);
594 $morehtmlref.=$proj->getNomUrl();
595 } else {
596 $morehtmlref.='';
597 }
598 }
599}
600*/
601$morehtmlref .= '</div>';
602
603
604dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
605
606
607print '<div class="fichecenter">';
608print '<div class="fichehalfleft">';
609print '<div class="underbanner clearboth"></div>';
610print '<table class="border centpercent tableforfield">'."\n";
611
612// Common attributes
613include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
614
615// Other attributes. Fields from hook formObjectOptions and Extrafields.
616include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
617
618//print '<tr><td class="titlefield fieldname_invcode">'.$langs->trans("InventoryCode").'</td><td>INV'.$object->id.'</td></tr>';
619
620print '</table>';
621print '</div>';
622print '</div>';
623
624print '<div class="clearboth"></div>';
625
626print dol_get_fiche_end();
627
628print '<form id="formrecord" name="formrecord" method="POST" action="'.$_SERVER["PHP_SELF"].'?page='.$page.'&id='.$object->id.'">';
629print '<input type="hidden" name="token" value="'.newToken().'">';
630print '<input type="hidden" name="action" value="updateinventorylines">';
631print '<input type="hidden" name="id" value="'.$object->id.'">';
632print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
633print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
634// Keep the same limit as the displayed page, otherwise the save reads a different page slice
635// (plimit($limit, $offset)) than the one shown and quantities of the extra rows are lost (#35207).
636print '<input type="hidden" name="limit" value="' . ((int) $limit) . '">';
637if ($backtopage) {
638 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
639}
640
641
642// Buttons for actions
643if ($action != 'record') {
644 print '<div class="tabsAction">'."\n";
645 $parameters = array();
646 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
647 if ($reshook < 0) {
648 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
649 }
650
651 if (empty($reshook)) {
652 if ($object->status == Inventory::STATUS_DRAFT) {
653 if ($permissiontoupdatestock) {
654 if (getDolGlobalInt('INVENTORY_INCLUDE_SUB_WAREHOUSE') && !empty($object->fk_warehouse)) {
655 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate&token='.newToken().'">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>';
656 } else {
657 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes&token='.newToken().'">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>';
658 }
659 } else {
660 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n";
661 }
662 }
663
664 // Save
665 if ($object->status == $object::STATUS_VALIDATED) {
666 if ($permissiontoupdatestock) {
667 print '<a class="butAction classfortooltip" id="idbuttonmakemovementandclose" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=record&page='.$page.$paramwithsearch.'&token='.newToken().'" title="'.dol_escape_htmltag($langs->trans("MakeMovementsAndClose")).'">'.$langs->trans("MakeMovementsAndClose").'</a>'."\n";
668 } else {
669 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('MakeMovementsAndClose').'</a>'."\n";
670 }
671
672 if ($permissiontoupdatestock) {
673 print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_cancel&page='.$page.$paramwithsearch.'&token='.newToken().'">'.$langs->trans("Cancel").'</a>'."\n";
674 }
675 }
676 }
677 print '</div>'."\n";
678
679 if ($object->status != Inventory::STATUS_DRAFT && $object->status != Inventory::STATUS_VALIDATED) {
680 print '<br><br>';
681 }
682}
683
684
685
686if ($object->status == Inventory::STATUS_VALIDATED) {
687 print '<center>';
688 if (!empty($conf->use_javascript_ajax)) {
689 if ($permissiontoupdatestock) {
690 // Link to launch scan tool
691 if (isModEnabled('barcode') || isModEnabled('productbatch')) {
692 print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=updatebyscaning&token='.currentToken().'" class="marginrightonly paddingright marginleftonly paddingleft">'.img_picto('', 'barcode', 'class="paddingrightonly"').$langs->trans("UpdateByScaning").'</a>';
693 }
694
695 // Link to autofill
696 print '<a id="fillwithexpected" class="marginrightonly paddingright marginleftonly paddingleft" href="#">'.img_picto('', 'autofill', 'class="paddingrightonly"').$langs->trans('AutofillWithExpected').'</a>';
697 print '<script>';
698 print '$( document ).ready(function() {';
699 print ' $("#fillwithexpected").on("click",function fillWithExpected(){
700 $(".expectedqty").each(function(){
701 var object = $(this)[0];
702 var objecttofill = $("#"+object.id+"_input")[0];
703 objecttofill.value = object.innerText;
704 jQuery(".realqty").trigger("change");
705 })
706 console.log("Values filled (after click on fillwithexpected)");
707 /* disablebuttonmakemovementandclose(); */
708 return false;
709 });';
710 print '});';
711 print '</script>';
712
713 // Link to reset qty
714 print '<a href="#" id="clearqty" class="marginrightonly paddingright marginleftonly paddingleft">'.img_picto('', 'eraser', 'class="paddingrightonly"').$langs->trans("ClearQtys").'</a>';
715 } else {
716 print '<a class="classfortooltip marginrightonly paddingright marginleftonly paddingleft" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("Save").'</a>'."\n";
717 }
718 }
719 print '<br>';
720 print '<br>';
721 print '</center>';
722}
723
724
725// Popup for mass barcode scanning
726if ($action == 'updatebyscaning') {
727 if ($permissiontoupdatestock) {
728 // Output the javascript to manage the scanner tool.
729 print '<script>';
730
731 print '
732 var duplicatedbatchcode = [];
733 var errortab1 = [];
734 var errortab2 = [];
735 var errortab3 = [];
736 var errortab4 = [];
737
738 function barcodescannerjs(){
739 console.log("We catch inputs in scanner box");
740 jQuery("#scantoolmessage").text();
741
742 var selectaddorreplace = $("select[name=selectaddorreplace]").val();
743 var barcodemode = $("input[name=barcodemode]:checked").val();
744 var barcodeproductqty = $("input[name=barcodeproductqty]").val();
745 var textarea = $("textarea[name=barcodelist]").val();
746 var textarray = textarea.split(/[\s,;]+/);
747 var tabproduct = [];
748 duplicatedbatchcode = [];
749 errortab1 = [];
750 errortab2 = [];
751 errortab3 = [];
752 errortab4 = [];
753
754 textarray = textarray.filter(function(value){
755 return value != "";
756 });
757 if(textarray.some((element) => element != "")){
758 $(".expectedqty").each(function(){
759 id = this.id;
760 console.log("Analyze the line "+id+" in inventory, barcodemode="+barcodemode);
761 warehouse = $("#"+id+"_warehouse").attr(\'data-ref\');
762 //console.log(warehouse);
763 productbarcode = $("#"+id+"_product").attr(\'data-barcode\');
764 //console.log(productbarcode);
765 productbatchcode = $("#"+id+"_batch").attr(\'data-batch\');
766 //console.log(productbatchcode);
767
768 if (barcodemode != "barcodeforproduct") {
769 tabproduct.forEach(product=>{
770 console.log("product.Batch="+product.Batch+" productbatchcode="+productbatchcode);
771 if(product.Batch != "" && product.Batch == productbatchcode){
772 console.log("duplicate batch code found for batch code "+productbatchcode);
773 duplicatedbatchcode.push(productbatchcode);
774 }
775 })
776 }
777 productinput = $("#"+id+"_input").val();
778 if(productinput == ""){
779 productinput = 0
780 }
781 tabproduct.push({\'Id\':id,\'Warehouse\':warehouse,\'Barcode\':productbarcode,\'Batch\':productbatchcode,\'Qty\':productinput,\'fetched\':false});
782 });
783
784 console.log("Loop on each record entered in the textarea");
785 textarray.forEach(function(element,index){
786 console.log("Process record element="+element+" id="+id);
787 var verify_batch = false;
788 var verify_barcode = false;
789 switch(barcodemode){
790 case "barcodeforautodetect":
791 verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode",true);
792 verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial",true);
793 break;
794 case "barcodeforproduct":
795 verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode");
796 break;
797 case "barcodeforlotserial":
798 verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial");
799 break;
800 default:
801 alert(\''.dol_escape_js($langs->trans("ErrorWrongBarcodemode")).' "\'+barcodemode+\'"\');
802 throw \''.dol_escape_js($langs->trans('ErrorWrongBarcodemode')).' "\'+barcodemode+\'"\';
803 }
804
805 if (verify_batch == false && verify_barcode == false) { /* If the 2 flags are false, not found error */
806 errortab2.push(element);
807 } else if (verify_batch == true && verify_barcode == true) { /* If the 2 flags are true, error: we don t know which one to take */
808 errortab3.push(element);
809 } else if (verify_batch == true) {
810 console.log("element="+element);
811 console.log(duplicatedbatchcode);
812 if (duplicatedbatchcode.includes(element)) {
813 errortab1.push(element);
814 }
815 }
816 });
817
818 if (Object.keys(errortab1).length < 1 && Object.keys(errortab2).length < 1 && Object.keys(errortab3).length < 1) {
819 tabproduct.forEach(product => {
820 if(product.Qty!=0){
821 console.log("We change #"+product.Id+"_input to match input in scanner box");
822 if(product.hasOwnProperty("reelqty")){
823 $.ajax({ url: \''.DOL_URL_ROOT.'/product/inventory/ajax/searchfrombarcode.php\',
824 data: { "token":"'.newToken().'", "action":"addnewlineproduct", "fk_entrepot":product.Warehouse, "batch":product.Batch, "fk_inventory":'.dol_escape_js((string) $object->id).', "fk_product":product.fk_product, "reelqty":product.reelqty},
825 type: \'POST\',
826 async: false,
827 success: function(response) {
828 if (typeof response == "object") {
829 console.log("response is already type object, no need to parse it");
830 } else {
831 console.log("response is type "+(typeof response));
832 response = JSON.parse(response);
833 }
834 if(response.status == "success"){
835 console.log(response.message);
836 $("<input type=\'text\' value=\'"+product.Qty+"\' />")
837 .attr("id", "id_"+response.id_line+"_input")
838 .attr("name", "id_"+response.id_line)
839 .appendTo("#formrecord");
840 }else{
841 console.error(response.message);
842 }
843 },
844 error : function(output) {
845 console.error("Error on line creation function");
846 },
847 });
848 } else {
849 $("#"+product.Id+"_input").val(product.Qty);
850 }
851 }
852 });
853 jQuery("#scantoolmessage").text("'.dol_escape_js($langs->transnoentities("QtyWasAddedToTheScannedBarcode")).'\n");
854 /* document.forms["formrecord"].submit(); */
855 } else {
856 let stringerror = "";
857 if (Object.keys(errortab1).length > 0) {
858 stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorSameBatchNumber')).': ";
859 errortab1.forEach(element => {
860 stringerror += (element + ", ")
861 });
862 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
863 }
864 if (Object.keys(errortab2).length > 0) {
865 stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorCantFindCodeInInventory')).': ";
866 errortab2.forEach(element => {
867 stringerror += (element + ", ")
868 });
869 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
870 }
871 if (Object.keys(errortab3).length > 0) {
872 stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorCodeScannedIsBothProductAndSerial')).': ";
873 errortab3.forEach(element => {
874 stringerror += (element + ", ")
875 });
876 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
877 }
878 if (Object.keys(errortab4).length > 0) {
879 stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorBarcodeNotFoundForProductWarehouse')).': ";
880 errortab4.forEach(element => {
881 stringerror += (element + ", ")
882 });
883 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
884 }
885
886 jQuery("#scantoolmessage").html(\''.dol_escape_js($langs->transnoentities("ErrorOnElementsInventory")).'\' + stringerror);
887 //alert("'.dol_escape_js($langs->trans("ErrorOnElementsInventory")).' :\n" + stringerror);
888 }
889 }
890
891 }
892
893 /* This methode is called by parent barcodescannerjs() */
894 function barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,mode,autodetect=false){
895 BarcodeIsInProduct=0;
896 newproductrow=0
897 result=false;
898 tabproduct.forEach(product => {
899 $.ajax({ url: \''.DOL_URL_ROOT.'/product/inventory/ajax/searchfrombarcode.php\',
900 data: { "token":"'.newToken().'", "action":"existbarcode", '.(!empty($object->fk_warehouse) ? '"fk_entrepot":'.$object->fk_warehouse.', ' : '').(!empty($object->fk_product) ? '"fk_product":'.$object->fk_product.', ' : '').'"barcode":element, "product":product, "mode":mode},
901 type: \'POST\',
902 async: false,
903 success: function(response) {
904 if (typeof response == "object") {
905 console.log("response is already type object, no need to parse it");
906 } else {
907 console.log("response is type "+(typeof response));
908 response = JSON.parse(response);
909 }
910 if (response.status == "success"){
911 console.log(response.message);
912 if(!newproductrow){
913 newproductrow = response.object;
914 }
915 }else{
916 if (mode!="lotserial" && autodetect==false && !errortab4.includes(element)){
917 errortab4.push(element);
918 console.error(response.message);
919 }
920 }
921 },
922 error : function(output) {
923 console.error("Error on barcodeserialforproduct function");
924 },
925 });
926 console.log("Product "+(index+=1)+": "+element);
927 if(mode == "barcode"){
928 testonproduct = product.Barcode
929 }else if (mode == "lotserial"){
930 testonproduct = product.Batch
931 }
932 if(testonproduct == element){
933 if(selectaddorreplace == "add"){
934 productqty = parseInt(product.Qty,10);
935 product.Qty = productqty + parseInt(barcodeproductqty,10);
936 }else if(selectaddorreplace == "replace"){
937 if(product.fetched == false){
938 product.Qty = barcodeproductqty
939 product.fetched=true
940 }else{
941 productqty = parseInt(product.Qty,10);
942 product.Qty = productqty + parseInt(barcodeproductqty,10);
943 }
944 }
945 BarcodeIsInProduct+=1;
946 }
947 })
948 if(BarcodeIsInProduct==0 && newproductrow!=0){
949 tabproduct.push({\'Id\':tabproduct.length-1,\'Warehouse\':newproductrow.fk_warehouse,\'Barcode\':mode=="barcode"?element:null,\'Batch\':mode=="lotserial"?element:null,\'Qty\':barcodeproductqty,\'fetched\':true,\'reelqty\':newproductrow.reelqty,\'fk_product\':newproductrow.fk_product,\'mode\':mode});
950 result = true;
951 }
952 if(BarcodeIsInProduct > 0){
953 result = true;
954 }
955 return result;
956 }
957 ';
958 print '</script>';
959 }
960 include DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
961 $formother = new FormOther($db);
962 print $formother->getHTMLScannerForm("barcodescannerjs", 'all');
963}
964
965//Call method to undo changes in real qty
966print '<script>';
967print 'jQuery(document).ready(function() {
968 $("#clearqty").on("click", function() {
969 console.log("Clear all values");
970 /* disablebuttonmakemovementandclose(); */
971 jQuery(".realqty").val("");
972 jQuery(".realqty").trigger("change");
973 return false; /* disable submit */
974 });
975 $(".undochangesqty").on("click", function undochangesqty() {
976 console.log("Clear value of inventory line");
977 id = this.id;
978 id = id.split("_")[1];
979 tmpvalue = $("#id_"+id+"_input_tmp").val()
980 $("#id_"+id+"_input")[0].value = tmpvalue;
981 /* disablebuttonmakemovementandclose(); */
982 return false; /* disable submit */
983 });
984});';
985print '</script>';
986
987print '<div class="fichecenter">';
988//print '<div class="fichehalfleft">';
989print '<div class="clearboth"></div>';
990
991//print load_fiche_titre($langs->trans('Consumption'), '', '');
992
993print '<div class="div-table-responsive-no-min">';
994print '<table id="tablelines" class="noborder noshadow centpercent">';
995
996print '<tr class="liste_titre">';
997print getTitleFieldOfList($langs->trans("Warehouse"), 0, $_SERVER['PHP_SELF'], 'e.ref', '', 'id=' . $object->id . '&page=' . $page . $param, '', $sortfield, $sortorder, '', 0, '') . "\n";
998print getTitleFieldOfList($langs->trans("Product"), 0, $_SERVER['PHP_SELF'], 'p.ref', '', 'id=' . $object->id . '&page=' . $page . $param, '', $sortfield, $sortorder, '', 0, '') . "\n";
999if (isModEnabled('productbatch')) {
1000 print '<td>';
1001 print $langs->trans("Batch");
1002 print '</td>';
1003}
1004if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
1005 // Expected quantity = If inventory is open: Quantity currently in stock (may change if stock movement are done during the inventory)
1006 print '<td class="right">'.$form->textwithpicto($langs->trans("ExpectedQty"), $langs->trans("QtyCurrentlyKnownInStock")).'</td>';
1007} else {
1008 // Expected quantity = If inventory is closed: Quantity we had in stock when we start the inventory.
1009 print '<td class="right">'.$form->textwithpicto($langs->trans("ExpectedQty"), $langs->trans("QtyInStockWhenInventoryWasValidated")).'</td>';
1010}
1011if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1012 print '<td class="right">'.$langs->trans('PMPExpected').'</td>';
1013 print '<td class="right">'.$langs->trans('ExpectedValuation').'</td>';
1014 print '<td class="right">'.$form->textwithpicto($langs->trans("RealQty"), $langs->trans("InventoryRealQtyHelp")).'</td>';
1015 print '<td class="right">'.$langs->trans('PMPReal').'</td>';
1016 print '<td class="right">'.$langs->trans('RealValuation').'</td>';
1017} else {
1018 print '<td class="right">';
1019 print $form->textwithpicto($langs->trans("RealQty"), $langs->trans("InventoryRealQtyHelp"));
1020 print '</td>';
1021}
1022if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
1023 // Actions or link to stock movement
1024 print '<td class="center">';
1025 print '</td>';
1026} else {
1027 // Actions or link to stock movement
1028 print '<td class="right">';
1029 //print $langs->trans("StockMovement");
1030 print '</td>';
1031}
1032print '</tr>';
1033
1034// Line to add a new line in inventory
1035if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
1036 print '<tr>';
1037 print '<td>';
1038 print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? GETPOSTINT('fk_warehouse') : $object->fk_warehouse), 'fk_warehouse', 'warehouseopen', 1, 0, 0, '', 0, 0, array(), 'maxwidth300');
1039 print '</td>';
1040 print '<td>';
1041 if (getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1042 $filtertype = '';
1043 } else {
1044 $filtertype = 0;
1045 }
1046 print $form->select_produits((GETPOSTISSET('fk_product') ? GETPOSTINT('fk_product') : $object->fk_product), 'fk_product', $filtertype, 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300');
1047 print '</td>';
1048 if (isModEnabled('productbatch')) {
1049 print '<td>';
1050 print '<input type="text" name="batch" class="maxwidth100" value="'.(GETPOSTISSET('batch') ? GETPOST('batch') : '').'">';
1051 print '</td>';
1052 }
1053 print '<td class="right"></td>';
1054 if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1055 print '<td class="right">';
1056 print '</td>';
1057 print '<td class="right">';
1058 print '</td>';
1059 print '<td class="right">';
1060 print '<input type="text" name="qtytoadd" class="maxwidth75" value="">';
1061 print '</td>';
1062 print '<td class="right">';
1063 print '</td>';
1064 print '<td class="right">';
1065 print '</td>';
1066 } else {
1067 print '<td class="right">';
1068 print '<input type="text" name="qtytoadd" class="maxwidth75" value="">';
1069 print '</td>';
1070 }
1071 // Actions
1072 print '<td class="center">';
1073 if ($permissiontoupdatestock) {
1074 print '<input type="submit" class="button paddingright" name="addline" value="'.$langs->trans("Add").'">';
1075 } else {
1076 print '<input type="submit" class="button paddingright" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'" name="addline" value="'.$langs->trans("Add").'">';
1077 }
1078 print '</td>';
1079 print '</tr>';
1080}
1081
1082// Request to show lines of inventory (prefilled after start/validate step)
1083$sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
1084$sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.fk_movement, id.pmp_real, id.pmp_expected';
1085$sql .= ' FROM ' . $db->prefix() . 'inventorydet as id';
1086$sql .= ' LEFT JOIN ' . $db->prefix() . 'product as p ON id.fk_product = p.rowid';
1087$sql .= ' LEFT JOIN ' . $db->prefix() . 'entrepot as e ON id.fk_warehouse = e.rowid';
1088$sql .= ' WHERE id.fk_inventory = ' . ((int) $object->id);
1089$sql .= $db->order($sortfieldforsql, $sortorderforsql);
1090$sql .= $db->plimit($limit, $offset);
1091
1092$cacheOfProducts = array();
1093$cacheOfWarehouses = array();
1094
1095//$sql = '';
1096$resql = $db->query($sql);
1097if ($resql) {
1098 $num = $db->num_rows($resql);
1099
1100 if (!empty($limit != 0) || $num > $limit || $page) {
1101 print_fleche_navigation($page, $_SERVER["PHP_SELF"], '&id='.$object->id.$paramwithsearch, ($num >= $limit ? 1 : 0), '<li class="pagination"><span>' . $langs->trans("Page") . ' ' . ($page + 1) . '</span></li>', '', $limit);
1102 }
1103
1104 $i = 0;
1105 $hasinput = false;
1106 $totalarray = array();
1107 while ($i < $num) {
1108 $obj = $db->fetch_object($resql);
1109
1110 if (isset($cacheOfWarehouses[$obj->fk_warehouse])) {
1111 $warehouse_static = $cacheOfWarehouses[$obj->fk_warehouse];
1112 } else {
1113 $warehouse_static = new Entrepot($db);
1114 $warehouse_static->fetch($obj->fk_warehouse);
1115
1116 $cacheOfWarehouses[$warehouse_static->id] = $warehouse_static;
1117 }
1118
1119 // Load real stock we have now
1120 $option = '';
1121 if (isset($cacheOfProducts[$obj->fk_product])) {
1122 $product_static = $cacheOfProducts[$obj->fk_product];
1123 } else {
1124 $product_static = new Product($db);
1125 $result = $product_static->fetch($obj->fk_product, '', '', '', 1, 1, 1);
1126
1127 //$option = 'nobatch';
1128 $option .= ',novirtual';
1129 $product_static->load_stock($option); // Load stock_reel + stock_warehouse.
1130
1131 $cacheOfProducts[$product_static->id] = $product_static;
1132 }
1133
1134 print '<tr class="oddeven">';
1135 print '<td id="id_'.$obj->rowid.'_warehouse" data-ref="'.dol_escape_htmltag($warehouse_static->ref).'">';
1136 print $warehouse_static->getNomUrl(1);
1137 print '</td>';
1138 print '<td id="id_'.$obj->rowid.'_product" data-ref="'.dol_escape_htmltag($product_static->ref).'" data-barcode="'.dol_escape_htmltag($product_static->barcode).'">';
1139 print $product_static->getNomUrl(1).' - '.$product_static->label;
1140 print '</td>';
1141
1142 if (isModEnabled('productbatch')) {
1143 print '<td id="id_'.$obj->rowid.'_batch" data-batch="'.dol_escape_htmltag($obj->batch).'">';
1144 $batch_static = new Productlot($db);
1145 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1146 $res = $batch_static->fetch(0, $product_static->id, $obj->batch);
1147 if ($res) {
1148 print $batch_static->getNomUrl(1);
1149 } else {
1150 print dol_escape_htmltag($obj->batch);
1151 }
1152 print '</td>';
1153 }
1154
1155 // Expected quantity = If inventory is open: Quantity currently in stock (may change if stock movement are done during the inventory)
1156 // Expected quantity = If inventory is closed: Quantity we had in stock when we start the inventory.
1157 print '<td class="right expectedqty" id="id_'.$obj->rowid.'" title="Stock viewed at last update: '.$obj->qty_stock.'">';
1158 $valuetoshow = $obj->qty_stock;
1159 // For inventory not yet close, we overwrite with the real value in stock now
1160 if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
1161 if (isModEnabled('productbatch') && $product_static->hasbatch()) {
1162 $valuetoshow = $product_static->stock_warehouse[$obj->fk_warehouse]->detail_batch[$obj->batch]->qty ?? 0;
1163 } else {
1164 $valuetoshow = !empty($product_static->stock_warehouse[$obj->fk_warehouse]->real) ? $product_static->stock_warehouse[$obj->fk_warehouse]->real : 0;
1165 }
1166 }
1167 print price2num($valuetoshow, 'MS');
1168 print '<input type="hidden" name="stock_qty_'.$obj->rowid.'" value="'.$valuetoshow.'">';
1169 print '</td>';
1170
1171 // Real quantity
1172 if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
1173 $qty_view = GETPOST("id_".$obj->rowid) && price2num(GETPOST("id_".$obj->rowid), 'MS') >= 0 ? GETPOST("id_".$obj->rowid) : $obj->qty_view;
1174
1175 //if (!$hasinput && $qty_view !== null && $obj->qty_stock != $qty_view) {
1176 if ($qty_view != '') {
1177 $hasinput = true;
1178 }
1179
1180 if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1181 //PMP Expected
1182 if (!empty($obj->pmp_expected)) {
1183 $pmp_expected = $obj->pmp_expected;
1184 } else {
1185 $pmp_expected = $product_static->pmp;
1186 }
1187 $pmp_valuation = $pmp_expected * $valuetoshow;
1188 print '<td class="right">';
1189 print is_null($pmp_expected) ? '' : price($pmp_expected);
1190 print '<input type="hidden" name="expectedpmp_'.$obj->rowid.'" value="'.$pmp_expected.'"/>';
1191 print '</td>';
1192 print '<td class="right">';
1193 print price($pmp_valuation);
1194 print '</td>';
1195
1196 print '<td class="right">';
1197 print '<a id="undochangesqty_'.$obj->rowid.'" href="#" class="undochangesqty reposition marginrightonly" title="'.dol_escape_htmltag($langs->trans("Clear")).'">';
1198 print img_picto('', 'eraser', 'class="opacitymedium"');
1199 print '</a>';
1200 print '<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input" value="'.$qty_view.'">';
1201 print '</td>';
1202
1203 //PMP Real
1204 print '<td class="right">';
1205 if (!empty($obj->pmp_real) || (string) $obj->pmp_real === '0') {
1206 $pmp_real = $obj->pmp_real;
1207 } else {
1208 $pmp_real = $product_static->pmp;
1209 }
1210 $pmp_valuation_real = $pmp_real * $qty_view;
1211 print '<input type="text" class="maxwidth75 right realpmp'.$obj->fk_product.'" name="realpmp_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input_pmp" value="'.(is_null($pmp_real) ? '' : price2num($pmp_real)).'">';
1212 print '</td>';
1213 print '<td class="right">';
1214 print '<input type="text" class="maxwidth75 right realvaluation'.$obj->fk_product.'" name="realvaluation_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input_real_valuation" value="'.$pmp_valuation_real.'">';
1215 print '</td>';
1216
1217 $totalExpectedValuation += $pmp_valuation;
1218 $totalRealValuation += $pmp_valuation_real;
1219 } else {
1220 print '<td class="right">';
1221 print '<a id="undochangesqty_'.$obj->rowid.'" href="#" class="undochangesqty reposition marginrightonly" title="'.dol_escape_htmltag($langs->trans("Clear")).'">';
1222 print img_picto('', 'eraser', 'class="opacitymedium"');
1223 print '</a>';
1224 print '<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input" value="'.$qty_view.'">';
1225 print '</td>';
1226 }
1227
1228 // Picto delete line
1229 print '<td class="right">';
1230 if ($permissiontoupdatestock) {
1231 print '<a class="reposition" href="'.DOL_URL_ROOT.'/product/inventory/inventory.php?id='.$object->id.'&lineid='.$obj->rowid.'&action=deleteline&page='.$page.$paramwithsearch.'&token='.newToken().'">'.img_delete().'</a>';
1232 }
1233 $qty_tmp = price2num(GETPOST("id_".$obj->rowid."_input_tmp"), 'MS') >= 0 ? GETPOST("id_".$obj->rowid."_input_tmp") : $qty_view;
1234 print '<input type="hidden" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'_input_tmp" id="id_'.$obj->rowid.'_input_tmp" value="'.$qty_tmp.'">';
1235 print '</td>';
1236 } else {
1237 if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1238 // PMP Expected
1239 if (!empty($obj->pmp_expected)) {
1240 $pmp_expected = $obj->pmp_expected;
1241 } else {
1242 $pmp_expected = $product_static->pmp;
1243 }
1244 $pmp_valuation = $pmp_expected * $valuetoshow;
1245 print '<td class="right">';
1246 print is_null($pmp_expected) ? '' : price($pmp_expected);
1247 print '</td>';
1248 print '<td class="right">';
1249 print price($pmp_valuation);
1250 print '</td>';
1251
1252 print '<td class="right nowraponall">';
1253 print $obj->qty_view; // qty found
1254 print '</td>';
1255
1256 // PMP Real
1257 print '<td class="right">';
1258 if (!empty($obj->pmp_real)) {
1259 $pmp_real = $obj->pmp_real;
1260 } else {
1261 $pmp_real = $product_static->pmp;
1262 }
1263 $pmp_valuation_real = $pmp_real * $obj->qty_view;
1264 print is_null($pmp_real) ? '' : price($pmp_real);
1265 print '</td>';
1266 print '<td class="right">';
1267 print price($pmp_valuation_real);
1268 print '</td>';
1269 print '<td class="nowraponall right">';
1270
1271 $totalExpectedValuation += $pmp_valuation;
1272 $totalRealValuation += $pmp_valuation_real;
1273 } else {
1274 print '<td class="right nowraponall">';
1275 print $obj->qty_view; // qty found
1276 print '</td>';
1277 }
1278 print '<td>';
1279 if ($obj->fk_movement > 0) {
1280 $stockmovment = new MouvementStock($db);
1281 $stockmovment->fetch($obj->fk_movement);
1282 print $stockmovment->getNomUrl(1, 'movements');
1283 }
1284 print '</td>';
1285 }
1286 print '</tr>';
1287
1288 $i++;
1289 }
1290} else {
1291 dol_print_error($db);
1292}
1293if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1294 print '<tr class="liste_total">';
1295 print '<td colspan="4">'.$langs->trans("Total").'</td>';
1296 print '<td class="right" colspan="2">'.price($totalExpectedValuation).'</td>';
1297 print '<td class="right" id="totalRealValuation" colspan="3">'.price($totalRealValuation).'</td>';
1298 print '<td></td>';
1299 print '</tr>';
1300}
1301print '</table>';
1302
1303print '</div>';
1304
1305if ($object->status == $object::STATUS_VALIDATED) {
1306 print '<center><input id="submitrecord" type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'"></center>';
1307}
1308
1309print '</div>';
1310
1311
1312// Call method to disable the button if no qty entered yet for inventory
1313/*
1314if ($object->status != $object::STATUS_VALIDATED || !$hasinput) {
1315 print '<script type="text/javascript">
1316 jQuery(document).ready(function() {
1317 console.log("Call disablebuttonmakemovementandclose because status = '.((int) $object->status).' or $hasinput = '.((int) $hasinput).'");
1318 disablebuttonmakemovementandclose();
1319 });
1320 </script>';
1321}
1322*/
1323
1324print '</form>';
1325
1326print '<script type="text/javascript">
1327 $(document).ready(function() {
1328
1329 $(".paginationnext:last").click(function(e){
1330 var form = $("#formrecord");
1331 var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
1332 $.ajax({
1333 url: actionURL,
1334 data: form.serialize(),
1335 cache: false,
1336 success: function(result){
1337 window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page + 1).$paramwithsearch.'";
1338 }});
1339 return false;
1340 });
1341
1342
1343 $(".paginationprevious:last").click(function(e){
1344 var form = $("#formrecord");
1345 var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
1346 $.ajax({
1347 url: actionURL,
1348 data: form.serialize(),
1349 cache: false,
1350 success: function(result){
1351 window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page - 1).$paramwithsearch.'";
1352 }});
1353 return false;
1354 });
1355
1356 $("#idbuttonmakemovementandclose").click(function(e){
1357 var form = $("#formrecord");
1358 var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
1359 $.ajax({
1360 url: actionURL,
1361 type: "POST",
1362 data: form.serialize(),
1363 cache: false,
1364 success: function(result){
1365 window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'&action=record";
1366 }});
1367 return false;
1368 });
1369 });
1370</script>';
1371
1372
1373if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
1374 ?>
1375<script type="text/javascript">
1376$('.realqty').on('change', function () {
1377 let realqty = $(this).closest('tr').find('.realqty').val();
1378 let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
1379 let realpmp = $(inputPmp).val();
1380 if (!isNaN(realqty) && !isNaN(realpmp)) {
1381 let realval = realqty * realpmp;
1382 $(this).closest('tr').find('input[name^=realvaluation]').val(realval.toFixed(2));
1383 }
1384 updateTotalValuation();
1385});
1386
1387$('input[class*=realpmp]').on('change', function () {
1388 let inputQtyReal = $(this).closest('tr').find('.realqty');
1389 let realqty = $(inputQtyReal).val();
1390 let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
1391 console.log(inputPmp);
1392 let realPmpClassname = $(inputPmp).attr('class').match(/[\w-]*realpmp[\w-]*/g)[0];
1393 let realpmp = $(inputPmp).val();
1394 if (!isNaN(realpmp)) {
1395 $('.'+realPmpClassname).val(realpmp); //For batch case if pmp is changed we change it everywhere it's same product and calc back everything
1396
1397 if (!isNaN(realqty)) {
1398 let realval = realqty * realpmp;
1399 $(this).closest('tr').find('input[name^=realvaluation]').val(realval.toFixed(2));
1400 }
1401 $('.realqty').trigger('change');
1402 updateTotalValuation();
1403 }
1404});
1405
1406$('input[name^=realvaluation]').on('change', function () {
1407 let inputQtyReal = $(this).closest('tr').find('.realqty');
1408 let realqty = $(inputQtyReal).val();
1409 let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
1410 let inputRealValuation = $(this).closest('tr').find('input[name^=realvaluation]');
1411 let realPmpClassname = $(inputPmp).attr('class').match(/[\w-]*realpmp[\w-]*/g)[0];
1412 let realvaluation = $(inputRealValuation).val();
1413 if (!isNaN(realvaluation) && !isNaN(realqty) && realvaluation !== '' && realqty !== '' && realqty !== 0) {
1414 let realpmp = realvaluation / realqty
1415 $('.'+realPmpClassname).val(realpmp); //For batch case if pmp is changed we change it everywhere it's same product and calc back everything
1416 $('.realqty').trigger('change');
1417 updateTotalValuation();
1418 }
1419});
1420
1421function updateTotalValuation() {
1422 let total = 0;
1423 $('input[name^=realvaluation]').each(function( index ) {
1424 let val = $(this).val();
1425 if(!isNaN(val)) total += parseFloat($(this).val());
1426 });
1427 let currencyFractionDigits = new Intl.NumberFormat('fr-FR', {
1428 style: 'currency',
1429 currency: 'EUR',
1430 }).resolvedOptions().maximumFractionDigits;
1431 $('#totalRealValuation').html(total.toLocaleString('fr-FR', {
1432 maximumFractionDigits: currencyFractionDigits
1433 }));
1434}
1435
1436
1437</script>
1438 <?php
1439}
1440
1441// End of page
1442llxFooter();
1443$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$totalarray
Definition export.php:1216
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class permettant la generation de composants html autre Only common components are here.
Class with static methods for building HTML components related to products Only components common to ...
Class for Inventory.
Class InventoryLine.
Class to manage stock movements.
Class to manage products or services.
Class with list of lots and properties.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
currentToken()
Return the value of token currently saved into session with name 'token'.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='', $forcenowrapcolumntitle=0)
Get title line of an array.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $selectlimitsuffix='', $beforearrows='', $hidenavigation=0)
Function to show navigation arrows into lists.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
inventoryPrepareHead(&$inventory, $title='Inventory', $get='')
Define head array for tabs of inventory tools setup pages.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:132
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.