mo_production.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  1. <?php
  2. /* Copyright (C) 2019-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2023 Christian Humpel <christian.humpel@gmail.com>
  4. * Copyright (C) 2023 Vincent de Grandpré <vincent@de-grandpre.quebec>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file mo_production.php
  21. * \ingroup mrp
  22. * \brief Page to make production on a MO
  23. */
  24. // Load Dolibarr environment
  25. require '../main.inc.php';
  26. require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp_mo.lib.php';
  32. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  34. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
  39. // Load translation files required by the page
  40. $langs->loadLangs(array("mrp", "stocks", "other", "product", "productbatch"));
  41. // Get parameters
  42. $id = GETPOST('id', 'int');
  43. $ref = GETPOST('ref', 'alpha');
  44. $action = GETPOST('action', 'aZ09');
  45. $confirm = GETPOST('confirm', 'alpha');
  46. $cancel = GETPOST('cancel', 'aZ09');
  47. $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search
  48. $backtopage = GETPOST('backtopage', 'alpha');
  49. $lineid = GETPOST('lineid', 'int');
  50. $fk_movement = GETPOST('fk_movement', 'int');
  51. $fk_default_warehouse = GETPOST('fk_default_warehouse', 'int');
  52. $collapse = GETPOST('collapse', 'aZ09comma');
  53. // Initialize technical objects
  54. $object = new Mo($db);
  55. $extrafields = new ExtraFields($db);
  56. $diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id;
  57. $objectline = new MoLine($db);
  58. $hookmanager->initHooks(array('moproduction', 'globalcard')); // Note that conf->hooks_modules contains array
  59. // Fetch optionals attributes and labels
  60. $extrafields->fetch_name_optionals_label($object->table_element);
  61. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  62. // Initialize array of search criterias
  63. $search_all = GETPOST("search_all", 'alpha');
  64. $search = array();
  65. foreach ($object->fields as $key => $val) {
  66. if (GETPOST('search_'.$key, 'alpha')) {
  67. $search[$key] = GETPOST('search_'.$key, 'alpha');
  68. }
  69. }
  70. if (empty($action) && empty($id) && empty($ref)) {
  71. $action = 'view';
  72. }
  73. // Load object
  74. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
  75. // Security check - Protection if external user
  76. //if ($user->socid > 0) accessforbidden();
  77. //if ($user->socid > 0) $socid = $user->socid;
  78. $isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
  79. $result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'rowid', $isdraft);
  80. // Permissions
  81. $permissionnote = $user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php
  82. $permissiondellink = $user->rights->mrp->write; // Used by the include of actions_dellink.inc.php
  83. $permissiontoadd = $user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
  84. $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
  85. $permissiontoproduce = $permissiontoadd;
  86. $permissiontoupdatecost = $user->hasRight('bom', 'read'); // User who can define cost must have knowledge of pricing
  87. $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
  88. /*
  89. * Actions
  90. */
  91. $parameters = array();
  92. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  93. if ($reshook < 0) {
  94. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  95. }
  96. if (empty($reshook)) {
  97. $error = 0;
  98. $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
  99. if (empty($backtopage) || ($cancel && empty($id))) {
  100. //var_dump($backurlforlist);exit;
  101. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  102. $backtopage = $backurlforlist;
  103. } else {
  104. $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__');
  105. }
  106. }
  107. $triggermodname = 'MO_MODIFY'; // Name of trigger action code to execute when we modify record
  108. if ($action == 'confirm_cancel' && $confirm == 'yes' && !empty($permissiontoadd)) {
  109. $also_cancel_consumed_and_produced_lines = (GETPOST('alsoCancelConsumedAndProducedLines', 'alpha') ? 1 : 0);
  110. $result = $object->cancel($user, 0, $also_cancel_consumed_and_produced_lines);
  111. if ($result > 0) {
  112. header("Location: " . dol_buildpath('/mrp/mo_card.php?id=' . $object->id, 1));
  113. exit;
  114. } else {
  115. $action = '';
  116. setEventMessages($object->error, $object->errors, 'errors');
  117. }
  118. } elseif ($action == 'confirm_delete' && $confirm == 'yes' && !empty($permissiontodelete)) {
  119. $also_cancel_consumed_and_produced_lines = (GETPOST('alsoCancelConsumedAndProducedLines', 'alpha') ? 1 : 0);
  120. $result = $object->delete($user, 0, $also_cancel_consumed_and_produced_lines);
  121. if ($result > 0) {
  122. header("Location: " . $backurlforlist);
  123. exit;
  124. } else {
  125. $action = '';
  126. setEventMessages($object->error, $object->errors, 'errors');
  127. }
  128. }
  129. // Actions cancel, add, update, delete or clone
  130. include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
  131. // Actions when linking object each other
  132. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
  133. // Actions when printing a doc from card
  134. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  135. // Actions to send emails
  136. $triggersendname = 'MO_SENTBYMAIL';
  137. $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO';
  138. $trackid = 'mo'.$object->id;
  139. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  140. // Action to move up and down lines of object
  141. //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  142. if ($action == 'set_thirdparty' && $permissiontoadd) {
  143. $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, $triggermodname);
  144. }
  145. if ($action == 'classin' && $permissiontoadd) {
  146. $object->setProject(GETPOST('projectid', 'int'));
  147. }
  148. if ($action == 'confirm_reopen' && $permissiontoadd) {
  149. $result = $object->setStatut($object::STATUS_INPROGRESS, 0, '', 'MRP_REOPEN');
  150. }
  151. if (($action == 'confirm_addconsumeline' && GETPOST('addconsumelinebutton') && $permissiontoadd)
  152. || ($action == 'confirm_addproduceline' && GETPOST('addproducelinebutton') && $permissiontoadd)) {
  153. $moline = new MoLine($db);
  154. // Line to produce
  155. $moline->fk_mo = $object->id;
  156. $moline->qty = GETPOST('qtytoadd', 'int');
  157. $moline->fk_product = GETPOST('productidtoadd', 'int');
  158. if (GETPOST('addconsumelinebutton')) {
  159. $moline->role = 'toconsume';
  160. } else {
  161. $moline->role = 'toproduce';
  162. }
  163. $moline->origin_type = 'free'; // free consume line
  164. $moline->position = 0;
  165. // Is it a product or a service ?
  166. if (!empty($moline->fk_product)) {
  167. $tmpproduct = new Product($db);
  168. $tmpproduct->fetch($moline->fk_product);
  169. if ($tmpproduct->type == Product::TYPE_SERVICE) {
  170. $moline->fk_default_workstation = $tmpproduct->fk_default_workstation;
  171. }
  172. $moline->disable_stock_change = ($tmpproduct->type == Product::TYPE_SERVICE ? 1 : 0);
  173. if ($conf->global->PRODUCT_USE_UNITS) {
  174. $moline->fk_unit = $tmpproduct->fk_unit;
  175. }
  176. }
  177. // Extrafields
  178. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  179. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  180. // Unset extrafield
  181. if (is_array($extralabelsline)) {
  182. // Get extra fields
  183. foreach ($extralabelsline as $key => $value) {
  184. unset($_POST["options_".$key]);
  185. }
  186. }
  187. if (is_array($array_options) && count($array_options) > 0) {
  188. $moline->array_options = $array_options;
  189. }
  190. $resultline = $moline->create($user, false); // Never use triggers here
  191. if ($resultline <= 0) {
  192. $error++;
  193. setEventMessages($moline->error, $moline->errors, 'errors');
  194. }
  195. $action = '';
  196. // Redirect to refresh the tab information
  197. header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
  198. exit;
  199. }
  200. if (in_array($action, array('confirm_consumeorproduce', 'confirm_consumeandproduceall')) && $permissiontoproduce) {
  201. $stockmove = new MouvementStock($db);
  202. $labelmovement = GETPOST('inventorylabel', 'alphanohtml');
  203. $codemovement = GETPOST('inventorycode', 'alphanohtml');
  204. $db->begin();
  205. $pos = 0;
  206. // Process line to consume
  207. foreach ($object->lines as $line) {
  208. if ($line->role == 'toconsume') {
  209. $tmpproduct = new Product($db);
  210. $tmpproduct->fetch($line->fk_product);
  211. $i = 1;
  212. while (GETPOSTISSET('qty-'.$line->id.'-'.$i)) {
  213. $qtytoprocess = price2num(GETPOST('qty-'.$line->id.'-'.$i));
  214. if ($qtytoprocess != 0) {
  215. // Check warehouse is set if we should have to
  216. if (GETPOSTISSET('idwarehouse-'.$line->id.'-'.$i)) { // If there is a warehouse to set
  217. if (!(GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set.
  218. $langs->load("errors");
  219. setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors');
  220. $error++;
  221. }
  222. if ($tmpproduct->status_batch && (!GETPOST('batch-'.$line->id.'-'.$i))) {
  223. $langs->load("errors");
  224. setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors');
  225. $error++;
  226. }
  227. }
  228. $idstockmove = 0;
  229. if (!$error && GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0) {
  230. // Record stock movement
  231. $id_product_batch = 0;
  232. $stockmove->setOrigin($object->element, $object->id);
  233. $stockmove->context['mrp_role'] = 'toconsume';
  234. if ($qtytoprocess >= 0) {
  235. $idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement);
  236. } else {
  237. $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess * -1, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement);
  238. }
  239. if ($idstockmove < 0) {
  240. $error++;
  241. setEventMessages($stockmove->error, $stockmove->errors, 'errors');
  242. }
  243. }
  244. if (!$error) {
  245. // Record consumption
  246. $moline = new MoLine($db);
  247. $moline->fk_mo = $object->id;
  248. $moline->position = $pos;
  249. $moline->fk_product = $line->fk_product;
  250. $moline->fk_warehouse = GETPOST('idwarehouse-'.$line->id.'-'.$i);
  251. $moline->qty = $qtytoprocess;
  252. $moline->batch = GETPOST('batch-'.$line->id.'-'.$i);
  253. $moline->role = 'consumed';
  254. $moline->fk_mrp_production = $line->id;
  255. $moline->fk_stock_movement = $idstockmove == 0 ? null : $idstockmove;
  256. $moline->fk_user_creat = $user->id;
  257. $resultmoline = $moline->create($user);
  258. if ($resultmoline <= 0) {
  259. $error++;
  260. setEventMessages($moline->error, $moline->errors, 'errors');
  261. }
  262. $pos++;
  263. }
  264. }
  265. $i++;
  266. }
  267. }
  268. }
  269. // Process line to produce
  270. $pos = 0;
  271. foreach ($object->lines as $line) {
  272. if ($line->role == 'toproduce') {
  273. $tmpproduct = new Product($db);
  274. $tmpproduct->fetch($line->fk_product);
  275. $i = 1;
  276. while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
  277. $qtytoprocess = price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i));
  278. $pricetoprocess = GETPOST('pricetoproduce-'.$line->id.'-'.$i) ? price2num(GETPOST('pricetoproduce-'.$line->id.'-'.$i)) : 0;
  279. if ($qtytoprocess != 0) {
  280. // Check warehouse is set if we should have to
  281. if (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i)) { // If there is a warehouse to set
  282. if (!(GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set.
  283. $langs->load("errors");
  284. setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors');
  285. $error++;
  286. }
  287. if (isModEnabled('productbatch') && $tmpproduct->status_batch && (!GETPOST('batchtoproduce-'.$line->id.'-'.$i))) {
  288. $langs->load("errors");
  289. setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors');
  290. $error++;
  291. }
  292. }
  293. $idstockmove = 0;
  294. if (!$error && GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0) {
  295. // Record stock movement
  296. $id_product_batch = 0;
  297. $stockmove->origin_type = $object->element;
  298. $stockmove->origin_id = $object->id;
  299. $stockmove->context['mrp_role'] = 'toproduce';
  300. $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, $pricetoprocess, $labelmovement, '', '', GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement);
  301. if ($idstockmove < 0) {
  302. $error++;
  303. setEventMessages($stockmove->error, $stockmove->errors, 'errors');
  304. }
  305. }
  306. if (!$error) {
  307. // Record production
  308. $moline = new MoLine($db);
  309. $moline->fk_mo = $object->id;
  310. $moline->position = $pos;
  311. $moline->fk_product = $line->fk_product;
  312. $moline->fk_warehouse = GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i);
  313. $moline->qty = $qtytoprocess;
  314. $moline->batch = GETPOST('batchtoproduce-'.$line->id.'-'.$i);
  315. $moline->role = 'produced';
  316. $moline->fk_mrp_production = $line->id;
  317. $moline->fk_stock_movement = $idstockmove;
  318. $moline->fk_user_creat = $user->id;
  319. $resultmoline = $moline->create($user);
  320. if ($resultmoline <= 0) {
  321. $error++;
  322. setEventMessages($moline->error, $moline->errors, 'errors');
  323. }
  324. $pos++;
  325. }
  326. }
  327. $i++;
  328. }
  329. }
  330. }
  331. if (!$error) {
  332. $consumptioncomplete = true;
  333. $productioncomplete = true;
  334. if (GETPOST('autoclose', 'int')) {
  335. foreach ($object->lines as $line) {
  336. if ($line->role == 'toconsume') {
  337. $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
  338. $alreadyconsumed = 0;
  339. foreach ($arrayoflines as $line2) {
  340. $alreadyconsumed += $line2['qty'];
  341. }
  342. if ($alreadyconsumed < $line->qty) {
  343. $consumptioncomplete = false;
  344. }
  345. }
  346. if ($line->role == 'toproduce') {
  347. $arrayoflines = $object->fetchLinesLinked('produced', $line->id);
  348. $alreadyproduced = 0;
  349. foreach ($arrayoflines as $line2) {
  350. $alreadyproduced += $line2['qty'];
  351. }
  352. if ($alreadyproduced < $line->qty) {
  353. $productioncomplete = false;
  354. }
  355. }
  356. }
  357. } else {
  358. $consumptioncomplete = false;
  359. $productioncomplete = false;
  360. }
  361. // Update status of MO
  362. dol_syslog("consumptioncomplete = ".$consumptioncomplete." productioncomplete = ".$productioncomplete);
  363. //var_dump("consumptioncomplete = ".$consumptioncomplete." productioncomplete = ".$productioncomplete);
  364. if ($consumptioncomplete && $productioncomplete) {
  365. $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
  366. } else {
  367. $result = $object->setStatut($object::STATUS_INPROGRESS, 0, '', 'MRP_MO_PRODUCED');
  368. }
  369. if ($result <= 0) {
  370. $error++;
  371. setEventMessages($object->error, $object->errors, 'errors');
  372. }
  373. }
  374. if ($error) {
  375. $action = str_replace('confirm_', '', $action);
  376. $db->rollback();
  377. } else {
  378. $db->commit();
  379. // Redirect to avoid to action done a second time if we make a back from browser
  380. header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
  381. exit;
  382. }
  383. }
  384. // Action close produced
  385. if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) {
  386. $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
  387. if ($result >= 0) {
  388. // Define output language
  389. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  390. $outputlangs = $langs;
  391. $newlang = '';
  392. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  393. $newlang = GETPOST('lang_id', 'aZ09');
  394. }
  395. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  396. $newlang = $object->thirdparty->default_lang;
  397. }
  398. if (!empty($newlang)) {
  399. $outputlangs = new Translate("", $conf);
  400. $outputlangs->setDefaultLang($newlang);
  401. }
  402. $model = $object->model_pdf;
  403. $ret = $object->fetch($id); // Reload to get new records
  404. $object->generateDocument($model, $outputlangs, 0, 0, 0);
  405. }
  406. } else {
  407. setEventMessages($object->error, $object->errors, 'errors');
  408. }
  409. }
  410. if ($action == 'confirm_editline' && $permissiontoadd) {
  411. $moline = new MoLine($db);
  412. $res = $moline->fetch(GETPOST('lineid', 'int'));
  413. if ($result > 0) {
  414. $extrafields->fetch_name_optionals_label($moline->element);
  415. foreach ($extrafields->attributes[$moline->table_element]['label'] as $key => $label) {
  416. $value = GETPOST('options_'.$key, 'alphanohtml');
  417. $moline->array_options["options_".$key] = $value;
  418. }
  419. $moline->qty = GETPOST('qty_lineProduce', 'int');
  420. $res = $moline->update($user);
  421. if ($res < 0) {
  422. setEventMessages($moline->error, $moline->errors, 'errors');
  423. header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
  424. exit;
  425. }
  426. header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
  427. exit;
  428. }
  429. }
  430. }
  431. /*
  432. * View
  433. */
  434. $form = new Form($db);
  435. $formproject = new FormProjets($db);
  436. $formproduct = new FormProduct($db);
  437. $tmpwarehouse = new Entrepot($db);
  438. $tmpbatch = new Productlot($db);
  439. $tmpstockmovement = new MouvementStock($db);
  440. $help_url = 'EN:Module_Manufacturing_Orders|FR:Module_Ordres_de_Fabrication|DE:Modul_Fertigungsauftrag';
  441. $morejs = array('/mrp/js/lib_dispatch.js.php');
  442. llxHeader('', $langs->trans('Mo'), $help_url, '', 0, 0, $morejs);
  443. $newToken = newToken();
  444. // Part to show record
  445. if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
  446. $res = $object->fetch_thirdparty();
  447. $res = $object->fetch_optionals();
  448. if (getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') && $object->fk_warehouse > 0) {
  449. $tmpwarehouse->fetch($object->fk_warehouse);
  450. $fk_default_warehouse = $object->fk_warehouse;
  451. }
  452. $head = moPrepareHead($object);
  453. print dol_get_fiche_head($head, 'production', $langs->trans("ManufacturingOrder"), -1, $object->picto);
  454. $formconfirm = '';
  455. // Confirmation to delete
  456. if ($action == 'delete') {
  457. $formquestion = array(
  458. array(
  459. 'label' => $langs->trans('MoCancelConsumedAndProducedLines'),
  460. 'name' => 'alsoCancelConsumedAndProducedLines',
  461. 'type' => 'checkbox',
  462. 'value' => 0
  463. ),
  464. );
  465. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', $formquestion, 0, 1);
  466. }
  467. // Confirmation to delete line
  468. if ($action == 'deleteline') {
  469. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid.'&fk_movement='.$fk_movement, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
  470. }
  471. // Clone confirmation
  472. if ($action == 'clone') {
  473. // Create an array for form
  474. $formquestion = array();
  475. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  476. }
  477. // Confirmation of validation
  478. if ($action == 'validate') {
  479. // We check that object has a temporary ref
  480. $ref = substr($object->ref, 1, 4);
  481. if ($ref == 'PROV') {
  482. $object->fetch_product();
  483. $numref = $object->getNextNumRef($object->product);
  484. } else {
  485. $numref = $object->ref;
  486. }
  487. $text = $langs->trans('ConfirmValidateMo', $numref);
  488. /*if (isModEnabled('notification'))
  489. {
  490. require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
  491. $notify = new Notify($db);
  492. $text .= '<br>';
  493. $text .= $notify->confirmMessage('BOM_VALIDATE', $object->socid, $object);
  494. }*/
  495. $formquestion = array();
  496. if (isModEnabled('mrp')) {
  497. $langs->load("mrp");
  498. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  499. $formproduct = new FormProduct($db);
  500. $forcecombo = 0;
  501. if ($conf->browser->name == 'ie') {
  502. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  503. }
  504. $formquestion = array(
  505. // 'text' => $langs->trans("ConfirmClone"),
  506. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  507. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  508. );
  509. }
  510. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220);
  511. }
  512. // Confirmation to cancel
  513. if ($action == 'cancel') {
  514. $formquestion = array(
  515. array(
  516. 'label' => $langs->trans('MoCancelConsumedAndProducedLines'),
  517. 'name' => 'alsoCancelConsumedAndProducedLines',
  518. 'type' => 'checkbox',
  519. 'value' => !getDolGlobalString('MO_ALSO_CANCEL_CONSUMED_AND_PRODUCED_LINES_BY_DEFAULT') ? 0 : 1
  520. ),
  521. );
  522. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CancelMo'), $langs->trans('ConfirmCancelMo'), 'confirm_cancel', $formquestion, 0, 1);
  523. }
  524. // Call Hook formConfirm
  525. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
  526. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  527. if (empty($reshook)) {
  528. $formconfirm .= $hookmanager->resPrint;
  529. } elseif ($reshook > 0) {
  530. $formconfirm = $hookmanager->resPrint;
  531. }
  532. // Print form confirm
  533. print $formconfirm;
  534. // MO file
  535. // ------------------------------------------------------------
  536. $linkback = '<a href="'.DOL_URL_ROOT.'/mrp/mo_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  537. $morehtmlref = '<div class="refidno">';
  538. /*
  539. // Ref bis
  540. $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', 0, 1);
  541. $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', null, null, '', 1);
  542. */
  543. // Thirdparty
  544. if (is_object($object->thirdparty)) {
  545. $morehtmlref .= $object->thirdparty->getNomUrl(1, 'customer');
  546. if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
  547. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
  548. }
  549. }
  550. // Project
  551. if (isModEnabled('project')) {
  552. $langs->load("projects");
  553. if (is_object($object->thirdparty)) {
  554. $morehtmlref .= '<br>';
  555. }
  556. if ($permissiontoadd) {
  557. $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
  558. if ($action != 'classify') {
  559. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
  560. }
  561. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
  562. } else {
  563. if (!empty($object->fk_project)) {
  564. $proj = new Project($db);
  565. $proj->fetch($object->fk_project);
  566. $morehtmlref .= $proj->getNomUrl(1);
  567. if ($proj->title) {
  568. $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
  569. }
  570. }
  571. }
  572. }
  573. $morehtmlref .= '</div>';
  574. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  575. print '<div class="fichecenter">';
  576. print '<div class="fichehalfleft">';
  577. print '<div class="underbanner clearboth"></div>';
  578. print '<table class="border centpercent tableforfield">'."\n";
  579. // Common attributes
  580. $keyforbreak = 'fk_warehouse';
  581. unset($object->fields['fk_project']);
  582. unset($object->fields['fk_soc']);
  583. include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
  584. // Other attributes
  585. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  586. print '</table>';
  587. print '</div>';
  588. print '</div>';
  589. print '<div class="clearboth"></div>';
  590. print dol_get_fiche_end();
  591. if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  592. print '<div class="tabsAction">';
  593. $parameters = array();
  594. // Note that $action and $object may be modified by hook
  595. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
  596. if (empty($reshook)) {
  597. // Validate
  598. if ($object->status == $object::STATUS_DRAFT) {
  599. if ($permissiontoadd) {
  600. if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
  601. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate&token='.$newToken.'">'.$langs->trans("Validate").'</a>';
  602. } else {
  603. $langs->load("errors");
  604. print '<a class="butActionRefused" href="" title="'.$langs->trans("ErrorAddAtLeastOneLineFirst").'">'.$langs->trans("Validate").'</a>';
  605. }
  606. }
  607. }
  608. // Consume or produce
  609. if ($object->status == Mo::STATUS_VALIDATED || $object->status == Mo::STATUS_INPROGRESS) {
  610. if ($permissiontoproduce) {
  611. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=consumeorproduce&token='.$newToken.'">'.$langs->trans('ConsumeOrProduce').'</a>';
  612. } else {
  613. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ConsumeOrProduce').'</a>';
  614. }
  615. } elseif ($object->status == Mo::STATUS_DRAFT) {
  616. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("ValidateBefore").'">'.$langs->trans('ConsumeOrProduce').'</a>';
  617. }
  618. // ConsumeAndProduceAll
  619. if ($object->status == Mo::STATUS_VALIDATED || $object->status == Mo::STATUS_INPROGRESS) {
  620. if ($permissiontoproduce) {
  621. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=consumeandproduceall&token='.$newToken.'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
  622. } else {
  623. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
  624. }
  625. } elseif ($object->status == Mo::STATUS_DRAFT) {
  626. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("ValidateBefore").'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
  627. }
  628. // Cancel - Reopen
  629. if ($permissiontoadd) {
  630. if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) {
  631. $arrayproduced = $object->fetchLinesLinked('produced', 0);
  632. $nbProduced = 0;
  633. foreach ($arrayproduced as $lineproduced) {
  634. $nbProduced += $lineproduced['qty'];
  635. }
  636. if ($nbProduced > 0) { // If production has started, we can close it
  637. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_produced&confirm=yes&token='.$newToken.'">'.$langs->trans("Close").'</a>'."\n";
  638. } else {
  639. print '<a class="butActionRefused" href="#" title="'.$langs->trans("GoOnTabProductionToProduceFirst", $langs->transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").'</a>'."\n";
  640. }
  641. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.$newToken.'">'.$langs->trans("Cancel").'</a>'."\n";
  642. }
  643. if ($object->status == $object::STATUS_CANCELED) {
  644. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes&token='.$newToken.'">'.$langs->trans("ReOpen").'</a>'."\n";
  645. }
  646. if ($object->status == $object::STATUS_PRODUCED) {
  647. if ($permissiontoproduce) {
  648. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&token='.$newToken.'">'.$langs->trans('ReOpen').'</a>';
  649. } else {
  650. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ReOpen').'</a>';
  651. }
  652. }
  653. }
  654. }
  655. print '</div>';
  656. }
  657. if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline', 'addproduceline', 'editline'))) {
  658. print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  659. print '<input type="hidden" name="token" value="'.newToken().'">';
  660. print '<input type="hidden" name="action" value="confirm_'.$action.'">';
  661. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  662. print '<input type="hidden" name="id" value="'.$id.'">';
  663. // Note: closing form is add end of page
  664. if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  665. $defaultstockmovementlabel = GETPOST('inventorylabel', 'alphanohtml') ? GETPOST('inventorylabel', 'alphanohtml') : $langs->trans("ProductionForRef", $object->ref);
  666. $defaultstockmovementcode = GETPOST('inventorycode', 'alphanohtml') ? GETPOST('inventorycode', 'alphanohtml') : dol_print_date(dol_now(), 'dayhourlog');
  667. print '<div class="center'.(in_array($action, array('consumeorproduce', 'consumeandproduceall')) ? ' formconsumeproduce' : '').'">';
  668. print '<div class="opacitymedium hideonsmartphone paddingbottom">'.$langs->trans("ConfirmProductionDesc", $langs->transnoentitiesnoconv("Confirm")).'<br></div>';
  669. print '<span class="fieldrequired">'.$langs->trans("InventoryCode").':</span> <input type="text" class="minwidth150 maxwidth200" name="inventorycode" value="'.$defaultstockmovementcode.'"> &nbsp; ';
  670. print '<span class="clearbothonsmartphone"></span>';
  671. print $langs->trans("MovementLabel").': <input type="text" class="minwidth300" name="inventorylabel" value="'.$defaultstockmovementlabel.'"><br><br>';
  672. print '<input type="checkbox" id="autoclose" name="autoclose" value="1"'.(GETPOSTISSET('inventorylabel') ? (GETPOST('autoclose') ? ' checked="checked"' : '') : ' checked="checked"').'> <label for="autoclose">'.$langs->trans("AutoCloseMO").'</label><br>';
  673. print '<input type="submit" class="button" value="'.$langs->trans("Confirm").'" name="confirm">';
  674. print ' &nbsp; ';
  675. print '<input class="button button-cancel" type="submit" value="'.$langs->trans("Cancel").'" name="cancel">';
  676. print '<br><br>';
  677. print '</div>';
  678. print '<br>';
  679. }
  680. }
  681. /*
  682. * Lines
  683. */
  684. $collapse = 1;
  685. if (!empty($object->table_element_line)) {
  686. // Show object lines
  687. $object->fetchLines();
  688. $bomcost = 0;
  689. if ($object->fk_bom > 0) {
  690. $bom = new BOM($db);
  691. $res = $bom->fetch($object->fk_bom);
  692. if ($res > 0) {
  693. $bom->calculateCosts();
  694. $bomcost = $bom->unit_cost;
  695. }
  696. }
  697. // Lines to consume
  698. print '<div class="fichecenter">';
  699. print '<div class="fichehalfleft">';
  700. print '<div class="clearboth"></div>';
  701. $url = $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addconsumeline&token='.newToken();
  702. $permissiontoaddaconsumeline = $object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED;
  703. $parameters = array('morecss'=>'reposition');
  704. $newcardbutton = '';
  705. if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') {
  706. $newcardbutton = dolGetButtonTitle($langs->trans('AddNewConsumeLines'), '', 'fa fa-plus-circle size15x', $url, '', $permissiontoaddaconsumeline, $parameters);
  707. }
  708. print load_fiche_titre($langs->trans('Consumption'), $newcardbutton, '', 0, '', '', '');
  709. print '<div class="div-table-responsive-no-min">';
  710. print '<table class="noborder noshadow centpercent nobottom">';
  711. print '<tr class="liste_titre">';
  712. // Product
  713. print '<td>'.$langs->trans("Product").'</td>';
  714. // Qty
  715. print '<td class="right">'.$langs->trans("Qty").'</td>';
  716. // Unit
  717. if ($conf->global->PRODUCT_USE_UNITS) {
  718. print '<td class="right">' . $langs->trans("Unit") . '</td>';
  719. }
  720. // Cost price
  721. if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
  722. print '<td class="right">'.$langs->trans("UnitCost").'</td>';
  723. }
  724. // Qty already consumed
  725. print '<td class="right">'.$form->textwithpicto($langs->trans("QtyAlreadyConsumedShort"), $langs->trans("QtyAlreadyConsumed")).'</td>';
  726. // Warehouse
  727. print '<td>';
  728. if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  729. print $langs->trans("Warehouse");
  730. if (isModEnabled('workstation')) {
  731. print ' '.$langs->trans("or").' '.$langs->trans("Workstation");
  732. }
  733. // Select warehouse to force it everywhere
  734. if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  735. $listwarehouses = $tmpwarehouse->list_array(1);
  736. if (count($listwarehouses) > 1) {
  737. print '<br>'.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, $langs->trans("ForceTo"), 0, 0, '', 0, 0, 0, '', 'minwidth100 maxwidth200', 1);
  738. } elseif (count($listwarehouses) == 1) {
  739. print '<br>'.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100 maxwidth200', 1);
  740. }
  741. }
  742. }
  743. print '</td>';
  744. if (isModEnabled('stock')) {
  745. // Available
  746. print '<td align="right">';
  747. if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  748. print $langs->trans("Stock");
  749. }
  750. print '</td>';
  751. }
  752. // Lot - serial
  753. if (isModEnabled('productbatch')) {
  754. print '<td>';
  755. if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  756. print $langs->trans("Batch");
  757. }
  758. print '</td>';
  759. }
  760. // Action
  761. if ($permissiontodelete) {
  762. print '<td></td>';
  763. }
  764. // Split
  765. print '<td></td>';
  766. // SplitAll
  767. print '<td></td>';
  768. // Edit Line
  769. if ($object->status == Mo::STATUS_DRAFT) {
  770. print '<td></td>';
  771. }
  772. print '</tr>';
  773. if ($action == 'addconsumeline') {
  774. print '<!-- Add line to consume -->'."\n";
  775. print '<tr class="liste_titre">';
  776. // Product
  777. print '<td>';
  778. print $form->select_produits('', 'productidtoadd', '', 0, 0, -1, 2, '', 1, array(), 0, '1', 0, 'maxwidth300');
  779. print '</td>';
  780. // Qty
  781. print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>';
  782. if ($conf->global->PRODUCT_USE_UNITS) {
  783. print '<td></td>';
  784. }
  785. // Cost price
  786. if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
  787. print '<td></td>';
  788. }
  789. // Qty already consumed + Warehouse
  790. print '<td colspan="2">';
  791. print '<input type="submit" class="button buttongen button-add" name="addconsumelinebutton" value="'.$langs->trans("Add").'">';
  792. print '<input type="submit" class="button buttongen button-cancel" name="canceladdconsumelinebutton" value="'.$langs->trans("Cancel").'">';
  793. print '</td>';
  794. if (isModEnabled('stock')) {
  795. print '<td></td>';
  796. }
  797. // Lot - serial
  798. if (isModEnabled('productbatch')) {
  799. print '<td></td>';
  800. }
  801. // Action
  802. if ($permissiontodelete) {
  803. print '<td></td>';
  804. }
  805. // Split
  806. print '<td></td>';
  807. // SplitAll
  808. print '<td></td>';
  809. // Edit Line
  810. if ($object->status == Mo::STATUS_DRAFT) {
  811. print '<td></td>';
  812. }
  813. print '</tr>';
  814. // Extrafields Line
  815. if (is_object($objectline)) {
  816. $extrafields->fetch_name_optionals_label($object->table_element_line);
  817. $temps = $objectline->showOptionals($extrafields, 'edit', array(), '', '', 1, 'line');
  818. if (!empty($temps)) {
  819. print '<tr class="liste_titre"><td style="padding-top: 20px" colspan="9" id="extrafield_lines_area_edit" name="extrafield_lines_area_edit">';
  820. print $temps;
  821. print '</td></tr>';
  822. }
  823. }
  824. }
  825. // Lines to consume
  826. $bomcostupdated = 0; // We will recalculate the unitary cost to produce a product using the real "products to consume into MO"
  827. if (!empty($object->lines)) {
  828. $nblinetoconsume = 0;
  829. foreach ($object->lines as $line) {
  830. if ($line->role == 'toconsume') {
  831. $nblinetoconsume++;
  832. }
  833. }
  834. $nblinetoconsumecursor = 0;
  835. foreach ($object->lines as $line) {
  836. if ($line->role == 'toconsume') {
  837. $nblinetoconsumecursor++;
  838. $tmpproduct = new Product($db);
  839. $tmpproduct->fetch($line->fk_product);
  840. $linecost = price2num($tmpproduct->pmp, 'MT');
  841. if ($object->qty > 0) {
  842. // add free consume line cost to $bomcostupdated
  843. $costprice = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
  844. if (empty($costprice)) {
  845. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  846. $productFournisseur = new ProductFournisseur($db);
  847. if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
  848. $costprice = $productFournisseur->fourn_unitprice;
  849. } else {
  850. $costprice = 0;
  851. }
  852. }
  853. $linecost = price2num(($line->qty * $costprice) / $object->qty, 'MT'); // price for line for all quantities
  854. $bomcostupdated += price2num(($line->qty * $costprice) / $object->qty, 'MU'); // same but with full accuracy
  855. }
  856. $bomcostupdated = price2num($bomcostupdated, 'MU');
  857. $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
  858. $alreadyconsumed = 0;
  859. foreach ($arrayoflines as $line2) {
  860. $alreadyconsumed += $line2['qty'];
  861. }
  862. if ($action == 'editline' && $lineid == $line->id) {
  863. $linecost = price2num($tmpproduct->pmp, 'MT');
  864. $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
  865. $alreadyconsumed = 0;
  866. if (is_array($arrayoflines) && !empty($arrayoflines)) {
  867. foreach ($arrayoflines as $line2) {
  868. $alreadyconsumed += $line2['qty'];
  869. }
  870. }
  871. $suffix = '_' . $line->id;
  872. print '<!-- Line to dispatch ' . $suffix . ' -->' . "\n";
  873. // hidden fields for js function
  874. print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $line->qty . '">';
  875. // Duration - Time spent
  876. print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . $alreadyconsumed . '">';
  877. print '<tr>';
  878. print '<input name="lineid" type="hidden" value="' . $line->id . '">';
  879. // Product
  880. print '<td>' . $tmpproduct->getNomUrl(1);
  881. print '<br><div class="opacitymedium small tdoverflowmax150" title="' . dol_escape_htmltag($tmpproduct->label) . '">' . $tmpproduct->label . '</span>';
  882. print '</td>';
  883. // Qty
  884. print '<td class="right nowraponall">';
  885. print '<input class="width40" name="qty_lineProduce" value="'. $line->qty.'">';
  886. print '</td>';
  887. // Unit
  888. if ($conf->global->PRODUCT_USE_UNITS) {
  889. print '<td class="right nowraponall">';
  890. print measuringUnitString($line->fk_unit, '', '', 1);
  891. print '</td>';
  892. }
  893. // Qty consumed
  894. print '<td class="right">';
  895. print ' ' . price2num($alreadyconsumed, 'MS');
  896. print '</td>';
  897. // Entrepot
  898. print '<td class="right">';
  899. print '</td>';
  900. // Stock
  901. print '<td class="nowraponall right">';
  902. if ($tmpproduct->isStockManaged()) {
  903. if ($tmpproduct->stock_reel < ($line->qty - $alreadyconsumed)) {
  904. print img_warning($langs->trans('StockTooLow')).' ';
  905. }
  906. print '<span class="left">'. $tmpproduct->stock_reel .' </span>';
  907. }
  908. print '</td>';
  909. // Batch
  910. /*
  911. print '<td class="right">';
  912. print '</td>';
  913. */
  914. // Action delete line
  915. print '<td colspan="2">';
  916. print '<input type="submit" class="button buttongen button-add small nominwidth" name="save" value="' . $langs->trans("Save") . '">';
  917. print '<input type="submit" class="button buttongen button-cancel small nominwidth" name="cancel" value="' . $langs->trans("Cancel") . '">';
  918. print '</td>';
  919. // Action delete line
  920. if ($permissiontodelete) {
  921. print '<td></td>';
  922. }
  923. print '<td></td>';
  924. print '</tr>';
  925. // Extrafields Line
  926. if (!empty($extrafields)) {
  927. $line->fetch_optionals();
  928. $temps = $line->showOptionals($extrafields, 'edit', array(), '', '', 1, 'line');
  929. if (!empty($temps)) {
  930. print '<td colspan="10"><div style="padding-top: 20px" id="extrafield_lines_area_edit" name="extrafield_lines_area_edit">';
  931. print $temps;
  932. print '</div></td>';
  933. }
  934. }
  935. } else {
  936. $suffix = '_' . $line->id;
  937. print '<!-- Line to dispatch ' . $suffix . ' -->' . "\n";
  938. // hidden fields for js function
  939. print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $line->qty . '">';
  940. print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . $alreadyconsumed . '">';
  941. print '<tr data-line-id="' . $line->id . '">';
  942. // Product
  943. print '<td>' . $tmpproduct->getNomUrl(1);
  944. print '<br><div class="opacitymedium small tdoverflowmax150" title="' . dol_escape_htmltag($tmpproduct->label) . '">' . $tmpproduct->label . '</div>';
  945. print '</td>';
  946. // Qty
  947. print '<td class="right nowraponall">';
  948. $help = '';
  949. $picto = 'help';
  950. if ($line->qty_frozen) {
  951. $help = ($help ? '<br>' : '') . '<strong>' . $langs->trans("QuantityFrozen") . '</strong>: ' . yn(1) . ' (' . $langs->trans("QuantityConsumedInvariable") . ')';
  952. print $form->textwithpicto('', $help, -1, 'lock') . ' ';
  953. }
  954. if ($line->disable_stock_change) {
  955. $help = ($help ? '<br>' : '') . '<strong>' . $langs->trans("DisableStockChange") . '</strong>: ' . yn(1) . ' (' . (($tmpproduct->type == Product::TYPE_SERVICE && !getDolGlobalString('STOCK_SUPPORTS_SERVICES')) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")) . ')';
  956. print $form->textwithpicto('', $help, -1, 'help') . ' ';
  957. }
  958. print price2num($line->qty, 'MS');
  959. print '</td>';
  960. // Unit
  961. if ($conf->global->PRODUCT_USE_UNITS) {
  962. print '<td class="right nowraponall">';
  963. print measuringUnitString($line->fk_unit, '', '', 1);
  964. print '</td>';
  965. }
  966. // Cost price
  967. if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
  968. print '<td class="right nowraponall">';
  969. print price($linecost);
  970. print '</td>';
  971. }
  972. // Already consumed
  973. print '<td class="right">';
  974. if ($alreadyconsumed) {
  975. print '<script>';
  976. print 'jQuery(document).ready(function() {
  977. jQuery("#expandtoproduce' . $line->id . '").click(function() {
  978. console.log("Expand mrp_production line ' . $line->id . '");
  979. jQuery(".expanddetail' . $line->id . '").toggle();';
  980. if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line
  981. print 'if (jQuery("#tablelines").hasClass("nobottom")) { jQuery("#tablelines").removeClass("nobottom"); } else { jQuery("#tablelines").addClass("nobottom"); }';
  982. }
  983. print '
  984. });
  985. });';
  986. print '</script>';
  987. if (empty($conf->use_javascript_ajax)) {
  988. print '<a href="' . $_SERVER["PHP_SELF"] . '?collapse=' . $collapse . ',' . $line->id . '">';
  989. }
  990. print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce' . $line->id . '"');
  991. if (empty($conf->use_javascript_ajax)) {
  992. print '</a>';
  993. }
  994. } else {
  995. if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line
  996. print '<script>jQuery("#tablelines").removeClass("nobottom");</script>';
  997. }
  998. }
  999. print ' ' . price2num($alreadyconsumed, 'MS');
  1000. print '</td>';
  1001. // Warehouse and/or workstation
  1002. print '<td>';
  1003. if (getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') && $tmpwarehouse->id > 0) {
  1004. print img_picto('', $tmpwarehouse->picto) . " " . $tmpwarehouse->label;
  1005. }
  1006. if (isModEnabled('workstation') && $line->fk_default_workstation > 0) {
  1007. $tmpworkstation = new Workstation($db);
  1008. $tmpworkstation->fetch($line->fk_default_workstation);
  1009. print $tmpworkstation->getNomUrl(1);
  1010. }
  1011. print '</td>';
  1012. // Stock
  1013. if (isModEnabled('stock')) {
  1014. print '<td class="nowraponall right">';
  1015. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES') && $tmpproduct->type != Product::TYPE_SERVICE) {
  1016. if (!$line->disable_stock_change && $tmpproduct->stock_reel < ($line->qty - $alreadyconsumed)) {
  1017. print img_warning($langs->trans('StockTooLow')) . ' ';
  1018. }
  1019. if (!getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') || empty($tmpwarehouse->id)) {
  1020. print price2num($tmpproduct->stock_reel, 'MS'); // Available
  1021. } else {
  1022. // Print only the stock in the selected warehouse
  1023. $tmpproduct->load_stock();
  1024. $wh_stock = $tmpproduct->stock_warehouse[$tmpwarehouse->id];
  1025. if (!empty($wh_stock)) {
  1026. print price2num($wh_stock->real, 'MS');
  1027. } else {
  1028. print "0";
  1029. }
  1030. }
  1031. }
  1032. print '</td>';
  1033. }
  1034. // Lot
  1035. if (isModEnabled('productbatch')) {
  1036. print '<td></td>';
  1037. }
  1038. // Split
  1039. print '<td></td>';
  1040. // Split All
  1041. print '<td></td>';
  1042. // Action Edit line
  1043. if ($object->status == Mo::STATUS_DRAFT) {
  1044. $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=editline&token=' . newToken() . '&lineid=' . ((int) $line->id);
  1045. print '<td class="center">';
  1046. print '<a class="reposition" href="' . $href . '">';
  1047. print img_picto($langs->trans('TooltipEditAndRevertStockMovement'), 'edit');
  1048. print '</a>';
  1049. print '</td>';
  1050. }
  1051. // Action delete line
  1052. if ($permissiontodelete) {
  1053. $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=deleteline&token=' . newToken() . '&lineid=' . ((int) $line->id);
  1054. print '<td class="center">';
  1055. print '<a class="reposition" href="' . $href . '">';
  1056. print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), 'delete');
  1057. print '</a>';
  1058. print '</td>';
  1059. }
  1060. print '</tr>';
  1061. // Extrafields Line
  1062. if (!empty($extrafields)) {
  1063. $line->fetch_optionals();
  1064. $temps = $line->showOptionals($extrafields, 'view', array(), '', '', 1, 'line');
  1065. if (!empty($temps)) {
  1066. print '<td colspan="10"><div id="extrafield_lines_area_'.$line->id.'" name="extrafield_lines_area_'.$line->id.'">';
  1067. print $temps;
  1068. print '</div></td>';
  1069. }
  1070. }
  1071. }
  1072. // Show detailed of already consumed with js code to collapse
  1073. foreach ($arrayoflines as $line2) {
  1074. print '<tr class="expanddetail'.$line->id.' hideobject opacitylow">';
  1075. // Date
  1076. print '<td>';
  1077. $tmpstockmovement->id = $line2['fk_stock_movement'];
  1078. print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>';
  1079. print dol_print_date($line2['date'], 'dayhour', 'tzuserrel');
  1080. print '</td>';
  1081. // Already consumed
  1082. print '<td></td>';
  1083. // Qty
  1084. print '<td class="right">'.$line2['qty'].'</td>';
  1085. // Cost price
  1086. if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
  1087. print '<td></td>';
  1088. }
  1089. // Warehouse
  1090. print '<td class="tdoverflowmax150">';
  1091. if ($line2['fk_warehouse'] > 0) {
  1092. $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
  1093. if ($result > 0) {
  1094. print $tmpwarehouse->getNomUrl(1);
  1095. }
  1096. }
  1097. print '</td>';
  1098. // Stock
  1099. if (isModEnabled('stock')) {
  1100. print '<td></td>';
  1101. }
  1102. // Lot Batch
  1103. if (isModEnabled('productbatch')) {
  1104. print '<td>';
  1105. if ($line2['batch'] != '') {
  1106. $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']);
  1107. print $tmpbatch->getNomUrl(1);
  1108. }
  1109. print '</td>';
  1110. }
  1111. // Split
  1112. print '<td></td>';
  1113. // Split All
  1114. print '<td></td>';
  1115. // Action Edit line
  1116. if ($object->status == Mo::STATUS_DRAFT) {
  1117. $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=editline&token=' . newToken() . '&lineid=' . ((int) $line2['rowid']);
  1118. print '<td class="center">';
  1119. print '<a class="reposition" href="' . $href . '">';
  1120. print img_picto($langs->trans('TooltipEditAndRevertStockMovement'), 'edit');
  1121. print '</a>';
  1122. print '</td>';
  1123. }
  1124. // Action delete line
  1125. if ($permissiontodelete) {
  1126. $href = $_SERVER["PHP_SELF"].'?id='.((int) $object->id).'&action=deleteline&token='.newToken().'&lineid='.((int) $line2['rowid']).'&fk_movement='.((int) $line2['fk_stock_movement']);
  1127. print '<td class="center">';
  1128. print '<a class="reposition" href="'.$href.'">';
  1129. print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), 'delete');
  1130. print '</a>';
  1131. print '</td>';
  1132. }
  1133. print '</tr>';
  1134. }
  1135. if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  1136. $i = 1;
  1137. print '<!-- Enter line to consume -->'."\n";
  1138. $maxQty = 1;
  1139. print '<tr data-max-qty="'.$maxQty.'" name="batch_'.$line->id.'_'.$i.'">';
  1140. // Ref
  1141. print '<td><span class="opacitymedium">'.$langs->trans("ToConsume").'</span></td>';
  1142. $preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed));
  1143. if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) {
  1144. $preselected = 0;
  1145. }
  1146. $disable = '';
  1147. if (getDolGlobalString('MRP_NEVER_CONSUME_MORE_THAN_EXPECTED') && ($line->qty - $alreadyconsumed) <= 0) {
  1148. $disable = 'disabled';
  1149. }
  1150. // input hidden with fk_product of line
  1151. print '<input type="hidden" name="product-'.$line->id.'-'.$i.'" value="'.$line->fk_product.'">';
  1152. // Qty
  1153. print '<td class="right"><input type="text" class="width50 right" id="qtytoconsume-' . $line->id . '-' . $i . '" name="qty-' . $line->id . '-' . $i . '" value="' . $preselected . '" ' . $disable . '></td>';
  1154. // Unit
  1155. if ($conf->global->PRODUCT_USE_UNITS) {
  1156. print '<td></td>';
  1157. }
  1158. // Cost
  1159. if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
  1160. print '<td></td>';
  1161. }
  1162. // Already consumed
  1163. print '<td></td>';
  1164. // Warehouse
  1165. print '<td>';
  1166. if ($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1167. if (empty($line->disable_stock_change)) {
  1168. $preselected = (GETPOSTISSET('idwarehouse-'.$line->id.'-'.$i) ? GETPOST('idwarehouse-'.$line->id.'-'.$i) : ($tmpproduct->fk_default_warehouse > 0 ? $tmpproduct->fk_default_warehouse : 'ifone'));
  1169. print $formproduct->selectWarehouses($preselected, 'idwarehouse-'.$line->id.'-'.$i, '', 1, 0, $line->fk_product, '', 1, 0, null, 'maxwidth200 csswarehouse_'.$line->id.'_'.$i);
  1170. } else {
  1171. print '<span class="opacitymedium">'.$langs->trans("DisableStockChange").'</span>';
  1172. }
  1173. } else {
  1174. print '<span class="opacitymedium">'.$langs->trans("NoStockChangeOnServices").'</span>';
  1175. }
  1176. print '</td>';
  1177. // Stock
  1178. if (isModEnabled('stock')) {
  1179. print '<td></td>';
  1180. }
  1181. // Lot / Batch
  1182. if (isModEnabled('productbatch')) {
  1183. print '<td class="nowraponall">';
  1184. if ($tmpproduct->status_batch) {
  1185. $preselected = (GETPOSTISSET('batch-'.$line->id.'-'.$i) ? GETPOST('batch-'.$line->id.'-'.$i) : '');
  1186. print '<input type="text" class="width75" name="batch-'.$line->id.'-'.$i.'" value="'.$preselected.'" list="batch-'.$line->id.'-'.$i.'">';
  1187. print $formproduct->selectLotDataList('batch-'.$line->id.'-'.$i, 0, $line->fk_product, '', '');
  1188. }
  1189. print '</td>';
  1190. }
  1191. // Split
  1192. $type = 'batch';
  1193. print '<td align="right" class="split">';
  1194. print ' '.img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.((int) $line->id).', \''.dol_escape_js($type).'\', \'qtymissingconsume\')"');
  1195. print '</td>';
  1196. // Split All
  1197. print '<td align="right" class="splitall">';
  1198. if (($action == 'consumeorproduce' || $action == 'consumeandproduceall') && $tmpproduct->status_batch == 2) {
  1199. print img_picto($langs->trans('SplitAllQuantity'), 'split.png', 'class="splitbutton splitallbutton field-error-icon" data-max-qty="1" onClick="addDispatchLine('.$line->id.', \'batch\', \'allmissingconsume\')"');
  1200. }
  1201. print '</td>';
  1202. // Edit Line
  1203. if ($object->status == Mo::STATUS_DRAFT) {
  1204. print '<td></td>';
  1205. }
  1206. // Action delete line
  1207. if ($permissiontodelete) {
  1208. print '<td></td>';
  1209. }
  1210. print '</tr>';
  1211. }
  1212. }
  1213. }
  1214. }
  1215. print '</table>';
  1216. print '</div>';
  1217. // default warehouse processing
  1218. print '<script type="text/javascript">
  1219. $(document).ready(function () {
  1220. $("select[name=fk_default_warehouse]").change(function() {
  1221. var fk_default_warehouse = $("option:selected", this).val();
  1222. $("select[name^=idwarehouse-]").val(fk_default_warehouse).change();
  1223. });
  1224. });
  1225. </script>';
  1226. if (in_array($action, array('consumeorproduce', 'consumeandproduceall')) &&
  1227. getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE')) {
  1228. print '<script>$(document).ready(function () {
  1229. $("#fk_default_warehouse").change();
  1230. });</script>';
  1231. }
  1232. // Lines to produce
  1233. print '</div>';
  1234. print '<div class="fichehalfright">';
  1235. print '<div class="clearboth"></div>';
  1236. $nblinetoproduce = 0;
  1237. foreach ($object->lines as $line) {
  1238. if ($line->role == 'toproduce') {
  1239. $nblinetoproduce++;
  1240. }
  1241. }
  1242. $newcardbutton = '';
  1243. $url = $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addproduceline&token='.newToken();
  1244. $permissiontoaddaproductline = $object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED;
  1245. $parameters = array('morecss'=>'reposition');
  1246. if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') {
  1247. if ($nblinetoproduce == 0 || $object->mrptype == 1) {
  1248. $newcardbutton = dolGetButtonTitle($langs->trans('AddNewProduceLines'), '', 'fa fa-plus-circle size15x', $url, '', $permissiontoaddaproductline, $parameters);
  1249. }
  1250. }
  1251. print load_fiche_titre($langs->trans('Production'), $newcardbutton, '', 0, '', '');
  1252. print '<div class="div-table-responsive-no-min">';
  1253. print '<table id="tablelinestoproduce" class="noborder noshadow nobottom centpercent">';
  1254. print '<tr class="liste_titre">';
  1255. // Product
  1256. print '<td>'.$langs->trans("Product").'</td>';
  1257. // Qty
  1258. print '<td class="right">'.$langs->trans("Qty").'</td>';
  1259. /// Unit
  1260. if ($conf->global->PRODUCT_USE_UNITS) {
  1261. print '<td class="right">'.$langs->trans("Unit").'</td>';
  1262. }
  1263. // Cost price
  1264. if ($permissiontoupdatecost) {
  1265. if (empty($bomcostupdated)) {
  1266. print '<td class="right">'.$form->textwithpicto($langs->trans("UnitCost"), $langs->trans("AmountUsedToUpdateWAP")).'</td>';
  1267. } else {
  1268. print '<td class="right">'.$form->textwithpicto($langs->trans("ManufacturingPrice"), $langs->trans("AmountUsedToUpdateWAP")).'</td>';
  1269. }
  1270. }
  1271. // Already produced
  1272. print '<td class="right">'.$form->textwithpicto($langs->trans("QtyAlreadyProducedShort"), $langs->trans("QtyAlreadyProduced")).'</td>';
  1273. // Warehouse
  1274. print '<td>';
  1275. if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  1276. print $langs->trans("Warehouse");
  1277. }
  1278. print '</td>';
  1279. // Lot
  1280. if (isModEnabled('productbatch')) {
  1281. print '<td>';
  1282. if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  1283. print $langs->trans("Batch");
  1284. }
  1285. print '</td>';
  1286. // Split
  1287. print '<td></td>';
  1288. // Split All
  1289. print '<td></td>';
  1290. }
  1291. // Action delete
  1292. if ($permissiontodelete) {
  1293. print '<td></td>';
  1294. }
  1295. print '</tr>';
  1296. if ($action == 'addproduceline') {
  1297. print '<!-- Add line to produce -->'."\n";
  1298. print '<tr class="liste_titre">';
  1299. // Product
  1300. print '<td>';
  1301. print $form->select_produits('', 'productidtoadd', '', 0, 0, -1, 2, '', 1, array(), 0, '1', 0, 'maxwidth300');
  1302. print '</td>';
  1303. // Qty
  1304. print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>';
  1305. //Unit
  1306. if ($conf->global->PRODUCT_USE_UNITS) {
  1307. print '<td></td>';
  1308. }
  1309. // Cost price
  1310. if ($permissiontoupdatecost) {
  1311. print '<td></td>';
  1312. }
  1313. // Action (cost price + already produced)
  1314. print '<td colspan="2">';
  1315. print '<input type="submit" class="button buttongen button-add" name="addproducelinebutton" value="'.$langs->trans("Add").'">';
  1316. print '<input type="submit" class="button buttongen button-cancel" name="canceladdproducelinebutton" value="'.$langs->trans("Cancel").'">';
  1317. print '</td>';
  1318. // Lot - serial
  1319. if (isModEnabled('productbatch')) {
  1320. print '<td></td>';
  1321. // Split
  1322. print '<td></td>';
  1323. // Split All
  1324. print '<td></td>';
  1325. }
  1326. // Action delete
  1327. if ($permissiontodelete) {
  1328. print '<td></td>';
  1329. }
  1330. print '</tr>';
  1331. }
  1332. if (!empty($object->lines)) {
  1333. $nblinetoproduce = 0;
  1334. foreach ($object->lines as $line) {
  1335. if ($line->role == 'toproduce') {
  1336. $nblinetoproduce++;
  1337. }
  1338. }
  1339. $nblinetoproducecursor = 0;
  1340. foreach ($object->lines as $line) {
  1341. if ($line->role == 'toproduce') {
  1342. $i = 1;
  1343. $nblinetoproducecursor++;
  1344. $tmpproduct = new Product($db);
  1345. $tmpproduct->fetch($line->fk_product);
  1346. $arrayoflines = $object->fetchLinesLinked('produced', $line->id);
  1347. $alreadyproduced = 0;
  1348. foreach ($arrayoflines as $line2) {
  1349. $alreadyproduced += $line2['qty'];
  1350. }
  1351. $suffix = '_'.$line->id;
  1352. print '<!-- Line to dispatch '.$suffix.' -->'."\n";
  1353. // hidden fields for js function
  1354. print '<input id="qty_ordered'.$suffix.'" type="hidden" value="'.$line->qty.'">';
  1355. print '<input id="qty_dispatched'.$suffix.'" type="hidden" value="'.$alreadyproduced.'">';
  1356. print '<tr>';
  1357. // Product
  1358. print '<td>'.$tmpproduct->getNomUrl(1);
  1359. print '<br><span class="opacitymedium small">'.$tmpproduct->label.'</span>';
  1360. print '</td>';
  1361. // Qty
  1362. print '<td class="right">'.$line->qty.'</td>';
  1363. // Unit
  1364. if ($conf->global->PRODUCT_USE_UNITS) {
  1365. print '<td class="right">'.measuringUnitString($line->fk_unit, '', '', 1).'</td>';
  1366. }
  1367. // Cost price
  1368. if ($permissiontoupdatecost) {
  1369. // Defined $manufacturingcost
  1370. $manufacturingcost = 0;
  1371. $manufacturingcostsrc = '';
  1372. if ($object->mrptype == 0) { // If MO is a "Manufacture" type (and not "Disassemble")
  1373. $manufacturingcost = $bomcostupdated;
  1374. $manufacturingcostsrc = $langs->trans("CalculatedFromProductsToConsume");
  1375. if (empty($manufacturingcost)) {
  1376. $manufacturingcost = $bomcost;
  1377. $manufacturingcostsrc = $langs->trans("ValueFromBom");
  1378. }
  1379. if (empty($manufacturingcost)) {
  1380. $manufacturingcost = price2num($tmpproduct->cost_price, 'MU');
  1381. $manufacturingcostsrc = $langs->trans("CostPrice");
  1382. }
  1383. if (empty($manufacturingcost)) {
  1384. $manufacturingcost = price2num($tmpproduct->pmp, 'MU');
  1385. $manufacturingcostsrc = $langs->trans("PMPValue");
  1386. }
  1387. }
  1388. print '<td class="right nowraponall" title="'.dol_escape_htmltag($manufacturingcostsrc).'">';
  1389. if ($manufacturingcost) {
  1390. print price($manufacturingcost);
  1391. }
  1392. print '</td>';
  1393. }
  1394. // Already produced
  1395. print '<td class="right nowraponall">';
  1396. if ($alreadyproduced) {
  1397. print '<script>';
  1398. print 'jQuery(document).ready(function() {
  1399. jQuery("#expandtoproduce'.$line->id.'").click(function() {
  1400. console.log("Expand mrp_production line '.$line->id.'");
  1401. jQuery(".expanddetailtoproduce'.$line->id.'").toggle();';
  1402. if ($nblinetoproduce == $nblinetoproducecursor) {
  1403. print 'if (jQuery("#tablelinestoproduce").hasClass("nobottom")) { jQuery("#tablelinestoproduce").removeClass("nobottom"); } else { jQuery("#tablelinestoproduce").addClass("nobottom"); }';
  1404. }
  1405. print '
  1406. });
  1407. });';
  1408. print '</script>';
  1409. if (empty($conf->use_javascript_ajax)) {
  1410. print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">';
  1411. }
  1412. print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"');
  1413. if (empty($conf->use_javascript_ajax)) {
  1414. print '</a>';
  1415. }
  1416. }
  1417. print ' '.$alreadyproduced;
  1418. print '</td>';
  1419. // Warehouse
  1420. print '<td>';
  1421. print '</td>';
  1422. // Lot
  1423. if (isModEnabled('productbatch')) {
  1424. print '<td></td>';
  1425. // Split
  1426. print '<td></td>';
  1427. // Split All
  1428. print '<td></td>';
  1429. }
  1430. // Delete
  1431. if ($permissiontodelete) {
  1432. if ($line->origin_type == 'free') {
  1433. $href = $_SERVER["PHP_SELF"];
  1434. $href .= '?id='.$object->id;
  1435. $href .= '&action=deleteline';
  1436. $href .= '&lineid='.$line->id;
  1437. print '<td class="center">';
  1438. print '<a class="reposition" href="'.$href.'">';
  1439. print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), "delete");
  1440. print '</a>';
  1441. print '</td>';
  1442. } else {
  1443. print '<td></td>';
  1444. }
  1445. }
  1446. print '</tr>';
  1447. // Show detailed of already consumed with js code to collapse
  1448. foreach ($arrayoflines as $line2) {
  1449. print '<tr class="expanddetailtoproduce'.$line->id.' hideobject opacitylow">';
  1450. // Product
  1451. print '<td>';
  1452. $tmpstockmovement->id = $line2['fk_stock_movement'];
  1453. print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>';
  1454. print dol_print_date($line2['date'], 'dayhour', 'tzuserrel');
  1455. print '</td>';
  1456. // Qty
  1457. print '<td></td>';
  1458. // Unit
  1459. if ($conf->global->PRODUCT_USE_UNITS) {
  1460. print '<td></td>';
  1461. }
  1462. // Cost price
  1463. if ($permissiontoupdatecost) {
  1464. print '<td></td>';
  1465. }
  1466. // Already produced
  1467. print '<td class="right">'.$line2['qty'].'</td>';
  1468. // Warehouse
  1469. print '<td class="tdoverflowmax150">';
  1470. if ($line2['fk_warehouse'] > 0) {
  1471. $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
  1472. if ($result > 0) {
  1473. print $tmpwarehouse->getNomUrl(1);
  1474. }
  1475. }
  1476. print '</td>';
  1477. // Lot
  1478. if (isModEnabled('productbatch')) {
  1479. print '<td>';
  1480. if ($line2['batch'] != '') {
  1481. $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']);
  1482. print $tmpbatch->getNomUrl(1);
  1483. }
  1484. print '</td>';
  1485. // Split
  1486. print '<td></td>';
  1487. // Split All
  1488. print '<td></td>';
  1489. }
  1490. // Action delete
  1491. if ($permissiontodelete) {
  1492. print '<td></td>';
  1493. }
  1494. print '</tr>';
  1495. }
  1496. if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
  1497. print '<!-- Enter line to produce -->'."\n";
  1498. $maxQty = 1;
  1499. print '<tr data-max-qty="'.$maxQty.'" name="batch_'.$line->id.'_'.$i.'">';
  1500. // Product
  1501. print '<td><span class="opacitymedium">'.$langs->trans("ToProduce").'</span></td>';
  1502. $preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced));
  1503. if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
  1504. $preselected = 0;
  1505. }
  1506. // Qty
  1507. print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
  1508. //Unit
  1509. if ($conf->global->PRODUCT_USE_UNITS) {
  1510. print '<td class="right"></td>';
  1511. }
  1512. // Cost
  1513. if ($permissiontoupdatecost) {
  1514. // Defined $manufacturingcost
  1515. $manufacturingcost = 0;
  1516. $manufacturingcostsrc = '';
  1517. if ($object->mrptype == 0) { // If MO is a "Manufacture" type (and not "Disassemble")
  1518. $manufacturingcost = $bomcostupdated;
  1519. $manufacturingcostsrc = $langs->trans("CalculatedFromProductsToConsume");
  1520. if (empty($manufacturingcost)) {
  1521. $manufacturingcost = $bomcost;
  1522. $manufacturingcostsrc = $langs->trans("ValueFromBom");
  1523. }
  1524. if (empty($manufacturingcost)) {
  1525. $manufacturingcost = price2num($tmpproduct->cost_price, 'MU');
  1526. $manufacturingcostsrc = $langs->trans("CostPrice");
  1527. }
  1528. if (empty($manufacturingcost)) {
  1529. $manufacturingcost = price2num($tmpproduct->pmp, 'MU');
  1530. $manufacturingcostsrc = $langs->trans("PMPValue");
  1531. }
  1532. }
  1533. if ($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1534. $preselected = (GETPOSTISSET('pricetoproduce-'.$line->id.'-'.$i) ? GETPOST('pricetoproduce-'.$line->id.'-'.$i) : ($manufacturingcost ? price($manufacturingcost) : ''));
  1535. print '<td class="right"><input type="text" class="width75 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
  1536. } else {
  1537. print '<td><input type="hidden" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.($manufacturingcost ? $manufacturingcost : '').'"></td>';
  1538. }
  1539. }
  1540. // Already produced
  1541. print '<td></td>';
  1542. // Warehouse
  1543. print '<td>';
  1544. if ($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1545. $preselected = (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i) ? GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) : ($object->fk_warehouse > 0 ? $object->fk_warehouse : 'ifone'));
  1546. print $formproduct->selectWarehouses($preselected, 'idwarehousetoproduce-'.$line->id.'-'.$i, '', 1, 0, $line->fk_product, '', 1, 0, null, 'maxwidth200 csswarehouse_'.$line->id.'_'.$i);
  1547. } else {
  1548. print '<span class="opacitymedium">'.$langs->trans("NoStockChangeOnServices").'</span>';
  1549. }
  1550. print '</td>';
  1551. // Lot
  1552. if (isModEnabled('productbatch')) {
  1553. print '<td>';
  1554. if ($tmpproduct->status_batch) {
  1555. $preselected = (GETPOSTISSET('batchtoproduce-'.$line->id.'-'.$i) ? GETPOST('batchtoproduce-'.$line->id.'-'.$i) : '');
  1556. print '<input type="text" class="width75" name="batchtoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'">';
  1557. }
  1558. print '</td>';
  1559. // Batch number in same column than the stock movement picto
  1560. if ($tmpproduct->status_batch) {
  1561. $type = 'batch';
  1562. print '<td align="right" class="split">';
  1563. print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$line->id.', \''.$type.'\', \'qtymissing\')"');
  1564. print '</td>';
  1565. print '<td align="right" class="splitall">';
  1566. if (($action == 'consumeorproduce' || $action == 'consumeandproduceall') && $tmpproduct->status_batch == 2) {
  1567. print img_picto($langs->trans('SplitAllQuantity'), 'split.png', 'class="splitbutton splitallbutton field-error-icon" onClick="addDispatchLine('.$line->id.', \'batch\', \'alltoproduce\')"');
  1568. } //
  1569. print '</td>';
  1570. } else {
  1571. print '<td></td>';
  1572. print '<td></td>';
  1573. }
  1574. }
  1575. // Action delete
  1576. print '<td></td>';
  1577. print '</tr>';
  1578. }
  1579. }
  1580. }
  1581. }
  1582. print '</table>';
  1583. print '</div>';
  1584. print '</div>';
  1585. print '</div>';
  1586. }
  1587. if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) {
  1588. print "</form>\n";
  1589. } ?>
  1590. <script type="text/javascript" language="javascript">
  1591. $(document).ready(function() {
  1592. //Consumption : When a warehouse is selected, only the lot/serial numbers that are available in it are offered
  1593. updateselectbatchbywarehouse();
  1594. //Consumption : When a lot/serial number is selected and it is only available in one warehouse, the warehouse is automatically selected
  1595. updateselectwarehousebybatch();
  1596. });
  1597. function updateselectbatchbywarehouse() {
  1598. $(document).on('change', "select[name*='idwarehouse']", function () {
  1599. console.log("We change warehouse so we update the list of possible batch number");
  1600. var selectwarehouse = $(this);
  1601. var selectbatch_name = selectwarehouse.attr('name').replace('idwarehouse', 'batch');
  1602. var selectbatch = $("datalist[id*='" + selectbatch_name + "']");
  1603. var selectedbatch = selectbatch.val();
  1604. var product_element_name = selectwarehouse.attr('name').replace('idwarehouse', 'product');
  1605. $.ajax({
  1606. type: "POST",
  1607. url: "<?php echo DOL_URL_ROOT . '/mrp/ajax/interface.php'; ?>",
  1608. data: {
  1609. action: "updateselectbatchbywarehouse",
  1610. permissiontoproduce: <?php echo $permissiontoproduce ?>,
  1611. warehouse_id: $(this).val(),
  1612. token: '<?php echo currentToken(); ?>',
  1613. product_id: $("input[name='" + product_element_name + "']").val()
  1614. }
  1615. }).done(function (data) {
  1616. selectbatch.empty();
  1617. if (typeof data == "object") {
  1618. console.log("data is already type object, no need to parse it");
  1619. } else {
  1620. console.log("data is type "+(typeof data));
  1621. data = JSON.parse(data);
  1622. }
  1623. selectbatch.append($('<option>', {
  1624. value: '',
  1625. }));
  1626. $.each(data, function (key, value) {
  1627. if(selectwarehouse.val() == -1) {
  1628. var label = " (<?php echo $langs->trans('Stock total') ?> : " + value + ")";
  1629. } else {
  1630. var label = " (<?php echo $langs->trans('Stock') ?> : " + value + ")";
  1631. }
  1632. if(key === selectedbatch) {
  1633. var option ='<option value="'+key+'" selected>'+ label +'</option>';
  1634. } else {
  1635. var option ='<option value="'+key+'">'+ label +'</option>';
  1636. }
  1637. selectbatch.append(option);
  1638. });
  1639. });
  1640. });
  1641. }
  1642. function updateselectwarehousebybatch() {
  1643. $(document).on('change', 'input[name*=batch]', function(){
  1644. console.log("We change batch so we update the list of possible warehouses");
  1645. var selectbatch = $(this);
  1646. var selectwarehouse_name = selectbatch.attr('name').replace('batch', 'idwarehouse');
  1647. var selectwarehouse = $("select[name*='" + selectwarehouse_name + "']");
  1648. var selectedwarehouse = selectwarehouse.val();
  1649. if(selectedwarehouse != -1){
  1650. return;
  1651. }
  1652. var product_element_name = selectbatch.attr('name').replace('batch', 'product');
  1653. $.ajax({
  1654. type: "POST",
  1655. url: "<?php echo DOL_URL_ROOT . '/mrp/ajax/interface.php'; ?>",
  1656. data: {
  1657. action: "updateselectwarehousebybatch",
  1658. permissiontoproduce: <?php echo $permissiontoproduce ?>,
  1659. batch: $(this).val(),
  1660. token: '<?php echo currentToken(); ?>',
  1661. product_id: $("input[name='" + product_element_name + "']").val()
  1662. }
  1663. }).done(function (data) {
  1664. if (typeof data == "object") {
  1665. console.log("data is already type object, no need to parse it");
  1666. } else {
  1667. console.log("data is type "+(typeof data));
  1668. data = JSON.parse(data);
  1669. }
  1670. if(data != 0){
  1671. selectwarehouse.val(data).change();
  1672. }
  1673. });
  1674. });
  1675. }
  1676. </script>
  1677. <?php
  1678. }
  1679. // End of page
  1680. llxFooter();
  1681. $db->close();