massstockmove.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. <?php
  2. /* Copyright (C) 2013-2022 Laurent Destaileur <ely@users.sourceforge.net>
  3. * Copyright (C) 2014 Regis Houssin <regis.houssin@inodbox.com>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/product/stock/massstockmove.php
  20. * \ingroup stock
  21. * \brief This page allows to select several products, then incoming warehouse and
  22. * outgoing warehouse and create all stock movements for this.
  23. */
  24. // Load Dolibarr environment
  25. require '../../main.inc.php';
  26. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/modules/import/import_csv.modules.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/lib/import.lib.php';
  35. $confirm = GETPOST('confirm', 'alpha');
  36. $filetoimport = GETPOST('filetoimport');
  37. // Load translation files required by the page
  38. $langs->loadLangs(array('products', 'stocks', 'orders', 'productbatch'));
  39. //init Hook
  40. $hookmanager->initHooks(array('massstockmove'));
  41. // Security check
  42. if ($user->socid) {
  43. $socid = $user->socid;
  44. }
  45. $result = restrictedArea($user, 'produit|service');
  46. //checks if a product has been ordered
  47. $action = GETPOST('action', 'aZ09');
  48. $id_product = GETPOST('productid', 'int');
  49. $id_sw = GETPOST('id_sw', 'int');
  50. $id_tw = GETPOST('id_tw', 'int');
  51. $batch = GETPOST('batch');
  52. $qty = GETPOST('qty');
  53. $idline = GETPOST('idline');
  54. // Load variable for pagination
  55. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  56. $sortfield = GETPOST('sortfield', 'aZ09comma');
  57. $sortorder = GETPOST('sortorder', 'aZ09comma');
  58. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  59. if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
  60. // If $page is not defined, or '' or -1 or if we click on clear filters
  61. $page = 0;
  62. }
  63. $offset = $limit * $page;
  64. $pageprev = $page - 1;
  65. $pagenext = $page + 1;
  66. if (!$sortfield) {
  67. $sortfield = 'p.ref';
  68. }
  69. if (!$sortorder) {
  70. $sortorder = 'ASC';
  71. }
  72. if (GETPOST('init')) {
  73. unset($_SESSION['massstockmove']);
  74. }
  75. $listofdata = array();
  76. if (!empty($_SESSION['massstockmove'])) {
  77. $listofdata = json_decode($_SESSION['massstockmove'], true);
  78. }
  79. $error = 0;
  80. /*
  81. * Actions
  82. */
  83. if ($action == 'addline' && $user->hasRight('stock', 'mouvement', 'creer')) {
  84. if (!($id_sw > 0)) {
  85. //$error++;
  86. //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors');
  87. if ($id_sw < 0) {
  88. $id_sw = 0;
  89. }
  90. }
  91. if (!($id_tw > 0)) {
  92. $error++;
  93. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors');
  94. }
  95. if ($id_sw > 0 && $id_tw == $id_sw) {
  96. $error++;
  97. $langs->load("errors");
  98. setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors');
  99. }
  100. if (!($id_product > 0)) {
  101. $error++;
  102. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
  103. }
  104. if (!$qty) {
  105. $error++;
  106. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
  107. }
  108. // Check a batch number is provided if product need it
  109. if (!$error) {
  110. $producttmp = new Product($db);
  111. $producttmp->fetch($id_product);
  112. if ($producttmp->hasbatch()) {
  113. if (empty($batch)) {
  114. $error++;
  115. $langs->load("errors");
  116. setEventMessages($langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $producttmp->ref), null, 'errors');
  117. }
  118. }
  119. }
  120. // TODO Check qty is ok for stock move. Note qty may not be enough yet, but we make a check now to report a warning.
  121. // What is more important is to have qty when doing action 'createmovements'
  122. if (!$error) {
  123. // Warning, don't forget lines already added into the $_SESSION['massstockmove']
  124. if ($producttmp->hasbatch()) {
  125. } else {
  126. }
  127. }
  128. //var_dump($_SESSION['massstockmove']);exit;
  129. if (!$error) {
  130. if (count(array_keys($listofdata)) > 0) {
  131. $id = max(array_keys($listofdata)) + 1;
  132. } else {
  133. $id = 1;
  134. }
  135. $listofdata[$id] = array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch);
  136. $_SESSION['massstockmove'] = json_encode($listofdata);
  137. //unset($id_sw);
  138. //unset($id_tw);
  139. unset($id_product);
  140. unset($batch);
  141. unset($qty);
  142. }
  143. }
  144. if ($action == 'delline' && $idline != '' && $user->hasRight('stock', 'mouvement', 'creer')) {
  145. if (!empty($listofdata[$idline])) {
  146. unset($listofdata[$idline]);
  147. }
  148. if (count($listofdata) > 0) {
  149. $_SESSION['massstockmove'] = json_encode($listofdata);
  150. } else {
  151. unset($_SESSION['massstockmove']);
  152. }
  153. }
  154. if ($action == 'createmovements' && $user->hasRight('stock', 'mouvement', 'creer')) {
  155. $error = 0;
  156. if (!GETPOST("label")) {
  157. $error++;
  158. setEventMessages($langs->trans("ErrorFieldRequired"), $langs->transnoentitiesnoconv("MovementLabel"), null, 'errors');
  159. }
  160. $db->begin();
  161. if (!$error) {
  162. $product = new Product($db);
  163. foreach ($listofdata as $key => $val) { // Loop on each movement to do
  164. $id = $val['id'];
  165. $id_product = $val['id_product'];
  166. $id_sw = $val['id_sw'];
  167. $id_tw = $val['id_tw'];
  168. $qty = price2num($val['qty']);
  169. $batch = $val['batch'];
  170. $dlc = -1; // They are loaded later from serial
  171. $dluo = -1; // They are loaded later from serial
  172. if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) {
  173. $result = $product->fetch($id_product);
  174. $product->load_stock('novirtual'); // Load array product->stock_warehouse
  175. // Define value of products moved
  176. $pricesrc = 0;
  177. if (!empty($product->pmp)) {
  178. $pricesrc = $product->pmp;
  179. }
  180. $pricedest = $pricesrc;
  181. //print 'price src='.$pricesrc.', price dest='.$pricedest;exit;
  182. if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { // If product does not need lot/serial
  183. // Remove stock if source warehouse defined
  184. if ($id_sw > 0) {
  185. $result1 = $product->correct_stock(
  186. $user,
  187. $id_sw,
  188. $qty,
  189. 1,
  190. GETPOST("label"),
  191. $pricesrc,
  192. GETPOST("codemove")
  193. );
  194. if ($result1 < 0) {
  195. $error++;
  196. setEventMessages($product->error, $product->errors, 'errors');
  197. }
  198. }
  199. // Add stock
  200. $result2 = $product->correct_stock(
  201. $user,
  202. $id_tw,
  203. $qty,
  204. 0,
  205. GETPOST("label"),
  206. $pricedest,
  207. GETPOST("codemove")
  208. );
  209. if ($result2 < 0) {
  210. $error++;
  211. setEventMessages($product->error, $product->errors, 'errors');
  212. }
  213. } else {
  214. $arraybatchinfo = $product->loadBatchInfo($batch);
  215. if (count($arraybatchinfo) > 0) {
  216. $firstrecord = array_shift($arraybatchinfo);
  217. $dlc = $firstrecord['eatby'];
  218. $dluo = $firstrecord['sellby'];
  219. //var_dump($batch);
  220. //var_dump($arraybatchinfo);
  221. //var_dump($firstrecord);
  222. //var_dump($dlc);
  223. //var_dump($dluo); exit;
  224. } else {
  225. $dlc = '';
  226. $dluo = '';
  227. }
  228. // Remove stock
  229. if ($id_sw > 0) {
  230. $result1 = $product->correct_stock_batch(
  231. $user,
  232. $id_sw,
  233. $qty,
  234. 1,
  235. GETPOST("label"),
  236. $pricesrc,
  237. $dlc,
  238. $dluo,
  239. $batch,
  240. GETPOST("codemove")
  241. );
  242. if ($result1 < 0) {
  243. $error++;
  244. setEventMessages($product->error, $product->errors, 'errors');
  245. }
  246. }
  247. // Add stock
  248. $result2 = $product->correct_stock_batch(
  249. $user,
  250. $id_tw,
  251. $qty,
  252. 0,
  253. GETPOST("label"),
  254. $pricedest,
  255. $dlc,
  256. $dluo,
  257. $batch,
  258. GETPOST("codemove")
  259. );
  260. if ($result2 < 0) {
  261. $error++;
  262. setEventMessages($product->error, $product->errors, 'errors');
  263. }
  264. }
  265. } else {
  266. // dol_print_error('',"Bad value saved into sessions");
  267. $error++;
  268. }
  269. }
  270. }
  271. //var_dump($_SESSION['massstockmove']);exit;
  272. if (!$error) {
  273. unset($_SESSION['massstockmove']);
  274. $db->commit();
  275. setEventMessages($langs->trans("StockMovementRecorded"), null, 'mesgs');
  276. header("Location: ".DOL_URL_ROOT.'/product/stock/index.php'); // Redirect to avoid pb when using back
  277. exit;
  278. } else {
  279. $db->rollback();
  280. setEventMessages($langs->trans("Error"), null, 'errors');
  281. }
  282. }
  283. if ($action == 'importCSV' && $user->hasRight('stock', 'mouvement', 'creer')) {
  284. dol_mkdir($conf->stock->dir_temp);
  285. $nowyearmonth = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
  286. $fullpath = $conf->stock->dir_temp."/".$user->id.'-csvfiletotimport.csv';
  287. $resultupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1);
  288. if (is_numeric($resultupload) && $resultupload > 0) {
  289. dol_syslog("File ".$fullpath." was added for import");
  290. } else {
  291. $error++;
  292. $langs->load("errors");
  293. if ($resultupload === 'ErrorDirNotWritable') {
  294. setEventMessages($langs->trans("ErrorFailedToSaveFile").' - '.$langs->trans($resultupload, $fullpath), null, 'errors');
  295. } else {
  296. setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
  297. }
  298. }
  299. if (!$error) {
  300. $importcsv = new ImportCsv($db, 'massstocklist');
  301. //print $importcsv->separator;
  302. $nblinesrecord = $importcsv->import_get_nb_of_lines($fullpath)-1;
  303. $importcsv->import_open_file($fullpath);
  304. $labelsrecord = $importcsv->import_read_record();
  305. if ($nblinesrecord < 1) {
  306. setEventMessages($langs->trans("BadNumberOfLinesMustHaveAtLeastOneLinePlusTitle"), null, 'errors');
  307. } else {
  308. $i=0;
  309. $data = array();
  310. $productstatic = new Product($db);
  311. $warehousestatics = new Entrepot($db);
  312. $warehousestatict = new Entrepot($db);
  313. // Loop on each line in CSV file
  314. while (($i < $nblinesrecord) && !$error) {
  315. $newrecord = $importcsv->import_read_record();
  316. $data[$i] = $newrecord;
  317. if (count($data[$i]) == 1) {
  318. // Only 1 empty line
  319. unset($data[$i]);
  320. $i++;
  321. continue;
  322. }
  323. $tmp_id_sw = $data[$i][0]['val'];
  324. $tmp_id_tw = $data[$i][1]['val'];
  325. $tmp_id_product = $data[$i][2]['val'];
  326. $tmp_qty = $data[$i][3]['val'];
  327. $tmp_batch = $data[$i][4]['val'];
  328. $errorforproduct = 0;
  329. $isidorref = 'ref';
  330. if (!is_numeric($tmp_id_product) && $tmp_id_product != '' && preg_match('/^id:/i', $tmp_id_product)) {
  331. $isidorref = 'id';
  332. }
  333. $tmp_id_product = preg_replace('/^(id|ref):/i', '', $tmp_id_product);
  334. if ($isidorref === 'ref') {
  335. $tmp_id_product = preg_replace('/^ref:/', '', $tmp_id_product);
  336. $result = fetchref($productstatic, $tmp_id_product);
  337. if ($result === -2) {
  338. $error++;
  339. $errorforproduct = 1;
  340. $langs->load("errors");
  341. setEventMessages($langs->trans("ErrorMultipleRecordFoundFromRef", $tmp_id_product), null, 'errors');
  342. } elseif ($result <= 0) {
  343. $error++;
  344. $errorforproduct = 1;
  345. $langs->load("errors");
  346. setEventMessages($langs->trans("ErrorRefNotFound", $tmp_id_product), null, 'errors');
  347. }
  348. $tmp_id_product = $result;
  349. }
  350. $data[$i][2]['val'] = $tmp_id_product;
  351. if (!$errorforproduct && !($tmp_id_product > 0)) {
  352. $error++;
  353. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
  354. }
  355. if ($tmp_id_sw !== '') {
  356. // For source, we allow empty value
  357. $errorforwarehouses = 0;
  358. $isidorref = 'ref';
  359. if (!is_numeric($tmp_id_sw) && $tmp_id_sw != '' && preg_match('/^id:/i', $tmp_id_sw)) {
  360. $isidorref = 'id';
  361. }
  362. $tmp_id_sw = preg_replace('/^(id|ref):/i', '', $tmp_id_sw);
  363. if ($isidorref === 'ref') {
  364. $tmp_id_sw = preg_replace('/^ref:/', '', $tmp_id_sw);
  365. $result = fetchref($warehousestatics, $tmp_id_sw);
  366. if ($result === -2) {
  367. $error++;
  368. $errorforwarehouses = 1;
  369. $langs->load("errors");
  370. setEventMessages($langs->trans("ErrorMultipleRecordFoundFromRef", $tmp_id_sw), null, 'errors');
  371. } elseif ($result <= 0) {
  372. $error++;
  373. $errorforwarehouses = 1;
  374. $langs->load("errors");
  375. setEventMessages($langs->trans("ErrorRefNotFound", $tmp_id_sw), null, 'errors');
  376. }
  377. $tmp_id_sw = $result;
  378. }
  379. $data[$i][0]['val'] = $tmp_id_sw;
  380. if (!$errorforwarehouses && !($tmp_id_sw > 0)) {
  381. $error++;
  382. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors');
  383. }
  384. }
  385. $errorforwarehouset = 0;
  386. $isidorref = 'ref';
  387. if (!is_numeric($tmp_id_tw) && $tmp_id_tw != '' && preg_match('/^id:/i', $tmp_id_tw)) {
  388. $isidorref = 'id';
  389. }
  390. $tmp_id_tw = preg_replace('/^(id|ref):/i', '', $tmp_id_tw);
  391. if ($isidorref === 'ref') {
  392. $tmp_id_tw = preg_replace('/^ref:/', '', $tmp_id_tw);
  393. $result = fetchref($warehousestatict, $tmp_id_tw);
  394. if ($result === -2) {
  395. $error++;
  396. $errorforwarehouset = 1;
  397. $langs->load("errors");
  398. setEventMessages($langs->trans("ErrorMultipleRecordFoundFromRef", $tmp_id_tw), null, 'errors');
  399. } elseif ($result <= 0) {
  400. $error++;
  401. $errorforwarehouset = 1;
  402. $langs->load("errors");
  403. setEventMessages($langs->trans("ErrorRefNotFound", $tmp_id_tw), null, 'errors');
  404. }
  405. $tmp_id_tw = $result;
  406. }
  407. $data[$i][1]['val'] = $tmp_id_tw;
  408. if (!$errorforwarehouset && !($tmp_id_tw > 0)) {
  409. $error++;
  410. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors');
  411. }
  412. // If a source is provided and same than target
  413. if ($tmp_id_sw > 0 && $tmp_id_tw == $tmp_id_sw) {
  414. $error++;
  415. $langs->load("errors");
  416. setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors');
  417. }
  418. if (!$tmp_qty) {
  419. $error++;
  420. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
  421. }
  422. // Check a batch number is provided if product need it
  423. if (!$error) {
  424. $producttmp = new Product($db);
  425. $producttmp->fetch($tmp_id_product);
  426. if ($producttmp->hasbatch()) {
  427. if (empty($tmp_batch)) {
  428. $error++;
  429. $langs->load("errors");
  430. setEventMessages($langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $producttmp->ref), null, 'errors');
  431. }
  432. }
  433. }
  434. $i++;
  435. }
  436. if (!$error) {
  437. foreach ($data as $key => $value) {
  438. if (count(array_keys($listofdata)) > 0) {
  439. $id = max(array_keys($listofdata)) + 1;
  440. } else {
  441. $id = 1;
  442. }
  443. $tmp_id_sw = $data[$key][0]['val'];
  444. $tmp_id_tw = $data[$key][1]['val'];
  445. $tmp_id_product = $data[$key][2]['val'];
  446. $tmp_qty = $data[$key][3]['val'];
  447. $tmp_batch = $data[$key][4]['val'];
  448. $listofdata[$key] = array('id'=>$key, 'id_sw'=>$tmp_id_sw, 'id_tw'=>$tmp_id_tw, 'id_product'=>$tmp_id_product, 'qty'=>$tmp_qty, 'batch'=>$tmp_batch);
  449. }
  450. }
  451. }
  452. }
  453. if ($error) {
  454. $listofdata = array();
  455. }
  456. $_SESSION['massstockmove'] = json_encode($listofdata);
  457. }
  458. if ($action == 'confirm_deletefile' && $confirm == 'yes') {
  459. $langs->load("other");
  460. $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
  461. if ($excludefirstline) {
  462. $param .= '&excludefirstline='.urlencode($excludefirstline);
  463. }
  464. if ($endatlinenb) {
  465. $param .= '&endatlinenb='.urlencode($endatlinenb);
  466. }
  467. $file = $conf->stock->dir_temp.'/'.GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
  468. $ret = dol_delete_file($file);
  469. if ($ret) {
  470. setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
  471. } else {
  472. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
  473. }
  474. Header('Location: '.$_SERVER["PHP_SELF"]);
  475. exit;
  476. }
  477. /*
  478. * View
  479. */
  480. $now = dol_now();
  481. $error = 0;
  482. $form = new Form($db);
  483. $formproduct = new FormProduct($db);
  484. $productstatic = new Product($db);
  485. $warehousestatics = new Entrepot($db);
  486. $warehousestatict = new Entrepot($db);
  487. $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks|DE:Modul_Bestände';
  488. $title = $langs->trans('MassMovement');
  489. llxHeader('', $title, $help_url);
  490. print load_fiche_titre($langs->trans("MassStockTransferShort"), '', 'stock');
  491. $titletoadd = $langs->trans("Select");
  492. $buttonrecord = $langs->trans("RecordMovements");
  493. $titletoaddnoent = $langs->transnoentitiesnoconv("Select");
  494. $buttonrecordnoent = $langs->transnoentitiesnoconv("RecordMovements");
  495. print '<span class="opacitymedium">'.$langs->trans("SelectProductInAndOutWareHouse", $titletoaddnoent, $buttonrecordnoent).'</span>';
  496. print '<br>';
  497. //print '<br>';
  498. // Form to upload a file
  499. print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
  500. print '<input type="hidden" name="token" value="'.newToken().'">';
  501. print '<input type="hidden" name="action" value="importCSV">';
  502. if (!empty($conf->dol_optimize_smallscreen)) {
  503. print '<br>';
  504. }
  505. print '<span class="opacitymedium">';
  506. print $langs->trans("or");
  507. print ' ';
  508. $importcsv = new ImportCsv($db, 'massstocklist');
  509. print $form->textwithpicto($langs->trans('SelectAStockMovementFileToImport'), $langs->transnoentitiesnoconv("InfoTemplateImport", $importcsv->separator));
  510. print '</span>';
  511. $maxfilesizearray = getMaxFileSizeArray();
  512. $maxmin = $maxfilesizearray['maxmin'];
  513. if ($maxmin > 0) {
  514. print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  515. }
  516. print '<input type="file" name="userfile" size="20" maxlength="80"> &nbsp; &nbsp; ';
  517. $out = (!getDolGlobalString('MAIN_UPLOAD_DOC') ? ' disabled' : '');
  518. print '<input type="submit" class="button small smallpaddingimp" value="'.$langs->trans("ImportFromCSV").'"'.$out.' name="sendit">';
  519. $out = '';
  520. if (getDolGlobalString('MAIN_UPLOAD_DOC')) {
  521. $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb
  522. $maxphp = @ini_get('upload_max_filesize'); // In unknown
  523. if (preg_match('/k$/i', $maxphp)) {
  524. $maxphp = preg_replace('/k$/i', '', $maxphp);
  525. $maxphp = $maxphp * 1;
  526. }
  527. if (preg_match('/m$/i', $maxphp)) {
  528. $maxphp = preg_replace('/m$/i', '', $maxphp);
  529. $maxphp = $maxphp * 1024;
  530. }
  531. if (preg_match('/g$/i', $maxphp)) {
  532. $maxphp = preg_replace('/g$/i', '', $maxphp);
  533. $maxphp = $maxphp * 1024 * 1024;
  534. }
  535. if (preg_match('/t$/i', $maxphp)) {
  536. $maxphp = preg_replace('/t$/i', '', $maxphp);
  537. $maxphp = $maxphp * 1024 * 1024 * 1024;
  538. }
  539. $maxphp2 = @ini_get('post_max_size'); // In unknown
  540. if (preg_match('/k$/i', $maxphp2)) {
  541. $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
  542. $maxphp2 = $maxphp2 * 1;
  543. }
  544. if (preg_match('/m$/i', $maxphp2)) {
  545. $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
  546. $maxphp2 = $maxphp2 * 1024;
  547. }
  548. if (preg_match('/g$/i', $maxphp2)) {
  549. $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
  550. $maxphp2 = $maxphp2 * 1024 * 1024;
  551. }
  552. if (preg_match('/t$/i', $maxphp2)) {
  553. $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
  554. $maxphp2 = $maxphp2 * 1024 * 1024 * 1024;
  555. }
  556. // Now $max and $maxphp and $maxphp2 are in Kb
  557. $maxmin = $max;
  558. $maxphptoshow = $maxphptoshowparam = '';
  559. if ($maxphp > 0) {
  560. $maxmin = min($max, $maxphp);
  561. $maxphptoshow = $maxphp;
  562. $maxphptoshowparam = 'upload_max_filesize';
  563. }
  564. if ($maxphp2 > 0) {
  565. $maxmin = min($max, $maxphp2);
  566. if ($maxphp2 < $maxphp) {
  567. $maxphptoshow = $maxphp2;
  568. $maxphptoshowparam = 'post_max_size';
  569. }
  570. }
  571. $langs->load('other');
  572. $out .= ' ';
  573. $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
  574. } else {
  575. $out .= ' ('.$langs->trans("UploadDisabled").')';
  576. }
  577. print $out;
  578. print '</form>';
  579. print '<br><br>';
  580. // Form to add a line
  581. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">';
  582. print '<input type="hidden" name="token" value="'.newToken().'">';
  583. print '<input type="hidden" name="action" value="addline">';
  584. print '<div class="div-table-responsive-no-min">';
  585. print '<table class="liste centpercent">';
  586. $param = '';
  587. print '<tr class="liste_titre">';
  588. print getTitleFieldOfList($langs->trans('WarehouseSource'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone ');
  589. print getTitleFieldOfList($langs->trans('WarehouseTarget'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone ');
  590. print getTitleFieldOfList($langs->trans('Product'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone ');
  591. if (isModEnabled('productbatch')) {
  592. print getTitleFieldOfList($langs->trans('Batch'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone ');
  593. }
  594. print getTitleFieldOfList($langs->trans('Qty'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right tagtd maxwidthonsmartphone ');
  595. print getTitleFieldOfList('', 0);
  596. print '</tr>';
  597. print '<tr class="oddeven">';
  598. // From warehouse
  599. print '<td class="nowraponall">';
  600. print img_picto($langs->trans("WarehouseSource"), 'stock', 'class="paddingright"').$formproduct->selectWarehouses($id_sw, 'id_sw', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200');
  601. print '</td>';
  602. // To warehouse
  603. print '<td class="nowraponall">';
  604. print img_picto($langs->trans("WarehouseTarget"), 'stock', 'class="paddingright"').$formproduct->selectWarehouses($id_tw, 'id_tw', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200');
  605. print '</td>';
  606. // Product
  607. print '<td class="nowraponall">';
  608. $filtertype = 0;
  609. if (getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  610. $filtertype = '';
  611. }
  612. if (getDolGlobalInt('PRODUIT_LIMIT_SIZE') <= 0) {
  613. $limit = '';
  614. } else {
  615. $limit = $conf->global->PRODUIT_LIMIT_SIZE;
  616. }
  617. print img_picto($langs->trans("Product"), 'product', 'class="paddingright"');
  618. print $form->select_produits($id_product, 'productid', $filtertype, $limit, 0, -1, 2, '', 1, array(), 0, '1', 0, 'minwidth200imp maxwidth300', 1, '', null, 1);
  619. print '</td>';
  620. // Batch number
  621. if (isModEnabled('productbatch')) {
  622. print '<td class="nowraponall">';
  623. print img_picto($langs->trans("LotSerial"), 'lot', 'class="paddingright"');
  624. print '<input type="text" name="batch" class="flat maxwidth75" value="'.dol_escape_htmltag($batch).'">';
  625. print '</td>';
  626. }
  627. // Qty
  628. print '<td class="right"><input type="text" class="flat maxwidth50 right" name="qty" value="'.price2num((float) $qty, 'MS').'"></td>';
  629. // Button to add line
  630. print '<td class="right"><input type="submit" class="button" name="addline" value="'.dol_escape_htmltag($titletoadd).'"></td>';
  631. print '</tr>';
  632. foreach ($listofdata as $key => $val) {
  633. $productstatic->id = 0;
  634. $productstatic->fetch($val['id_product']);
  635. $warehousestatics->id = 0;
  636. if ($val['id_sw'] > 0) {
  637. $warehousestatics->fetch($val['id_sw']);
  638. }
  639. $warehousestatict->id = 0;
  640. if ($val['id_tw'] > 0) {
  641. $warehousestatict->fetch($val['id_tw']);
  642. }
  643. if ($productstatic->id <= 0) {
  644. $error++;
  645. setEventMessages($langs->trans("ObjectNotFound", $langs->transnoentitiesnoconv("Product").' (id='.$val['id_product'].')'), null, 'errors');
  646. }
  647. if ($warehousestatics->id < 0) { // We accept 0 for source warehouse id
  648. $error++;
  649. setEventMessages($langs->trans("ObjectNotFound", $langs->transnoentitiesnoconv("WarehouseSource").' (id='.$val['id_sw'].')'), null, 'errors');
  650. }
  651. if ($warehousestatict->id <= 0) {
  652. $error++;
  653. setEventMessages($langs->trans("ObjectNotFound", $langs->transnoentitiesnoconv("WarehouseTarget").' (id='.$val['id_tw'].')'), null, 'errors');
  654. }
  655. if (!$error) {
  656. print '<tr class="oddeven">';
  657. print '<td>';
  658. if ($warehousestatics->id > 0) {
  659. print $warehousestatics->getNomUrl(1);
  660. } else {
  661. print '<span class="opacitymedium">';
  662. print $langs->trans("None");
  663. print '</span>';
  664. }
  665. print '</td>';
  666. print '<td>';
  667. print $warehousestatict->getNomUrl(1);
  668. print '</td>';
  669. print '<td>';
  670. print $productstatic->getNomUrl(1).' - '.dol_escape_htmltag($productstatic->label);
  671. print '</td>';
  672. if (isModEnabled('productbatch')) {
  673. print '<td>';
  674. print dol_escape_htmltag($val['batch']);
  675. print '</td>';
  676. }
  677. print '<td class="right">'.price2num((float) $val['qty'], 'MS').'</td>';
  678. print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=delline&token='.newToken().'&idline='.$val['id'].'">'.img_delete($langs->trans("Remove")).'</a></td>';
  679. print '</tr>';
  680. }
  681. }
  682. print '</table>';
  683. print '</div>';
  684. print '</form>';
  685. print '<br>';
  686. // Form to validate all movements
  687. if (count($listofdata)) {
  688. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire2" class="formconsumeproduce">';
  689. print '<input type="hidden" name="token" value="'.newToken().'">';
  690. print '<input type="hidden" name="action" value="createmovements">';
  691. // Button to record mass movement
  692. $codemove = (GETPOSTISSET("codemove") ? GETPOST("codemove", 'alpha') : dol_print_date(dol_now(), '%Y%m%d%H%M%S'));
  693. $labelmovement = GETPOST("label") ? GETPOST('label') : $langs->trans("MassStockTransferShort").' '.dol_print_date($now, '%Y-%m-%d %H:%M');
  694. print '<div class="center">';
  695. print '<span class="fieldrequired">'.$langs->trans("InventoryCode").':</span> ';
  696. print '<input type="text" name="codemove" class="maxwidth300" value="'.dol_escape_htmltag($codemove).'"> &nbsp; ';
  697. print '<span class="clearbothonsmartphone"></span>';
  698. print $langs->trans("MovementLabel").': ';
  699. print '<input type="text" name="label" class="minwidth300" value="'.dol_escape_htmltag($labelmovement).'"><br>';
  700. print '<br>';
  701. print '<div class="center"><input type="submit" class="button" name="valid" value="'.dol_escape_htmltag($buttonrecord).'"></div>';
  702. print '<br>';
  703. print '</div>';
  704. print '</form>';
  705. }
  706. if ($action == 'delete') {
  707. print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=3'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
  708. }
  709. // End of page
  710. llxFooter();
  711. $db->close();
  712. /**
  713. * Verify if $haystack startswith $needle
  714. *
  715. * @param string $haystack string to test
  716. * @param string $needle string to find
  717. * @return bool false if Ko true else
  718. */
  719. function startsWith($haystack, $needle)
  720. {
  721. $length = strlen($needle);
  722. return substr($haystack, 0, $length) === $needle;
  723. }
  724. /**
  725. * Fetch object with ref
  726. *
  727. * @param Object $static_object static object to fetch
  728. * @param string $tmp_ref ref of the object to fetch
  729. * @return int Return integer <0 if Ko or Id of object
  730. */
  731. function fetchref($static_object, $tmp_ref)
  732. {
  733. if (startsWith($tmp_ref, 'ref:')) {
  734. $tmp_ref = str_replace('ref:', '', $tmp_ref);
  735. }
  736. $static_object->id = 0;
  737. $static_object->fetch('', $tmp_ref);
  738. return $static_object->id;
  739. }