inventory.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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. // Load Dolibarr environment
  23. require '../../main.inc.php';
  24. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  25. include_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  26. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  27. include_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
  28. include_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
  29. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  30. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
  31. // Load translation files required by the page
  32. $langs->loadLangs(array("stocks", "other", "productbatch"));
  33. // Get parameters
  34. $id = GETPOST('id', 'int');
  35. $ref = GETPOST('ref', 'alpha');
  36. $action = GETPOST('action', 'aZ09');
  37. $confirm = GETPOST('confirm', 'alpha');
  38. $cancel = GETPOST('cancel', 'aZ09');
  39. $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search
  40. $backtopage = GETPOST('backtopage', 'alpha');
  41. $listoffset = GETPOST('listoffset', 'alpha');
  42. $limit = GETPOST('limit', 'int') > 0 ? GETPOST('limit', 'int') : $conf->liste_limit;
  43. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  44. if (empty($page) || $page == -1) {
  45. $page = 0;
  46. }
  47. $offset = $limit * $page;
  48. $pageprev = $page - 1;
  49. $pagenext = $page + 1;
  50. $fk_warehouse = GETPOST('fk_warehouse', 'int');
  51. $fk_product = GETPOST('fk_product', 'int');
  52. $lineid = GETPOST('lineid', 'int');
  53. $batch = GETPOST('batch', 'alphanohtml');
  54. $totalExpectedValuation = 0;
  55. $totalRealValuation = 0;
  56. if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
  57. $result = restrictedArea($user, 'stock', $id);
  58. } else {
  59. $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance');
  60. }
  61. // Initialize technical objects
  62. $object = new Inventory($db);
  63. $extrafields = new ExtraFields($db);
  64. $diroutputmassaction = $conf->stock->dir_output.'/temp/massgeneration/'.$user->id;
  65. $hookmanager->initHooks(array('inventorycard')); // Note that conf->hooks_modules contains array
  66. // Fetch optionals attributes and labels
  67. $extrafields->fetch_name_optionals_label($object->table_element);
  68. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  69. // Initialize array of search criterias
  70. $search_all = GETPOST("search_all", 'alpha');
  71. $search = array();
  72. foreach ($object->fields as $key => $val) {
  73. if (GETPOST('search_'.$key, 'alpha')) {
  74. $search[$key] = GETPOST('search_'.$key, 'alpha');
  75. }
  76. }
  77. if (empty($action) && empty($id) && empty($ref)) {
  78. $action = 'view';
  79. }
  80. // Load object
  81. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
  82. // Security check - Protection if external user
  83. //if ($user->socid > 0) accessforbidden();
  84. //if ($user->socid > 0) $socid = $user->socid;
  85. //$result = restrictedArea($user, 'mymodule', $id);
  86. //Parameters Page
  87. $paramwithsearch = '';
  88. if ($limit > 0 && $limit != $conf->liste_limit) {
  89. $paramwithsearch .= '&limit='.((int) $limit);
  90. }
  91. if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
  92. $permissiontoadd = $user->rights->stock->creer;
  93. $permissiontodelete = $user->rights->stock->supprimer;
  94. } else {
  95. $permissiontoadd = $user->rights->stock->inventory_advance->write;
  96. $permissiontodelete = $user->rights->stock->inventory_advance->write;
  97. }
  98. $now = dol_now();
  99. /*
  100. * Actions
  101. */
  102. if ($cancel) {
  103. $action = '';
  104. }
  105. $parameters = array();
  106. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  107. if ($reshook < 0) {
  108. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  109. }
  110. if (empty($reshook)) {
  111. $error = 0;
  112. if ($action == 'cancel_record' && $permissiontoadd) {
  113. $object->setCanceled($user);
  114. }
  115. // Close inventory by recording the stock movements
  116. if ($action == 'update' && $user->hasRight('stock', 'mouvement', 'creer') && $object->status == $object::STATUS_VALIDATED) {
  117. $stockmovment = new MouvementStock($db);
  118. $stockmovment->setOrigin($object->element, $object->id);
  119. $cacheOfProducts = array();
  120. $db->begin();
  121. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  122. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.pmp_real';
  123. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  124. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  125. $resql = $db->query($sql);
  126. if ($resql) {
  127. $num = $db->num_rows($resql);
  128. $i = 0;
  129. $totalarray = array();
  130. while ($i < $num) {
  131. $line = $db->fetch_object($resql);
  132. $qty_stock = $line->qty_stock;
  133. $qty_view = $line->qty_view; // The quantity viewed by inventorier, the qty we target
  134. // Load real stock we have now.
  135. if (isset($cacheOfProducts[$line->fk_product])) {
  136. $product_static = $cacheOfProducts[$line->fk_product];
  137. } else {
  138. $product_static = new Product($db);
  139. $result = $product_static->fetch($line->fk_product, '', '', '', 1, 1, 1);
  140. //$option = 'nobatch';
  141. $option .= ',novirtual';
  142. $product_static->load_stock($option); // Load stock_reel + stock_warehouse.
  143. $cacheOfProducts[$product_static->id] = $product_static;
  144. }
  145. // Get the real quantity in stock now, but before the stock move for inventory.
  146. $realqtynow = $product_static->stock_warehouse[$line->fk_warehouse]->real;
  147. if (isModEnabled('productbatch') && $product_static->hasbatch()) {
  148. $realqtynow = $product_static->stock_warehouse[$line->fk_warehouse]->detail_batch[$line->batch]->qty;
  149. }
  150. if (!is_null($qty_view)) {
  151. $stock_movement_qty = price2num($qty_view - $realqtynow, 'MS');
  152. if ($stock_movement_qty != 0) {
  153. if ($stock_movement_qty < 0) {
  154. $movement_type = 1;
  155. } else {
  156. $movement_type = 0;
  157. }
  158. $datemovement = '';
  159. //$inventorycode = 'INV'.$object->id;
  160. $inventorycode = 'INV-'.$object->ref;
  161. $price = 0;
  162. if (!empty($line->pmp_real) && getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  163. $price = $line->pmp_real;
  164. }
  165. $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);
  166. if ($idstockmove < 0) {
  167. $error++;
  168. setEventMessages($stockmovment->error, $stockmovment->errors, 'errors');
  169. break;
  170. }
  171. // Update line with id of stock movement (and the start quantity if it has changed this last recording)
  172. $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."inventorydet";
  173. $sqlupdate .= " SET fk_movement = ".((int) $idstockmove);
  174. if ($qty_stock != $realqtynow) {
  175. $sqlupdate .= ", qty_stock = ".((float) $realqtynow);
  176. }
  177. $sqlupdate .= " WHERE rowid = ".((int) $line->rowid);
  178. $resqlupdate = $db->query($sqlupdate);
  179. if (! $resqlupdate) {
  180. $error++;
  181. setEventMessages($db->lasterror(), null, 'errors');
  182. break;
  183. }
  184. }
  185. if (!empty($line->pmp_real) && getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  186. $sqlpmp = 'UPDATE '.MAIN_DB_PREFIX.'product SET pmp = '.((float) $line->pmp_real).' WHERE rowid = '.((int) $line->fk_product);
  187. $resqlpmp = $db->query($sqlpmp);
  188. if (! $resqlpmp) {
  189. $error++;
  190. setEventMessages($db->lasterror(), null, 'errors');
  191. break;
  192. }
  193. if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
  194. $sqlpmp = 'UPDATE '.MAIN_DB_PREFIX.'product_perentity SET pmp = '.((float) $line->pmp_real).' WHERE fk_product = '.((int) $line->fk_product).' AND entity='.$conf->entity;
  195. $resqlpmp = $db->query($sqlpmp);
  196. if (! $resqlpmp) {
  197. $error++;
  198. setEventMessages($db->lasterror(), null, 'errors');
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. $i++;
  205. }
  206. if (!$error) {
  207. $object->setRecorded($user);
  208. }
  209. } else {
  210. setEventMessages($db->lasterror, null, 'errors');
  211. $error++;
  212. }
  213. if (! $error) {
  214. $db->commit();
  215. } else {
  216. $db->rollback();
  217. }
  218. }
  219. // Save quantity found during inventory (when we click on Save button on inventory page)
  220. if ($action =='updateinventorylines' && $permissiontoadd) {
  221. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  222. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated';
  223. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  224. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  225. $sql .= $db->order('id.rowid', 'ASC');
  226. $sql .= $db->plimit($limit, $offset);
  227. $db->begin();
  228. $resql = $db->query($sql);
  229. if ($resql) {
  230. $num = $db->num_rows($resql);
  231. $i = 0;
  232. $totalarray = array();
  233. $inventoryline = new InventoryLine($db);
  234. while ($i < $num) {
  235. $line = $db->fetch_object($resql);
  236. $lineid = $line->rowid;
  237. $result = 0;
  238. $resultupdate = 0;
  239. if (GETPOST("id_".$lineid, 'alpha') != '') { // If a value was set ('0' or something else)
  240. $qtytoupdate = price2num(GETPOST("id_".$lineid, 'alpha'), 'MS');
  241. $result = $inventoryline->fetch($lineid);
  242. if ($qtytoupdate < 0) {
  243. $result = -1;
  244. setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
  245. }
  246. if ($result > 0) {
  247. $inventoryline->qty_stock = price2num(GETPOST('stock_qty_'.$lineid, 'alpha'), 'MS'); // The new value that was set in as hidden field
  248. $inventoryline->qty_view = $qtytoupdate; // The new value we want
  249. $inventoryline->pmp_real = price2num(GETPOST('realpmp_'.$lineid, 'alpha'), 'MS');
  250. $inventoryline->pmp_expected = price2num(GETPOST('expectedpmp_'.$lineid, 'alpha'), 'MS');
  251. $resultupdate = $inventoryline->update($user);
  252. }
  253. } elseif (GETPOSTISSET('id_' . $lineid)) {
  254. // Delete record
  255. $result = $inventoryline->fetch($lineid);
  256. if ($result > 0) {
  257. $inventoryline->qty_view = null; // The new value we want
  258. $inventoryline->pmp_real = price2num(GETPOST('realpmp_'.$lineid, 'alpha'), 'MS');
  259. $inventoryline->pmp_expected = price2num(GETPOST('expectedpmp_'.$lineid, 'alpha'), 'MS');
  260. $resultupdate = $inventoryline->update($user);
  261. }
  262. }
  263. if ($result < 0 || $resultupdate < 0) {
  264. $error++;
  265. }
  266. $i++;
  267. }
  268. }
  269. // Update line with id of stock movement (and the start quantity if it has changed this last recording)
  270. if (! $error) {
  271. $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."inventory";
  272. $sqlupdate .= " SET fk_user_modif = ".((int) $user->id);
  273. $sqlupdate .= " WHERE rowid = ".((int) $object->id);
  274. $resqlupdate = $db->query($sqlupdate);
  275. if (! $resqlupdate) {
  276. $error++;
  277. setEventMessages($db->lasterror(), null, 'errors');
  278. }
  279. }
  280. if (!$error) {
  281. $db->commit();
  282. } else {
  283. $db->rollback();
  284. }
  285. }
  286. $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php';
  287. $backtopage = DOL_URL_ROOT.'/product/inventory/inventory.php?id='.$object->id.'&page='.$page.$paramwithsearch;
  288. // Actions cancel, add, update, delete or clone
  289. include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
  290. // Actions when linking object each other
  291. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
  292. // Actions when printing a doc from card
  293. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  294. // Actions to send emails
  295. /*$triggersendname = 'MYOBJECT_SENTBYMAIL';
  296. $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
  297. $trackid='stockinv'.$object->id;
  298. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';*/
  299. if (GETPOST('addline', 'alpha')) {
  300. $qty= (GETPOST('qtytoadd') != '' ? price2num(GETPOST('qtytoadd', 'MS')) : null);
  301. if ($fk_warehouse <= 0) {
  302. $error++;
  303. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  304. }
  305. if ($fk_product <= 0) {
  306. $error++;
  307. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
  308. }
  309. if (price2num(GETPOST('qtytoadd'), 'MS') < 0) {
  310. $error++;
  311. setEventMessages($langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv("RealQty")), null, 'errors');
  312. }
  313. if (!$error && isModEnabled('productbatch')) {
  314. $tmpproduct = new Product($db);
  315. $result = $tmpproduct->fetch($fk_product);
  316. if (empty($error) && $tmpproduct->status_batch>0 && empty($batch)) {
  317. $error++;
  318. $langs->load("errors");
  319. setEventMessages($langs->trans("ErrorProductNeedBatchNumber", $tmpproduct->ref), null, 'errors');
  320. }
  321. if (empty($error) && $tmpproduct->status_batch==2 && !empty($batch) && $qty>1) {
  322. $error++;
  323. $langs->load("errors");
  324. setEventMessages($langs->trans("TooManyQtyForSerialNumber", $tmpproduct->ref, $batch), null, 'errors');
  325. }
  326. if (empty($error) && empty($tmpproduct->status_batch) && !empty($batch)) {
  327. $error++;
  328. $langs->load("errors");
  329. setEventMessages($langs->trans("ErrorProductDoesNotNeedBatchNumber", $tmpproduct->ref), null, 'errors');
  330. }
  331. }
  332. if (!$error) {
  333. $tmp = new InventoryLine($db);
  334. $tmp->fk_inventory = $object->id;
  335. $tmp->fk_warehouse = $fk_warehouse;
  336. $tmp->fk_product = $fk_product;
  337. $tmp->batch = $batch;
  338. $tmp->datec = $now;
  339. $tmp->qty_view = $qty;
  340. $result = $tmp->create($user);
  341. if ($result < 0) {
  342. if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  343. $langs->load("errors");
  344. setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
  345. } else {
  346. dol_print_error($db, $tmp->error, $tmp->errors);
  347. }
  348. } else {
  349. // Clear var
  350. $_POST['batch'] = '';
  351. $_POST['qtytoadd'] = '';
  352. }
  353. }
  354. }
  355. }
  356. /*
  357. * View
  358. */
  359. $form = new Form($db);
  360. $formproduct = new FormProduct($db);
  361. $help_url = '';
  362. llxHeader('', $langs->trans('Inventory'), $help_url);
  363. // Part to show record
  364. if ($object->id <= 0) {
  365. dol_print_error('', 'Bad value for object id');
  366. exit;
  367. }
  368. $res = $object->fetch_optionals();
  369. $head = inventoryPrepareHead($object);
  370. print dol_get_fiche_head($head, 'inventory', $langs->trans("Inventory"), -1, 'stock');
  371. $formconfirm = '';
  372. // Confirmation to delete
  373. if ($action == 'delete') {
  374. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
  375. }
  376. // Confirmation to delete line
  377. if ($action == 'deleteline') {
  378. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid.'&page='.$page.$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
  379. }
  380. // Clone confirmation
  381. if ($action == 'clone') {
  382. // Create an array for form
  383. $formquestion = array();
  384. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  385. }
  386. // Confirmation to close
  387. if ($action == 'record') {
  388. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&page='.$page.$paramwithsearch, $langs->trans('Close'), $langs->trans('ConfirmFinish'), 'update', '', 0, 1);
  389. $action = 'view';
  390. }
  391. // Confirmation to close
  392. if ($action == 'confirm_cancel') {
  393. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Cancel'), $langs->trans('ConfirmCancel'), 'cancel_record', '', 0, 1);
  394. $action = 'view';
  395. }
  396. if ($action == 'validate') {
  397. $form = new Form($db);
  398. $formquestion = '';
  399. if (getDolGlobalInt('INVENTORY_INCLUDE_SUB_WAREHOUSE') && !empty($object->fk_warehouse)) {
  400. $formquestion = array(
  401. array('type' => 'checkbox', 'name' => 'include_sub_warehouse', 'label' => $langs->trans("IncludeSubWarehouse"), 'value' => 1, 'size' => '10'),
  402. );
  403. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateInventory'), $langs->trans('IncludeSubWarehouseExplanation'), 'confirm_validate', $formquestion, '', 1);
  404. }
  405. }
  406. // Call Hook formConfirm
  407. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
  408. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  409. if (empty($reshook)) {
  410. $formconfirm .= $hookmanager->resPrint;
  411. } elseif ($reshook > 0) {
  412. $formconfirm = $hookmanager->resPrint;
  413. }
  414. // Print form confirm
  415. print $formconfirm;
  416. // Object card
  417. // ------------------------------------------------------------
  418. $linkback = '<a href="'.DOL_URL_ROOT.'/product/inventory/list.php">'.$langs->trans("BackToList").'</a>';
  419. $morehtmlref = '<div class="refidno">';
  420. /*
  421. // Ref bis
  422. $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', 0, 1);
  423. $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', null, null, '', 1);
  424. // Thirdparty
  425. $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1);
  426. // Project
  427. if (isModEnabled('project'))
  428. {
  429. $langs->load("projects");
  430. $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
  431. if ($user->rights->inventory->creer)
  432. {
  433. if ($action != 'classify')
  434. {
  435. $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
  436. if ($action == 'classify') {
  437. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  438. $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  439. $morehtmlref.='<input type="hidden" name="action" value="classin">';
  440. $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
  441. $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  442. $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  443. $morehtmlref.='</form>';
  444. } else {
  445. $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  446. }
  447. }
  448. } else {
  449. if (!empty($object->fk_project)) {
  450. $proj = new Project($db);
  451. $proj->fetch($object->fk_project);
  452. $morehtmlref.=$proj->getNomUrl();
  453. } else {
  454. $morehtmlref.='';
  455. }
  456. }
  457. }
  458. */
  459. $morehtmlref .= '</div>';
  460. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  461. print '<div class="fichecenter">';
  462. print '<div class="fichehalfleft">';
  463. print '<div class="underbanner clearboth"></div>';
  464. print '<table class="border centpercent tableforfield">'."\n";
  465. // Common attributes
  466. include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
  467. // Other attributes. Fields from hook formObjectOptions and Extrafields.
  468. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  469. //print '<tr><td class="titlefield fieldname_invcode">'.$langs->trans("InventoryCode").'</td><td>INV'.$object->id.'</td></tr>';
  470. print '</table>';
  471. print '</div>';
  472. print '</div>';
  473. print '<div class="clearboth"></div>';
  474. print dol_get_fiche_end();
  475. print '<form id="formrecord" name="formrecord" method="POST" action="'.$_SERVER["PHP_SELF"].'?page='.$page.'&id='.$object->id.'">';
  476. print '<input type="hidden" name="token" value="'.newToken().'">';
  477. print '<input type="hidden" name="action" value="updateinventorylines">';
  478. print '<input type="hidden" name="id" value="'.$object->id.'">';
  479. if ($backtopage) {
  480. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  481. }
  482. // Buttons for actions
  483. if ($action != 'record') {
  484. print '<div class="tabsAction">'."\n";
  485. $parameters = array();
  486. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  487. if ($reshook < 0) {
  488. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  489. }
  490. if (empty($reshook)) {
  491. if ($object->status == Inventory::STATUS_DRAFT) {
  492. if ($permissiontoadd) {
  493. if (getDolGlobalInt('INVENTORY_INCLUDE_SUB_WAREHOUSE') && !empty($object->fk_warehouse)) {
  494. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate&token='.newToken().'">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>';
  495. } else {
  496. 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>';
  497. }
  498. } else {
  499. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n";
  500. }
  501. }
  502. // Save
  503. if ($object->status == $object::STATUS_VALIDATED) {
  504. if ($permissiontoadd) {
  505. 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";
  506. } else {
  507. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('MakeMovementsAndClose').'</a>'."\n";
  508. }
  509. if ($permissiontoadd) {
  510. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_cancel&page='.$page.$paramwithsearch.'&token='.newToken().'">'.$langs->trans("Cancel").'</a>'."\n";
  511. }
  512. }
  513. }
  514. print '</div>'."\n";
  515. if ($object->status != Inventory::STATUS_DRAFT && $object->status != Inventory::STATUS_VALIDATED) {
  516. print '<br><br>';
  517. }
  518. }
  519. if ($object->status == Inventory::STATUS_VALIDATED) {
  520. print '<center>';
  521. if (!empty($conf->use_javascript_ajax)) {
  522. if ($permissiontoadd) {
  523. // Link to launch scan tool
  524. if (isModEnabled('barcode') || isModEnabled('productbatch')) {
  525. 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>';
  526. }
  527. // Link to autofill
  528. print '<a id="fillwithexpected" class="marginrightonly paddingright marginleftonly paddingleft" href="#">'.img_picto('', 'autofill', 'class="paddingrightonly"').$langs->trans('AutofillWithExpected').'</a>';
  529. print '<script>';
  530. print '$( document ).ready(function() {';
  531. print ' $("#fillwithexpected").on("click",function fillWithExpected(){
  532. $(".expectedqty").each(function(){
  533. var object = $(this)[0];
  534. var objecttofill = $("#"+object.id+"_input")[0];
  535. objecttofill.value = object.innerText;
  536. jQuery(".realqty").trigger("change");
  537. })
  538. console.log("Values filled (after click on fillwithexpected)");
  539. /* disablebuttonmakemovementandclose(); */
  540. return false;
  541. });';
  542. print '});';
  543. print '</script>';
  544. // Link to reset qty
  545. print '<a href="#" id="clearqty" class="marginrightonly paddingright marginleftonly paddingleft">'.img_picto('', 'eraser', 'class="paddingrightonly"').$langs->trans("ClearQtys").'</a>';
  546. } else {
  547. print '<a class="classfortooltip marginrightonly paddingright marginleftonly paddingleft" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("Save").'</a>'."\n";
  548. }
  549. }
  550. print '<br>';
  551. print '<br>';
  552. print '</center>';
  553. }
  554. // Popup for mass barcode scanning
  555. if ($action == 'updatebyscaning') {
  556. if ($permissiontoadd) {
  557. // Output the javascript to manage the scanner tool.
  558. print '<script>';
  559. print '
  560. var duplicatedbatchcode = [];
  561. var errortab1 = [];
  562. var errortab2 = [];
  563. var errortab3 = [];
  564. var errortab4 = [];
  565. function barcodescannerjs(){
  566. console.log("We catch inputs in scanner box");
  567. jQuery("#scantoolmessage").text();
  568. var selectaddorreplace = $("select[name=selectaddorreplace]").val();
  569. var barcodemode = $("input[name=barcodemode]:checked").val();
  570. var barcodeproductqty = $("input[name=barcodeproductqty]").val();
  571. var textarea = $("textarea[name=barcodelist]").val();
  572. var textarray = textarea.split(/[\s,;]+/);
  573. var tabproduct = [];
  574. duplicatedbatchcode = [];
  575. errortab1 = [];
  576. errortab2 = [];
  577. errortab3 = [];
  578. errortab4 = [];
  579. textarray = textarray.filter(function(value){
  580. return value != "";
  581. });
  582. if(textarray.some((element) => element != "")){
  583. $(".expectedqty").each(function(){
  584. id = this.id;
  585. console.log("Analyze the line "+id+" in inventory, barcodemode="+barcodemode);
  586. warehouse = $("#"+id+"_warehouse").attr(\'data-ref\');
  587. //console.log(warehouse);
  588. productbarcode = $("#"+id+"_product").attr(\'data-barcode\');
  589. //console.log(productbarcode);
  590. productbatchcode = $("#"+id+"_batch").attr(\'data-batch\');
  591. //console.log(productbatchcode);
  592. if (barcodemode != "barcodeforproduct") {
  593. tabproduct.forEach(product=>{
  594. console.log("product.Batch="+product.Batch+" productbatchcode="+productbatchcode);
  595. if(product.Batch != "" && product.Batch == productbatchcode){
  596. console.log("duplicate batch code found for batch code "+productbatchcode);
  597. duplicatedbatchcode.push(productbatchcode);
  598. }
  599. })
  600. }
  601. productinput = $("#"+id+"_input").val();
  602. if(productinput == ""){
  603. productinput = 0
  604. }
  605. tabproduct.push({\'Id\':id,\'Warehouse\':warehouse,\'Barcode\':productbarcode,\'Batch\':productbatchcode,\'Qty\':productinput,\'fetched\':false});
  606. });
  607. console.log("Loop on each record entered in the textarea");
  608. textarray.forEach(function(element,index){
  609. console.log("Process record element="+element+" id="+id);
  610. var verify_batch = false;
  611. var verify_barcode = false;
  612. switch(barcodemode){
  613. case "barcodeforautodetect":
  614. verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode",true);
  615. verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial",true);
  616. break;
  617. case "barcodeforproduct":
  618. verify_barcode = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"barcode");
  619. break;
  620. case "barcodeforlotserial":
  621. verify_batch = barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,"lotserial");
  622. break;
  623. default:
  624. alert(\''.dol_escape_js($langs->trans("ErrorWrongBarcodemode")).' "\'+barcodemode+\'"\');
  625. throw \''.dol_escape_js($langs->trans('ErrorWrongBarcodemode')).' "\'+barcodemode+\'"\';
  626. }
  627. if (verify_batch == false && verify_barcode == false) { /* If the 2 flags are false, not found error */
  628. errortab2.push(element);
  629. } else if (verify_batch == true && verify_barcode == true) { /* If the 2 flags are true, error: we don t know which one to take */
  630. errortab3.push(element);
  631. } else if (verify_batch == true) {
  632. console.log("element="+element);
  633. console.log(duplicatedbatchcode);
  634. if (duplicatedbatchcode.includes(element)) {
  635. errortab1.push(element);
  636. }
  637. }
  638. });
  639. if (Object.keys(errortab1).length < 1 && Object.keys(errortab2).length < 1 && Object.keys(errortab3).length < 1) {
  640. tabproduct.forEach(product => {
  641. if(product.Qty!=0){
  642. console.log("We change #"+product.Id+"_input to match input in scanner box");
  643. if(product.hasOwnProperty("reelqty")){
  644. $.ajax({ url: \''.DOL_URL_ROOT.'/product/inventory/ajax/searchfrombarcode.php\',
  645. 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},
  646. type: \'POST\',
  647. async: false,
  648. success: function(response) {
  649. response = JSON.parse(response);
  650. if(response.status == "success"){
  651. console.log(response.message);
  652. $("<input type=\'text\' value=\'"+product.Qty+"\' />")
  653. .attr("id", "id_"+response.id_line+"_input")
  654. .attr("name", "id_"+response.id_line)
  655. .appendTo("#formrecord");
  656. }else{
  657. console.error(response.message);
  658. }
  659. },
  660. error : function(output) {
  661. console.error("Error on line creation function");
  662. },
  663. });
  664. } else {
  665. $("#"+product.Id+"_input").val(product.Qty);
  666. }
  667. }
  668. });
  669. jQuery("#scantoolmessage").text("'.dol_escape_js($langs->transnoentities("QtyWasAddedToTheScannedBarcode")).'\n");
  670. /* document.forms["formrecord"].submit(); */
  671. } else {
  672. let stringerror = "";
  673. if (Object.keys(errortab1).length > 0) {
  674. stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorSameBatchNumber')).': ";
  675. errortab1.forEach(element => {
  676. stringerror += (element + ", ")
  677. });
  678. stringerror = stringerror.slice(0, -2); /* Remove last ", " */
  679. }
  680. if (Object.keys(errortab2).length > 0) {
  681. stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorCantFindCodeInInventory')).': ";
  682. errortab2.forEach(element => {
  683. stringerror += (element + ", ")
  684. });
  685. stringerror = stringerror.slice(0, -2); /* Remove last ", " */
  686. }
  687. if (Object.keys(errortab3).length > 0) {
  688. stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorCodeScannedIsBothProductAndSerial')).': ";
  689. errortab3.forEach(element => {
  690. stringerror += (element + ", ")
  691. });
  692. stringerror = stringerror.slice(0, -2); /* Remove last ", " */
  693. }
  694. if (Object.keys(errortab4).length > 0) {
  695. stringerror += "<br>'.dol_escape_js($langs->transnoentities('ErrorBarcodeNotFoundForProductWarehouse')).': ";
  696. errortab4.forEach(element => {
  697. stringerror += (element + ", ")
  698. });
  699. stringerror = stringerror.slice(0, -2); /* Remove last ", " */
  700. }
  701. jQuery("#scantoolmessage").html(\''.dol_escape_js($langs->transnoentities("ErrorOnElementsInventory")).'\' + stringerror);
  702. //alert("'.dol_escape_js($langs->trans("ErrorOnElementsInventory")).' :\n" + stringerror);
  703. }
  704. }
  705. }
  706. /* This methode is called by parent barcodescannerjs() */
  707. function barcodeserialforproduct(tabproduct,index,element,barcodeproductqty,selectaddorreplace,mode,autodetect=false){
  708. BarcodeIsInProduct=0;
  709. newproductrow=0
  710. result=false;
  711. tabproduct.forEach(product => {
  712. $.ajax({ url: \''.DOL_URL_ROOT.'/product/inventory/ajax/searchfrombarcode.php\',
  713. 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},
  714. type: \'POST\',
  715. async: false,
  716. success: function(response) {
  717. response = JSON.parse(response);
  718. if (response.status == "success"){
  719. console.log(response.message);
  720. if(!newproductrow){
  721. newproductrow = response.object;
  722. }
  723. }else{
  724. if (mode!="lotserial" && autodetect==false && !errortab4.includes(element)){
  725. errortab4.push(element);
  726. console.error(response.message);
  727. }
  728. }
  729. },
  730. error : function(output) {
  731. console.error("Error on barcodeserialforproduct function");
  732. },
  733. });
  734. console.log("Product "+(index+=1)+": "+element);
  735. if(mode == "barcode"){
  736. testonproduct = product.Barcode
  737. }else if (mode == "lotserial"){
  738. testonproduct = product.Batch
  739. }
  740. if(testonproduct == element){
  741. if(selectaddorreplace == "add"){
  742. productqty = parseInt(product.Qty,10);
  743. product.Qty = productqty + parseInt(barcodeproductqty,10);
  744. }else if(selectaddorreplace == "replace"){
  745. if(product.fetched == false){
  746. product.Qty = barcodeproductqty
  747. product.fetched=true
  748. }else{
  749. productqty = parseInt(product.Qty,10);
  750. product.Qty = productqty + parseInt(barcodeproductqty,10);
  751. }
  752. }
  753. BarcodeIsInProduct+=1;
  754. }
  755. })
  756. if(BarcodeIsInProduct==0 && newproductrow!=0){
  757. 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});
  758. result = true;
  759. }
  760. if(BarcodeIsInProduct > 0){
  761. result = true;
  762. }
  763. return result;
  764. }
  765. ';
  766. print '</script>';
  767. }
  768. include DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  769. $formother = new FormOther($db);
  770. print $formother->getHTMLScannerForm("barcodescannerjs", 'all');
  771. }
  772. //Call method to undo changes in real qty
  773. print '<script>';
  774. print 'jQuery(document).ready(function() {
  775. $("#clearqty").on("click", function() {
  776. console.log("Clear all values");
  777. /* disablebuttonmakemovementandclose(); */
  778. jQuery(".realqty").val("");
  779. jQuery(".realqty").trigger("change");
  780. return false; /* disable submit */
  781. });
  782. $(".undochangesqty").on("click", function undochangesqty() {
  783. console.log("Clear value of inventory line");
  784. id = this.id;
  785. id = id.split("_")[1];
  786. tmpvalue = $("#id_"+id+"_input_tmp").val()
  787. $("#id_"+id+"_input")[0].value = tmpvalue;
  788. /* disablebuttonmakemovementandclose(); */
  789. return false; /* disable submit */
  790. });
  791. });';
  792. print '</script>';
  793. print '<div class="fichecenter">';
  794. //print '<div class="fichehalfleft">';
  795. print '<div class="clearboth"></div>';
  796. //print load_fiche_titre($langs->trans('Consumption'), '', '');
  797. print '<div class="div-table-responsive-no-min">';
  798. print '<table id="tablelines" class="noborder noshadow centpercent">';
  799. print '<tr class="liste_titre">';
  800. print '<td>'.$langs->trans("Warehouse").'</td>';
  801. print '<td>'.$langs->trans("Product").'</td>';
  802. if (isModEnabled('productbatch')) {
  803. print '<td>';
  804. print $langs->trans("Batch");
  805. print '</td>';
  806. }
  807. print '<td class="right">'.$langs->trans("ExpectedQty").'</td>';
  808. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  809. print '<td class="right">'.$langs->trans('PMPExpected').'</td>';
  810. print '<td class="right">'.$langs->trans('ExpectedValuation').'</td>';
  811. print '<td class="right">'.$form->textwithpicto($langs->trans("RealQty"), $langs->trans("InventoryRealQtyHelp")).'</td>';
  812. print '<td class="right">'.$langs->trans('PMPReal').'</td>';
  813. print '<td class="right">'.$langs->trans('RealValuation').'</td>';
  814. } else {
  815. print '<td class="right">';
  816. print $form->textwithpicto($langs->trans("RealQty"), $langs->trans("InventoryRealQtyHelp"));
  817. print '</td>';
  818. }
  819. if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
  820. // Actions or link to stock movement
  821. print '<td class="center">';
  822. print '</td>';
  823. } else {
  824. // Actions or link to stock movement
  825. print '<td class="right">';
  826. //print $langs->trans("StockMovement");
  827. print '</td>';
  828. }
  829. print '</tr>';
  830. // Line to add a new line in inventory
  831. if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
  832. print '<tr>';
  833. print '<td>';
  834. print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? GETPOST('fk_warehouse', 'int') : $object->fk_warehouse), 'fk_warehouse', 'warehouseopen', 1, 0, 0, '', 0, 0, array(), 'maxwidth300');
  835. print '</td>';
  836. print '<td>';
  837. 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');
  838. print '</td>';
  839. if (isModEnabled('productbatch')) {
  840. print '<td>';
  841. print '<input type="text" name="batch" class="maxwidth100" value="'.(GETPOSTISSET('batch') ? GETPOST('batch') : '').'">';
  842. print '</td>';
  843. }
  844. print '<td class="right"></td>';
  845. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  846. print '<td class="right">';
  847. print '</td>';
  848. print '<td class="right">';
  849. print '</td>';
  850. print '<td class="right">';
  851. print '<input type="text" name="qtytoadd" class="maxwidth75" value="">';
  852. print '</td>';
  853. print '<td class="right">';
  854. print '</td>';
  855. print '<td class="right">';
  856. print '</td>';
  857. } else {
  858. print '<td class="right">';
  859. print '<input type="text" name="qtytoadd" class="maxwidth75" value="">';
  860. print '</td>';
  861. }
  862. // Actions
  863. print '<td class="center">';
  864. print '<input type="submit" class="button paddingright" name="addline" value="'.$langs->trans("Add").'">';
  865. print '</td>';
  866. print '</tr>';
  867. }
  868. // Request to show lines of inventory (prefilled after start/validate step)
  869. $sql = 'SELECT id.rowid, id.datec as date_creation, id.tms as date_modification, id.fk_inventory, id.fk_warehouse,';
  870. $sql .= ' id.fk_product, id.batch, id.qty_stock, id.qty_view, id.qty_regulated, id.fk_movement, id.pmp_real, id.pmp_expected';
  871. $sql .= ' FROM '.MAIN_DB_PREFIX.'inventorydet as id';
  872. $sql .= ' WHERE id.fk_inventory = '.((int) $object->id);
  873. $sql .= $db->order('id.rowid', 'ASC');
  874. $sql .= $db->plimit($limit, $offset);
  875. $cacheOfProducts = array();
  876. $cacheOfWarehouses = array();
  877. //$sql = '';
  878. $resql = $db->query($sql);
  879. if ($resql) {
  880. $num = $db->num_rows($resql);
  881. if (!empty($limit != 0) || $num > $limit || $page) {
  882. print_fleche_navigation($page, $_SERVER["PHP_SELF"], '&id='.$object->id.$paramwithsearch, ($num >= $limit), '<li class="pagination"><span>' . $langs->trans("Page") . ' ' . ($page + 1) . '</span></li>', '', $limit);
  883. }
  884. $i = 0;
  885. $hasinput = false;
  886. $totalarray = array();
  887. while ($i < $num) {
  888. $obj = $db->fetch_object($resql);
  889. if (isset($cacheOfWarehouses[$obj->fk_warehouse])) {
  890. $warehouse_static = $cacheOfWarehouses[$obj->fk_warehouse];
  891. } else {
  892. $warehouse_static = new Entrepot($db);
  893. $warehouse_static->fetch($obj->fk_warehouse);
  894. $cacheOfWarehouses[$warehouse_static->id] = $warehouse_static;
  895. }
  896. // Load real stock we have now
  897. $option = '';
  898. if (isset($cacheOfProducts[$obj->fk_product])) {
  899. $product_static = $cacheOfProducts[$obj->fk_product];
  900. } else {
  901. $product_static = new Product($db);
  902. $result = $product_static->fetch($obj->fk_product, '', '', '', 1, 1, 1);
  903. //$option = 'nobatch';
  904. $option .= ',novirtual';
  905. $product_static->load_stock($option); // Load stock_reel + stock_warehouse.
  906. $cacheOfProducts[$product_static->id] = $product_static;
  907. }
  908. print '<tr class="oddeven">';
  909. print '<td id="id_'.$obj->rowid.'_warehouse" data-ref="'.dol_escape_htmltag($warehouse_static->ref).'">';
  910. print $warehouse_static->getNomUrl(1);
  911. print '</td>';
  912. print '<td id="id_'.$obj->rowid.'_product" data-ref="'.dol_escape_htmltag($product_static->ref).'" data-barcode="'.dol_escape_htmltag($product_static->barcode).'">';
  913. print $product_static->getNomUrl(1).' - '.$product_static->label;
  914. print '</td>';
  915. if (isModEnabled('productbatch')) {
  916. print '<td id="id_'.$obj->rowid.'_batch" data-batch="'.dol_escape_htmltag($obj->batch).'">';
  917. $batch_static = new Productlot($db);
  918. $res = $batch_static->fetch(0, $product_static->id, $obj->batch);
  919. if ($res) {
  920. print $batch_static->getNomUrl(1);
  921. } else {
  922. print dol_escape_htmltag($obj->batch);
  923. }
  924. print '</td>';
  925. }
  926. // Expected quantity = Quantity in stock when we start inventory
  927. print '<td class="right expectedqty" id="id_'.$obj->rowid.'" title="Stock viewed at last update: '.$obj->qty_stock.'">';
  928. $valuetoshow = $obj->qty_stock;
  929. // For inventory not yet close, we overwrite with the real value in stock now
  930. if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
  931. if (isModEnabled('productbatch') && $product_static->hasbatch()) {
  932. $valuetoshow = $product_static->stock_warehouse[$obj->fk_warehouse]->detail_batch[$obj->batch]->qty ?? 0;
  933. } else {
  934. $valuetoshow = $product_static->stock_warehouse[$obj->fk_warehouse]->real ?? 0;
  935. }
  936. }
  937. print price2num($valuetoshow, 'MS');
  938. print '<input type="hidden" name="stock_qty_'.$obj->rowid.'" value="'.$valuetoshow.'">';
  939. print '</td>';
  940. // Real quantity
  941. if ($object->status == $object::STATUS_DRAFT || $object->status == $object::STATUS_VALIDATED) {
  942. $qty_view = GETPOST("id_".$obj->rowid) && price2num(GETPOST("id_".$obj->rowid), 'MS') >= 0 ? GETPOST("id_".$obj->rowid) : $obj->qty_view;
  943. //if (!$hasinput && $qty_view !== null && $obj->qty_stock != $qty_view) {
  944. if ($qty_view != '') {
  945. $hasinput = true;
  946. }
  947. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  948. //PMP Expected
  949. if (!empty($obj->pmp_expected)) {
  950. $pmp_expected = $obj->pmp_expected;
  951. } else {
  952. $pmp_expected = $product_static->pmp;
  953. }
  954. $pmp_valuation = $pmp_expected * $valuetoshow;
  955. print '<td class="right">';
  956. print price($pmp_expected);
  957. print '<input type="hidden" name="expectedpmp_'.$obj->rowid.'" value="'.$pmp_expected.'"/>';
  958. print '</td>';
  959. print '<td class="right">';
  960. print price($pmp_valuation);
  961. print '</td>';
  962. print '<td class="right">';
  963. print '<a id="undochangesqty_'.$obj->rowid.'" href="#" class="undochangesqty reposition marginrightonly" title="'.dol_escape_htmltag($langs->trans("Clear")).'">';
  964. print img_picto('', 'eraser', 'class="opacitymedium"');
  965. print '</a>';
  966. print '<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input" value="'.$qty_view.'">';
  967. print '</td>';
  968. //PMP Real
  969. print '<td class="right">';
  970. if (!empty($obj->pmp_real)) {
  971. $pmp_real = $obj->pmp_real;
  972. } else {
  973. $pmp_real = $product_static->pmp;
  974. }
  975. $pmp_valuation_real = $pmp_real * $qty_view;
  976. 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).'">';
  977. print '</td>';
  978. print '<td class="right">';
  979. 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.'">';
  980. print '</td>';
  981. $totalExpectedValuation += $pmp_valuation;
  982. $totalRealValuation += $pmp_valuation_real;
  983. } else {
  984. print '<td class="right">';
  985. print '<a id="undochangesqty_'.$obj->rowid.'" href="#" class="undochangesqty reposition marginrightonly" title="'.dol_escape_htmltag($langs->trans("Clear")).'">';
  986. print img_picto('', 'eraser', 'class="opacitymedium"');
  987. print '</a>';
  988. print '<input type="text" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'" id="id_'.$obj->rowid.'_input" value="'.$qty_view.'">';
  989. print '</td>';
  990. }
  991. // Picto delete line
  992. print '<td class="right">';
  993. 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>';
  994. $qty_tmp = price2num(GETPOST("id_".$obj->rowid."_input_tmp", 'MS')) >= 0 ? GETPOST("id_".$obj->rowid."_input_tmp") : $qty_view;
  995. print '<input type="hidden" class="maxwidth50 right realqty" name="id_'.$obj->rowid.'_input_tmp" id="id_'.$obj->rowid.'_input_tmp" value="'.$qty_tmp.'">';
  996. print '</td>';
  997. } else {
  998. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  999. //PMP Expected
  1000. if (!empty($obj->pmp_expected)) {
  1001. $pmp_expected = $obj->pmp_expected;
  1002. } else {
  1003. $pmp_expected = $product_static->pmp;
  1004. }
  1005. $pmp_valuation = $pmp_expected * $valuetoshow;
  1006. print '<td class="right">';
  1007. print price($pmp_expected);
  1008. print '</td>';
  1009. print '<td class="right">';
  1010. print price($pmp_valuation);
  1011. print '</td>';
  1012. print '<td class="right nowraponall">';
  1013. print $obj->qty_view; // qty found
  1014. print '</td>';
  1015. //PMP Real
  1016. print '<td class="right">';
  1017. if (!empty($obj->pmp_real)) {
  1018. $pmp_real = $obj->pmp_real;
  1019. } else {
  1020. $pmp_real = $product_static->pmp;
  1021. }
  1022. $pmp_valuation_real = $pmp_real * $obj->qty_view;
  1023. print price($pmp_real);
  1024. print '</td>';
  1025. print '<td class="right">';
  1026. print price($pmp_valuation_real);
  1027. print '</td>';
  1028. print '<td class="nowraponall right">';
  1029. $totalExpectedValuation += $pmp_valuation;
  1030. $totalRealValuation += $pmp_valuation_real;
  1031. } else {
  1032. print '<td class="right nowraponall">';
  1033. print $obj->qty_view; // qty found
  1034. print '</td>';
  1035. }
  1036. print '<td>';
  1037. if ($obj->fk_movement > 0) {
  1038. $stockmovment = new MouvementStock($db);
  1039. $stockmovment->fetch($obj->fk_movement);
  1040. print $stockmovment->getNomUrl(1, 'movements');
  1041. }
  1042. print '</td>';
  1043. }
  1044. print '</tr>';
  1045. $i++;
  1046. }
  1047. } else {
  1048. dol_print_error($db);
  1049. }
  1050. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  1051. print '<tr class="liste_total">';
  1052. print '<td colspan="4">'.$langs->trans("Total").'</td>';
  1053. print '<td class="right" colspan="2">'.price($totalExpectedValuation).'</td>';
  1054. print '<td class="right" id="totalRealValuation" colspan="3">'.price($totalRealValuation).'</td>';
  1055. print '<td></td>';
  1056. print '</tr>';
  1057. }
  1058. print '</table>';
  1059. print '</div>';
  1060. if ($object->status == $object::STATUS_VALIDATED) {
  1061. print '<center><input id="submitrecord" type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'"></center>';
  1062. }
  1063. print '</div>';
  1064. // Call method to disable the button if no qty entered yet for inventory
  1065. /*
  1066. if ($object->status != $object::STATUS_VALIDATED || !$hasinput) {
  1067. print '<script type="text/javascript">
  1068. jQuery(document).ready(function() {
  1069. console.log("Call disablebuttonmakemovementandclose because status = '.((int) $object->status).' or $hasinput = '.((int) $hasinput).'");
  1070. disablebuttonmakemovementandclose();
  1071. });
  1072. </script>';
  1073. }
  1074. */
  1075. print '</form>';
  1076. print '<script type="text/javascript">
  1077. $(document).ready(function() {
  1078. $(".paginationnext:last").click(function(e){
  1079. var form = $("#formrecord");
  1080. var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
  1081. $.ajax({
  1082. url: actionURL,
  1083. data: form.serialize(),
  1084. cache: false,
  1085. success: function(result){
  1086. window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page + 1).$paramwithsearch.'";
  1087. }});
  1088. });
  1089. $(".paginationprevious:last").click(function(e){
  1090. var form = $("#formrecord");
  1091. var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
  1092. $.ajax({
  1093. url: actionURL,
  1094. data: form.serialize(),
  1095. cache: false,
  1096. success: function(result){
  1097. window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page - 1).$paramwithsearch.'";
  1098. }});
  1099. });
  1100. $("#idbuttonmakemovementandclose").click(function(e){
  1101. var form = $("#formrecord");
  1102. var actionURL = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page).$paramwithsearch.'";
  1103. $.ajax({
  1104. url: actionURL,
  1105. data: form.serialize(),
  1106. cache: false,
  1107. success: function(result){
  1108. window.location.href = "'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&page='.($page - 1).$paramwithsearch.'&action=record";
  1109. }});
  1110. });
  1111. });
  1112. </script>';
  1113. if (getDolGlobalString('INVENTORY_MANAGE_REAL_PMP')) {
  1114. ?>
  1115. <script type="text/javascript">
  1116. $('.realqty').on('change', function () {
  1117. let realqty = $(this).closest('tr').find('.realqty').val();
  1118. let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
  1119. let realpmp = $(inputPmp).val();
  1120. if (!isNaN(realqty) && !isNaN(realpmp)) {
  1121. let realval = realqty * realpmp;
  1122. $(this).closest('tr').find('input[name^=realvaluation]').val(realval.toFixed(2));
  1123. }
  1124. updateTotalValuation();
  1125. });
  1126. $('input[class*=realpmp]').on('change', function () {
  1127. let inputQtyReal = $(this).closest('tr').find('.realqty');
  1128. let realqty = $(inputQtyReal).val();
  1129. let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
  1130. console.log(inputPmp);
  1131. let realPmpClassname = $(inputPmp).attr('class').match(/[\w-]*realpmp[\w-]*/g)[0];
  1132. let realpmp = $(inputPmp).val();
  1133. if (!isNaN(realpmp)) {
  1134. $('.'+realPmpClassname).val(realpmp); //For batch case if pmp is changed we change it everywhere it's same product and calc back everything
  1135. if (!isNaN(realqty)) {
  1136. let realval = realqty * realpmp;
  1137. $(this).closest('tr').find('input[name^=realvaluation]').val(realval.toFixed(2));
  1138. }
  1139. $('.realqty').trigger('change');
  1140. updateTotalValuation();
  1141. }
  1142. });
  1143. $('input[name^=realvaluation]').on('change', function () {
  1144. let inputQtyReal = $(this).closest('tr').find('.realqty');
  1145. let realqty = $(inputQtyReal).val();
  1146. let inputPmp = $(this).closest('tr').find('input[class*=realpmp]');
  1147. let inputRealValuation = $(this).closest('tr').find('input[name^=realvaluation]');
  1148. let realPmpClassname = $(inputPmp).attr('class').match(/[\w-]*realpmp[\w-]*/g)[0];
  1149. let realvaluation = $(inputRealValuation).val();
  1150. if (!isNaN(realvaluation) && !isNaN(realqty) && realvaluation !== '' && realqty !== '' && realqty !== 0) {
  1151. let realpmp = realvaluation / realqty
  1152. $('.'+realPmpClassname).val(realpmp); //For batch case if pmp is changed we change it everywhere it's same product and calc back everything
  1153. $('.realqty').trigger('change');
  1154. updateTotalValuation();
  1155. }
  1156. });
  1157. function updateTotalValuation() {
  1158. let total = 0;
  1159. $('input[name^=realvaluation]').each(function( index ) {
  1160. let val = $(this).val();
  1161. if(!isNaN(val)) total += parseFloat($(this).val());
  1162. });
  1163. let currencyFractionDigits = new Intl.NumberFormat('fr-FR', {
  1164. style: 'currency',
  1165. currency: 'EUR',
  1166. }).resolvedOptions().maximumFractionDigits;
  1167. $('#totalRealValuation').html(total.toLocaleString('fr-FR', {
  1168. maximumFractionDigits: currencyFractionDigits
  1169. }));
  1170. }
  1171. </script>
  1172. <?php
  1173. }
  1174. // End of page
  1175. llxFooter();
  1176. $db->close();