dolibarr 23.0.4
mo_production.php
Go to the documentation of this file.
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 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
8 * Copyright (C) 2025 Noé Cendrier <noe.cendrier@altairis.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30// Load Dolibarr environment
31require '../main.inc.php';
32require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
36require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
37require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp_mo.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
39require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
40require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
41require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
42require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
43require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
44require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
45
46
55// Load translation files required by the page
56$langs->loadLangs(array("mrp", "stocks", "other", "product", "productbatch"));
57
58// Get parameters
59$id = GETPOSTINT('id');
60$ref = GETPOST('ref', 'alpha');
61$action = GETPOST('action', 'aZ09');
62$confirm = GETPOST('confirm', 'alpha');
63$cancel = GETPOST('cancel');
64$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search
65$backtopage = GETPOST('backtopage', 'alpha');
66$lineid = GETPOSTINT('lineid');
67$fk_movement = GETPOSTINT('fk_movement');
68$fk_default_warehouse = GETPOSTINT('fk_default_warehouse');
69
70$collapse = GETPOST('collapse', 'aZ09comma');
71
72// Initialize a technical objects
73$object = new Mo($db);
74$extrafields = new ExtraFields($db);
75$diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id;
76$objectline = new MoLine($db);
77
78$hookmanager->initHooks(array('moproduction', 'globalcard')); // Note that conf->hooks_modules contains array
79
80// Fetch optionals attributes and labels
81$extrafields->fetch_name_optionals_label($object->table_element);
82
83$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
84
85// Initialize array of search criteria
86$search_all = GETPOST("search_all", 'alpha');
87$search = array();
88foreach ($object->fields as $key => $val) {
89 if (GETPOST('search_'.$key, 'alpha')) {
90 $search[$key] = GETPOST('search_'.$key, 'alpha');
91 }
92}
93
94if (empty($action) && empty($id) && empty($ref)) {
95 $action = 'view';
96}
97
98// Load object
99include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'.
100
101// Security check - Protection if external user
102//if ($user->socid > 0) accessforbidden();
103//if ($user->socid > 0) $socid = $user->socid;
104$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
105$result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'rowid', $isdraft);
106
107// Permissions
108$permissionnote = $user->hasRight('mrp', 'write'); // Used by the include of actions_setnotes.inc.php
109$permissiondellink = $user->hasRight('mrp', 'write'); // Used by the include of actions_dellink.inc.php
110$permissiontoadd = $user->hasRight('mrp', 'write'); // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
111$permissiontodelete = $user->hasRight('mrp', 'delete') || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
112
113$permissiontoproduce = $permissiontoadd;
114$permissiontoupdatecost = $user->hasRight('bom', 'read'); // User who can define cost must have knowledge of pricing
115
116$upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
117
118
119/*
120 * Actions
121 */
122
123$parameters = array();
124$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
125if ($reshook < 0) {
126 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
127}
128
129if (empty($reshook)) {
130 $error = 0;
131
132 $backurlforlist = DOL_URL_ROOT.'/mrp/mo_list.php';
133
134 if (empty($backtopage) || ($cancel && empty($id))) {
135 //var_dump($backurlforlist);exit;
136 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
137 $backtopage = $backurlforlist;
138 } else {
139 $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__');
140 }
141 }
142 $triggermodname = 'MO_MODIFY'; // Name of trigger action code to execute when we modify record
143
144 if ($action == 'confirm_cancel' && $confirm == 'yes' && !empty($permissiontoadd)) {
145 $also_cancel_consumed_and_produced_lines = (GETPOST('alsoCancelConsumedAndProducedLines', 'alpha') ? 1 : 0);
146 $result = $object->cancel($user, 0, (bool) $also_cancel_consumed_and_produced_lines);
147 if ($result > 0) {
148 header("Location: " . DOL_URL_ROOT.'/mrp/mo_card.php?id=' . $object->id);
149 exit;
150 } else {
151 $action = '';
152 setEventMessages($object->error, $object->errors, 'errors');
153 }
154 } elseif ($action == 'confirm_delete' && $confirm == 'yes' && !empty($permissiontodelete)) {
155 $also_cancel_consumed_and_produced_lines = (GETPOST('alsoCancelConsumedAndProducedLines', 'alpha') ? 1 : 0);
156 $result = $object->delete($user, 0, (bool) $also_cancel_consumed_and_produced_lines);
157 if ($result > 0) {
158 header("Location: " . $backurlforlist);
159 exit;
160 } else {
161 $action = '';
162 setEventMessages($object->error, $object->errors, 'errors');
163 }
164 }
165
166 // Allow editing qty while MO is still in draft status.
167 // IMPORTANT: this handler MUST run BEFORE actions_addupdatedelete.inc.php,
168 // which has a generic 'set<key>' matcher that would intercept 'setqty' and
169 // call $object->fetch() + update() without setting $object->oldQty, so
170 // Mo::updateProduction() would skip the line scaling (its condition is
171 // !empty($this->oldQty)).
172 if ($action == 'setqty' && $permissiontoadd && $object->status == Mo::STATUS_DRAFT) {
173 $newqty = GETPOSTFLOAT('qty');
174 if ($newqty > 0) {
175 $object->oldQty = (float) $object->qty;
176 $object->qty = $newqty;
177 $res = $object->update($user);
178 if ($res > 0) {
179 // Enforce invariant: the 'toproduce' line for the MO's main product
180 // must equal the MO qty. Mo::updateProduction() scales by ratio
181 // (newQty/oldQty) which can drift if the line state was already
182 // inconsistent (e.g. legacy data from before this patch). Realign
183 // the main product line, leaving sub-products and frozen lines
184 // untouched.
185 $object->fetchLines();
186 foreach ($object->lines as $line) {
187 if ($line->role === 'toproduce'
188 && (int) $line->fk_product === (int) $object->fk_product
189 && empty($line->qty_frozen)
190 && (float) $line->qty != (float) $object->qty) {
191 $line->qty = (float) $object->qty;
192 $line->update($user);
193 }
194 }
195 setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
196 } else {
197 setEventMessages($object->error, $object->errors, 'errors');
198 }
199 } else {
200 setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Qty")), null, 'errors');
201 }
202 header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
203 exit;
204 }
205
206 // Actions cancel, add, update, delete or clone
207 include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
208
209 // Actions when linking object each other
210 include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
211
212 // Actions when printing a doc from card
213 include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
214
215 // Actions to send emails
216 $triggersendname = 'MO_SENTBYMAIL';
217 $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO';
218 $trackid = 'mo'.$object->id;
219 include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
220
221 // Action to move up and down lines of object
222 //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
223
224 if ($action == 'set_thirdparty' && $permissiontoadd) {
225 $object->setValueFrom('fk_soc', GETPOSTINT('fk_soc'), '', null, 'date', '', $user, $triggermodname);
226 }
227 if ($action == 'classin' && $permissiontoadd) {
228 $object->setProject(GETPOSTINT('projectid'));
229 }
230
231 if ($action == 'confirm_reopen' && $permissiontoadd && $object->status == $object::STATUS_PRODUCED) { // The reopen of a canceled MO is done by $object->reopen() (with confirm=yes)
232 $result = $object->setStatut($object::STATUS_INPROGRESS, 0, '', 'MRP_REOPEN');
233 }
234
235 if (($action == 'confirm_addconsumeline' && GETPOST('addconsumelinebutton') && $permissiontoadd)
236 || ($action == 'confirm_addproduceline' && GETPOST('addproducelinebutton') && $permissiontoadd)) {
237 $moline = new MoLine($db);
238
239 // Line to produce
240 $moline->fk_mo = $object->id;
241 $moline->qty = GETPOSTFLOAT('qtytoadd');
242 $moline->fk_product = GETPOSTINT('productidtoadd');
243 if (GETPOST('addconsumelinebutton')) {
244 $moline->role = 'toconsume';
245 } else {
246 $moline->role = 'toproduce';
247 }
248 $moline->origin_type = 'free'; // free consume line
249 $moline->position = 0;
250
251 // Is it a product or a service ?
252 if (!empty($moline->fk_product)) {
253 $tmpproduct = new Product($db);
254 $tmpproduct->fetch($moline->fk_product);
255 if ($tmpproduct->type == Product::TYPE_SERVICE) {
256 $moline->fk_default_workstation = $tmpproduct->fk_default_workstation;
257 $moline->disable_stock_change = 1;
258 if ($tmpproduct->duration_unit) {
259 $moline->qty = $tmpproduct->duration_value;
260 include_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php';
261 $cunits = new CUnits($db);
262 $res = $cunits->fetch(0, '', $tmpproduct->duration_unit, 'time');
263 if ($res > 0) {
264 $moline->fk_unit = $cunits->id;
265 }
266 }
267 } else {
268 $moline->disable_stock_change = 0;
269 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
270 $moline->fk_unit = $tmpproduct->fk_unit;
271 }
272 }
273 }
274 // Extrafields
275 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
276 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
277 // Unset extrafield
278 if (is_array($extralabelsline)) {
279 // Get extra fields
280 foreach ($extralabelsline as $key => $value) {
281 unset($_POST["options_".$key]);
282 }
283 }
284 if (is_array($array_options) && count($array_options) > 0) {
285 $moline->array_options = $array_options;
286 }
287
288 $resultline = $moline->create($user, 0); // Never use triggers here
289 if ($resultline <= 0) {
290 $error++;
291 setEventMessages($moline->error, $moline->errors, 'errors');
292 }
293
294 $action = '';
295 // Redirect to refresh the tab information
296 header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
297 exit;
298 }
299
300 // Consumption and production are possible only on a validated or in progress MO
301 if (in_array($action, array('confirm_consumeorproduce', 'confirm_consumeandproduceall')) && $object->status != $object::STATUS_VALIDATED && $object->status != $object::STATUS_INPROGRESS) {
302 $langs->load("errors");
303 setEventMessages($langs->trans("ErrorObjectHasWrongStatus", $object->ref), null, 'errors');
304 $action = '';
305 }
306
307 if (in_array($action, array('confirm_consumeorproduce', 'confirm_consumeandproduceall')) && $permissiontoproduce) {
308 $stockmove = new MouvementStock($db);
309
310 $labelmovement = GETPOST('inventorylabel', 'alphanohtml');
311 $codemovement = GETPOST('inventorycode', 'alphanohtml');
312
313 $db->begin();
314 $pos = 0;
315 // Process line to consume
316 foreach ($object->lines as $line) {
317 if ($line->role == 'toconsume') {
318 $tmpproduct = new Product($db);
319 $tmpproduct->fetch($line->fk_product);
320
321 $i = 1;
322 while (GETPOSTISSET('qty-'.$line->id.'-'.$i)) {
323 $qtytoprocess = (float) price2num(GETPOST('qty-'.$line->id.'-'.$i));
324
325 if ($qtytoprocess != 0) {
326 // Check warehouse is set if we should have to
327 if (GETPOSTISSET('idwarehouse-'.$line->id.'-'.$i)) { // If there is a warehouse to set
328 if (!(GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set.
329 $langs->load("errors");
330 setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors');
331 $error++;
332 }
333 if (isModEnabled('productbatch') && $tmpproduct->status_batch && (!GETPOST('batch-'.$line->id.'-'.$i))) {
334 $langs->load("errors");
335 setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors');
336 $error++;
337 }
338 }
339
340 $idstockmove = 0;
341 if (!$error && GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0) {
342 // Record stock movement
343 $id_product_batch = 0;
344 $stockmove->setOrigin($object->element, $object->id);
345 $stockmove->context['mrp_role'] = 'toconsume';
346
347 if ($qtytoprocess >= 0) {
348 $idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOSTINT('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement);
349 } else {
350 $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOSTINT('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess * -1, 0, $labelmovement, '', '', GETPOST('batch-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement);
351 }
352 if ($idstockmove < 0) {
353 $error++;
354 setEventMessages($stockmove->error, $stockmove->errors, 'errors');
355 }
356 }
357
358 if (!$error) {
359 // Record consumption
360 $moline = new MoLine($db);
361 $moline->fk_mo = $object->id;
362 $moline->position = $pos;
363 $moline->fk_product = $line->fk_product;
364 $moline->fk_warehouse = GETPOSTINT('idwarehouse-'.$line->id.'-'.$i);
365 $moline->qty = $qtytoprocess;
366 $moline->batch = GETPOST('batch-'.$line->id.'-'.$i);
367 $moline->role = 'consumed';
368 $moline->fk_mrp_production = $line->id;
369 $moline->fk_stock_movement = $idstockmove == 0 ? null : $idstockmove;
370 $moline->fk_user_creat = $user->id;
371
372 $resultmoline = $moline->create($user);
373 if ($resultmoline <= 0) {
374 $error++;
375 setEventMessages($moline->error, $moline->errors, 'errors');
376 }
377
378 $pos++;
379 }
380 }
381
382 $i++;
383 }
384 }
385 }
386
387 // Process line to produce
388 $pos = 0;
389
390 foreach ($object->lines as $line) {
391 if ($line->role == 'toproduce') {
392 $tmpproduct = new Product($db);
393 $tmpproduct->fetch($line->fk_product);
394
395 $i = 1;
396 while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
397 $qtytoprocess = (float) price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i));
398 $pricetoprocess = GETPOST('pricetoproduce-'.$line->id.'-'.$i) ? price2num(GETPOST('pricetoproduce-'.$line->id.'-'.$i)) : 0;
399
400 if ($qtytoprocess != 0) {
401 // Check warehouse is set if we should have to
402 if (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i)) { // If there is a warehouse to set
403 if (!(GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set.
404 $langs->load("errors");
405 setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors');
406 $error++;
407 }
408 if (isModEnabled('productbatch') && $tmpproduct->status_batch && (!GETPOST('batchtoproduce-'.$line->id.'-'.$i))) {
409 $langs->load("errors");
410 setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors');
411 $error++;
412 }
413 }
414
415 $idstockmove = 0;
416 if (!$error && GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0) {
417 // Record stock movement
418 $id_product_batch = 0;
419 $stockmove->origin_type = $object->element;
420 $stockmove->origin_id = $object->id;
421 $stockmove->context['mrp_role'] = 'toproduce';
422
423 $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOSTINT('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, $pricetoprocess, $labelmovement, GETPOSTDATE('eatby-'.$line->id.'-'.$i), GETPOSTDATE('sellby-'.$line->id.'-'.$i), GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement);
424 if ($idstockmove < 0) {
425 $error++;
426 setEventMessages($stockmove->error, $stockmove->errors, 'errors');
427 }
428 }
429
430 if (!$error) {
431 // Record production
432 $moline = new MoLine($db);
433 $moline->fk_mo = $object->id;
434 $moline->position = $pos;
435 $moline->fk_product = $line->fk_product;
436 $moline->fk_warehouse = GETPOSTINT('idwarehousetoproduce-'.$line->id.'-'.$i);
437 $moline->qty = $qtytoprocess;
438 $moline->batch = GETPOST('batchtoproduce-'.$line->id.'-'.$i);
439 $moline->role = 'produced';
440 $moline->fk_mrp_production = $line->id;
441 $moline->fk_stock_movement = (($idstockmove == 0) ? null : $idstockmove);
442 $moline->fk_user_creat = $user->id;
443
444 $resultmoline = $moline->create($user);
445 if ($resultmoline <= 0) {
446 $error++;
447 setEventMessages($moline->error, $moline->errors, 'errors');
448 }
449
450 $pos++;
451 }
452 }
453
454 $i++;
455 }
456 }
457 }
458
459 if (!$error) {
460 $consumptioncomplete = true;
461 $productioncomplete = true;
462
463 if (GETPOSTINT('autoclose')) {
464 foreach ($object->lines as $line) {
465 $tmpproduct = new Product($db);
466 $tmpproduct->fetch($line->fk_product);
467 if ((int) $tmpproduct->stockable_product > 0) {
468 if ($line->role == 'toconsume') {
469 $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
470 $alreadyconsumed = 0;
471 foreach ($arrayoflines as $line2) {
472 $alreadyconsumed += $line2['qty'];
473 }
474
475 if ($alreadyconsumed < $line->qty) {
476 $consumptioncomplete = false;
477 }
478 }
479 if ($line->role == 'toproduce') {
480 $arrayoflines = $object->fetchLinesLinked('produced', $line->id);
481 $alreadyproduced = 0;
482 foreach ($arrayoflines as $line2) {
483 $alreadyproduced += $line2['qty'];
484 }
485
486 if ($alreadyproduced < $line->qty) {
487 $productioncomplete = false;
488 }
489 }
490 }
491 }
492 } else {
493 $consumptioncomplete = false;
494 $productioncomplete = false;
495 }
496
497 // Update status of MO
498 dol_syslog("consumptioncomplete = ".json_encode($consumptioncomplete)." productioncomplete = ".json_encode($productioncomplete));
499 if ($consumptioncomplete && $productioncomplete) {
500 $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
501 } else {
502 $result = $object->setStatut($object::STATUS_INPROGRESS, 0, '', 'MRP_MO_PRODUCED');
503 }
504 if ($result <= 0) {
505 $error++;
506 setEventMessages($object->error, $object->errors, 'errors');
507 }
508 }
509
510 if ($error) {
511 $action = str_replace('confirm_', '', $action);
512 $db->rollback();
513 } else {
514 $db->commit();
515
516 // Redirect to avoid to action done a second time if we make a back from browser
517 header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
518 exit;
519 }
520 }
521
522 // Action close produced
523 if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) {
524 $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
525 if ($result >= 0) {
526 // Define output language
527 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
528 $outputlangs = $langs;
529 $newlang = '';
530 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
531 $newlang = GETPOST('lang_id', 'aZ09');
532 }
533 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
534 $newlang = $object->thirdparty->default_lang;
535 }
536 if (!empty($newlang)) {
537 $outputlangs = new Translate("", $conf);
538 $outputlangs->setDefaultLang($newlang);
539 }
540 $model = $object->model_pdf;
541 $ret = $object->fetch($id); // Reload to get new records
542
543 $object->generateDocument($model, $outputlangs, 0, 0, 0);
544 }
545 } else {
546 setEventMessages($object->error, $object->errors, 'errors');
547 }
548 }
549
550 if ($action == 'confirm_editline' && $permissiontoadd && !in_array($object->status, array($object::STATUS_PRODUCED, $object::STATUS_CANCELED))) {
551 $moline = new MoLine($db);
552 $result = $moline->fetch(GETPOSTINT('lineid'));
553 if ($result > 0 && $moline->fk_mo != $object->id) {
554 $result = -1; // The line must belong to this MO
555 }
556 if ($result > 0 && in_array($moline->role, array('consumed', 'produced'))) {
557 $result = -1; // A consumed or produced quantity is changed by its stock movement, not here (only the quantities to consume or produce can be edited)
558 }
559 if ($result > 0) {
560 $extrafields->fetch_name_optionals_label($moline->table_element);
561 if (!empty($extrafields->attributes[$moline->table_element]['label'])) {
562 foreach ($extrafields->attributes[$moline->table_element]['label'] as $key => $label) {
563 $value = GETPOST('options_'.$key, 'alphanohtml');
564 $moline->array_options["options_".$key] = $value;
565 }
566 }
567 $moline->qty = GETPOSTFLOAT('qty_lineProduce');
568 if (GETPOSTISSET('warehouse_lineProduce')) {
569 $moline->fk_warehouse = (GETPOSTINT('warehouse_lineProduce') > 0 ? GETPOSTINT('warehouse_lineProduce') : 0);
570 }
571 if (GETPOSTISSET('workstation_lineProduce')) {
572 $moline->fk_default_workstation = (GETPOSTINT('workstation_lineProduce') > 0 ? GETPOSTINT('workstation_lineProduce') : 0);
573 }
574
575 $res = $moline->update($user);
576
577 if ($res < 0) {
578 setEventMessages($moline->error, $moline->errors, 'errors');
579 header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
580 exit;
581 }
582 header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
583 exit;
584 }
585 }
586}
587
588
589
590/*
591 * View
592 */
593
594$form = new Form($db);
595$formproject = new FormProjets($db);
596$formproduct = new FormProduct($db);
597$tmpwarehouse = new Entrepot($db);
598$tmpbatch = new Productlot($db);
599$tmpstockmovement = new MouvementStock($db);
600
601$title = $langs->trans('Mo');
602$help_url = 'EN:Module_Manufacturing_Orders|FR:Module_Ordres_de_Fabrication|DE:Modul_Fertigungsauftrag';
603$morejs = array('/mrp/js/lib_dispatch.js.php');
604llxHeader('', $title, $help_url, '', 0, 0, $morejs, '', '', 'mod-mrp page-card_production');
605
606$newToken = newToken();
607
608// Part to show record
609if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create' && $action != 'reload'))) {
610 $res = $object->fetch_thirdparty();
611 $res = $object->fetch_optionals();
612
613 if (getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') && $object->fk_warehouse > 0) {
614 $tmpwarehouse->fetch((int) $object->fk_warehouse);
615 $fk_default_warehouse = (int) $object->fk_warehouse;
616 }
617
618 $head = moPrepareHead($object);
619
620 print dol_get_fiche_head($head, 'production', $langs->trans("ManufacturingOrder"), -1, $object->picto);
621
622 $formconfirm = '';
623
624 // Confirmation to delete
625 if ($action == 'delete') {
626 $formquestion = array(
627 array(
628 'label' => $langs->trans('MoCancelConsumedAndProducedLines'),
629 'name' => 'alsoCancelConsumedAndProducedLines',
630 'type' => 'checkbox',
631 'value' => 0
632 ),
633 );
634 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', $formquestion, 0, 1);
635 }
636 // Confirmation to delete line
637 if ($action == 'deleteline') {
638 $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);
639 }
640 // Clone confirmation
641 if ($action == 'clone') {
642 // Create an array for form
643 $formquestion = array();
644 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
645 }
646
647 // Confirmation of validation
648 if ($action == 'validate') {
649 // We check that object has a temporary ref
650 $ref = substr($object->ref, 1, 4);
651 if ($ref == 'PROV') {
652 $object->fetch_product();
653 $numref = $object->getNextNumRef($object->product);
654 } else {
655 $numref = (string) $object->ref;
656 }
657
658 $text = $langs->trans('ConfirmValidateMo', $numref);
659 /*if (isModEnabled('notification'))
660 {
661 require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
662 $notify = new Notify($db);
663 $text .= '<br>';
664 $text .= $notify->confirmMessage('BOM_VALIDATE', $object->socid, $object);
665 }*/
666
667 $formquestion = array();
668 if (isModEnabled('mrp')) {
669 $langs->load("mrp");
670 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
671 $formproduct = new FormProduct($db);
672 $forcecombo = 0;
673 if ($conf->browser->name == 'ie') {
674 $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
675 }
676 $formquestion = array(
677 // 'text' => $langs->trans("ConfirmClone"),
678 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
679 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
680 );
681 }
682
683 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220);
684 }
685
686 // Confirmation to cancel
687 if ($action == 'cancel') {
688 $formquestion = array(
689 array(
690 'label' => $langs->trans('MoCancelConsumedAndProducedLines'),
691 'name' => 'alsoCancelConsumedAndProducedLines',
692 'type' => 'checkbox',
693 'value' => !getDolGlobalString('MO_ALSO_CANCEL_CONSUMED_AND_PRODUCED_LINES_BY_DEFAULT') ? 0 : 1
694 ),
695 );
696 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('CancelMo'), $langs->trans('ConfirmCancelMo'), 'confirm_cancel', $formquestion, 0, 1);
697 }
698
699 // Call Hook formConfirm
700 $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
701 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
702 if (empty($reshook)) {
703 $formconfirm .= $hookmanager->resPrint;
704 } elseif ($reshook > 0) {
705 $formconfirm = $hookmanager->resPrint;
706 }
707
708 // Print form confirm
709 print $formconfirm;
710
711
712 // MO file
713 // ------------------------------------------------------------
714 $linkback = '<a href="'.DOL_URL_ROOT.'/mrp/mo_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
715
716 $morehtmlref = '<div class="refidno">';
717
718 /*
719 // Ref bis
720 $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', 0, 1);
721 $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', null, null, '', 1);
722 */
723
724 // Thirdparty
725 if (is_object($object->thirdparty)) {
726 $morehtmlref .= $object->thirdparty->getNomUrl(1, 'customer');
727 if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
728 $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->thirdparty->id.'">'.$langs->trans("OtherOrders").'</a>)';
729 }
730 }
731
732 // Project
733 if (isModEnabled('project')) {
734 $langs->load("projects");
735 if (is_object($object->thirdparty)) {
736 $morehtmlref .= '<br>';
737 }
738 if ($permissiontoadd) {
739 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
740 if ($action != 'classify') {
741 $morehtmlref .= '<a class="editfielda" href="'.dolBuildUrl($_SERVER['PHP_SELF'], ['action' => 'classify', 'id' => $object->id], true).'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
742 }
743 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
744 } else {
745 if (!empty($object->fk_project)) {
746 $proj = new Project($db);
747 $proj->fetch($object->fk_project);
748 $morehtmlref .= $proj->getNomUrl(1);
749 if ($proj->title) {
750 $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
751 }
752 }
753 }
754 }
755 $morehtmlref .= '</div>';
756
757
758 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
759
760
761 print '<div class="fichecenter">';
762 print '<div class="fichehalfleft">';
763 print '<div class="underbanner clearboth"></div>';
764 print '<table class="border centpercent tableforfield">'."\n";
765
766 // Common attributes
767 $keyforbreak = 'fk_warehouse';
768 unset($object->fields['fk_project']);
769 unset($object->fields['fk_soc']);
770 // Allow inline edit of qty while MO is in draft status.
771 // Note: editfieldval() does not handle type 'real' (no <input> rendered, only
772 // Save/Cancel buttons appear). So we override the type to 'numeric' only when
773 // the user has actually clicked the edit pencil (action=editqty). This keeps
774 // the read-mode rendering (price() format) untouched.
775 if ($object->status == Mo::STATUS_DRAFT && $permissiontoadd && isset($object->fields['qty'])) {
776 $object->fields['qty']['alwayseditable'] = 1;
777 if ($action == 'editqty') {
778 $object->fields['qty']['type'] = 'numeric';
779 }
780 }
781
782 include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
783
784 // Other attributes
785 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
786
787 print '</table>';
788 print '</div>';
789 print '</div>';
790
791 print '<div class="clearboth"></div>';
792
793 print dol_get_fiche_end();
794
795
796 if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
797 print '<div class="tabsAction">';
798
799 $parameters = array();
800 // Note that $action and $object may be modified by hook
801 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
802 if (empty($reshook)) {
803 // Validate
804 if ($object->status == $object::STATUS_DRAFT) {
805 if ($permissiontoadd) {
806 if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
807 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate&token='.$newToken.'">'.$langs->trans("Validate").'</a>';
808 } else {
809 $langs->load("errors");
810 print '<a class="butActionRefused" href="" title="'.$langs->trans("ErrorAddAtLeastOneLineFirst").'">'.$langs->trans("Validate").'</a>';
811 }
812 }
813 }
814
815 // Consume or produce
816 if ($object->status == Mo::STATUS_VALIDATED || $object->status == Mo::STATUS_INPROGRESS) {
817 if ($permissiontoproduce) {
818 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=consumeorproduce&token='.$newToken.'">'.$langs->trans('ConsumeOrProduce').'</a>';
819 } else {
820 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ConsumeOrProduce').'</a>';
821 }
822 } elseif ($object->status == Mo::STATUS_DRAFT) {
823 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("ValidateBefore").'">'.$langs->trans('ConsumeOrProduce').'</a>';
824 }
825
826 // ConsumeAndProduceAll
827 if ($object->status == Mo::STATUS_VALIDATED || $object->status == Mo::STATUS_INPROGRESS) {
828 if ($permissiontoproduce) {
829 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=consumeandproduceall&token='.$newToken.'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
830 } else {
831 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
832 }
833 } elseif ($object->status == Mo::STATUS_DRAFT) {
834 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("ValidateBefore").'">'.$langs->trans('ConsumeAndProduceAll').'</a>';
835 }
836
837 // Cancel - Reopen
838 if ($permissiontoadd) {
839 if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) {
840 $arrayproduced = $object->fetchLinesLinked('produced', 0);
841 $nbProduced = 0;
842 foreach ($arrayproduced as $lineproduced) {
843 $nbProduced += $lineproduced['qty'];
844 }
845 if ($nbProduced > 0) { // If production has started, we can close it
846 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_produced&confirm=yes&token='.$newToken.'">'.$langs->trans("Close").'</a>'."\n";
847 } else {
848 print '<a class="butActionRefused" href="#" title="'.$langs->trans("GoOnTabProductionToProduceFirst", $langs->transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").'</a>'."\n";
849 }
850
851 print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.$newToken.'">'.$langs->trans("Cancel").'</a>'."\n";
852 }
853
854 if ($object->status == $object::STATUS_CANCELED) {
855 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes&token='.$newToken.'">'.$langs->trans("ReOpen").'</a>'."\n";
856 }
857
858 if ($object->status == $object::STATUS_PRODUCED) {
859 if ($permissiontoproduce) {
860 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&token='.$newToken.'">'.$langs->trans('ReOpen').'</a>';
861 } else {
862 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('ReOpen').'</a>';
863 }
864 }
865 }
866 }
867
868 print '</div>';
869 }
870
871 if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline', 'addproduceline', 'editline'))) {
872 print '<!-- Form to enter value for consumption/production -->';
873 print '<form method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
874 print '<input type="hidden" name="token" value="'.newToken().'">';
875 print '<input type="hidden" name="action" value="confirm_'.$action.'">';
876 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
877 print '<input type="hidden" name="id" value="'.$id.'">';
878 // Note: closing form is add end of page
879
880 if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
881 $defaultstockmovementlabel = GETPOST('inventorylabel', 'alphanohtml') ? GETPOST('inventorylabel', 'alphanohtml') : $langs->trans("ProductionForRef", $object->ref);
882 $defaultstockmovementcode = GETPOST('inventorycode', 'alphanohtml') ? GETPOST('inventorycode', 'alphanohtml') : dol_print_date(dol_now(), 'dayhourlog');
883
884 print '<div class="center'.(in_array($action, array('consumeorproduce', 'consumeandproduceall')) ? ' formconsumeproduce' : '').'">';
885 print '<div class="opacitymedium hideonsmartphone paddingbottom marginbottomonly">'.$langs->trans("ConfirmProductionDesc", $langs->transnoentitiesnoconv("Confirm")).'<br></div>';
886 print '<span class="paddingright">'.$langs->trans("InventoryCode").':</span>';
887 print '<span class="clearbothonsmartphone"></span>';
888 print '<input type="text" class="minwidth125 maxwidth150" name="inventorycode" value="'.$defaultstockmovementcode.'">';
889 print '<span class="hideonsmartphone">&nbsp; &nbsp;</span>';
890 print '<span class="clearbothonsmartphone"></span>';
891 print '<span class="paddingright">'.$langs->trans("MovementLabel").':</span>';
892 print '<span class="clearbothonsmartphone"></span>';
893 print '<input type="text" class="minwidth300" name="inventorylabel" value="'.$defaultstockmovementlabel.'"><br><br>';
894 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>';
895 print '<input type="submit" class="button margintoponly" value="'.$langs->trans("Confirm").'" name="confirm">';
896 print ' &nbsp; ';
897 print '<input class="button margintoponly button-cancel" type="submit" value="'.$langs->trans("Cancel").'" name="cancel">';
898 print '<br><br>';
899 print '</div>';
900
901 print '<br>';
902 }
903 }
904
905
906 /*
907 * Lines
908 */
909 $collapse = 1;
910
911 if (!empty($object->table_element_line)) {
912 // Show object lines
913 $object->fetchLines();
914
915 $bomcost = 0;
916 if ($object->fk_bom > 0) {
917 $bom = new BOM($db);
918 $res = $bom->fetch($object->fk_bom);
919 if ($res > 0) {
920 $bom->calculateCosts();
921 $bomcost = $bom->unit_cost;
922 }
923 }
924
925 // Lines to consume
926
927 print '<!-- Lines to consume -->'."\n";
928 print '<div class="fichecenter">';
929 print '<div class="fichehalfleft">';
930 print '<div class="clearboth"></div>';
931
932 $url = $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addconsumeline&token='.newToken();
933 $permissiontoaddaconsumeline = ($object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED) ? 1 : -2;
934 $parameters = array('morecss' => 'reposition');
935 $helpText = '';
936 if ($permissiontoaddaconsumeline == -2) {
937 $helpText = $langs->trans('MOIsClosed');
938 }
939
940 $newcardbutton = '';
941 if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') {
942 $newcardbutton = dolGetButtonTitle($langs->trans('AddNewConsumeLines'), $helpText, 'fa fa-plus-circle size15x', $url, '', $permissiontoaddaconsumeline, $parameters);
943 }
944
945 print load_fiche_titre($langs->trans('Consumption'), $newcardbutton, '', 0, '', '', '');
946
947 print '<div class="div-table-responsive-no-min">';
948 print '<table class="noborder noshadow centpercent nobottom">';
949
950 print '<!-- Line of title for products to consume -->'."\n";
951 print '<tr class="liste_titre trheight5em">';
952 // Product
953 print '<td>'.$langs->trans("Product").'</td>';
954 // Qty
955 print '<td class="right">'.$langs->trans("Qty").'</td>';
956 // Unit
957 print '<td></td>';
958 // Cost price
959 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
960 print '<td class="right">'.$langs->trans("UnitCost").'</td>';
961 }
962 // Qty already consumed
963 print '<td class="right classfortooltip" title="'.$langs->trans("QtyAlreadyConsumed").'">';
964 print $langs->trans("QtyAlreadyConsumedShort");
965 print '</td>';
966 // Warehouse
967 print '<td>';
968 if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
969 print $langs->trans("Warehouse");
970 if (isModEnabled('workstation')) {
971 print ' '.$langs->trans("or").' '.$langs->trans("Workstation");
972 }
973 // Select warehouse to force it everywhere
974 if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
975 $listwarehouses = $tmpwarehouse->list_array(1);
976 if (count($listwarehouses) > 1) {
977 print '<br>'.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, $langs->trans("ForceTo"), 0, 0, '', 0, 0, 0, '', 'minwidth100 maxwidth200', 1);
978 } elseif (count($listwarehouses) == 1) {
979 print '<br>'.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100 maxwidth200', 1);
980 }
981 }
982 }
983 print '</td>';
984
985 if (isModEnabled('stock')) {
986 // Available
987 print '<td align="right">';
988 if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
989 print $langs->trans("Stock");
990 }
991 print '</td>';
992 }
993 // Lot - serial
994 if (isModEnabled('productbatch')) {
995 print '<td>';
996 if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
997 print $langs->trans("Batch");
998 }
999 print '</td>';
1000 }
1001
1002 // Split
1003 print '<td></td>';
1004
1005 // SplitAll
1006 print '<td></td>';
1007
1008 // Edit Line
1009 if ($object->status == Mo::STATUS_DRAFT) {
1010 print '<td></td>';
1011 }
1012
1013 // Action
1014 if ($permissiontodelete) {
1015 print '<td></td>';
1016 }
1017
1018 print '</tr>';
1019
1020 if ($action == 'addconsumeline') {
1021 print '<!-- Add line to consume -->'."\n";
1022 print '<tr class="liste_titre">';
1023 // Product
1024 print '<td>';
1025 print $form->select_produits(0, 'productidtoadd', '', 0, 0, -1, 2, '', 1, array(), 0, '1', 0, 'maxwidth150');
1026 print '</td>';
1027 // Qty
1028 print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width40 right"></td>';
1029 // Unit
1030 print '<td>';
1031 //if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1032 //...
1033 //}
1034 print '</td>';
1035 // Cost price
1036 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
1037 print '<td></td>';
1038 }
1039
1040 $colspan = 3;
1041 if (isModEnabled('stock')) {
1042 $colspan++;
1043 }
1044 if (isModEnabled('productbatch')) {
1045 $colspan++;
1046 }
1047 // Qty already consumed + Warehouse
1048 print '<td colspan="'.$colspan.'">';
1049 print '<input type="submit" class="button buttongen button-add" name="addconsumelinebutton" value="'.$langs->trans("Add").'">';
1050 print '<input type="submit" class="button buttongen button-cancel" name="canceladdconsumelinebutton" value="'.$langs->trans("Cancel").'">';
1051 print '</td>';
1052 // Split All
1053 print '<td></td>';
1054 // Edit Line
1055 if ($object->status == Mo::STATUS_DRAFT) {
1056 print '<td></td>';
1057 }
1058 // Action
1059 if ($permissiontodelete) {
1060 print '<td></td>';
1061 }
1062 print '</tr>';
1063
1064 // Extrafields Line
1065 if (is_object($objectline)) {
1066 $extrafields->fetch_name_optionals_label($object->table_element_line);
1067 $temps = $objectline->showOptionals($extrafields, 'edit', array(), '', '', '1', 'line');
1068 if (!empty($temps)) {
1069 print '<tr class="liste_titre"><td style="padding-top: 20px" colspan="9" id="extrafield_lines_area_edit" name="extrafield_lines_area_edit">';
1070 print $temps;
1071 print '</td></tr>';
1072 }
1073 }
1074 }
1075
1076 // Lines to consume
1077
1078 $bomcostupdated = 0; // We will recalculate the unitary cost to produce a product using the real "products to consume into MO"
1079
1080 if (!empty($object->lines)) {
1081 $nblinetoconsume = 0;
1082 foreach ($object->lines as $line) {
1083 if ($line->role == 'toconsume') {
1084 $nblinetoconsume++;
1085 }
1086 }
1087
1088 $nblinetoconsumecursor = 0;
1089 foreach ($object->lines as $line) {
1090 if ($line->role == 'toconsume') {
1091 $nblinetoconsumecursor++;
1092
1093 $tmpproduct = new Product($db);
1094 $tmpproduct->fetch($line->fk_product);
1095 $linecost = price2num($tmpproduct->pmp, 'MT');
1096
1097 if ($object->qty > 0) {
1098 // add free consume line cost to $bomcostupdated
1099 $costprice = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
1100 if (empty($costprice)) {
1101 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1102 $productFournisseur = new ProductFournisseur($db);
1103 if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product, $line->qty) > 0) {
1104 $costprice = $productFournisseur->fourn_unitprice;
1105 } else {
1106 $costprice = 0;
1107 }
1108 }
1109
1110 $useunit = (($tmpproduct->type == Product::TYPE_PRODUCT && getDolGlobalInt('PRODUCT_USE_UNITS')) || (($tmpproduct->type == Product::TYPE_SERVICE) && ($line->fk_unit)));
1111
1112 if ($useunit && $line->fk_unit > 0) {
1113 $reg = [];
1114 $qtyhourservice = 0;
1115 if (preg_match('/^(\d+)([a-z]+)$/', $tmpproduct->duration, $reg)) {
1116 $qtyhourservice = convertDurationtoHour((float) $reg[1], (string) $reg[2]);
1117 }
1118 $qtyhourforline = 0;
1119 if ($line->fk_unit) {
1120 $unitforline = measuringUnitString($line->fk_unit, '', null, 1);
1121 $qtyhourforline = convertDurationtoHour($line->qty, $unitforline);
1122 }
1123
1124 // Add the workstation cost for the manufacturing order cost when a workstation is set
1125 if (isModEnabled('workstation') && $line->fk_default_workstation > 0) {
1126 $workstation = new Workstation($db);
1127 $workstation->fetch($line->fk_default_workstation);
1128 $linecost = price2num($qtyhourforline * ($workstation->thm_operator_estimated + $workstation->thm_machine_estimated) / $object->qty, 'MT'); //if global const MRP_SHOW_COST_FOR_CONSUMPTION is used to show price for each line
1129 $bomcostupdated += price2num($qtyhourforline * ($workstation->thm_operator_estimated + $workstation->thm_machine_estimated) / $object->qty, 'MU');
1130 } elseif ($qtyhourservice && $qtyhourforline) {
1131 $linecost = price2num(($qtyhourforline / $qtyhourservice * $costprice) / $object->qty, 'MT'); // price for line for all quantities
1132 $bomcostupdated += price2num(($qtyhourforline / $qtyhourservice * $costprice) / $object->qty, 'MU'); // same but with full accuracy
1133 } else {
1134 $linecost = price2num(($line->qty * $costprice) / $object->qty, 'MT'); // price for line for all quantities
1135 $bomcostupdated += price2num(($line->qty * $costprice) / $object->qty, 'MU'); // same but with full accuracy
1136 }
1137 } else {
1138 $linecost = price2num(($line->qty * $costprice) / $object->qty, 'MT'); // price for line for all quantities
1139 $bomcostupdated += price2num(($line->qty * $costprice) / $object->qty, 'MU'); // same but with full accuracy
1140 }
1141 }
1142
1143 $bomcostupdated = price2num($bomcostupdated, 'MU');
1144 $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
1145 $alreadyconsumed = 0;
1146 foreach ($arrayoflines as $line2) {
1147 $alreadyconsumed += $line2['qty'];
1148 }
1149
1150 if ($action == 'editline' && $lineid == $line->id) {
1151 $linecost = price2num($tmpproduct->pmp, 'MT');
1152
1153 $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
1154 $alreadyconsumed = 0;
1155 if (is_array($arrayoflines) && !empty($arrayoflines)) {
1156 foreach ($arrayoflines as $line2) {
1157 $alreadyconsumed += $line2['qty'];
1158 }
1159 }
1160 $suffix = '_' . $line->id;
1161 print '<!-- Line to dispatch ' . $suffix . ' (line edited) -->' . "\n";
1162 // hidden fields for js function
1163 print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $line->qty . '">';
1164 // Duration - Time spent
1165 print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . $alreadyconsumed . '">';
1166 print '<tr>';
1167 print '<input name="lineid" type="hidden" value="' . $line->id . '">';
1168
1169 // Product
1170 print '<td>' . $tmpproduct->getNomUrl(1);
1171 print '<br><div class="opacitymedium small tdoverflowmax150" title="' . dol_escape_htmltag($tmpproduct->label) . '">' . $tmpproduct->label . '</span>';
1172 print '</td>';
1173
1174 // Qty
1175 print '<td class="right nowraponall">';
1176 print '<input class="width40 right" name="qty_lineProduce" value="'. $line->qty.'">';
1177 print '</td>';
1178
1179 // Unit
1180 print '<td class="right nowraponall">';
1181 $useunit = (($tmpproduct->type == Product::TYPE_PRODUCT && getDolGlobalInt('PRODUCT_USE_UNITS')) || (($tmpproduct->type == Product::TYPE_SERVICE) && ($line->fk_unit)));
1182 if ($useunit) {
1183 print measuringUnitString($line->fk_unit, '', null, 2);
1184 }
1185 print '</td>';
1186
1187 // Cost price
1188 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
1189 print '<td></td>';
1190 }
1191
1192 // Qty consumed
1193 print '<td class="right">';
1194 print ' ' . price2num($alreadyconsumed, 'MS');
1195 print '</td>';
1196
1197 // Warehouse / Workstation
1198 print '<td>';
1199 if ($tmpproduct->type == Product::TYPE_PRODUCT) {
1200 print $formproduct->selectWarehouses($line->fk_warehouse, 'warehouse_lineProduce', 'warehouseopen', 1);
1201 } elseif (isModEnabled('workstation')) {
1202 print $formproduct->selectWorkstations($line->fk_default_workstation, 'workstation_lineProduce', 1);
1203 }
1204 print '</td>';
1205
1206 // Stock
1207 if (isModEnabled('stock')) {
1208 print '<td class="nowraponall right">';
1209 if ($tmpproduct->isStockManaged()) {
1210 if ($tmpproduct->stock_reel < ($line->qty - $alreadyconsumed)) {
1211 print img_warning($langs->trans('StockTooLow')).' ';
1212 }
1213 print '<span class="left">'. $tmpproduct->stock_reel .' </span>';
1214 }
1215 print '</td>';
1216 }
1217
1218 // Lot - serial
1219 if (isModEnabled('productbatch')) {
1220 print '<td></td>';
1221 }
1222 // Split + SplitAll + Edit line + Delete
1223 print '<td colspan="'.(3 + ($object->status == Mo::STATUS_DRAFT ? 1 : 0) + ($permissiontodelete ? 1 : 0)).'">';
1224 print '<input type="submit" class="button buttongen button-add small nominwidth" name="save" value="' . $langs->trans("Save") . '">';
1225 print '<input type="submit" class="button buttongen button-cancel small nominwidth" name="cancel" value="' . $langs->trans("Cancel") . '">';
1226 print '</td>';
1227
1228 print '</tr>';
1229
1230 // Extrafields Line
1231 if (!empty($extrafields)) {
1232 $line->fetch_optionals();
1233 $temps = $line->showOptionals($extrafields, 'edit', array(), '', '', '1', 'line');
1234 if (!empty($temps)) {
1235 $colspan = 10;
1236 print '<tr><td colspan="'.$colspan.'"><div style="padding-top: 20px" id="extrafield_lines_area_edit" name="extrafield_lines_area_edit">';
1237 print $temps;
1238 print '</div></td></tr>';
1239 }
1240 }
1241 } else {
1242 $suffix = '_' . $line->id;
1243 print '<!-- Line to dispatch ' . $suffix . ' -->' . "\n";
1244 // hidden fields for js function
1245 print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $line->qty . '">';
1246 print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . $alreadyconsumed . '">';
1247
1248 print '<tr data-line-id="' . $line->id . '">';
1249
1250 // Product
1251 print '<td>' . $tmpproduct->getNomUrl(1);
1252 print '<br><div class="opacitymedium small tdoverflowmax150" title="' . dol_escape_htmltag($tmpproduct->label) . '">' . $tmpproduct->label . '</div>';
1253 print '</td>';
1254
1255 // Qty
1256 print '<td class="right nowraponall">';
1257 $help = '';
1258 if ($line->qty_frozen) {
1259 $help = ($help ? '<br>' : '') . '<strong>' . $langs->trans("QuantityFrozen") . '</strong>: ' . yn(1) . ' (' . $langs->trans("QuantityConsumedInvariable") . ')';
1260 print $form->textwithpicto('', $help, -1, 'lock') . ' ';
1261 }
1262 if ($line->disable_stock_change) {
1263 $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")) . ')';
1264 print $form->textwithpicto('', $help, -1, 'help') . ' ';
1265 }
1266 print price2num($line->qty, 'MS');
1267 print '</td>';
1268
1269 // Unit
1270 print '<td class="right nowraponall">';
1271 $useunit = (($tmpproduct->type == Product::TYPE_PRODUCT && getDolGlobalInt('PRODUCT_USE_UNITS')) || (($tmpproduct->type == Product::TYPE_SERVICE) && ($line->fk_unit)));
1272 if ($useunit) {
1273 print measuringUnitString($line->fk_unit, '', null, 2);
1274 }
1275 print '</td>';
1276
1277 // Cost price
1278 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
1279 print '<td class="right nowraponall">';
1280 print price($linecost);
1281 print '</td>';
1282 }
1283
1284 // Already consumed
1285 print '<td class="right">';
1286 if ($alreadyconsumed) {
1287 print '<script>';
1288 print 'jQuery(document).ready(function() {
1289 jQuery("#expandtoproduce' . $line->id . '").click(function() {
1290 console.log("Expand mrp_production line ' . $line->id . '");
1291 jQuery(".expanddetail' . $line->id . '").toggle();';
1292 if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line
1293 print 'if (jQuery("#tablelines").hasClass("nobottom")) { jQuery("#tablelines").removeClass("nobottom"); } else { jQuery("#tablelines").addClass("nobottom"); }';
1294 }
1295 print '
1296 });
1297 });';
1298 print '</script>';
1299 if (empty($conf->use_javascript_ajax)) {
1300 print '<a href="' . $_SERVER["PHP_SELF"] . '?collapse=' . $collapse . ',' . $line->id . '">';
1301 }
1302 print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce' . $line->id . '"');
1303 if (empty($conf->use_javascript_ajax)) {
1304 print '</a>';
1305 }
1306 } else {
1307 if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line
1308 print '<script>jQuery("#tablelines").removeClass("nobottom");</script>';
1309 }
1310 }
1311 print ' ' . price2num($alreadyconsumed, 'MS');
1312 print '</td>';
1313
1314 // Warehouse and/or workstation
1315 print '<td class="tdoverflowmax100">';
1316 if ($tmpproduct->isStockManaged()) {
1317 // When STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE is set, we always use the warehouse of the MO, the same than production.
1318 if (getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') && $tmpwarehouse->id > 0) {
1319 print img_picto('', $tmpwarehouse->picto) . " " . $tmpwarehouse->label;
1320 } else {
1321 if ($line->fk_warehouse > 0) {
1322 $warehouseline = new Entrepot($db);
1323 $warehouseline->fetch($line->fk_warehouse);
1324 print $warehouseline->getNomUrl(1);
1325 }
1326 }
1327 }
1328 if (isModEnabled('workstation') && $line->fk_default_workstation > 0) {
1329 $tmpworkstation = new Workstation($db);
1330 $tmpworkstation->fetch($line->fk_default_workstation);
1331 print $tmpworkstation->getNomUrl(1);
1332 }
1333 print '</td>';
1334
1335 // Stock
1336 if (isModEnabled('stock')) {
1337 print '<td class="nowraponall right">';
1338 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES') && $tmpproduct->type != Product::TYPE_SERVICE) {
1339 if (!$line->disable_stock_change && $tmpproduct->stock_reel < ($line->qty - $alreadyconsumed)) {
1340 print img_warning($langs->trans('StockTooLow')) . ' ';
1341 }
1342 if (!getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE') || empty($tmpwarehouse->id)) {
1343 print price2num($tmpproduct->stock_reel, 'MS'); // Available
1344 } else {
1345 // Print only the stock in the selected warehouse
1346 $tmpproduct->load_stock();
1347 $wh_stock = $tmpproduct->stock_warehouse[$tmpwarehouse->id];
1348 if (!empty($wh_stock)) {
1349 print price2num($wh_stock->real, 'MS');
1350 } else {
1351 print "0";
1352 }
1353 }
1354 }
1355 print '</td>';
1356 }
1357
1358 // Lot
1359 if (isModEnabled('productbatch')) {
1360 print '<td></td>';
1361 }
1362
1363 // Split
1364 print '<td></td>';
1365
1366 // Split All
1367 print '<td></td>';
1368
1369 // Action Edit line
1370 if ($object->status == Mo::STATUS_DRAFT) {
1371 $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=editline&token=' . newToken() . '&lineid=' . ((int) $line->id);
1372 print '<td class="center">';
1373 print '<a class="reposition editfielda" href="' . $href . '">';
1374 print img_picto($langs->trans('TooltipEditAndRevertStockMovement'), 'edit');
1375 print '</a>';
1376 print '</td>';
1377 }
1378
1379 // Action delete line, if no consumption has occurred for this product
1380 if ($permissiontodelete && empty($arrayoflines)) {
1381 $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=deleteline&token=' . newToken() . '&lineid=' . ((int) $line->id);
1382 print '<td class="center">';
1383 print '<a class="reposition" href="' . $href . '">';
1384 print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), 'delete');
1385 print '</a>';
1386 print '</td>';
1387 }
1388
1389 print '</tr>';
1390
1391 // Extrafields Line
1392 if (!empty($extrafields)) {
1393 $line->fetch_optionals();
1394 $temps = $line->showOptionals($extrafields, 'view', array(), '', '', '1', 'line');
1395 if (!empty($temps)) {
1396 $colspan = 10;
1397 print '<tr><td colspan="'.$colspan.'"><div id="extrafield_lines_area_'.$line->id.'" name="extrafield_lines_area_'.$line->id.'">';
1398 print $temps;
1399 print '</div></td></tr>';
1400 }
1401 }
1402 }
1403
1404 // Show detailed of already consumed with js code to collapse
1405 foreach ($arrayoflines as $line2) {
1406 print '<tr class="expanddetail'.$line->id.' hideobject opacitylow">';
1407
1408 // Date
1409 print '<td>';
1410 $tmpstockmovement->id = $line2['fk_stock_movement'];
1411 print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>';
1412 print dol_print_date($line2['date'], 'dayhour', 'tzuserrel');
1413 print '</td>';
1414
1415 // Qty
1416 print '<td></td>';
1417
1418 // Unit
1419 print '<td></td>';
1420
1421 // Cost price
1422 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
1423 print '<td></td>';
1424 }
1425
1426 //Already consumed
1427 print '<td class="right">'.$line2['qty'].'</td>';
1428
1429 // Warehouse
1430 print '<td class="tdoverflowmax150">';
1431 if ($line2['fk_warehouse'] > 0) {
1432 $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
1433 if ($result > 0) {
1434 print $tmpwarehouse->getNomUrl(1);
1435 }
1436 }
1437 print '</td>';
1438
1439 // Stock
1440 if (isModEnabled('stock')) {
1441 print '<td></td>';
1442 }
1443
1444 // Lot Batch
1445 if (isModEnabled('productbatch')) {
1446 print '<td>';
1447 if ($line2['batch'] != '') {
1448 $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']);
1449 print $tmpbatch->getNomUrl(1);
1450 }
1451 print '</td>';
1452 }
1453
1454 // Split
1455 print '<td></td>';
1456
1457 // Split All
1458 print '<td></td>';
1459
1460 // Action Edit line
1461 if ($object->status == Mo::STATUS_DRAFT) {
1462 $href = $_SERVER["PHP_SELF"] . '?id=' . ((int) $object->id) . '&action=editline&token=' . newToken() . '&lineid=' . ((int) $line2['rowid']);
1463 print '<td class="center">';
1464 print '<a class="reposition" href="' . $href . '">';
1465 print img_picto($langs->trans('TooltipEditAndRevertStockMovement'), 'edit');
1466 print '</a>';
1467 print '</td>';
1468 }
1469
1470 // Action delete line
1471 if ($permissiontodelete) {
1472 $href = $_SERVER["PHP_SELF"].'?id='.((int) $object->id).'&action=deleteline&token='.newToken().'&lineid='.((int) $line2['rowid']).'&fk_movement='.((int) $line2['fk_stock_movement']);
1473 print '<td class="center">';
1474 print '<a class="reposition" href="'.$href.'">';
1475 print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), 'delete');
1476 print '</a>';
1477 print '</td>';
1478 }
1479
1480 print '</tr>';
1481 }
1482
1483 if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
1484 $i = 1;
1485 print '<!-- Enter line to consume -->'."\n";
1486 $maxQty = 1;
1487 print '<tr data-max-qty="'.$maxQty.'" name="batch_'.$line->id.'_'.$i.'">';
1488 // Ref
1489 print '<td><span class="opacitymedium">'.$langs->trans("ToConsume").'</span></td>';
1490 $preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed));
1491 if ($action == 'consumeorproduce' && !getDolGlobalString('MRP_AUTO_SET_REMAINING_QUANTITIES_TO_BE_CONSUMED') && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) {
1492 $preselected = 0;
1493 }
1494
1495 $disable = '';
1496 if (getDolGlobalString('MRP_NEVER_CONSUME_MORE_THAN_EXPECTED') && ($line->qty - $alreadyconsumed) <= 0) {
1497 $disable = 'disabled';
1498 }
1499
1500 // input hidden with fk_product of line
1501 print '<input type="hidden" name="product-'.$line->id.'-'.$i.'" value="'.$line->fk_product.'">';
1502
1503 // Qty
1504 print '<td class="right">';
1505 if ((int) $tmpproduct->stockable_product > 0) {
1506 print '<input type="text" class="width50 right" id="qtytoconsume-' . $line->id . '-' . $i . '" name="qty-' . $line->id . '-' . $i . '" value="' . $preselected . '" ' . $disable . '>';
1507 } else {
1508 print '<input type="hidden" id="qtytoconsume-' . $line->id . '-' . $i . '" name="qty-' . $line->id . '-' . $i . '" value="0">';
1509 print '<span class="opacitymedium">' . $langs->trans("StockDisabled") . '</span>';
1510 }
1511 print '</td>';
1512
1513 // Unit
1514 print '<td></td>';
1515
1516 // Cost
1517 if ($permissiontoupdatecost && getDolGlobalString('MRP_SHOW_COST_FOR_CONSUMPTION')) {
1518 print '<td></td>';
1519 }
1520
1521 // Already consumed
1522 print '<td></td>';
1523
1524 // Warehouse
1525 print '<td>';
1526 if (($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))
1527 && ((int) $tmpproduct->stockable_product > 0)) {
1528 if (empty($line->disable_stock_change)) {
1529 $preselected = (GETPOSTISSET('idwarehouse-'.$line->id.'-'.$i) ? GETPOST('idwarehouse-'.$line->id.'-'.$i) : ($tmpproduct->fk_default_warehouse > 0 ? $tmpproduct->fk_default_warehouse : 'ifone'));
1530 print $formproduct->selectWarehouses($preselected, 'idwarehouse-'.$line->id.'-'.$i, '', 1, 0, $line->fk_product, '', 1, 0, array(), 'maxwidth200 csswarehouse_'.$line->id.'_'.$i);
1531 } else {
1532 print '<span class="opacitymedium">'.$langs->trans("DisableStockChange").'</span>';
1533 }
1534 } else {
1535 if ((int) $tmpproduct->stockable_product > 0) {
1536 print '<span class="opacitymedium">' . $langs->trans("StockDisabled") . '</span>';
1537 } else {
1538 print '<span class="opacitymedium">' . $langs->trans("NoStockChangeOnServices") . '</span>';
1539 }
1540 }
1541 print '</td>';
1542
1543 // Stock
1544 if (isModEnabled('stock')) {
1545 print '<td></td>';
1546 }
1547
1548 // Lot / Batch
1549 if (isModEnabled('productbatch')) {
1550 print '<td class="nowraponall">';
1551 if ($tmpproduct->status_batch) {
1552 $preselected = (GETPOSTISSET('batch-'.$line->id.'-'.$i) ? GETPOST('batch-'.$line->id.'-'.$i) : '');
1553 print '<input type="text" class="width75" name="batch-'.$line->id.'-'.$i.'" value="'.$preselected.'" list="batch-'.$line->id.'-'.$i.'">';
1554 print $formproduct->selectLotDataList('batch-'.$line->id.'-'.$i, 0, $line->fk_product, 0, array());
1555 }
1556 print '</td>';
1557 }
1558
1559 // Split
1560 $type = 'batch';
1561 print '<td align="right" class="split">';
1562 print ' '.img_picto($langs->trans('AddStockLocationLine'), 'split', 'class="splitbutton" onClick="addDispatchLine('.((int) $line->id).', \''.dol_escape_js($type).'\', \'qtymissingconsume\', 1)"');
1563 print '</td>';
1564
1565 // Split All
1566 print '<td align="right" class="splitall">';
1567 if (($action == 'consumeorproduce' || $action == 'consumeandproduceall') && $tmpproduct->status_batch == 2) {
1568 print img_picto($langs->trans('SplitAllQuantity'), 'split', 'class="splitbutton splitallbutton field-error-icon" data-max-qty="1" onClick="addDispatchLine('.$line->id.', \'batch\', \'allmissingconsume\', 1)"');
1569 }
1570 print '</td>';
1571
1572 // Edit Line
1573 if ($object->status == Mo::STATUS_DRAFT) {
1574 print '<td></td>';
1575 }
1576
1577 // Action delete line
1578 if ($permissiontodelete) {
1579 print '<td></td>';
1580 }
1581
1582 print '</tr>';
1583 }
1584 }
1585 }
1586 }
1587
1588 print '</table>';
1589 print '</div>';
1590
1591 // default warehouse processing
1592 print '<script type="text/javascript">
1593 $(document).ready(function () {
1594 $("select[name=fk_default_warehouse]").change(function() {
1595 var fk_default_warehouse = $("option:selected", this).val();
1596 $("select[name^=idwarehouse-]").val(fk_default_warehouse).change();
1597 });
1598 });
1599 </script>';
1600
1601 if (in_array($action, array('consumeorproduce', 'consumeandproduceall')) &&
1602 getDolGlobalString('STOCK_CONSUMPTION_FROM_MANUFACTURING_WAREHOUSE')) {
1603 print '<script>$(document).ready(function () {
1604 $("#fk_default_warehouse").change();
1605 });</script>';
1606 }
1607
1608
1609 // Lines to produce
1610
1611 print '</div>';
1612 print '<div class="fichehalfright">';
1613 print '<div class="clearboth"></div>';
1614
1615 $nblinetoproduce = 0;
1616 $atLeastOneEatBy = false;
1617 $atLeastOneSellBy = false;
1618 foreach ($object->lines as $line) {
1619 if ($line->role == 'toproduce') {
1620 $tmpproduct = new Product($db);
1621 $tmpproduct->fetch($line->fk_product);
1622 if (
1623 $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY
1624 || $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT
1625 ) {
1626 $atLeastOneEatBy = true;
1627 }
1628 if (
1629 $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY
1630 || $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT
1631 ) {
1632 $atLeastOneSellBy = true;
1633 }
1634 $nblinetoproduce++;
1635 }
1636 }
1637
1638 $newcardbutton = '';
1639 $url = $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addproduceline&token='.newToken();
1640 $permissiontoaddaproductline = $object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED;
1641 $parameters = array('morecss' => 'reposition');
1642 if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') {
1643 if ($nblinetoproduce == 0 || $object->mrptype == 1) {
1644 $newcardbutton = dolGetButtonTitle($langs->trans('AddNewProduceLines'), '', 'fa fa-plus-circle size15x', $url, '', (int) $permissiontoaddaproductline, $parameters);
1645 }
1646 }
1647
1648 print load_fiche_titre($langs->trans('Production'), $newcardbutton, '', 0, '', '');
1649
1650 print '<div class="div-table-responsive-no-min">';
1651 print '<table id="tablelinestoproduce" class="noborder noshadow nobottom centpercent">';
1652
1653 print '<tr class="liste_titre trheight5em">';
1654 // Product
1655 print '<td>'.$langs->trans("Product").'</td>';
1656 // Qty
1657 print '<td class="right">'.$langs->trans("Qty").'</td>';
1659 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1660 print '<td class="right">'.$langs->trans("Unit").'</td>';
1661 }
1662 // Cost price
1663 if ($permissiontoupdatecost) {
1664 if (empty($bomcostupdated)) {
1665 print '<td class="right classfortooltip" title="'.$langs->trans("AmountUsedToUpdateWAP").'">';
1666 print $langs->trans("UnitCost");
1667 print '</td>';
1668 } else {
1669 print '<td class="right classfortooltip" title="'.$langs->trans("AmountUsedToUpdateWAP").'">';
1670 print $langs->trans("ManufacturingPrice");
1671 print '</td>';
1672 }
1673 }
1674 // Already produced
1675 print '<td class="right classfortooltip" title="'.$langs->trans("QtyAlreadyProduced").'">';
1676 print $langs->trans("QtyAlreadyProducedShort");
1677 print '</td>';
1678 // Warehouse
1679 print '<td>';
1680 if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
1681 print $langs->trans("Warehouse");
1682 }
1683 print '</td>';
1684
1685 // Lot
1686 if (isModEnabled('productbatch')) {
1687 print '<td>';
1688 if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
1689 print $langs->trans("Batch");
1690 }
1691 print '</td>';
1692
1693 // Split
1694 print '<td></td>';
1695
1696 // Split All
1697 print '<td></td>';
1698
1699 // sell by
1700 if ($atLeastOneEatBy) {
1701 print '<td>'.$langs->trans("EatByDate").'</td>';
1702 }
1703
1704 // eat by
1705 if ($atLeastOneSellBy) {
1706 print '<td>'.$langs->trans("SellByDate").'</td>';
1707 }
1708 }
1709
1710 // Action delete
1711 if ($permissiontodelete) {
1712 print '<td></td>';
1713 }
1714
1715 print '</tr>';
1716
1717 if ($action == 'addproduceline') {
1718 print '<!-- Add line to produce -->'."\n";
1719 print '<tr class="liste_titre">';
1720
1721 // Product
1722 print '<td>';
1723 print $form->select_produits(0, 'productidtoadd', '', 0, 0, -1, 2, '', 1, array(), 0, '1', 0, 'maxwidth300');
1724 print '</td>';
1725 // Qty
1726 print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>';
1727 //Unit
1728 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1729 print '<td></td>';
1730 }
1731 // Cost price
1732 if ($permissiontoupdatecost) {
1733 print '<td></td>';
1734 }
1735 // Action (cost price + already produced)
1736 print '<td colspan="2">';
1737 print '<input type="submit" class="button buttongen button-add" name="addproducelinebutton" value="'.$langs->trans("Add").'">';
1738 print '<input type="submit" class="button buttongen button-cancel" name="canceladdproducelinebutton" value="'.$langs->trans("Cancel").'">';
1739 print '</td>';
1740 // Lot - serial
1741 if (isModEnabled('productbatch')) {
1742 print '<td></td>';
1743
1744 // Split
1745 print '<td></td>';
1746
1747 // Split All
1748 print '<td></td>';
1749 }
1750 // Action delete
1751 if ($permissiontodelete) {
1752 print '<td></td>';
1753 }
1754 print '</tr>';
1755 }
1756
1757 if (!empty($object->lines)) {
1758 $nblinetoproduce = 0;
1759 foreach ($object->lines as $line) {
1760 if ($line->role == 'toproduce') {
1761 $nblinetoproduce++;
1762 }
1763 }
1764
1765 $nblinetoproducecursor = 0;
1766 foreach ($object->lines as $line) {
1767 if ($line->role == 'toproduce') {
1768 $i = 1;
1769
1770 $nblinetoproducecursor++;
1771
1772 $tmpproduct = new Product($db);
1773 $tmpproduct->fetch($line->fk_product);
1774
1775 $arrayoflines = $object->fetchLinesLinked('produced', $line->id);
1776 $alreadyproduced = 0;
1777 foreach ($arrayoflines as $line2) {
1778 $alreadyproduced += $line2['qty'];
1779 }
1780
1781 $suffix = '_'.$line->id;
1782 print '<!-- Line to dispatch '.$suffix.' (toproduce) -->'."\n";
1783 // hidden fields for js function
1784 print '<input id="qty_ordered'.$suffix.'" type="hidden" value="'.$line->qty.'">';
1785 print '<input id="qty_dispatched'.$suffix.'" type="hidden" value="'.$alreadyproduced.'">';
1786
1787 print '<tr>';
1788 // Product
1789 print '<td>'.$tmpproduct->getNomUrl(1);
1790 print '<br><span class="opacitymedium small">'.$tmpproduct->label.'</span>';
1791 print '</td>';
1792 // Qty
1793 print '<td class="right">'.$line->qty.'</td>';
1794 // Unit
1795 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1796 print '<td class="right">'.measuringUnitString($line->fk_unit, '', null, 1).'</td>';
1797 }
1798 // Cost price
1799 if ($permissiontoupdatecost) {
1800 // Defined $manufacturingcost
1801 $manufacturingcost = 0;
1802 $manufacturingcostsrc = '';
1803 if ($object->mrptype == 0) { // If MO is a "Manufacture" type (and not "Disassemble")
1804 $manufacturingcost = $bomcostupdated;
1805 $manufacturingcostsrc = $langs->trans("CalculatedFromProductsToConsume");
1806 if (empty($manufacturingcost)) {
1807 $manufacturingcost = $bomcost;
1808 $manufacturingcostsrc = $langs->trans("ValueFromBom");
1809 }
1810 if (empty($manufacturingcost)) {
1811 $manufacturingcost = price2num($tmpproduct->cost_price, 'MU');
1812 $manufacturingcostsrc = $langs->trans("CostPrice");
1813 }
1814 if (empty($manufacturingcost)) {
1815 $manufacturingcost = price2num($tmpproduct->pmp, 'MU');
1816 $manufacturingcostsrc = $langs->trans("PMPValue");
1817 }
1818 }
1819
1820 print '<td class="right nowraponall" title="'.dol_escape_htmltag($manufacturingcostsrc).'">';
1821 if ($manufacturingcost) {
1822 print price($manufacturingcost);
1823 }
1824 print '</td>';
1825 }
1826 // Already produced
1827 print '<td class="right nowraponall">';
1828 if ($alreadyproduced) {
1829 print '<script>';
1830 print 'jQuery(document).ready(function() {
1831 jQuery("#expandtoproduce'.$line->id.'").click(function() {
1832 console.log("Expand mrp_production line '.$line->id.'");
1833 jQuery(".expanddetailtoproduce'.$line->id.'").toggle();';
1834 if ($nblinetoproduce == $nblinetoproducecursor) {
1835 print 'if (jQuery("#tablelinestoproduce").hasClass("nobottom")) { jQuery("#tablelinestoproduce").removeClass("nobottom"); } else { jQuery("#tablelinestoproduce").addClass("nobottom"); }';
1836 }
1837 print '
1838 });
1839 });';
1840 print '</script>';
1841 if (empty($conf->use_javascript_ajax)) {
1842 print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">';
1843 }
1844 print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"');
1845 if (empty($conf->use_javascript_ajax)) {
1846 print '</a>';
1847 }
1848 }
1849 print ' '.$alreadyproduced;
1850 print '</td>';
1851 // Warehouse
1852 print '<td>';
1853 print '</td>';
1854 // Lot
1855 if (isModEnabled('productbatch')) {
1856 print '<td></td>';
1857
1858 // Split
1859 print '<td></td>';
1860
1861 // Split All
1862 print '<td></td>';
1863 }
1864 // Delete, if nothing was produced for this line
1865 if ($permissiontodelete) {
1866 if ($line->origin_type == 'free' && empty($arrayoflines)) {
1867 $href = $_SERVER["PHP_SELF"];
1868 $href .= '?id='.$object->id;
1869 $href .= '&action=deleteline';
1870 $href .= '&token='.newToken();
1871 $href .= '&lineid='.$line->id;
1872 print '<td class="center">';
1873 print '<a class="reposition" href="'.$href.'">';
1874 print img_picto($langs->trans('TooltipDeleteAndRevertStockMovement'), "delete");
1875 print '</a>';
1876 print '</td>';
1877 } else {
1878 print '<td></td>';
1879 }
1880 }
1881 print '</tr>';
1882
1883 // Show detailed of already consumed with js code to collapse
1884 foreach ($arrayoflines as $line2) {
1885 print '<tr class="expanddetailtoproduce'.$line->id.' hideobject opacitylow">';
1886 // Product
1887 print '<td>';
1888 $tmpstockmovement->id = $line2['fk_stock_movement'];
1889 print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>';
1890 print dol_print_date($line2['date'], 'dayhour', 'tzuserrel');
1891 print '</td>';
1892 // Qty
1893 print '<td></td>';
1894 // Unit
1895 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1896 print '<td></td>';
1897 }
1898 // Cost price
1899 if ($permissiontoupdatecost) {
1900 print '<td></td>';
1901 }
1902 // Already produced
1903 print '<td class="right">'.$line2['qty'].'</td>';
1904 // Warehouse
1905 print '<td class="tdoverflowmax150">';
1906 if ($line2['fk_warehouse'] > 0) {
1907 $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
1908 if ($result > 0) {
1909 print $tmpwarehouse->getNomUrl(1);
1910 }
1911 }
1912 print '</td>';
1913 // Lot
1914 if (isModEnabled('productbatch')) {
1915 print '<td>';
1916 if ($line2['batch'] != '') {
1917 $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']);
1918 print $tmpbatch->getNomUrl(1);
1919 }
1920 print '</td>';
1921
1922 // Split
1923 print '<td></td>';
1924
1925 // Split All
1926 print '<td></td>';
1927 }
1928 // Action delete
1929 if ($permissiontodelete) {
1930 print '<td></td>';
1931 }
1932 print '</tr>';
1933 }
1934
1935 if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
1936 print '<!-- Enter line to produce -->'."\n";
1937 $maxQty = 1;
1938 print '<tr data-max-qty="'.$maxQty.'" name="batch_'.$line->id.'_'.$i.'">';
1939 // Product
1940 print '<td><span class="opacitymedium">'.$langs->trans("ToProduce").'</span></td>';
1941 $preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced));
1942 if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
1943 $preselected = 0;
1944 }
1945 // Qty
1946 print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
1947 //Unit
1948 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1949 print '<td class="right"></td>';
1950 }
1951 // Cost
1952 if ($permissiontoupdatecost) {
1953 // Defined $manufacturingcost
1954 $manufacturingcost = 0;
1955 $manufacturingcostsrc = '';
1956 if ($object->mrptype == 0) { // If MO is a "Manufacture" type (and not "Disassemble")
1957 $manufacturingcost = $bomcostupdated;
1958 $manufacturingcostsrc = $langs->trans("CalculatedFromProductsToConsume");
1959 if (empty($manufacturingcost)) {
1960 $manufacturingcost = $bomcost;
1961 $manufacturingcostsrc = $langs->trans("ValueFromBom");
1962 }
1963 if (empty($manufacturingcost)) {
1964 $manufacturingcost = price2num($tmpproduct->cost_price, 'MU');
1965 $manufacturingcostsrc = $langs->trans("CostPrice");
1966 }
1967 if (empty($manufacturingcost)) {
1968 $manufacturingcost = price2num($tmpproduct->pmp, 'MU');
1969 $manufacturingcostsrc = $langs->trans("PMPValue");
1970 }
1971 }
1972
1973 if ($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1974 $preselected = (GETPOSTISSET('pricetoproduce-'.$line->id.'-'.$i) ? GETPOST('pricetoproduce-'.$line->id.'-'.$i) : ($manufacturingcost ? price($manufacturingcost) : ''));
1975 print '<td class="right"><input type="text" class="width75 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
1976 } else {
1977 print '<td><input type="hidden" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.($manufacturingcost ? $manufacturingcost : '').'"></td>';
1978 }
1979 }
1980 // Already produced
1981 print '<td></td>';
1982 // Warehouse
1983 print '<td>';
1984 if ($tmpproduct->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1985 $preselected = (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i) ? GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) : ($object->fk_warehouse > 0 ? $object->fk_warehouse : 'ifone'));
1986 print $formproduct->selectWarehouses($preselected, 'idwarehousetoproduce-'.$line->id.'-'.$i, '', 1, 0, $line->fk_product, '', 1, 0, array(), 'maxwidth200 csswarehouse_'.$line->id.'_'.$i);
1987 } else {
1988 print '<span class="opacitymedium">'.$langs->trans("NoStockChangeOnServices").'</span>';
1989 }
1990 print '</td>';
1991 // Lot
1992 if (isModEnabled('productbatch')) {
1993 print '<td>';
1994 if ($tmpproduct->status_batch) {
1995 $preselected = (GETPOSTISSET('batchtoproduce-'.$line->id.'-'.$i) ? GETPOST('batchtoproduce-'.$line->id.'-'.$i) : '');
1996 print '<input type="text" class="width75" name="batchtoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'">';
1997 }
1998 print '</td>';
1999 // Batch number in same column than the stock movement picto
2000 if ($tmpproduct->status_batch) {
2001 $type = 'batch';
2002 print '<td align="right" class="split">';
2003 print img_picto($langs->trans('AddStockLocationLine'), 'split', 'class="splitbutton" onClick="addDispatchLine('.$line->id.', \''.$type.'\', \'qtymissing\')"');
2004 print '</td>';
2005
2006 print '<td align="right" class="splitall">';
2007 if (($action == 'consumeorproduce' || $action == 'consumeandproduceall') && $tmpproduct->status_batch == 2) {
2008 print img_picto($langs->trans('SplitAllQuantity'), 'split', 'class="splitbutton splitallbutton field-error-icon" onClick="addDispatchLine('.$line->id.', \'batch\', \'alltoproduce\')"');
2009 } //
2010 print '</td>';
2011 } else {
2012 print '<td></td>';
2013
2014 print '<td></td>';
2015 }
2016 }
2017
2018 // sell by mandatory
2019 if ($tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY || $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT) {
2020 print '<td align="right">';
2021 $preselectedSellBy = (GETPOSTISSET('sellby-' . $line->id . '-' . $i) ? GETPOSTDATE('sellby-' . $line->id . '-' . $i) : '');
2022 print $form->selectDate($preselectedSellBy, 'sellby-' . $line->id . '-' . $i, 0, 0, 1, '', 1, 0);
2023 print '</td>';
2024 } else {
2025 if ($atLeastOneSellBy) {
2026 print '<td></td>';
2027 }
2028 }
2029
2030 // eat by mandatory
2031 if ($tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY || $tmpproduct->sell_or_eat_by_mandatory == $tmpproduct::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT) {
2032 print '<td align="right">';
2033 $preselectedEatBy = (GETPOSTISSET('eatby-' . $line->id . '-' . $i) ? GETPOSTDATE('eatby-' . $line->id . '-' . $i) : '');
2034 print $form->selectDate($preselectedEatBy, 'eatby-' . $line->id . '-' . $i, 0, 0, 1, '', 1, 0);
2035 print '</td>';
2036 } else {
2037 if ($atLeastOneEatBy) {
2038 print '<td></td>';
2039 }
2040 }
2041
2042 // Action delete
2043 print '<td></td>';
2044
2045 print '</tr>';
2046 }
2047 }
2048 }
2049 }
2050
2051 print '</table>';
2052 print '</div>';
2053
2054 print '</div>';
2055 print '</div>';
2056 }
2057
2058 if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) {
2059 print "</form>\n";
2060 } ?>
2061
2062 <script type="text/javascript" language="javascript">
2063
2064 $(document).ready(function() {
2065 //Consumption : When a warehouse is selected, only the lot/serial numbers that are available in it are offered
2066 updateselectbatchbywarehouse();
2067 //Consumption : When a lot/serial number is selected and it is only available in one warehouse, the warehouse is automatically selected
2068 updateselectwarehousebybatch();
2069 });
2070
2071 function updateselectbatchbywarehouse() {
2072 $(document).on('change', "select[name*='idwarehouse']", function () {
2073 console.log("We change warehouse so we update the list of possible batch number");
2074
2075 var selectwarehouse = $(this);
2076
2077 var selectbatch_name = selectwarehouse.attr('name').replace('idwarehouse', 'batch');
2078 var selectbatch = $("datalist[id*='" + selectbatch_name + "']");
2079 var selectedbatch = selectbatch.val();
2080
2081 var product_element_name = selectwarehouse.attr('name').replace('idwarehouse', 'product');
2082
2083 $.ajax({
2084 type: "POST",
2085 url: "<?php echo DOL_URL_ROOT . '/mrp/ajax/interface.php'; ?>",
2086 data: {
2087 action: "updateselectbatchbywarehouse",
2088 permissiontoproduce: <?php echo $permissiontoproduce ?>,
2089 warehouse_id: $(this).val(),
2090 token: '<?php echo currentToken(); ?>',
2091 product_id: $("input[name='" + product_element_name + "']").val()
2092 }
2093 }).done(function (data) {
2094
2095 selectbatch.empty();
2096
2097 if (typeof data == "object") {
2098 console.log("data is already type object, no need to parse it");
2099 } else {
2100 console.log("data is type "+(typeof data));
2101 data = JSON.parse(data);
2102 }
2103
2104 selectbatch.append($('<option>', {
2105 value: '',
2106 }));
2107
2108 $.each(data, function (key, value) {
2109
2110 if(selectwarehouse.val() == -1) {
2111 var label = key + " (<?php echo $langs->trans('TotalStock') ?> : " + value + ")";
2112 } else {
2113 var label = key + " (<?php echo $langs->trans('Stock') ?> : " + value + ")";
2114 }
2115
2116 if(key === selectedbatch) {
2117 var option ='<option value="'+key+'" selected>'+ label +'</option>';
2118 } else {
2119 var option ='<option value="'+key+'">'+ label +'</option>';
2120 }
2121
2122 selectbatch.append(option);
2123 });
2124 });
2125 });
2126 }
2127
2128 function updateselectwarehousebybatch() {
2129 $(document).on('change', 'input[name*=batch]', function(){
2130 console.log("We change batch so we update the list of possible warehouses");
2131
2132 var selectbatch = $(this);
2133
2134 var selectwarehouse_name = selectbatch.attr('name').replace('batch', 'idwarehouse');
2135 var selectwarehouse = $("select[name*='" + selectwarehouse_name + "']");
2136 var selectedwarehouse = selectwarehouse.val();
2137
2138 if(selectedwarehouse != -1){
2139 return;
2140 }
2141
2142 var product_element_name = selectbatch.attr('name').replace('batch', 'product');
2143
2144 $.ajax({
2145 type: "POST",
2146 url: "<?php echo DOL_URL_ROOT . '/mrp/ajax/interface.php'; ?>",
2147 data: {
2148 action: "updateselectwarehousebybatch",
2149 permissiontoproduce: <?php echo $permissiontoproduce ?>,
2150 batch: $(this).val(),
2151 token: '<?php echo currentToken(); ?>',
2152 product_id: $("input[name='" + product_element_name + "']").val()
2153 }
2154 }).done(function (data) {
2155
2156 if (typeof data == "object") {
2157 console.log("data is already type object, no need to parse it");
2158 } else {
2159 console.log("data is type "+(typeof data));
2160 data = JSON.parse(data);
2161 }
2162
2163 if(data != 0){
2164 selectwarehouse.val(data).change();
2165 }
2166 });
2167 });
2168 }
2169
2170 </script>
2171
2172 <?php
2173}
2174
2175// End of page
2176llxFooter();
2177$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
$object ref
Definition info.php:90
Class for BOM.
Definition bom.class.php:42
Class of dictionary type of thirdparty (used by imports)
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class with static methods for building HTML components related to products Only components common to ...
Class to manage building of HTML components.
Class for Mo.
Definition mo.class.php:35
Class MoLine.
Class to manage stock movements.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
const TYPE_SERVICE
Service.
Class with list of lots and properties.
Class to manage projects.
Class to manage translations.
Class for Workstation.
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:356
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
moPrepareHead($object)
Prepare array of tabs for Mo.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:132
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.