dolibarr 21.0.3
api_mos.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019 Maxime Kohlhaas <maxime@atm-consulting.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
24
25
38class Mos extends DolibarrApi
39{
43 public $mo;
44
48 public function __construct()
49 {
50 global $db, $conf;
51 $this->db = $db;
52 $this->mo = new Mo($this->db);
53 }
54
66 public function get($id)
67 {
68 if (!DolibarrApiAccess::$user->hasRight('mrp', 'read')) {
69 throw new RestException(403);
70 }
71
72 $result = $this->mo->fetch($id);
73 if (!$result) {
74 throw new RestException(404, 'MO not found');
75 }
76
77 if (!DolibarrApi::_checkAccessToResource('mrp', $this->mo->id, 'mrp_mo')) {
78 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
79 }
80
81 return $this->_cleanObjectDatas($this->mo);
82 }
83
84
100 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
101 {
102 if (!DolibarrApiAccess::$user->hasRight('mrp', 'read')) {
103 throw new RestException(403);
104 }
105
106 $obj_ret = array();
107 $tmpobject = new Mo($this->db);
108
109 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : 0;
110
111 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
112
113 // If the internal user must only see his customers, force searching by him
114 $search_sale = 0;
115 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
116 $search_sale = DolibarrApiAccess::$user->id;
117 }
118
119 $sql = "SELECT t.rowid";
120 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
121 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmpobject->table_element."_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
122 $sql .= " WHERE 1 = 1";
123 if ($tmpobject->ismultientitymanaged) {
124 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
125 }
126 if ($restrictonsocid && $socid) {
127 $sql .= " AND t.fk_soc = ".((int) $socid);
128 }
129 // Search on sale representative
130 if ($search_sale && $search_sale != '-1') {
131 if ($search_sale == -2) {
132 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
133 } elseif ($search_sale > 0) {
134 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
135 }
136 }
137 if ($sqlfilters) {
138 $errormessage = '';
139 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
140 if ($errormessage) {
141 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
142 }
143 }
144
145 $sql .= $this->db->order($sortfield, $sortorder);
146 if ($limit) {
147 if ($page < 0) {
148 $page = 0;
149 }
150 $offset = $limit * $page;
151
152 $sql .= $this->db->plimit($limit + 1, $offset);
153 }
154
155 $result = $this->db->query($sql);
156 if ($result) {
157 $num = $this->db->num_rows($result);
158 $i = 0;
159 while ($i < $num) {
160 $obj = $this->db->fetch_object($result);
161 $tmp_object = new Mo($this->db);
162 if ($tmp_object->fetch($obj->rowid)) {
163 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
164 }
165 $i++;
166 }
167 } else {
168 throw new RestException(503, 'Error when retrieve MO list');
169 }
170
171 return $obj_ret;
172 }
173
180 public function post($request_data = null)
181 {
182 if (!DolibarrApiAccess::$user->hasRight('mrp', 'write')) {
183 throw new RestException(403);
184 }
185 // Check mandatory fields
186 $result = $this->_validate($request_data);
187
188 foreach ($request_data as $field => $value) {
189 if ($field === 'caller') {
190 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
191 $this->mo->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
192 continue;
193 }
194
195 $this->mo->$field = $this->_checkValForAPI($field, $value, $this->mo);
196 }
197
198 $this->checkRefNumbering();
199
200 if (!$this->mo->create(DolibarrApiAccess::$user)) {
201 throw new RestException(500, "Error creating MO", array_merge(array($this->mo->error), $this->mo->errors));
202 }
203 return $this->mo->id;
204 }
205
213 public function put($id, $request_data = null)
214 {
215 if (!DolibarrApiAccess::$user->hasRight('mrp', 'write')) {
216 throw new RestException(403);
217 }
218
219 $result = $this->mo->fetch($id);
220 if (!$result) {
221 throw new RestException(404, 'MO not found');
222 }
223
224 if (!DolibarrApi::_checkAccessToResource('mrp', $this->mo->id, 'mrp_mo')) {
225 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
226 }
227
228 foreach ($request_data as $field => $value) {
229 if ($field == 'id') {
230 continue;
231 }
232 if ($field === 'caller') {
233 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
234 $this->mo->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
235 continue;
236 }
237
238 if ($field == 'array_options' && is_array($value)) {
239 foreach ($value as $index => $val) {
240 $this->mo->array_options[$index] = $this->_checkValForAPI($field, $val, $this->mo);
241 }
242 continue;
243 }
244
245 $this->mo->$field = $this->_checkValForAPI($field, $value, $this->mo);
246 }
247
248 $this->checkRefNumbering();
249
250 if ($this->mo->update(DolibarrApiAccess::$user) > 0) {
251 return $this->get($id);
252 } else {
253 throw new RestException(500, $this->mo->error);
254 }
255 }
256
263 public function delete($id)
264 {
265 if (!DolibarrApiAccess::$user->hasRight('mrp', 'delete')) {
266 throw new RestException(403);
267 }
268 $result = $this->mo->fetch($id);
269 if (!$result) {
270 throw new RestException(404, 'MO not found');
271 }
272
273 if (!DolibarrApi::_checkAccessToResource('mrp', $this->mo->id, 'mrp_mo')) {
274 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
275 }
276
277 if (!$this->mo->delete(DolibarrApiAccess::$user)) {
278 throw new RestException(500, 'Error when deleting MO : '.$this->mo->error);
279 }
280
281 return array(
282 'success' => array(
283 'code' => 200,
284 'message' => 'MO deleted'
285 )
286 );
287 }
288
289
320 public function produceAndConsumeAll($id, $request_data = null)
321 {
322 global $langs;
323
324 $error = 0;
325
326 if (!DolibarrApiAccess::$user->hasRight('mrp', 'write')) {
327 throw new RestException(403, 'Not enough permission');
328 }
329 $result = $this->mo->fetch($id);
330 if (!$result) {
331 throw new RestException(404, 'MO not found');
332 }
333
334 if ($this->mo->status != Mo::STATUS_VALIDATED && $this->mo->status != Mo::STATUS_INPROGRESS) {
335 throw new RestException(405, 'Error bad status of MO');
336 }
337
338 // Code for consume and produce...
339 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
340 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
341 require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp_mo.lib.php';
342
343 $stockmove = new MouvementStock($this->db);
344
345 $labelmovement = '';
346 $codemovement = '';
347 $autoclose = 1;
348 $arraytoconsume = array();
349 $arraytoproduce = array();
350
351 foreach ($request_data as $field => $value) {
352 if ($field == 'inventorylabel') {
353 $labelmovement = $value;
354 }
355 if ($field == 'inventorycode') {
356 $codemovement = $value;
357 }
358 if ($field == 'autoclose') {
359 $autoclose = $value;
360 }
361 if ($field == 'arraytoconsume') {
362 $arraytoconsume = $value;
363 }
364 if ($field == 'arraytoproduce') {
365 $arraytoproduce = $value;
366 }
367 if ($field === 'caller') {
368 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
369 $stockmove->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
370 continue;
371 }
372 }
373
374 if (empty($labelmovement)) {
375 throw new RestException(500, "Field inventorylabel not provided");
376 }
377 if (empty($codemovement)) {
378 throw new RestException(500, "Field inventorycode not provided");
379 }
380
381 $consumptioncomplete = true;
382 $productioncomplete = true;
383
384 if (!empty($arraytoconsume) && !empty($arraytoproduce)) {
385 $pos = 0;
386 $arrayofarrayname = array("arraytoconsume","arraytoproduce");
387 foreach ($arrayofarrayname as $arrayname) {
388 foreach (${$arrayname} as $value) {
389 $tmpproduct = new Product($this->db);
390 if (empty($value["objectid"])) {
391 throw new RestException(500, "Field objectid required in ".$arrayname);
392 }
393 $tmpproduct->fetch($value["qty"]);
394 if (empty($value["qty"])) {
395 throw new RestException(500, "Field qty required in ".$arrayname);
396 }
397 if ($value["qty"] != 0) {
398 $qtytoprocess = $value["qty"];
399 if (isset($value["fk_warehouse"])) { // If there is a warehouse to set
400 if (!($value["fk_warehouse"] > 0)) { // If there is no warehouse set.
401 $error++;
402 throw new RestException(500, "Field fk_warehouse must be > 0 in ".$arrayname);
403 }
404 if ($tmpproduct->status_batch) {
405 $error++;
406 throw new RestException(500, "Product ".$tmpproduct->ref."must be in batch");
407 }
408 }
409 $idstockmove = 0;
410 if (!$error && $value["fk_warehouse"] > 0) {
411 // Record consumption to do and stock movement
412 $id_product_batch = 0;
413
414 $stockmove->setOrigin($this->mo->element, $this->mo->id);
415
416 if ($arrayname == 'arraytoconsume') {
417 $moline = new MoLine($this->db);
418 $moline->fk_mo = $this->mo->id;
419 $moline->position = $pos;
420 $moline->fk_product = $value["objectid"];
421 $moline->fk_warehouse = $value["fk_warehouse"];
422 $moline->qty = $qtytoprocess;
423 $moline->batch = (string) $tmpproduct->status_batch;
424 $moline->role = 'toproduce';
425 $moline->fk_mrp_production = 0;
426 $moline->fk_stock_movement = $idstockmove;
427 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
428
429 $resultmoline = $moline->create(DolibarrApiAccess::$user);
430 if ($resultmoline <= 0) {
431 $error++;
432 throw new RestException(500, $moline->error);
433 }
434 $idstockmove = $stockmove->livraison(DolibarrApiAccess::$user, $value["objectid"], $value["fk_warehouse"], $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
435 } else {
436 $moline = new MoLine($this->db);
437 $moline->fk_mo = $this->mo->id;
438 $moline->position = $pos;
439 $moline->fk_product = $value["objectid"];
440 $moline->fk_warehouse = $value["fk_warehouse"];
441 $moline->qty = $qtytoprocess;
442 $moline->batch = (string) $tmpproduct->status_batch;
443 $moline->role = 'toconsume';
444 $moline->fk_mrp_production = 0;
445 $moline->fk_stock_movement = $idstockmove;
446 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
447
448 $resultmoline = $moline->create(DolibarrApiAccess::$user);
449 if ($resultmoline <= 0) {
450 $error++;
451 throw new RestException(500, $moline->error);
452 }
453 $idstockmove = $stockmove->reception(DolibarrApiAccess::$user, $value["objectid"], $value["fk_warehouse"], $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
454 }
455 if ($idstockmove < 0) {
456 $error++;
457 throw new RestException(500, $stockmove->error);
458 }
459 }
460 if (!$error) {
461 // Record consumption done
462 $moline = new MoLine($this->db);
463 $moline->fk_mo = $this->mo->id;
464 $moline->position = $pos;
465 $moline->fk_product = $value["objectid"];
466 $moline->fk_warehouse = $value["fk_warehouse"];
467 $moline->qty = $qtytoprocess;
468 $moline->batch = (string) $tmpproduct->status_batch;
469 if ($arrayname == "arraytoconsume") {
470 $moline->role = 'consumed';
471 } else {
472 $moline->role = 'produced';
473 }
474 $moline->fk_mrp_production = 0;
475 $moline->fk_stock_movement = $idstockmove;
476 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
477
478 $resultmoline = $moline->create(DolibarrApiAccess::$user);
479 if ($resultmoline <= 0) {
480 $error++;
481 throw new RestException(500, $moline->error);
482 }
483
484 $pos++;
485 }
486 }
487 }
488 }
489 if (!$error) {
490 if ($autoclose <= 0) {
491 $consumptioncomplete = false;
492 $productioncomplete = false;
493 }
494 }
495 } else {
496 $pos = 0;
497 foreach ($this->mo->lines as $line) {
498 if ($line->role == 'toconsume') {
499 $tmpproduct = new Product($this->db);
500 $tmpproduct->fetch($line->fk_product);
501 if ($line->qty != 0) {
502 $qtytoprocess = $line->qty;
503 if (isset($line->fk_warehouse)) { // If there is a warehouse to set
504 if (!($line->fk_warehouse > 0)) { // If there is no warehouse set.
505 $langs->load("errors");
506 $error++;
507 throw new RestException(500, $langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref));
508 }
509 if ($tmpproduct->status_batch) {
510 $langs->load("errors");
511 $error++;
512 throw new RestException(500, $langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref));
513 }
514 }
515 $idstockmove = 0;
516 if (!$error && $line->fk_warehouse > 0) {
517 // Record stock movement
518 $id_product_batch = 0;
519 $stockmove->origin_type = 'mo';
520 $stockmove->origin_id = $this->mo->id;
521 if ($qtytoprocess >= 0) {
522 $idstockmove = $stockmove->livraison(DolibarrApiAccess::$user, $line->fk_product, $line->fk_warehouse, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
523 } else {
524 $idstockmove = $stockmove->reception(DolibarrApiAccess::$user, $line->fk_product, $line->fk_warehouse, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
525 }
526 if ($idstockmove < 0) {
527 $error++;
528 throw new RestException(500, $stockmove->error);
529 }
530 }
531 if (!$error) {
532 // Record consumption
533 $moline = new MoLine($this->db);
534 $moline->fk_mo = $this->mo->id;
535 $moline->position = $pos;
536 $moline->fk_product = $line->fk_product;
537 $moline->fk_warehouse = $line->fk_warehouse;
538 $moline->qty = $qtytoprocess;
539 $moline->batch = (string) $tmpproduct->status_batch;
540 $moline->role = 'consumed';
541 $moline->fk_mrp_production = $line->id;
542 $moline->fk_stock_movement = $idstockmove;
543 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
544
545 $resultmoline = $moline->create(DolibarrApiAccess::$user);
546 if ($resultmoline <= 0) {
547 $error++;
548 throw new RestException(500, $moline->error);
549 }
550
551 $pos++;
552 }
553 }
554 }
555 }
556 $pos = 0;
557 foreach ($this->mo->lines as $line) {
558 if ($line->role == 'toproduce') {
559 $tmpproduct = new Product($this->db);
560 $tmpproduct->fetch($line->fk_product);
561 if ($line->qty != 0) {
562 $qtytoprocess = $line->qty;
563 if (isset($line->fk_warehouse)) { // If there is a warehouse to set
564 if (!($line->fk_warehouse > 0)) { // If there is no warehouse set.
565 $langs->load("errors");
566 $error++;
567 throw new RestException(500, $langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref));
568 }
569 if ($tmpproduct->status_batch) {
570 $langs->load("errors");
571 $error++;
572 throw new RestException(500, $langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref));
573 }
574 }
575 $idstockmove = 0;
576 if (!$error && $line->fk_warehouse > 0) {
577 // Record stock movement
578 $id_product_batch = 0;
579 $stockmove->origin_type = 'mo';
580 $stockmove->origin_id = $this->mo->id;
581 if ($qtytoprocess >= 0) {
582 $idstockmove = $stockmove->reception(DolibarrApiAccess::$user, $line->fk_product, $line->fk_warehouse, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
583 } else {
584 $idstockmove = $stockmove->livraison(DolibarrApiAccess::$user, $line->fk_product, $line->fk_warehouse, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
585 }
586 if ($idstockmove < 0) {
587 $error++;
588 throw new RestException(500, $stockmove->error);
589 }
590 }
591 if (!$error) {
592 // Record consumption
593 $moline = new MoLine($this->db);
594 $moline->fk_mo = $this->mo->id;
595 $moline->position = $pos;
596 $moline->fk_product = $line->fk_product;
597 $moline->fk_warehouse = $line->fk_warehouse;
598 $moline->qty = $qtytoprocess;
599 $moline->batch = (string) $tmpproduct->status_batch;
600 $moline->role = 'produced';
601 $moline->fk_mrp_production = $line->id;
602 $moline->fk_stock_movement = $idstockmove;
603 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
604
605 $resultmoline = $moline->create(DolibarrApiAccess::$user);
606 if ($resultmoline <= 0) {
607 $error++;
608 throw new RestException(500, $moline->error);
609 }
610
611 $pos++;
612 }
613 }
614 }
615 }
616
617 if (!$error) {
618 if ($autoclose > 0) {
619 foreach ($this->mo->lines as $line) {
620 if ($line->role == 'toconsume') {
621 $arrayoflines = $this->mo->fetchLinesLinked('consumed', $line->id);
622 $alreadyconsumed = 0;
623 foreach ($arrayoflines as $line2) {
624 $alreadyconsumed += $line2['qty'];
625 }
626
627 if ($alreadyconsumed < $line->qty) {
628 $consumptioncomplete = false;
629 }
630 }
631 if ($line->role == 'toproduce') {
632 $arrayoflines = $this->mo->fetchLinesLinked('produced', $line->id);
633 $alreadyproduced = 0;
634 foreach ($arrayoflines as $line2) {
635 $alreadyproduced += $line2['qty'];
636 }
637
638 if ($alreadyproduced < $line->qty) {
639 $productioncomplete = false;
640 }
641 }
642 }
643 } else {
644 $consumptioncomplete = false;
645 $productioncomplete = false;
646 }
647 }
648 }
649
650 // Update status of MO
651 dol_syslog("consumptioncomplete = ".json_encode($consumptioncomplete)." productioncomplete = ".json_encode($productioncomplete));
652 if ($consumptioncomplete && $productioncomplete) {
653 $result = $this->mo->setStatut(Mo::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
654 } else {
655 $result = $this->mo->setStatut(Mo::STATUS_INPROGRESS, 0, '', 'MRP_MO_PRODUCED');
656 }
657 if ($result <= 0) {
658 throw new RestException(500, $this->mo->error);
659 }
660
661 return $this->mo->id;
662 }
663
696 public function produceAndConsume($id, $request_data = null)
697 {
698 if (!DolibarrApiAccess::$user->hasRight("mrp", "write")) {
699 throw new RestException(403, 'Not enough permission');
700 }
701 $result = $this->mo->fetch($id);
702 if (!$result) {
703 throw new RestException(404, 'MO not found');
704 }
705
706 if ($this->mo->status != Mo::STATUS_VALIDATED && $this->mo->status != Mo::STATUS_INPROGRESS) {
707 throw new RestException(405, 'Error bad status of MO');
708 }
709
710 // Code for consume and produce...
711 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
712 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
713 require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp_mo.lib.php';
714
715 $stockmove = new MouvementStock($this->db);
716
717 $labelmovement = '';
718 $codemovement = '';
719 $autoclose = 1;
720 $arraytoconsume = array();
721 $arraytoproduce = array();
722
723 foreach ($request_data as $field => $value) {
724 if ($field == 'inventorylabel') {
725 $labelmovement = $value;
726 }
727 if ($field == 'inventorycode') {
728 $codemovement = $value;
729 }
730 if ($field == 'autoclose') {
731 $autoclose = $value;
732 }
733 if ($field == 'arraytoconsume') {
734 $arraytoconsume = $value;
735 }
736 if ($field == 'arraytoproduce') {
737 $arraytoproduce = $value;
738 }
739 if ($field === 'caller') {
740 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
741 $stockmove->context['caller'] = $request_data['caller'];
742 continue;
743 }
744 }
745
746 if (empty($labelmovement)) {
747 throw new RestException(500, "Field inventorylabel not provided");
748 }
749 if (empty($codemovement)) {
750 throw new RestException(500, "Field inventorycode not provided");
751 }
752
753 $this->db->begin();
754
755 $pos = 0;
756 $arrayofarrayname = array("arraytoconsume","arraytoproduce");
757 foreach ($arrayofarrayname as $arrayname) {
758 foreach (${$arrayname} as $value) {
759 if (empty($value["objectid"])) {
760 throw new RestException(500, "Field objectid required in " . $arrayname);
761 }
762
763 $molinetoprocess = new MoLine($this->db);
764 $tmpmolineid = $molinetoprocess->fetch($value["objectid"]);
765 if ($tmpmolineid <= 0) {
766 throw new RestException(500, "MoLine with rowid " . $value["objectid"] . " not exist.");
767 }
768
769 $tmpproduct = new Product($this->db);
770 $tmpproduct->fetch($molinetoprocess->fk_product);
771 if ($tmpproduct->status_batch) {
772 throw new RestException(500, "Product " . $tmpproduct->ref . " must be in batch, this API can't handle it currently.");
773 }
774
775 if (empty($value["qty"]) && $value["qty"] != 0) {
776 throw new RestException(500, "Field qty with lower or higher then 0 required in " . $arrayname);
777 }
778 $qtytoprocess = $value["qty"];
779
780 $fk_warehousetoprocess = 0;
781 if ($molinetoprocess->disable_stock_change == false) {
782 if (isset($value["fk_warehouse"])) { // If there is a warehouse to set
783 if (!($value["fk_warehouse"] > 0)) { // If there is no warehouse set.
784 throw new RestException(500, "Field fk_warehouse required in " . $arrayname);
785 }
786 }
787 $fk_warehousetoprocess = (int) $value["fk_warehouse"];
788 }
789
790 $pricetoproduce = 0;
791 if (isset($value["pricetoproduce"])) { // If there is a price to produce set.
792 if ($value["pricetoproduce"] > 0) { // Only use prices grater then 0.
793 $pricetoproduce = $value["pricetoproduce"];
794 }
795 }
796
797 $idstockmove = 0;
798
799 if ($molinetoprocess->disable_stock_change == false) {
800 // Record stock movement
801 $id_product_batch = 0;
802 $stockmove->origin_type = 'mo';
803 $stockmove->origin_id = $this->mo->id;
804 if ($arrayname == "arraytoconsume") {
805 if ($qtytoprocess >= 0) {
806 $idstockmove = $stockmove->livraison(DolibarrApiAccess::$user, $molinetoprocess->fk_product, $fk_warehousetoprocess, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
807 } else {
808 $idstockmove = $stockmove->reception(DolibarrApiAccess::$user, $molinetoprocess->fk_product, $fk_warehousetoprocess, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
809 }
810 } else {
811 if ($qtytoprocess >= 0) {
812 $idstockmove = $stockmove->reception(DolibarrApiAccess::$user, $molinetoprocess->fk_product, $fk_warehousetoprocess, $qtytoprocess, $pricetoproduce, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
813 } else {
814 $idstockmove = $stockmove->livraison(DolibarrApiAccess::$user, $molinetoprocess->fk_product, $fk_warehousetoprocess, $qtytoprocess, 0, $labelmovement, dol_now(), '', '', $tmpproduct->status_batch, $id_product_batch, $codemovement);
815 }
816 }
817 if ($idstockmove <= 0) {
818 throw new RestException(500, $stockmove->error);
819 }
820 }
821
822 // Record consumption
823 $moline = new MoLine($this->db);
824 $moline->fk_mo = $this->mo->id;
825 $moline->position = $pos;
826 $moline->fk_product = $tmpproduct->id;
827 $moline->fk_warehouse = $idstockmove > 0 ? $fk_warehousetoprocess : null;
828 $moline->qty = $qtytoprocess;
829 $moline->batch = '';
830 $moline->fk_mrp_production = $molinetoprocess->id;
831 $moline->fk_stock_movement = $idstockmove > 0 ? $idstockmove : null;
832 $moline->fk_user_creat = DolibarrApiAccess::$user->id;
833
834 if ($arrayname == "arraytoconsume") {
835 $moline->role = 'consumed';
836 } else {
837 $moline->role = 'produced';
838 }
839
840 $resultmoline = $moline->create(DolibarrApiAccess::$user);
841 if ($resultmoline <= 0) {
842 throw new RestException(500, $moline->error);
843 }
844
845 $pos++;
846 }
847 }
848
849 $consumptioncomplete = true;
850 $productioncomplete = true;
851
852 if ($autoclose > 0) {
853 // Refresh Lines after consumptions.
854 $this->mo->fetchLines();
855
856 foreach ($this->mo->lines as $line) {
857 if ($line->role == 'toconsume') {
858 $arrayoflines = $this->mo->fetchLinesLinked('consumed', $line->id);
859 $alreadyconsumed = 0;
860 foreach ($arrayoflines as $line2) {
861 $alreadyconsumed += $line2['qty'];
862 }
863
864 if ($alreadyconsumed < $line->qty) {
865 $consumptioncomplete = false;
866 }
867 }
868 if ($line->role == 'toproduce') {
869 $arrayoflines = $this->mo->fetchLinesLinked('produced', $line->id);
870 $alreadyproduced = 0;
871 foreach ($arrayoflines as $line2) {
872 $alreadyproduced += $line2['qty'];
873 }
874
875 if ($alreadyproduced < $line->qty) {
876 $productioncomplete = false;
877 }
878 }
879 }
880 } else {
881 $consumptioncomplete = false;
882 $productioncomplete = false;
883 }
884
885 // Update status of MO
886 dol_syslog("consumptioncomplete = " . (string) $consumptioncomplete . " productioncomplete = " . (string) $productioncomplete);
887 //var_dump("consumptioncomplete = ".$consumptioncomplete." productioncomplete = ".$productioncomplete);
888 if ($consumptioncomplete && $productioncomplete) {
889 $result = $this->mo->setStatut(Mo::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
890 } else {
891 $result = $this->mo->setStatut(Mo::STATUS_INPROGRESS, 0, '', 'MRP_MO_PRODUCED');
892 }
893 if ($result <= 0) {
894 throw new RestException(500, $this->mo->error);
895 }
896
897 $this->db->commit();
898 return $this->mo->id;
899 }
900
901
902 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
909 protected function _cleanObjectDatas($object)
910 {
911 // phpcs:enable
912 $object = parent::_cleanObjectDatas($object);
913
914 unset($object->rowid);
915 unset($object->canvas);
916
917 unset($object->name);
918 unset($object->lastname);
919 unset($object->firstname);
920 unset($object->civility_id);
921 unset($object->statut);
922 unset($object->state);
923 unset($object->state_id);
924 unset($object->state_code);
925 unset($object->region);
926 unset($object->region_code);
927 unset($object->country);
928 unset($object->country_id);
929 unset($object->country_code);
930 unset($object->barcode_type);
931 unset($object->barcode_type_code);
932 unset($object->barcode_type_label);
933 unset($object->barcode_type_coder);
934 unset($object->total_ht);
935 unset($object->total_tva);
936 unset($object->total_localtax1);
937 unset($object->total_localtax2);
938 unset($object->total_ttc);
939 unset($object->fk_account);
940 unset($object->comments);
941 unset($object->note);
942 unset($object->mode_reglement_id);
943 unset($object->cond_reglement_id);
944 unset($object->cond_reglement);
945 unset($object->shipping_method_id);
946 unset($object->fk_incoterms);
947 unset($object->label_incoterms);
948 unset($object->location_incoterms);
949
950 // If object has lines, remove $db property
951 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
952 $nboflines = count($object->lines);
953 for ($i = 0; $i < $nboflines; $i++) {
954 $this->_cleanObjectDatas($object->lines[$i]);
955
956 unset($object->lines[$i]->lines);
957 unset($object->lines[$i]->note);
958 }
959 }
960
961 return $object;
962 }
963
972 private function _validate($data)
973 {
974 $myobject = array();
975 foreach ($this->mo->fields as $field => $propfield) {
976 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
977 continue; // Not a mandatory field
978 }
979 if (!isset($data[$field])) {
980 throw new RestException(400, "$field field missing");
981 }
982 $myobject[$field] = $data[$field];
983 }
984 return $myobject;
985 }
986
992 private function checkRefNumbering()
993 {
994 $ref = substr($this->mo->ref, 1, 4);
995 if ($this->mo->status > 0 && $ref == 'PROV') {
996 throw new RestException(400, "Wrong naming scheme '(PROV%)' is only allowed on 'DRAFT' status. For automatic increment use 'auto' on the 'ref' field.");
997 }
998
999 if (strtolower($this->mo->ref) == 'auto') {
1000 if (empty($this->mo->id) && $this->mo->status == 0) {
1001 $this->mo->ref = ''; // 'ref' will auto incremented with '(PROV' + newID + ')'
1002 } else {
1003 $this->mo->fetch_product();
1004 $numref = $this->mo->getNextNumRef($this->mo->product);
1005 $this->mo->ref = $numref;
1006 }
1007 }
1008 }
1009}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class for API REST v1.
Definition api.class.php:31
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:83
Class for Mo.
Definition mo.class.php:34
Class MoLine.
produceAndConsume($id, $request_data=null)
Produce and consume.
__construct()
Constructor.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List Mos.
put($id, $request_data=null)
Update MO.
post($request_data=null)
Create MO object.
_cleanObjectDatas($object)
Clean sensible object datas.
produceAndConsumeAll($id, $request_data=null)
Produce and consume all.
checkRefNumbering()
Validate the ref field and get the next Number if it's necessary.
_validate($data)
Validate fields before create or update object.
Class to manage stock movements.
Class to manage products or services.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79