26require
'../../main.inc.php';
27include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formcompany.class.php';
28include_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
29include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
30include_once DOL_DOCUMENT_ROOT.
'/product/inventory/class/inventory.class.php';
31include_once DOL_DOCUMENT_ROOT.
'/product/inventory/lib/inventory.lib.php';
32include_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
33include_once DOL_DOCUMENT_ROOT.
'/product/stock/class/productlot.class.php';
36$langs->loadLangs(array(
"stocks",
"other",
"productbatch"));
41$action =
GETPOST(
'action',
'aZ09');
42$confirm =
GETPOST(
'confirm',
'alpha');
43$cancel =
GETPOST(
'cancel',
'aZ09');
44$contextpage =
GETPOST(
'contextpage',
'aZ') ?
GETPOST(
'contextpage',
'aZ') :
'inventorycard';
45$backtopage =
GETPOST(
'backtopage',
'alpha');
46$listoffset =
GETPOST(
'listoffset',
'alpha');
49if (empty($page) || $page == -1) {
52$offset = $limit * $page;
59$batch =
GETPOST(
'batch',
'alphanohtml');
60$totalExpectedValuation = 0;
61$totalRealValuation = 0;
62$hookmanager->initHooks(array(
'inventorycard'));
66 $result =
restrictedArea($user,
'stock', $id,
'',
'inventory_advance');
72$diroutputmassaction = $conf->stock->dir_output.
'/temp/massgeneration/'.$user->id;
76$extrafields->fetch_name_optionals_label(
$object->table_element);
78$search_array_options = $extrafields->getOptionalsFromPost(
$object->table_element,
'',
'search_');
81$search_all =
GETPOST(
"search_all",
'alpha');
83foreach (
$object->fields as $key => $val) {
84 if (
GETPOST(
'search_'.$key,
'alpha')) {
85 $search[$key] =
GETPOST(
'search_'.$key,
'alpha');
89if (empty($action) && empty($id) && empty($ref)) {
94include DOL_DOCUMENT_ROOT.
'/core/actions_fetchobject.inc.php';
102$paramwithsearch =
'';
103if ($limit > 0 && $limit != $conf->liste_limit) {
104 $paramwithsearch .=
'&limit='.((int) $limit);
109 $permissiontoadd = $user->hasRight(
'stock',
'creer');
110 $permissiontodelete = $user->hasRight(
'stock',
'supprimer');
111 $permissiontoupdatestock = $user->hasRight(
'stock',
'mouvement',
'creer');
113 $permissiontoadd = $user->hasRight(
'stock',
'inventory_advance',
'write');
114 $permissiontodelete = $user->hasRight(
'stock',
'inventory_advance',
'write');
115 $permissiontoupdatestock = $user->hasRight(
'stock',
'inventory_advance',
'write');
131$parameters = array();
132$reshook = $hookmanager->executeHooks(
'doActions', $parameters, $object, $action);
137if (empty($reshook)) {
140 if ($action ==
'cancel_record' && $permissiontoupdatestock) {
145 if ($action ==
'update' && $permissiontoupdatestock &&
$object->status == $object::STATUS_VALIDATED) {
149 $cacheOfProducts = array();
153 $sql =
'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
154 $sql .=
' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.pmp_real';
155 $sql .=
' FROM '.MAIN_DB_PREFIX.
'inventorydet as id';
156 $sql .=
' WHERE id.fk_inventory = '.((int)
$object->id);
157 $sql .=
' ORDER BY id.rowid';
159 $resql = $db->query($sql);
161 $num = $db->num_rows($resql);
163 $totalarray = array();
167 $line = $db->fetch_object($resql);
169 $qty_stock = $line->qty_stock;
170 $qty_view = $line->qty_view;
174 if (isset($cacheOfProducts[$line->fk_product])) {
175 $product_static = $cacheOfProducts[$line->fk_product];
177 $product_static =
new Product($db);
178 $result = $product_static->fetch($line->fk_product,
'',
'',
'', 1, 1, 1);
181 $option .=
',novirtual';
182 $product_static->load_stock($option);
184 $cacheOfProducts[$product_static->id] = $product_static;
188 $realqtynow = $product_static->stock_warehouse[$line->fk_warehouse]->real;
189 if (isModEnabled(
'productbatch') && $product_static->hasbatch()) {
190 $realqtynow = $product_static->stock_warehouse[$line->fk_warehouse]->detail_batch[$line->batch]->qty;
193 if (!is_null($qty_view)) {
194 $stock_movement_qty =
price2num($qty_view - $realqtynow,
'MS');
197 if ($stock_movement_qty != 0) {
198 if ($stock_movement_qty < 0) {
206 $inventorycode =
'INV-'.$object->ref;
209 $price = $line->pmp_real;
212 $idstockmove = $stockmovment->_create($user, $line->fk_product, $line->fk_warehouse, $stock_movement_qty, $movement_type, $price, $langs->trans(
'LabelOfInventoryMovemement',
$object->ref), $inventorycode, $datemovement,
'',
'', $line->batch);
213 if ($idstockmove < 0) {
220 $sqlupdate =
"UPDATE ".MAIN_DB_PREFIX.
"inventorydet";
221 $sqlupdate .=
" SET fk_movement = ".((int) $idstockmove);
222 if ($qty_stock != $realqtynow) {
223 $sqlupdate .=
", qty_stock = ".((float) $realqtynow);
225 $sqlupdate .=
" WHERE rowid = ".((int) $line->rowid);
226 $resqlupdate = $db->query($sqlupdate);
227 if (! $resqlupdate) {
235 $sqlpmp =
'UPDATE '.MAIN_DB_PREFIX.
'product SET pmp = '.((float) $line->pmp_real).
' WHERE rowid = '.((int) $line->fk_product);
236 $resqlpmp = $db->query($sqlpmp);
243 $sqlpmp =
'UPDATE '.MAIN_DB_PREFIX.
'product_perentity SET pmp = '.((float) $line->pmp_real).
' WHERE fk_product = '.((int) $line->fk_product).
' AND entity='.$conf->entity;
244 $resqlpmp = $db->query($sqlpmp);
272 if ($action ==
'updateinventorylines' && $permissiontoupdatestock) {
273 $sql =
'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
274 $sql .=
' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
275 $sql .=
' FROM '.MAIN_DB_PREFIX.
'inventorydet as id';
276 $sql .=
' WHERE id.fk_inventory = '.((int)
$object->id);
277 $sql .= $db->order(
'id.rowid',
'ASC');
278 $sql .= $db->plimit($limit, $offset);
282 $resql = $db->query($sql);
284 $num = $db->num_rows($resql);
286 $totalarray = array();
290 $line = $db->fetch_object($resql);
291 $lineid = $line->rowid;
296 if (
GETPOST(
"id_".$lineid,
'alpha') !=
'') {
298 $result = $inventoryline->fetch($lineid);
299 if ($qtytoupdate < 0) {
301 setEventMessages($langs->trans(
"FieldCannotBeNegative", $langs->transnoentitiesnoconv(
"RealQty")),
null,
'errors');
304 $inventoryline->qty_stock = (float)
price2num(
GETPOST(
'stock_qty_'.$lineid,
'alpha'),
'MS');
305 $inventoryline->qty_view = $qtytoupdate;
306 $inventoryline->pmp_real =
price2num(
GETPOST(
'realpmp_'.$lineid,
'alpha'),
'MS');
307 $inventoryline->pmp_expected =
price2num(
GETPOST(
'expectedpmp_'.$lineid,
'alpha'),
'MS');
308 $resultupdate = $inventoryline->update($user);
310 } elseif (GETPOSTISSET(
'id_' . $lineid)) {
312 $result = $inventoryline->fetch($lineid);
314 $inventoryline->qty_view =
null;
315 $inventoryline->pmp_real =
price2num(
GETPOST(
'realpmp_'.$lineid,
'alpha'),
'MS');
316 $inventoryline->pmp_expected =
price2num(
GETPOST(
'expectedpmp_'.$lineid,
'alpha'),
'MS');
317 $resultupdate = $inventoryline->update($user);
321 if ($result < 0 || $resultupdate < 0) {
331 $sqlupdate =
"UPDATE ".MAIN_DB_PREFIX.
"inventory";
332 $sqlupdate .=
" SET fk_user_modif = ".((int) $user->id);
333 $sqlupdate .=
" WHERE rowid = ".((int)
$object->id);
334 $resqlupdate = $db->query($sqlupdate);
335 if (! $resqlupdate) {
348 $backurlforlist = DOL_URL_ROOT.
'/product/inventory/list.php';
349 $backtopage = DOL_URL_ROOT.
'/product/inventory/inventory.php?id='.
$object->id.
'&page='.$page.$paramwithsearch;
352 include DOL_DOCUMENT_ROOT.
'/core/actions_addupdatedelete.inc.php';
355 include DOL_DOCUMENT_ROOT.
'/core/actions_dellink.inc.php';
358 include DOL_DOCUMENT_ROOT.
'/core/actions_printing.inc.php';
366 if (
GETPOST(
'addline',
'alpha')) {
368 if ($fk_warehouse <= 0) {
370 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Warehouse")),
null,
'errors');
372 if ($fk_product <= 0) {
374 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Product")),
null,
'errors');
378 setEventMessages($langs->trans(
"FieldCannotBeNegative", $langs->transnoentitiesnoconv(
"RealQty")),
null,
'errors');
380 if (!$error && isModEnabled(
'productbatch')) {
381 $tmpproduct =
new Product($db);
382 $result = $tmpproduct->fetch($fk_product);
384 if (empty($error) && $tmpproduct->status_batch > 0 && empty($batch)) {
386 $langs->load(
"errors");
387 setEventMessages($langs->trans(
"ErrorProductNeedBatchNumber", $tmpproduct->ref),
null,
'errors');
389 if (empty($error) && $tmpproduct->status_batch == 2 && !empty($batch) && $qty > 1) {
391 $langs->load(
"errors");
392 setEventMessages($langs->trans(
"TooManyQtyForSerialNumber", $tmpproduct->ref, $batch),
null,
'errors');
394 if (empty($error) && empty($tmpproduct->status_batch) && !empty($batch)) {
396 $langs->load(
"errors");
397 setEventMessages($langs->trans(
"ErrorProductDoesNotNeedBatchNumber", $tmpproduct->ref),
null,
'errors');
402 $tmp->fk_inventory =
$object->id;
403 $tmp->fk_warehouse = $fk_warehouse;
404 $tmp->fk_product = $fk_product;
405 $tmp->batch = $batch;
407 $tmp->qty_view = $qty;
409 $result = $tmp->create($user);
411 if ($db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
412 $langs->load(
"errors");
413 setEventMessages($langs->trans(
"ErrorRecordAlreadyExists"),
null,
'errors');
419 $_POST[
'batch'] =
'';
420 $_POST[
'qtytoadd'] =
'';
432$form =
new Form($db);
437llxHeader(
'', $langs->trans(
'Inventory'), $help_url,
'', 0, 0,
'',
'',
'',
'mod-product page-inventory_inventory');
446$res =
$object->fetch_optionals();
454if ($action ==
'delete') {
455 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id, $langs->trans(
'DeleteInventory'), $langs->trans(
'ConfirmDeleteOrder'),
'confirm_delete',
'', 0, 1);
458if ($action ==
'deleteline') {
459 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'&lineid='.$lineid.
'&page='.$page.$paramwithsearch, $langs->trans(
'DeleteLine'), $langs->trans(
'ConfirmDeleteLine'),
'confirm_deleteline',
'', 0, 1);
463if ($action ==
'clone') {
465 $formquestion = array();
466 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id, $langs->trans(
'ToClone'), $langs->trans(
'ConfirmCloneMyObject',
$object->ref),
'confirm_clone', $formquestion,
'yes', 1);
470if ($action ==
'record') {
471 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'&page='.$page.$paramwithsearch, $langs->trans(
'Close'), $langs->trans(
'ConfirmFinish'),
'update',
'', 0, 1);
476if ($action ==
'confirm_cancel') {
477 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id, $langs->trans(
'Cancel'), $langs->trans(
'ConfirmCancel'),
'cancel_record',
'', 0, 1);
481if ($action ==
'validate') {
482 $form =
new Form($db);
485 $formquestion = array(
486 array(
'type' =>
'checkbox',
'name' =>
'include_sub_warehouse',
'label' => $langs->trans(
"IncludeSubWarehouse"),
'value' => 1,
'size' =>
'10'),
488 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id, $langs->trans(
'ValidateInventory'), $langs->trans(
'IncludeSubWarehouseExplanation'),
'confirm_validate', $formquestion,
'', 1);
493$parameters = array(
'formConfirm' => $formconfirm,
'lineid' => $lineid);
494$reshook = $hookmanager->executeHooks(
'formConfirm', $parameters, $object, $action);
495if (empty($reshook)) {
496 $formconfirm .= $hookmanager->resPrint;
497} elseif ($reshook > 0) {
498 $formconfirm = $hookmanager->resPrint;
507$linkback =
'<a href="'.DOL_URL_ROOT.
'/product/inventory/list.php">'.$langs->trans(
"BackToList").
'</a>';
509$morehtmlref =
'<div class="refidno">';
549$morehtmlref .=
'</div>';
552dol_banner_tab($object,
'ref', $linkback, 1,
'ref',
'ref', $morehtmlref);
555print
'<div class="fichecenter">';
556print
'<div class="fichehalfleft">';
557print
'<div class="underbanner clearboth"></div>';
558print
'<table class="border centpercent tableforfield">'.
"\n";
561include DOL_DOCUMENT_ROOT.
'/core/tpl/commonfields_view.tpl.php';
564include DOL_DOCUMENT_ROOT.
'/core/tpl/extrafields_view.tpl.php';
572print
'<div class="clearboth"></div>';
576print
'<form id="formrecord" name="formrecord" method="POST" action="'.$_SERVER[
"PHP_SELF"].
'?page='.$page.
'&id='.
$object->id.
'">';
577print
'<input type="hidden" name="token" value="'.newToken().
'">';
578print
'<input type="hidden" name="action" value="updateinventorylines">';
579print
'<input type="hidden" name="id" value="'.$object->id.
'">';
581 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
586if ($action !=
'record') {
587 print
'<div class="tabsAction">'.
"\n";
588 $parameters = array();
589 $reshook = $hookmanager->executeHooks(
'addMoreActionsButtons', $parameters, $object, $action);
594 if (empty($reshook)) {
595 if (
$object->status == Inventory::STATUS_DRAFT) {
596 if ($permissiontoupdatestock) {
598 print
'<a class="butAction" href="'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&action=validate&token='.
newToken().
'">'.$langs->trans(
"Validate").
' ('.$langs->trans(
"Start").
')</a>';
600 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>';
603 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans(
"NotEnoughPermissions")).
'">'.$langs->trans(
'Validate').
' ('.$langs->trans(
"Start").
')</a>'.
"\n";
608 if (
$object->status == $object::STATUS_VALIDATED) {
609 if ($permissiontoupdatestock) {
610 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";
612 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans(
"NotEnoughPermissions")).
'">'.$langs->trans(
'MakeMovementsAndClose').
'</a>'.
"\n";
615 if ($permissiontoupdatestock) {
616 print
'<a class="butActionDelete" href="'.$_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'&action=confirm_cancel&page='.$page.$paramwithsearch.
'&token='.
newToken().
'">'.$langs->trans(
"Cancel").
'</a>'.
"\n";
622 if (
$object->status != Inventory::STATUS_DRAFT &&
$object->status != Inventory::STATUS_VALIDATED) {
629if (
$object->status == Inventory::STATUS_VALIDATED) {
631 if (!empty($conf->use_javascript_ajax)) {
632 if ($permissiontoupdatestock) {
634 if (isModEnabled(
'barcode') || isModEnabled(
'productbatch')) {
635 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>';
639 print
'<a id="fillwithexpected" class="marginrightonly paddingright marginleftonly paddingleft" href="#">'.img_picto(
'',
'autofill',
'class="paddingrightonly"').$langs->trans(
'AutofillWithExpected').
'</a>';
641 print
'$( document ).ready(function() {';
642 print
' $("#fillwithexpected").on("click",function fillWithExpected(){
643 $(".expectedqty").each(function(){
644 var object = $(this)[0];
645 var objecttofill = $("#"+object.id+"_input")[0];
646 objecttofill.value = object.innerText;
647 jQuery(".realqty").trigger("change");
649 console.log("Values filled (after click on fillwithexpected)");
650 /* disablebuttonmakemovementandclose(); */
657 print
'<a href="#" id="clearqty" class="marginrightonly paddingright marginleftonly paddingleft">'.img_picto(
'',
'eraser',
'class="paddingrightonly"').$langs->trans(
"ClearQtys").
'</a>';
659 print
'<a class="classfortooltip marginrightonly paddingright marginleftonly paddingleft" href="#" title="'.dol_escape_htmltag($langs->trans(
"NotEnoughPermissions")).
'">'.$langs->trans(
"Save").
'</a>'.
"\n";
669if ($action ==
'updatebyscaning') {
670 if ($permissiontoupdatestock) {
675 var duplicatedbatchcode = [];
681 function barcodescannerjs(){
682 console.log("We catch inputs in scanner box");
683 jQuery("#scantoolmessage").text();
685 var selectaddorreplace = $("select[name=selectaddorreplace]").val();
686 var barcodemode = $("input[name=barcodemode]:checked").val();
687 var barcodeproductqty = $("input[name=barcodeproductqty]").val();
688 var textarea = $("textarea[name=barcodelist]").val();
689 var textarray = textarea.split(/[\s,;]+/);
691 duplicatedbatchcode = [];
697 textarray = textarray.filter(function(value){
700 if(textarray.some((element) => element != "")){
701 $(".expectedqty").each(function(){
703 console.log("Analyze the line "+id+" in inventory, barcodemode="+barcodemode);
704 warehouse = $("#"+id+"_warehouse").attr(\'data-ref\');
705 //console.log(warehouse);
706 productbarcode = $("#"+id+"_product").attr(\'data-barcode\');
707 //console.log(productbarcode);
708 productbatchcode = $("#"+id+"_batch").attr(\'data-batch\');
709 //console.log(productbatchcode);
711 if (barcodemode != "barcodeforproduct") {
712 tabproduct.forEach(product=>{
713 console.log("product.Batch="+product.Batch+" productbatchcode="+productbatchcode);
714 if(product.Batch != "" && product.Batch == productbatchcode){
715 console.log("duplicate batch code found for batch code "+productbatchcode);
716 duplicatedbatchcode.push(productbatchcode);
720 productinput = $("#"+id+"_input").val();
721 if(productinput == ""){
724 tabproduct.push({\'Id\':id,\'Warehouse\':warehouse,\'Barcode\':productbarcode,\'Batch\':productbatchcode,\'Qty\':productinput,\'fetched\':false});
727 console.log("Loop on each record entered in the textarea");
728 textarray.forEach(function(element,index){
729 console.log("Process record element="+element+" id="+id);
730 var verify_batch = false;
731 var verify_barcode = false;
733 case "barcodeforautodetect":
734 verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode",true);
735 verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial",true);
737 case "barcodeforproduct":
738 verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode");
740 case "barcodeforlotserial":
741 verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial");
744 alert(\''.dol_escape_js($langs->trans(
"ErrorWrongBarcodemode")).
' "\'+barcodemode+\'"\');
745 throw \''.
dol_escape_js($langs->trans(
'ErrorWrongBarcodemode')).
' "\'+barcodemode+\'"\';
748 if (verify_batch == false && verify_barcode == false) { /* If the 2 flags are false, not found error */
749 errortab2.push(element);
750 } else if (verify_batch == true && verify_barcode == true) { /* If the 2 flags are true, error: we don t know which one to take */
751 errortab3.push(element);
752 } else if (verify_batch == true) {
753 console.log("element="+element);
754 console.log(duplicatedbatchcode);
755 if (duplicatedbatchcode.includes(element)) {
756 errortab1.push(element);
761 if (Object.keys(errortab1).length < 1 && Object.keys(errortab2).length < 1 && Object.keys(errortab3).length < 1) {
762 tabproduct.forEach(product => {
764 console.log("We change #"+product.Id+"_input to match input in scanner box");
765 if(product.hasOwnProperty("reelqty")){
766 $.ajax({ url: \''.DOL_URL_ROOT.
'/product/inventory/ajax/searchfrombarcode.php\',
767 data: { "token":"'.
newToken().
'", "action":"addnewlineproduct", "fk_entrepot":product.Warehouse, "batch":product.Batch, "fk_inventory":'.
dol_escape_js(
$object->id).
', "fk_product":product.fk_product, "reelqty":product.reelqty},
770 success: function(response) {
771 response = JSON.parse(response);
772 if(response.status == "success"){
773 console.log(response.message);
774 $("<input type=\'text\' value=\'"+product.Qty+"\' />")
775 .attr("id", "id_"+response.id_line+"_input")
776 .attr("name", "id_"+response.id_line)
777 .appendTo("#formrecord");
779 console.error(response.message);
782 error : function(output) {
783 console.error("Error on line creation function");
787 $("#"+product.Id+"_input").val(product.Qty);
791 jQuery("#scantoolmessage").text("'.
dol_escape_js($langs->transnoentities(
"QtyWasAddedToTheScannedBarcode")).
'\n");
792 /* document.forms["formrecord"].submit(); */
794 let stringerror = "";
795 if (Object.keys(errortab1).length > 0) {
796 stringerror += "<br>'.
dol_escape_js($langs->transnoentities(
'ErrorSameBatchNumber')).
': ";
797 errortab1.forEach(element => {
798 stringerror += (element + ", ")
800 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
802 if (Object.keys(errortab2).length > 0) {
803 stringerror += "<br>'.
dol_escape_js($langs->transnoentities(
'ErrorCantFindCodeInInventory')).
': ";
804 errortab2.forEach(element => {
805 stringerror += (element + ", ")
807 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
809 if (Object.keys(errortab3).length > 0) {
810 stringerror += "<br>'.
dol_escape_js($langs->transnoentities(
'ErrorCodeScannedIsBothProductAndSerial')).
': ";
811 errortab3.forEach(element => {
812 stringerror += (element + ", ")
814 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
816 if (Object.keys(errortab4).length > 0) {
817 stringerror += "<br>'.
dol_escape_js($langs->transnoentities(
'ErrorBarcodeNotFoundForProductWarehouse')).
': ";
818 errortab4.forEach(element => {
819 stringerror += (element + ", ")
821 stringerror = stringerror.slice(0, -2); /* Remove last ", " */
824 jQuery("#scantoolmessage").html(\''.
dol_escape_js($langs->transnoentities(
"ErrorOnElementsInventory")).
'\' + stringerror);
832 function barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,mode,autodetect=
false){
833 BarcodeIsInProduct=0;
836 tabproduct.forEach(product => {
837 $.ajax({ url: \
''.DOL_URL_ROOT.
'/product/inventory/ajax/searchfrombarcode.php\',
838 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},
841 success: function(response) {
842 response = JSON.parse(response);
843 if (response.status == "success"){
844 console.log(response.message);
846 newproductrow = response.object;
849 if (mode!="lotserial" && autodetect==false && !errortab4.includes(element)){
850 errortab4.push(element);
851 console.error(response.message);
855 error : function(output) {
856 console.error("Error on barcodeserialforproduct function");
859 console.log("Product "+(index+=1)+": "+element);
860 if(mode == "barcode"){
861 testonproduct = product.Barcode
862 }else if (mode == "lotserial"){
863 testonproduct = product.Batch
865 if(testonproduct == element){
866 if(selectaddorreplace == "add"){
867 productqty = parseInt(product.Qty,10);
868 product.Qty = productqty + parseInt(barcodeproductqty,10);
869 }else if(selectaddorreplace == "replace"){
870 if(product.fetched == false){
871 product.Qty = barcodeproductqty
874 productqty = parseInt(product.Qty,10);
875 product.Qty = productqty + parseInt(barcodeproductqty,10);
878 BarcodeIsInProduct+=1;
881 if(BarcodeIsInProduct==0 && newproductrow!=0){
882 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});
885 if(BarcodeIsInProduct > 0){
893 include DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
895 print $formother->getHTMLScannerForm(
"barcodescannerjs",
'all');
900print
'jQuery(document).ready(function() {
901 $("#clearqty").on("click", function() {
902 console.log("Clear all values");
903 /* disablebuttonmakemovementandclose(); */
904 jQuery(".realqty").val("");
905 jQuery(".realqty").trigger("change");
906 return false; /* disable submit */
908 $(".undochangesqty").on("click", function undochangesqty() {
909 console.log("Clear value of inventory line");
911 id = id.split("_")[1];
912 tmpvalue = $("#id_"+id+"_input_tmp").val()
913 $("#id_"+id+"_input")[0].value = tmpvalue;
914 /* disablebuttonmakemovementandclose(); */
915 return false; /* disable submit */
920print
'<div class="fichecenter">';
922print
'<div class="clearboth"></div>';
926print
'<div class="div-table-responsive-no-min">';
927print
'<table id="tablelines" class="noborder noshadow centpercent">';
929print
'<tr class="liste_titre">';
930print
'<td>'.$langs->trans(
"Warehouse").
'</td>';
931print
'<td>'.$langs->trans(
"Product").
'</td>';
932if (isModEnabled(
'productbatch')) {
934 print $langs->trans(
"Batch");
937if (
$object->status == $object::STATUS_DRAFT ||
$object->status == $object::STATUS_VALIDATED) {
939 print
'<td class="right">'.$form->textwithpicto($langs->trans(
"ExpectedQty"), $langs->trans(
"QtyCurrentlyKnownInStock")).
'</td>';
942 print
'<td class="right">'.$form->textwithpicto($langs->trans(
"ExpectedQty"), $langs->trans(
"QtyInStockWhenInventoryWasValidated")).
'</td>';
945 print
'<td class="right">'.$langs->trans(
'PMPExpected').
'</td>';
946 print
'<td class="right">'.$langs->trans(
'ExpectedValuation').
'</td>';
947 print
'<td class="right">'.$form->textwithpicto($langs->trans(
"RealQty"), $langs->trans(
"InventoryRealQtyHelp")).
'</td>';
948 print
'<td class="right">'.$langs->trans(
'PMPReal').
'</td>';
949 print
'<td class="right">'.$langs->trans(
'RealValuation').
'</td>';
951 print
'<td class="right">';
952 print $form->textwithpicto($langs->trans(
"RealQty"), $langs->trans(
"InventoryRealQtyHelp"));
955if (
$object->status == $object::STATUS_DRAFT ||
$object->status == $object::STATUS_VALIDATED) {
957 print
'<td class="center">';
961 print
'<td class="right">';
968if (
$object->status == $object::STATUS_DRAFT ||
$object->status == $object::STATUS_VALIDATED) {
971 print $formproduct->selectWarehouses((GETPOSTISSET(
'fk_warehouse') ?
GETPOSTINT(
'fk_warehouse') :
$object->fk_warehouse),
'fk_warehouse',
'warehouseopen', 1, 0, 0,
'', 0, 0, array(),
'maxwidth300');
979 print $form->select_produits((GETPOSTISSET(
'fk_product') ?
GETPOSTINT(
'fk_product') :
$object->fk_product),
'fk_product', $filtertype, 0, 0, -1, 2,
'', 0, null, 0,
'1', 0,
'maxwidth300');
981 if (isModEnabled(
'productbatch')) {
983 print
'<input type="text" name="batch" class="maxwidth100" value="'.(GETPOSTISSET(
'batch') ?
GETPOST(
'batch') :
'').
'">';
986 print
'<td class="right"></td>';
988 print
'<td class="right">';
990 print
'<td class="right">';
992 print
'<td class="right">';
993 print
'<input type="text" name="qtytoadd" class="maxwidth75" value="">';
995 print
'<td class="right">';
997 print
'<td class="right">';
1000 print
'<td class="right">';
1001 print
'<input type="text" name="qtytoadd" class="maxwidth75" value="">';
1005 print
'<td class="center">';
1006 if ($permissiontoupdatestock) {
1007 print
'<input type="submit" class="button paddingright" name="addline" value="'.$langs->trans(
"Add").
'">';
1009 print
'<input type="submit" class="button paddingright" disabled="disabled" title="'.dol_escape_htmltag($langs->trans(
"NotEnoughPermissions")).
'" name="addline" value="'.$langs->trans(
"Add").
'">';
1016$sql =
'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
1017$sql .=
' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.fk_movement, id.pmp_real, id.pmp_expected';
1018$sql .=
' FROM '.MAIN_DB_PREFIX.
'inventorydet as id';
1019$sql .=
' WHERE id.fk_inventory = '.((int)
$object->id);
1020$sql .= $db->order(
'id.rowid',
'ASC');
1021$sql .= $db->plimit($limit, $offset);
1023$cacheOfProducts = array();
1024$cacheOfWarehouses = array();
1027$resql = $db->query($sql);
1029 $num = $db->num_rows($resql);
1031 if (!empty($limit != 0) || $num > $limit || $page) {
1032 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);
1037 $totalarray = array();
1039 $obj = $db->fetch_object($resql);
1041 if (isset($cacheOfWarehouses[$obj->fk_warehouse])) {
1042 $warehouse_static = $cacheOfWarehouses[$obj->fk_warehouse];
1044 $warehouse_static =
new Entrepot($db);
1045 $warehouse_static->fetch($obj->fk_warehouse);
1047 $cacheOfWarehouses[$warehouse_static->id] = $warehouse_static;
1052 if (isset($cacheOfProducts[$obj->fk_product])) {
1053 $product_static = $cacheOfProducts[$obj->fk_product];
1055 $product_static =
new Product($db);
1056 $result = $product_static->fetch($obj->fk_product,
'',
'',
'', 1, 1, 1);
1059 $option .=
',novirtual';
1060 $product_static->load_stock($option);
1062 $cacheOfProducts[$product_static->id] = $product_static;
1065 print
'<tr class="oddeven">';
1066 print
'<td id="id_'.$obj->rowid.
'_warehouse" data-ref="'.
dol_escape_htmltag($warehouse_static->ref).
'">';
1067 print $warehouse_static->getNomUrl(1);
1070 print $product_static->getNomUrl(1).
' - '.$product_static->label;
1073 if (isModEnabled(
'productbatch')) {
1074 print
'<td id="id_'.$obj->rowid.
'_batch" data-batch="'.
dol_escape_htmltag($obj->batch).
'">';
1077 $res = $batch_static->fetch(0, $product_static->id, $obj->batch);
1079 print $batch_static->getNomUrl(1);
1088 print
'<td class="right expectedqty" id="id_'.$obj->rowid.
'" title="Stock viewed at last update: '.$obj->qty_stock.
'">';
1089 $valuetoshow = $obj->qty_stock;
1091 if (
$object->status == $object::STATUS_DRAFT ||
$object->status == $object::STATUS_VALIDATED) {
1092 if (isModEnabled(
'productbatch') && $product_static->hasbatch()) {
1093 $valuetoshow = $product_static->stock_warehouse[$obj->fk_warehouse]->detail_batch[$obj->batch]->qty ?? 0;
1095 $valuetoshow = $product_static->stock_warehouse[$obj->fk_warehouse]->real ?? 0;
1099 print
'<input type="hidden" name="stock_qty_'.$obj->rowid.
'" value="'.$valuetoshow.
'">';
1103 if (
$object->status == $object::STATUS_DRAFT ||
$object->status == $object::STATUS_VALIDATED) {
1107 if ($qty_view !=
'') {
1113 if (!empty($obj->pmp_expected)) {
1114 $pmp_expected = $obj->pmp_expected;
1116 $pmp_expected = $product_static->pmp;
1118 $pmp_valuation = $pmp_expected * $valuetoshow;
1119 print
'<td class="right">';
1120 print
price($pmp_expected);
1121 print
'<input type="hidden" name="expectedpmp_'.$obj->rowid.
'" value="'.$pmp_expected.
'"/>';
1123 print
'<td class="right">';
1124 print
price($pmp_valuation);
1127 print
'<td class="right">';
1128 print
'<a id="undochangesqty_'.$obj->rowid.
'" href="#" class="undochangesqty reposition marginrightonly" title="'.
dol_escape_htmltag($langs->trans(
"Clear")).
'">';
1129 print
img_picto(
'',
'eraser',
'class="opacitymedium"');
1131 print
'<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.
'" id="id_'.$obj->rowid.
'_input" value="'.$qty_view.
'">';
1135 print
'<td class="right">';
1136 if (!empty($obj->pmp_real) || (
string) $obj->pmp_real ===
'0') {
1137 $pmp_real = $obj->pmp_real;
1139 $pmp_real = $product_static->pmp;
1141 $pmp_valuation_real = $pmp_real * $qty_view;
1142 print
'<input type="text" class="maxwidth75 right realpmp'.$obj->fk_product.
'" name="realpmp_'.$obj->rowid.
'" id="id_'.$obj->rowid.
'_input_pmp" value="'.
price2num($pmp_real).
'">';
1144 print
'<td class="right">';
1145 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.
'">';
1148 $totalExpectedValuation += $pmp_valuation;
1149 $totalRealValuation += $pmp_valuation_real;
1151 print
'<td class="right">';
1152 print
'<a id="undochangesqty_'.$obj->rowid.
'" href="#" class="undochangesqty reposition marginrightonly" title="'.
dol_escape_htmltag($langs->trans(
"Clear")).
'">';
1153 print
img_picto(
'',
'eraser',
'class="opacitymedium"');
1155 print
'<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.
'" id="id_'.$obj->rowid.
'_input" value="'.$qty_view.
'">';
1160 print
'<td class="right">';
1161 if ($permissiontoupdatestock) {
1162 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>';
1164 $qty_tmp =
price2num(
GETPOST(
"id_".$obj->rowid.
"_input_tmp",
'MS')) >= 0 ?
GETPOST(
"id_".$obj->rowid.
"_input_tmp") : $qty_view;
1165 print
'<input type="hidden" class="maxwidth50 right realqty" name="id_'.$obj->rowid.
'_input_tmp" id="id_'.$obj->rowid.
'_input_tmp" value="'.$qty_tmp.
'">';
1170 if (!empty($obj->pmp_expected)) {
1171 $pmp_expected = $obj->pmp_expected;
1173 $pmp_expected = $product_static->pmp;
1175 $pmp_valuation = $pmp_expected * $valuetoshow;
1176 print
'<td class="right">';
1177 print
price($pmp_expected);
1179 print
'<td class="right">';
1180 print
price($pmp_valuation);
1183 print
'<td class="right nowraponall">';
1184 print $obj->qty_view;
1188 print
'<td class="right">';
1189 if (!empty($obj->pmp_real)) {
1190 $pmp_real = $obj->pmp_real;
1192 $pmp_real = $product_static->pmp;
1194 $pmp_valuation_real = $pmp_real * $obj->qty_view;
1195 print
price($pmp_real);
1197 print
'<td class="right">';
1198 print
price($pmp_valuation_real);
1200 print
'<td class="nowraponall right">';
1202 $totalExpectedValuation += $pmp_valuation;
1203 $totalRealValuation += $pmp_valuation_real;
1205 print
'<td class="right nowraponall">';
1206 print $obj->qty_view;
1210 if ($obj->fk_movement > 0) {
1212 $stockmovment->fetch($obj->fk_movement);
1213 print $stockmovment->getNomUrl(1,
'movements');
1225 print
'<tr class="liste_total">';
1226 print
'<td colspan="4">'.$langs->trans(
"Total").
'</td>';
1227 print
'<td class="right" colspan="2">'.price($totalExpectedValuation).
'</td>';
1228 print
'<td class="right" id="totalRealValuation" colspan="3">'.price($totalRealValuation).
'</td>';
1236if (
$object->status == $object::STATUS_VALIDATED) {
1237 print
'<center><input id="submitrecord" type="submit" class="button button-save" name="save" value="'.$langs->trans(
"Save").
'"></center>';
1257print
'<script type="text/javascript">
1258 $(document).ready(function() {
1260 $(".paginationnext:last").click(function(e){
1261 var form = $("#formrecord");
1262 var actionURL = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page).$paramwithsearch.
'";
1265 data: form.serialize(),
1267 success: function(result){
1268 window.location.href = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page + 1).$paramwithsearch.
'";
1273 $(".paginationprevious:last").click(function(e){
1274 var form = $("#formrecord");
1275 var actionURL = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page).$paramwithsearch.
'";
1278 data: form.serialize(),
1280 success: function(result){
1281 window.location.href = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page - 1).$paramwithsearch.
'";
1285 $("#idbuttonmakemovementandclose").click(function(e){
1286 var form = $("#formrecord");
1287 var actionURL = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page).$paramwithsearch.
'";
1290 data: form.serialize(),
1292 success: function(result){
1293 window.location.href = "'.$_SERVER[
'PHP_SELF'].
'?id='.
$object->id.
'&page='.($page - 1).$paramwithsearch.
'&action=record";
1302<script
type=
"text/javascript">
1303$(
'.realqty').on(
'change',
function () {
1304 let realqty = $(
this).closest(
'tr').find(
'.realqty').val();
1305 let inputPmp = $(
this).closest(
'tr').find(
'input[class*=realpmp]');
1306 let realpmp = $(inputPmp).val();
1307 if (!isNaN(realqty) && !isNaN(realpmp)) {
1308 let realval = realqty * realpmp;
1309 $(
this).closest(
'tr').find(
'input[name^=realvaluation]').val(realval.toFixed(2));
1311 updateTotalValuation();
1314$(
'input[class*=realpmp]').on(
'change',
function () {
1315 let inputQtyReal = $(
this).closest(
'tr').find(
'.realqty');
1316 let realqty = $(inputQtyReal).val();
1317 let inputPmp = $(
this).closest(
'tr').find(
'input[class*=realpmp]');
1318 console.log(inputPmp);
1319 let realPmpClassname = $(inputPmp).attr(
'class').match(/[\w-]*realpmp[\w-]*/g)[0];
1320 let realpmp = $(inputPmp).val();
1321 if (!isNaN(realpmp)) {
1322 $(
'.'+realPmpClassname).val(realpmp);
1324 if (!isNaN(realqty)) {
1325 let realval = realqty * realpmp;
1326 $(
this).closest(
'tr').find(
'input[name^=realvaluation]').val(realval.toFixed(2));
1328 $(
'.realqty').trigger(
'change');
1329 updateTotalValuation();
1333$(
'input[name^=realvaluation]').on(
'change',
function () {
1334 let inputQtyReal = $(
this).closest(
'tr').find(
'.realqty');
1335 let realqty = $(inputQtyReal).val();
1336 let inputPmp = $(
this).closest(
'tr').find(
'input[class*=realpmp]');
1337 let inputRealValuation = $(
this).closest(
'tr').find(
'input[name^=realvaluation]');
1338 let realPmpClassname = $(inputPmp).attr(
'class').match(/[\w-]*realpmp[\w-]*/g)[0];
1339 let realvaluation = $(inputRealValuation).val();
1340 if (!isNaN(realvaluation) && !isNaN(realqty) && realvaluation !==
'' && realqty !==
'' && realqty !== 0) {
1341 let realpmp = realvaluation / realqty
1342 $(
'.'+realPmpClassname).val(realpmp);
1343 $(
'.realqty').trigger(
'change');
1344 updateTotalValuation();
1348function updateTotalValuation() {
1350 $(
'input[name^=realvaluation]').each(
function( index ) {
1351 let val = $(
this).val();
1352 if(!isNaN(val)) total += parseFloat($(
this).val());
1354 let currencyFractionDigits =
new Intl.NumberFormat(
'fr-FR', {
1357 }).resolvedOptions().maximumFractionDigits;
1358 $(
'#totalRealValuation').html(total.toLocaleString(
'fr-FR', {
1359 maximumFractionDigits: currencyFractionDigits
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
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.
Class to manage warehouses.
Class to manage stock movements.
Class to manage products or services.
Class with list of lots and properties.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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)
Show tabs of a record.
print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0, $beforearrows='', $hidenavigation=0)
Function to show navigation arrows into lists.
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.
dol_now($mode='auto')
Return date for now.
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'.
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...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
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.