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