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