PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/product/inventory/inventory.php

http://github.com/Dolibarr/dolibarr
PHP | 817 lines | 580 code | 117 blank | 120 comment | 125 complexity | df72b12499321e91c0cde59c0adfc5a7 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-3.0, LGPL-2.0, CC-BY-SA-4.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, MIT
  1. <?php
  2. /* Copyright (C) 2019 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/product/inventory/inventory.php
  19. * \ingroup inventory
  20. * \brief Tabe to enter counting
  21. */
  22. require '../../main.inc.php';
  23. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  24. include_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  25. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  26. include_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
  27. include_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
  28. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  29. // Load translation files required by the page
  30. $langs->loadLangs(array("stocks", "other", "productbatch"));
  31. // Get parameters
  32. $id = GETPOST('id', 'int');
  33. $ref = GETPOST('ref', 'alpha');
  34. $action = GETPOST('action', 'aZ09');
  35. $confirm = GETPOST('confirm', 'alpha');
  36. $cancel = GETPOST('cancel', 'aZ09');
  37. $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search
  38. $backtopage = GETPOST('backtopage', 'alpha');
  39. $fk_warehouse = GETPOST('fk_warehouse', 'int');
  40. $fk_product = GETPOST('fk_product', 'int');
  41. $lineid = GETPOST('lineid', 'int');
  42. $batch = GETPOST('batch', 'alphanohtml');
  43. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
  44. $result = restrictedArea($user, 'stock', $id);
  45. } else {
  46. $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance');
  47. }
  48. // Initialize technical objects
  49. $object = new Inventory($db);
  50. $extrafields = new ExtraFields($db);
  51. $diroutputmassaction = $conf->stock->dir_output.'/temp/massgeneration/'.$user->id;
  52. $hookmanager->initHooks(array('inventorycard')); // Note that conf->hooks_modules contains array
  53. // Fetch optionals attributes and labels
  54. $extrafields->fetch_name_optionals_label($object->table_element);
  55. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  56. // Initialize array of search criterias
  57. $search_all = GETPOST("search_all", 'alpha');
  58. $search = array();
  59. foreach ($object->fields as $key => $val) {
  60. if (GETPOST('search_'.$key, 'alpha')) {
  61. $search[$key] = GETPOST('search_'.$key, 'alpha');
  62. }
  63. }
  64. if (empty($action) && empty($id) && empty($ref)) {
  65. $action = 'view';
  66. }
  67. // Load object
  68. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
  69. // Security check - Protection if external user
  70. //if ($user->socid > 0) accessforbidden();
  71. //if ($user->socid > 0) $socid = $user->socid;
  72. //$result = restrictedArea($user, 'mymodule', $id);
  73. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
  74. $permissiontoadd = $user->rights->stock->creer;
  75. $permissiontodelete = $user->rights->stock->supprimer;
  76. } else {
  77. $permissiontoadd = $user->rights->stock->inventory_advance->write;
  78. $permissiontodelete = $user->rights->stock->inventory_advance->write;
  79. }
  80. $now = dol_now();
  81. /*
  82. * Actions
  83. */
  84. if ($cancel) {
  85. $action = '';
  86. }
  87. if ($action == 'cancel_record' && $permissiontoadd) {
  88. $object->setCanceled($user);
  89. }
  90. if ($action == 'update' && !empty($user->rights->stock->mouvement->creer)) {
  91. $stockmovment = new MouvementStock($db);
  92. $stockmovment->setOrigin($object->element, $object->id);
  93. $db->begin();
  94. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  95. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
  96. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  97. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  98. $resql = $db->query($sql);
  99. if ($resql) {
  100. $num = $db->num_rows($resql);
  101. $i = 0;
  102. $totalarray = array();
  103. while ($i < $num) {
  104. $line = $db->fetch_object($resql);
  105. $qty_stock = $line->qty_stock;
  106. $qty_view = $line->qty_view; // The quantity viewed by inventorier, the qty we target
  107. if (!is_null($qty_view)) {
  108. $stock_movement_qty = price2num($qty_view - $qty_stock, 'MS');
  109. if ($stock_movement_qty != 0) {
  110. if ($stock_movement_qty < 0) {
  111. $movement_type = 1;
  112. } else {
  113. $movement_type = 0;
  114. }
  115. $datemovement = '';
  116. $idstockmove = $stockmovment->_create($user, $line->fk_product, $line->fk_warehouse, $stock_movement_qty, $movement_type, 0, $langs->trans('LabelOfInventoryMovemement', $object->id), 'INV'.$object->id, $datemovement, '', '', $line->batch);
  117. if ($idstockmove < 0) {
  118. $error++;
  119. setEventMessages($stockmovment->error, $stockmovment->errors, 'errors');
  120. break;
  121. }
  122. }
  123. }
  124. $i++;
  125. }
  126. if (!$error) {
  127. $object->setRecorded($user);
  128. }
  129. } else {
  130. setEventMessages($db->lasterror, null, 'errors');
  131. $error++;
  132. }
  133. if (! $error) {
  134. $db->commit();
  135. } else {
  136. $db->rollback();
  137. }
  138. }
  139. if ($action =='updateinventorylines' && $permissiontoadd) {
  140. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  141. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
  142. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  143. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  144. $db->begin();
  145. $resql = $db->query($sql);
  146. if ($resql) {
  147. $num = $db->num_rows($resql);
  148. $i = 0;
  149. $totalarray = array();
  150. $inventoryline = new InventoryLine($db);
  151. while ($i < $num) {
  152. $line = $db->fetch_object($resql);
  153. $lineid = $line->rowid;
  154. if (GETPOST("id_".$lineid, 'alpha') != '') { // If a value was set ('0' or something else)
  155. $qtytoupdate = price2num(GETPOST("id_".$lineid, 'alpha'), 'MS');
  156. $result = $inventoryline->fetch($lineid);
  157. if ($qtytoupdate < 0) {
  158. $result = -1;
  159. setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
  160. }
  161. if ($result > 0) {
  162. $inventoryline->qty_view = $qtytoupdate;
  163. $resultupdate = $inventoryline->update($user);
  164. }
  165. } else {
  166. // Delete record
  167. $result = $inventoryline->fetch($lineid);
  168. if ($result > 0) {
  169. $inventoryline->qty_view = null;
  170. $resultupdate = $inventoryline->update($user);
  171. }
  172. }
  173. if ($result < 0 || $resultupdate < 0) {
  174. $error++;
  175. }
  176. $i++;
  177. }
  178. }
  179. if (!$error) {
  180. $db->commit();
  181. } else {
  182. $db->rollback();
  183. }
  184. }
  185. $parameters = array();
  186. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  187. if ($reshook < 0) {
  188. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  189. }
  190. if (empty($reshook)) {
  191. $error = 0;
  192. $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php';
  193. $backtopage = DOL_URL_ROOT.'/product/inventory/inventory.php?id='.$object->id;
  194. // Actions cancel, add, update, delete or clone
  195. include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
  196. // Actions when linking object each other
  197. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
  198. // Actions when printing a doc from card
  199. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  200. // Actions to send emails
  201. /*$triggersendname = 'MYOBJECT_SENTBYMAIL';
  202. $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
  203. $trackid='stockinv'.$object->id;
  204. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';*/
  205. if (GETPOST('addline', 'alpha')) {
  206. if ($fk_warehouse <= 0) {
  207. $error++;
  208. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  209. }
  210. if ($fk_product <= 0) {
  211. $error++;
  212. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
  213. }
  214. if (price2num(GETPOST('qtytoadd'), 'MS') < 0) {
  215. $error++;
  216. setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
  217. }
  218. if (!$error && !empty($conf->productbatch->enabled)) {
  219. $tmpproduct = new Product($db);
  220. $result = $tmpproduct->fetch($fk_product);
  221. if (!$error && $tmpproduct->status_batch && !$batch) {
  222. $error++;
  223. $langs->load("errors");
  224. setEventMessages($langs->trans("ErrorProductNeedBatchNumber", $tmpproduct->ref), null, 'errors');
  225. }
  226. if (!$error && !$tmpproduct->status_batch && $batch) {
  227. $error++;
  228. $langs->load("errors");
  229. setEventMessages($langs->trans("ErrorProductDoesNotNeedBatchNumber", $tmpproduct->ref), null, 'errors');
  230. }
  231. }
  232. if (!$error) {
  233. $tmp = new InventoryLine($db);
  234. $tmp->fk_inventory = $object->id;
  235. $tmp->fk_warehouse = $fk_warehouse;
  236. $tmp->fk_product = $fk_product;
  237. $tmp->batch = $batch;
  238. $tmp->datec = $now;
  239. $tmp->qty_view = (GETPOST('qtytoadd') != '' ? price2num(GETPOST('qtytoadd', 'MS')) : null);
  240. $result = $tmp->create($user);
  241. if ($result < 0) {
  242. if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  243. setEventMessages($langs->trans("DuplicateRecord"), null, 'errors');
  244. } else {
  245. dol_print_error($db, $tmp->error, $tmp->errors);
  246. }
  247. }
  248. }
  249. }
  250. }
  251. /*
  252. * View
  253. */
  254. $form = new Form($db);
  255. $formproduct = new FormProduct($db);
  256. $help_url = '';
  257. llxHeader('', $langs->trans('Inventory'), $help_url);
  258. // Disable button Generate movement if data were not saved
  259. print '<script type="text/javascript" language="javascript">
  260. function disablebuttonmakemovementandclose() {
  261. console.log("Disable button idbuttonmakemovementandclose until we save");
  262. jQuery("#idbuttonmakemovementandclose").attr(\'disabled\',\'disabled\');
  263. jQuery("#idbuttonmakemovementandclose").attr(\'class\',\'butActionRefused\');
  264. };
  265. jQuery(document).ready(function() {
  266. jQuery(".realqty").keyup(function() {
  267. disablebuttonmakemovementandclose();
  268. });
  269. jQuery(".realqty").change(function() {
  270. disablebuttonmakemovementandclose();
  271. });
  272. });
  273. </script>';
  274. // Part to show record
  275. if ($object->id > 0) {
  276. $res = $object->fetch_optionals();
  277. $head = inventoryPrepareHead($object);
  278. print dol_get_fiche_head($head, 'inventory', $langs->trans("Inventory"), -1, 'stock');
  279. $formconfirm = '';
  280. // Confirmation to delete
  281. if ($action == 'delete') {
  282. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
  283. }
  284. // Confirmation to delete line
  285. if ($action == 'deleteline') {
  286. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
  287. }
  288. // Clone confirmation
  289. if ($action == 'clone') {
  290. // Create an array for form
  291. $formquestion = array();
  292. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  293. }
  294. // Confirmation to close
  295. if ($action == 'record') {
  296. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Close'), $langs->trans('ConfirmFinish'), 'update', '', 0, 1);
  297. $action = 'view';
  298. }
  299. // Confirmation to close
  300. if ($action == 'confirm_cancel') {
  301. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Cancel'), $langs->trans('ConfirmCancel'), 'cancel_record', '', 0, 1);
  302. $action = 'view';
  303. }
  304. // Call Hook formConfirm
  305. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
  306. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  307. if (empty($reshook)) {
  308. $formconfirm .= $hookmanager->resPrint;
  309. } elseif ($reshook > 0) {
  310. $formconfirm = $hookmanager->resPrint;
  311. }
  312. // Print form confirm
  313. print $formconfirm;
  314. // Object card
  315. // ------------------------------------------------------------
  316. $linkback = '<a href="'.DOL_URL_ROOT.'/product/inventory/list.php">'.$langs->trans("BackToList").'</a>';
  317. $morehtmlref = '<div class="refidno">';
  318. /*
  319. // Ref bis
  320. $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', 0, 1);
  321. $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', null, null, '', 1);
  322. // Thirdparty
  323. $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1);
  324. // Project
  325. if (! empty($conf->projet->enabled))
  326. {
  327. $langs->load("projects");
  328. $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
  329. if ($user->rights->inventory->creer)
  330. {
  331. if ($action != 'classify')
  332. {
  333. $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
  334. if ($action == 'classify') {
  335. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  336. $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  337. $morehtmlref.='<input type="hidden" name="action" value="classin">';
  338. $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
  339. $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  340. $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  341. $morehtmlref.='</form>';
  342. } else {
  343. $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  344. }
  345. }
  346. } else {
  347. if (! empty($object->fk_project)) {
  348. $proj = new Project($db);
  349. $proj->fetch($object->fk_project);
  350. $morehtmlref.=$proj->getNomUrl();
  351. } else {
  352. $morehtmlref.='';
  353. }
  354. }
  355. }
  356. */
  357. $morehtmlref .= '</div>';
  358. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  359. print '<div class="fichecenter">';
  360. print '<div class="fichehalfleft">';
  361. print '<div class="underbanner clearboth"></div>';
  362. print '<table class="border centpercent tableforfield">'."\n";
  363. // Common attributes
  364. include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
  365. // Other attributes. Fields from hook formObjectOptions and Extrafields.
  366. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  367. print '</table>';
  368. print '</div>';
  369. print '</div>';
  370. print '<div class="clearboth"></div>';
  371. print dol_get_fiche_end();
  372. print '<form name="formrecord" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  373. print '<input type="hidden" name="token" value="'.newToken().'">';
  374. print '<input type="hidden" name="action" value="updateinventorylines">';
  375. print '<input type="hidden" name="id" value="'.$object->id.'">';
  376. if ($backtopage) {
  377. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  378. }
  379. // Buttons for actions
  380. if ($action != 'record') {
  381. print '<div class="tabsAction">'."\n";
  382. $parameters = array();
  383. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  384. if ($reshook < 0) {
  385. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  386. }
  387. if (empty($reshook)) {
  388. if ($object->status == Inventory::STATUS_DRAFT) {
  389. if ($permissiontoadd) {
  390. 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>'."\n";
  391. } else {
  392. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n";
  393. }
  394. }
  395. // Save
  396. if ($object->status == $object::STATUS_VALIDATED) {
  397. if ($permissiontoadd) {
  398. print '<a class="butAction" id="idbuttonmakemovementandclose" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=record&token='.newToken().'" title="'.dol_escape_htmltag("SaveQtyFirst").'">'.$langs->trans("MakeMovementsAndClose").'</a>'."\n";
  399. } else {
  400. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('MakeMovementsAndClose').'</a>'."\n";
  401. }
  402. if ($permissiontoadd) {
  403. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_cancel&token='.newToken().'">'.$langs->trans("Cancel").'</a>'."\n";
  404. }
  405. }
  406. }
  407. print '</div>'."\n";
  408. }
  409. if ($object->status == Inventory::STATUS_VALIDATED) {
  410. print '<center>';
  411. if ($permissiontoadd) {
  412. /*
  413. if (!empty($conf->barcode->enabled)) {
  414. print '<a href="#" class="butAction">'.$langs->trans("UpdateByScaningProductBarcode").'</a>';
  415. }
  416. if (!empty($conf->productbatch->enabled)) {
  417. print '<a href="#" class="butAction">'.$langs->trans('UpdateByScaningLot').'</a>';
  418. }*/
  419. if (!empty($conf->barcode->enabled) || !empty($conf->productbatch->enabled)) {
  420. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=updatebyscaning" class="">'.img_picto('', 'barcode', 'class="paddingrightonly"').$langs->trans("UpdateByScaning").'</a>';
  421. }
  422. } else {
  423. print '<a class="classfortooltip marginrightonly paddingright marginleftonly paddingleft" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("Save").'</a>'."\n";
  424. }
  425. if ($permissiontoadd && $conf->use_javascript_ajax) {
  426. print '<a id="fillwithexpected" class="marginrightonly paddingright marginleftonly paddingleft" href="#">'.img_picto('', 'autofill', 'class="paddingrightonly"').$langs->trans('AutofillWithExpected').'</a>';
  427. print '<script>';
  428. print '$( document ).ready(function() {';
  429. print ' $("#fillwithexpected").on("click",function fillWithExpected(){
  430. $(".expectedqty").each(function(){
  431. var object = $(this)[0];
  432. var objecttofill = $("#"+object.id+"_input")[0];
  433. objecttofill.value = object.innerText;
  434. })
  435. console.log("Values filled");
  436. console.log("Disable button idbuttonmakemovementandclose until we save");
  437. jQuery("#idbuttonmakemovementandclose").attr(\'disabled\',\'disabled\');
  438. jQuery("#idbuttonmakemovementandclose").attr(\'class\',\'butActionRefused\');
  439. });';
  440. print '});';
  441. print '</script>';
  442. }
  443. print '<br>';
  444. print '<br>';
  445. print '</center>';
  446. }
  447. // Popup for mass barcode scanning
  448. if ($action == 'updatebyscaning') {
  449. if ($permissiontoadd) {
  450. print '<script>';
  451. print 'function barcodescannerjs(){
  452. console.log("We catch inputs in sacnner box");
  453. var barcodemode = $("input[name=barcodemode]:checked").val();
  454. var barcodeproductqty = $("input[name=barcodeproductqty]").val();
  455. var textarea = $("textarea[name=barcodelist]").val();
  456. var textarray = textarea.split("\n");
  457. if(textarray[0] != ""){
  458. var tabproduct = [];
  459. $(".expectedqty").each(function(){
  460. id = this.id;
  461. warehouse = $("#"+id+"_warehouse").children().first().text();
  462. productbarcode = $("#"+id+"_product").children().first().attr("title");
  463. productbarcode = productbarcode.split("<br>");
  464. productbarcode = productbarcode.filter(barcode => barcode.includes("'.$langs->trans('BarCode').'"))[0];
  465. productbarcode = productbarcode.slice(productbarcode.indexOf("</b> ")+5);
  466. productbatchcode = $("#"+id+"_batch").text();
  467. if(barcodemode != "barcodeforproduct"){
  468. tabproduct.forEach(product=>{
  469. if(product.Batch == productbatchcode){
  470. alert("'.$langs->trans('ErrorSameBatchNumber').': "+productbatchcode);
  471. throw"'.$langs->trans('ErrorSameBatchNumber').': "+productbatchcode;
  472. }
  473. })
  474. }
  475. tabproduct.push({\'Id\':id,\'Warehouse\':warehouse,\'Barcode\':productbarcode,\'Batch\':productbatchcode,\'Qty\':0});
  476. })
  477. switch(barcodemode){
  478. case "barcodeforautodetect":
  479. textarray.forEach(function(element,index){
  480. console.log("Product autodetect "+(index+=1)+": "+element);
  481. BatchCodeDoesNotExist=0;
  482. tabproduct.forEach(product => {
  483. if(product.Batch == element || product.Barcode == element){
  484. product.Qty+=1;
  485. }else{
  486. BatchCodeDoesNotExist+=1;
  487. }
  488. })
  489. if(BatchCodeDoesNotExist >= tabproduct.length){
  490. alert("'.$langs->trans('ProductDoesNotExist').': "+element);
  491. }
  492. })
  493. break;
  494. case "barcodeforproduct":
  495. textarray.forEach(function(element,index){
  496. console.log("Product "+(index+=1)+": "+element);
  497. BarCodeDoesNotExist=0;
  498. tabproduct.forEach(product => {
  499. if(product.Barcode == element){
  500. product.Qty+=1;
  501. }else{
  502. BarCodeDoesNotExist+=1;
  503. }
  504. })
  505. if(BarCodeDoesNotExist >= tabproduct.length){
  506. alert("'.$langs->trans('ProductBarcodeDoesNotExist').': "+element);
  507. }
  508. })
  509. break;
  510. case "barcodeforlotserial":
  511. textarray.forEach(function(element,index){
  512. console.log("Product batch/serial "+(index+=1)+": "+element);
  513. BatchCodeDoesNotExist=0;
  514. tabproduct.forEach(product => {
  515. if(product.Batch == element){
  516. product.Qty+=1;
  517. }else{
  518. BatchCodeDoesNotExist+=1;
  519. }
  520. })
  521. if(BatchCodeDoesNotExist >= tabproduct.length){
  522. alert("'.$langs->trans('ProductBatchDoesNotExist').': "+element);
  523. }
  524. })
  525. break;
  526. default:
  527. alert("'.$langs->trans("ErrorWrongBarcodemode").' \""+barcodemode+"\"");
  528. throw"'.$langs->trans('ErrorWrongBarcodemode').' \""+barcodemode+"\"";
  529. }
  530. tabproduct.forEach(product => {
  531. if(product.Qty!=0){
  532. console.log("We change #"+product.Id+"_input to match input in scanner box");
  533. $("#"+product.Id+"_input").val(product.Qty*barcodeproductqty);
  534. }
  535. })
  536. document.forms["formrecord"].submit();
  537. }
  538. }';
  539. print '</script>';
  540. }
  541. include DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  542. $formother = new FormOther($db);
  543. print $formother->getHTMLScannerForm();
  544. }
  545. //Call method to undo changes in real qty
  546. print '<script>';
  547. print 'jQuery(document).ready(function() {
  548. $(".undochangesqty").on("click",function undochangesqty(){
  549. id = this.id;
  550. id = id.split("_")[1];
  551. tmpvalue = $("#id_"+id+"_input_tmp").val()
  552. $("#id_"+id+"_input")[0].value = tmpvalue;
  553. document.forms["formrecord"].submit();
  554. });
  555. });';
  556. print '</script>';
  557. print '<div class="fichecenter">';
  558. //print '<div class="fichehalfleft">';
  559. print '<div class="clearboth"></div>';
  560. //print load_fiche_titre($langs->trans('Consumption'), '', '');
  561. print '<div class="div-table-responsive-no-min">';
  562. print '<table id="tablelines" class="noborder noshadow centpercent">';
  563. print '<tr class="liste_titre">';
  564. print '<td>'.$langs->trans("Warehouse").'</td>';
  565. print '<td>'.$langs->trans("Product").'</td>';
  566. if ($conf->productbatch->enabled) {
  567. print '<td>';
  568. print $langs->trans("Batch");
  569. print '</td>';
  570. }
  571. print '<td class="right">'.$langs->trans("ExpectedQty").'</td>';
  572. print '<td class="center">';
  573. print $form->textwithpicto($langs->trans("RealQty"), $langs->trans("InventoryRealQtyHelp"));
  574. print '</td>';
  575. if ($object->status == $object::STATUS_VALIDATED) {
  576. // Actions
  577. print '<td class="center">';
  578. print '</td>';
  579. print '</tr>';
  580. }
  581. // Line to add a new line in inventory
  582. if ($object->status == $object::STATUS_VALIDATED) {
  583. print '<tr>';
  584. print '<td>';
  585. print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? GETPOST('fk_warehouse', 'int') : $object->fk_warehouse), 'fk_warehouse', 'warehouseopen', 1, 0, 0, '', 0, 0, array(), 'maxwidth300');
  586. print '</td>';
  587. print '<td>';
  588. print $form->select_produits((GETPOSTISSET('fk_product') ? GETPOST('fk_product', 'int') : $object->fk_product), 'fk_product', '', 0, 0, -1, 2, '', 0, null, 0, '1', 0, 'maxwidth300');
  589. print '</td>';
  590. if ($conf->productbatch->enabled) {
  591. print '<td>';
  592. print '<input type="text" name="batch" class="maxwidth100" value="'.(GETPOSTISSET('batch') ? GETPOST('batch') : '').'">';
  593. print '</td>';
  594. }
  595. print '<td class="right"></td>';
  596. print '<td class="center">';
  597. print '<input type="text" name="qtytoadd" class="maxwidth75" value="">';
  598. print '</td>';
  599. // Actions
  600. print '<td class="center">';
  601. print '<input type="submit" class="button paddingright" name="addline" value="'.$langs->trans("Add").'">';
  602. print '</td>';
  603. print '</tr>';
  604. }
  605. // Request to show lines of inventory (prefilled after start/validate step)
  606. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  607. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
  608. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  609. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  610. $cacheOfProducts = array();
  611. $cacheOfWarehouses = array();
  612. //$sql = '';
  613. $resql = $db->query($sql);
  614. if ($resql) {
  615. $num = $db->num_rows($resql);
  616. $i = 0;
  617. $hasinput = false;
  618. $totalarray = array();
  619. while ($i < $num) {
  620. $obj = $db->fetch_object($resql);
  621. if (isset($cacheOfWarehouses[$obj->fk_warehouse])) {
  622. $warehouse_static = $cacheOfWarehouses[$obj->fk_warehouse];
  623. } else {
  624. $warehouse_static = new Entrepot($db);
  625. $warehouse_static->fetch($obj->fk_warehouse);
  626. $cacheOfWarehouses[$warehouse_static->id] = $warehouse_static;
  627. }
  628. if (isset($cacheOfProducts[$obj->fk_product])) {
  629. $product_static = $cacheOfProducts[$obj->fk_product];
  630. } else {
  631. $product_static = new Product($db);
  632. $result = $product_static->fetch($obj->fk_product, '', '', '', 1, 1, 1);
  633. $option = 'nobatch';
  634. $option .= ',novirtual';
  635. $product_static->load_stock($option); // Load stock_reel + stock_warehouse. This can also call load_virtual_stock()
  636. $cacheOfProducts[$product_static->id] = $product_static;
  637. }
  638. print '<tr class="oddeven">';
  639. print '<td id="id_'.$obj->rowid.'_warehouse">';
  640. print $warehouse_static->getNomUrl(1);
  641. print '</td>';
  642. print '<td id="id_'.$obj->rowid.'_product">';
  643. print $product_static->getNomUrl(1).' - '.$product_static->label;
  644. print '</td>';
  645. if ($conf->productbatch->enabled) {
  646. print '<td id="id_'.$obj->rowid.'_batch">';
  647. print $obj->batch;
  648. print '</td>';
  649. }
  650. // Expected quantity
  651. print '<td class="right expectedqty" id="id_'.$obj->rowid.'">';
  652. print $obj->qty_stock;
  653. print '</td>';
  654. // Real quantity
  655. print '<td class="center">';
  656. if ($object->status == $object::STATUS_VALIDATED) {
  657. $qty_view = GETPOST("id_".$obj->rowid) && price2num(GETPOST("id_".$obj->rowid), 'MS') >= 0 ? GETPOST("id_".$obj->rowid) : $obj->qty_view;
  658. if (!$hasinput && $qty_view !== null && $obj->qty_stock != $qty_view) {
  659. $hasinput = true;
  660. }
  661. print '<input type="text" class="maxwidth75 right realqty" name="id_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input" value="'.$qty_view.'">';
  662. print '</td>';
  663. print '<td class="right">';
  664. print '<a id="undochangesqty_'.$obj->rowid.'" href="#" class="undochangesqty"><span class="fas fa-undo pictoundo" ></span></a> &nbsp';
  665. print '<a class="reposition" href="'.DOL_URL_ROOT.'/product/inventory/inventory.php?id='.$object->id.'&lineid='.$obj->rowid.'&action=deleteline&token='.newToken().'">'.img_delete().'</a>';
  666. print '</td>';
  667. $qty_tmp = price2num(GETPOST("id_".$obj->rowid."_input_tmp", 'MS')) >= 0 ? GETPOST("id_".$obj->rowid."_input_tmp") : $qty_view;
  668. print '<input type="hidden" class="maxwidth75 right realqty" name="id_'.$obj->rowid.'_input_tmp" id="id_'.$obj->rowid.'_input_tmp" value="'.$qty_tmp.'">';
  669. } else {
  670. print $obj->qty_view;
  671. print '</td>';
  672. }
  673. print '</tr>';
  674. $i++;
  675. }
  676. } else {
  677. dol_print_error($db);
  678. }
  679. print '</table>';
  680. print '</div>';
  681. if ($object->status == $object::STATUS_VALIDATED) {
  682. print '<center><input id="submitrecord" type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'"></center>';
  683. }
  684. print '</div>';
  685. // Call method to disable the button if no qty entered yet for inventory
  686. if ($object->status != $object::STATUS_VALIDATED || !$hasinput) {
  687. print '<script type="text/javascript" language="javascript">
  688. jQuery(document).ready(function() {
  689. disablebuttonmakemovementandclose();
  690. });
  691. </script>';
  692. }
  693. print '</form>';
  694. }
  695. // End of page
  696. llxFooter();
  697. $db->close();