dolibarr 25.0.0-alpha
reception.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
4 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
5 * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
6 * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
8 * Copyright (C) 2014 Cedric GROSS <c.gross@kreiz-it.fr>
9 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
10 * Copyright (C) 2014-2020 Francis Appels <francis.appels@yahoo.com>
11 * Copyright (C) 2015 Claudio Aschieri <c.aschieri@19.coop>
12 * Copyright (C) 2016-2022 Ferran Marcet <fmarcet@2byte.es>
13 * Copyright (C) 2018 Quentin Vial-Gouteyron <quentin.vial-gouteyron@atm-consulting.fr>
14 * Copyright (C) 2022-2025 Frédéric France <frederic.france@free.fr>
15 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
16 * Copyright (C) 2025-2026 Nick Fragoulis
17 * Copyright (C) 2026 Mathieu Moulin <mathieu@iprospective.fr>
18 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
41require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
43require_once DOL_DOCUMENT_ROOT.'/reception/class/receptionlinebatch.class.php';
44if (isModEnabled("propal")) {
45 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
46}
47if (isModEnabled('order')) {
48 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
49}
50
51
56{
57 use CommonIncoterm;
58
63 public $TRIGGER_PREFIX = 'RECEPTION'; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
64
68 public $code = "";
69
73 public $element = "reception";
74
78 public $fk_element = "fk_reception";
79
83 public $table_element = "reception";
84
88 public $table_element_line = "receptiondet_batch";
89
93 public $picto = 'dollyrevert';
94
98 public $socid;
102 public $ref_supplier;
103
107 public $entrepot_id;
111 public $tracking_number;
115 public $tracking_url;
119 public $billed;
120
124 public $weight;
128 public $trueWeight;
132 public $weight_units;
136 public $trueWidth;
140 public $width_units;
144 public $trueHeight;
148 public $height_units;
152 public $trueDepth;
156 public $depth_units;
160 public $trueSize;
164 public $size_units;
168 public $user_author_id;
169
173 public $date_delivery;
174
180 public $date;
181
185 public $date_reception;
186
190 public $date_valid;
191
195 public $fk_user_author;
196
200 public $fk_user_valid;
201
205 public $meths;
209 public $listmeths; // List of carriers
210
214 public $lines = array();
215
216
221 public $detail_batch;
222
223 const STATUS_CANCELED = -1;
224 const STATUS_DRAFT = 0;
225 const STATUS_VALIDATED = 1;
226 const STATUS_CLOSED = 2;
227
228
232 public $fk_warehouse;
233
239 public function __construct($db)
240 {
241 $this->db = $db;
242
243 $this->ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
244 $this->isextrafieldmanaged = 1;
245 }
246
253 public function getNextNumRef($soc)
254 {
255 global $langs, $conf;
256 $langs->load("receptions");
257
258 if (getDolGlobalString('RECEPTION_ADDON_NUMBER')) {
259 $mybool = false;
260
261 $file = getDolGlobalString('RECEPTION_ADDON_NUMBER') . ".php";
262 $classname = getDolGlobalString('RECEPTION_ADDON_NUMBER');
263
264 // Include file with class
265 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
266
267 foreach ($dirmodels as $reldir) {
268 $dir = dol_buildpath($reldir."core/modules/reception/");
269
270 // Load file with numbering class (if found)
271 $mybool = ((bool) @include_once $dir.$file) || $mybool;
272 }
273
274 if (!$mybool) {
275 dol_print_error(null, "Failed to include file ".$file);
276 return '';
277 }
278
279 $obj = new $classname();
280 '@phan-var-force ModelNumRefReception $obj';
283 $numref = $obj->getNextValue($soc, $this);
284
285 if ($numref != "") {
286 return $numref;
287 } else {
288 dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
289 return "";
290 }
291 } else {
292 print $langs->trans("Error")." ".$langs->trans("Error_RECEPTION_ADDON_NUMBER_NotDefined");
293 return "";
294 }
295 }
296
304 public function create($user, $notrigger = 0)
305 {
306 global $conf;
307
308 $now = dol_now();
309
310 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
311 $error = 0;
312
313 // Clean parameters
314 $this->tracking_number = dol_sanitizeFileName($this->tracking_number);
315 if (empty($this->fk_project)) {
316 $this->fk_project = 0;
317 }
318 if (empty($this->weight_units)) {
319 $this->weight_units = 0;
320 }
321 if (empty($this->size_units)) {
322 $this->size_units = 0;
323 }
324 if (empty($this->date_creation)) {
325 $this->date_creation = $now;
326 }
327
328 $this->entity = setEntity($this);
329
330 $this->user = $user;
331
332 $this->db->begin();
333
334 // If there is only one active warehouse, use it as the default warehouse of the reception
335 if (empty($this->fk_warehouse)) {
336 $resqlwh = $this->db->query("SELECT rowid FROM ".MAIN_DB_PREFIX."entrepot WHERE entity IN (".getEntity('stock').") AND statut = 1");
337 if ($resqlwh && $this->db->num_rows($resqlwh) == 1) {
338 $objwh = $this->db->fetch_object($resqlwh);
339 $this->fk_warehouse = (int) $objwh->rowid;
340 }
341 }
342
343 $sql = "INSERT INTO ".MAIN_DB_PREFIX."reception (";
344 $sql .= "ref";
345 $sql .= ", entity";
346 $sql .= ", ref_supplier";
347 $sql .= ", date_creation";
348 $sql .= ", fk_user_author";
349 $sql .= ", date_reception";
350 $sql .= ", date_delivery";
351 $sql .= ", fk_soc";
352 $sql .= ", fk_projet";
353 $sql .= ", fk_warehouse";
354 $sql .= ", fk_shipping_method";
355 $sql .= ", tracking_number";
356 $sql .= ", weight";
357 $sql .= ", size";
358 $sql .= ", width";
359 $sql .= ", height";
360 $sql .= ", weight_units";
361 $sql .= ", size_units";
362 $sql .= ", note_private";
363 $sql .= ", note_public";
364 $sql .= ", model_pdf";
365 $sql .= ", fk_incoterms, location_incoterms";
366 $sql .= ") VALUES (";
367 $sql .= "'(PROV)'";
368 $sql .= ", ".((int) $this->entity);
369 $sql .= ", ".($this->ref_supplier ? "'".$this->db->escape($this->ref_supplier)."'" : "null");
370 $sql .= ", '".$this->db->idate($this->date_creation)."'";
371 $sql .= ", ".((int) $user->id);
372 $sql .= ", ".($this->date_reception > 0 ? "'".$this->db->idate($this->date_reception)."'" : "null");
373 $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
374 $sql .= ", ".($this->socid > 0 ? ((int) $this->socid) : "null");
375 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
376 $sql .= ", ".($this->fk_warehouse > 0 ? ((int) $this->fk_warehouse) : "null");
377 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
378 $sql .= ", '".$this->db->escape($this->tracking_number)."'";
379 $sql .= ", ".(is_null($this->weight) ? "NULL" : ((float) $this->weight));
380 $sql .= ", ".(is_null($this->trueDepth) ? "NULL" : ((float) $this->trueDepth));
381 $sql .= ", ".(is_null($this->trueWidth) ? "NULL" : ((float) $this->trueWidth));
382 $sql .= ", ".(is_null($this->trueHeight) ? "NULL" : ((float) $this->trueHeight));
383 $sql .= ", ".((int) $this->weight_units);
384 $sql .= ", ".((int) $this->size_units);
385 $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
386 $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
387 $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
388 $sql .= ", ".(int) $this->fk_incoterms;
389 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
390 $sql .= ")";
391
392 dol_syslog(get_class($this)."::create", LOG_DEBUG);
393
394 $resql = $this->db->query($sql);
395
396 if ($resql) {
397 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."reception");
398
399 // update ref
400 $initialref = '(PROV'.$this->id.')';
401 if (!empty($this->ref)) {
402 $initialref = $this->ref;
403 }
404
405 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
406 $sql .= " SET ref = '".$this->db->escape($initialref)."'";
407 $sql .= " WHERE rowid = ".((int) $this->id);
408
409 dol_syslog(get_class($this)."::create", LOG_DEBUG);
410 if ($this->db->query($sql)) {
411 // Insert of lines
412 $num = count($this->lines);
413 for ($i = 0; $i < $num; $i++) {
414 $this->lines[$i]->fk_reception = $this->id;
415
416 if ($this->lines[$i]->create($user) <= 0) {
417 $this->setErrorsFromObject($this->lines[$i]);
418 $error++;
419 }
420 }
421
422 if (!$error && $this->id && $this->origin_id) {
423 $ret = $this->add_object_linked();
424 if (!$ret) {
425 $error++;
426 }
427 }
428
429 // Create extrafields
430 if (!$error) {
431 $result = $this->insertExtraFields();
432 if ($result < 0) {
433 $error++;
434 }
435 }
436
437 if (!$error && !$notrigger) {
438 // Call trigger
439 $result = $this->call_trigger('RECEPTION_CREATE', $user);
440 if ($result < 0) {
441 $error++;
442 }
443 // End call triggers
444 }
445
446 if (!$error) {
447 $this->db->commit();
448 return $this->id;
449 } else {
450 foreach ($this->errors as $errmsg) {
451 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
452 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
453 }
454 $this->db->rollback();
455 return -1 * $error;
456 }
457 } else {
458 $error++;
459 $this->error = $this->db->lasterror()." - sql=$sql";
460 $this->db->rollback();
461 return -2;
462 }
463 } else {
464 $error++;
465 $this->error = $this->db->error()." - sql=$sql";
466 $this->db->rollback();
467 return -1;
468 }
469 }
470
471 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
484 public function create_line($entrepot_id, $origin_line_id, $qty, $rang = 0, $array_options = [], $parent_line_id = 0, $product_id = 0)
485 {
486 //phpcs:enable
487 global $user;
488
489 $receptionline = new ReceptionLineBatch($this->db);
490 $receptionline->fk_reception = $this->id;
491 $receptionline->entrepot_id = $entrepot_id;
492 $receptionline->fk_elementdet = $origin_line_id;
493 $receptionline->element_type = $this->origin;
494 $receptionline->fk_parent = $parent_line_id;
495 $receptionline->fk_product = $product_id;
496 $receptionline->qty = $qty;
497 $receptionline->rang = $rang;
498 $receptionline->array_options = $array_options;
499
500 if (!($receptionline->fk_product > 0)) {
501 $order_line = new CommandeFournisseurLigne($this->db);
502 $order_line->fetch($receptionline->fk_elementdet);
503 $receptionline->fk_product = $order_line->fk_product;
504 }
505
506 if (($lineId = $receptionline->insert($user)) < 0) {
507 $this->errors[] = $receptionline->error;
508 }
509 return $lineId;
510 }
511
520 public function fetch($id, $ref = '', $ref_ext = '')
521 {
522 // Check parameters
523 if (empty($id) && empty($ref) && empty($ref_ext)) {
524 return -1;
525 }
526
527 $sql = "SELECT e.rowid, e.entity, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.fk_user_author, e.fk_statut as status, e.fk_projet as fk_project, e.billed, e.fk_warehouse";
528 $sql .= ", e.fk_user_valid";
529 $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
530 $sql .= ", e.date_reception as date_reception, e.model_pdf, e.date_delivery, e.date_valid";
531 $sql .= ", e.fk_shipping_method, e.tracking_number";
532 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
533 $sql .= ", e.note_private, e.note_public";
534 $sql .= ', e.fk_incoterms, e.location_incoterms';
535 $sql .= ', i.libelle as label_incoterms';
536 $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
537 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."' AND el.sourcetype = 'order_supplier'";
538 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
539
540 if ($id) {
541 $sql .= " WHERE e.rowid = ".((int) $id);
542 } else {
543 $sql .= " WHERE e.entity IN (".getEntity('reception').")";
544 if ($ref) {
545 $sql .= " AND e.ref = '".$this->db->escape($ref)."'";
546 } elseif ($ref_ext) {
547 $sql .= " AND e.ref_ext = '".$this->db->escape($ref_ext)."'";
548 }
549 }
550
551 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
552 $result = $this->db->query($sql);
553 if ($result) {
554 if ($this->db->num_rows($result)) {
555 $obj = $this->db->fetch_object($result);
556
557 $this->id = $obj->rowid;
558 $this->entity = $obj->entity;
559 $this->ref = $obj->ref;
560 $this->socid = $obj->socid;
561 $this->ref_supplier = $obj->ref_supplier;
562 $this->ref_ext = $obj->ref_ext;
563 $this->statut = $obj->status;
564 $this->status = $obj->status;
565 $this->billed = $obj->billed;
566 $this->fk_warehouse = $obj->fk_warehouse;
567 $this->fk_project = $obj->fk_project;
568 $this->user_author_id = $obj->fk_user_author;
569 $this->fk_user_author = $obj->fk_user_author;
570 $this->fk_user_valid = $obj->fk_user_valid;
571 $this->date_creation = $this->db->jdate($obj->date_creation);
572 $this->date = $this->db->jdate($obj->date_reception); // TODO deprecated
573 $this->date_reception = $this->db->jdate($obj->date_reception); // Date real
574 $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planned
575 $this->date_valid = $this->db->jdate($obj->date_valid); // Date validation
576 $this->model_pdf = $obj->model_pdf;
577 $this->shipping_method_id = $obj->fk_shipping_method;
578 $this->tracking_number = $obj->tracking_number;
579 $this->origin = ($obj->origin ? $obj->origin : ($obj->origin_id > 0 ? 'commande' : '')); // For compatibility. A standalone reception has no origin.
580 $this->origin_type = ($obj->origin ? $obj->origin : ($obj->origin_id > 0 ? 'commande' : '')); // For compatibility. A standalone reception has no origin.
581 $this->origin_id = $obj->origin_id;
582
583 $this->trueWeight = $obj->weight;
584 $this->weight_units = $obj->weight_units;
585
586 $this->trueWidth = $obj->width;
587 $this->width_units = $obj->size_units;
588 $this->trueHeight = $obj->height;
589 $this->height_units = $obj->size_units;
590 $this->trueDepth = $obj->size;
591 $this->depth_units = $obj->size_units;
592
593 $this->note_public = $obj->note_public;
594 $this->note_private = $obj->note_private;
595
596 // A denormalized value
597 $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
598 $this->size_units = $obj->size_units;
599
600 //Incoterms
601 $this->fk_incoterms = $obj->fk_incoterms;
602 $this->location_incoterms = $obj->location_incoterms;
603 $this->label_incoterms = $obj->label_incoterms;
604
605 $this->db->free($result);
606
607 //$file = $conf->reception->dir_output."/".get_exdir(0, 0, 0, 1, $this, 'reception')."/".$this->id.".pdf";
608 //$this->pdf_filename = $file;
609
610 // Tracking url
611 $this->getUrlTrackingStatus($obj->tracking_number);
612
613 /*
614 * Thirdparty
615 */
616 $result = $this->fetch_thirdparty();
617
618
619 // Retrieve all extrafields for reception
620 // fetch optionals attributes and labels
621 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
622 $extrafields = new ExtraFields($this->db);
623 $extrafields->fetch_name_optionals_label($this->table_element, true);
624 $this->fetch_optionals();
625
626 /*
627 * Lines
628 */
629 if (empty($obj->origin_id)) {
630 $result = $this->fetch_lines_free();
631 } else {
632 $result = $this->fetch_lines();
633 }
634 if ($result < 0) {
635 return -3;
636 }
637
638 return 1;
639 } else {
640 dol_syslog(get_class($this).'::Fetch no reception found', LOG_ERR);
641 $this->error = 'Reception with id '.$id.' not found';
642 return 0;
643 }
644 } else {
645 $this->error = $this->db->error();
646 return -1;
647 }
648 }
649
657 public function valid($user, $notrigger = 0)
658 {
659 global $conf, $langs;
660
661 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
662
663 dol_syslog(get_class($this)."::valid");
664
665 // Protection
666 if ($this->statut) {
667 dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
668 return 0;
669 }
670
671 if (!((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'creer'))
672 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'reception_advance', 'validate')))) {
673 $this->error = 'Permission denied';
674 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
675 return -1;
676 }
677
678 $this->db->begin();
679
680 $error = 0;
681
682 // Define new ref
683 $soc = new Societe($this->db);
684 $soc->fetch($this->socid);
685
686
687 // Define new ref
688 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
689 $numref = $this->getNextNumRef($soc);
690 } else {
691 $numref = (string) $this->ref;
692 }
693
694 $this->newref = dol_sanitizeFileName($numref);
695
696 $now = dol_now();
697
698 // Validate
699 $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
700 $sql .= " ref='".$this->db->escape($numref)."'";
701 $sql .= ", fk_statut = 1";
702 $sql .= ", date_valid = '".$this->db->idate($now)."'";
703 $sql .= ", fk_user_valid = ".((int) $user->id);
704 $sql .= " WHERE rowid = ".((int) $this->id);
705 dol_syslog(get_class($this)."::valid update reception", LOG_DEBUG);
706 $resql = $this->db->query($sql);
707 if (!$resql) {
708 $this->error = $this->db->lasterror();
709 $error++;
710 }
711
712 // If stock increment is done on reception (recommended choice)
713 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION')) {
714 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
715
716 $langs->load("agenda");
717
718 // Loop on each product line to add a stock movement
719 // TODO in future, reception lines may not be linked to order line
720 $sql = "SELECT COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) as fk_product, cd.subprice, cd.remise_percent,";
721 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
722 $sql .= " ed.eatby, ed.sellby, ed.batch,";
723 $sql .= " ed.fk_elementdet, ed.cost_price";
724 $sql .= " FROM ".MAIN_DB_PREFIX."receptiondet_batch as ed";
725 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = ed.fk_elementdet";
726 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
727 $sql .= " AND COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) IS NOT NULL";
728 $sql .= " AND ed.fk_entrepot IS NOT NULL AND ed.fk_entrepot > 0"; // A line without destination warehouse generates no stock movement (sample, servicing, ...)
729
730 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
731 $resql = $this->db->query($sql);
732 if ($resql) {
733 $cpt = $this->db->num_rows($resql);
734 for ($i = 0; $i < $cpt; $i++) {
735 $obj = $this->db->fetch_object($resql);
736
737 $qty = $obj->qty;
738
739 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
740 continue;
741 }
742
743 dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid);
744
745 //var_dump($this->lines[$i]);
746 $mouvS = new MouvementStock($this->db);
747 $mouvS->origin = &$this;
748 $mouvS->setOrigin($this->element, $this->id, $obj->fk_elementdet, $obj->rowid);
749
750 if (empty($obj->batch)) {
751 // line without batch detail
752
753 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
754 $inventorycode = '';
755 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
756
757 if (intval($result) < 0) {
758 $error++;
759 $this->setErrorsFromObject($mouvS);
760 break;
761 }
762 } else {
763 // line with batch detail
764
765 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
766 // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
767 $inventorycode = '';
768 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
769
770 if (intval($result) < 0) {
771 $error++;
772 $this->setErrorsFromObject($mouvS);
773 break;
774 }
775 }
776 }
777 } else {
778 $this->db->rollback();
779 $this->error = $this->db->error();
780 return -2;
781 }
782 }
783
784 if (!$error && $this->origin_id > 0) {
785 // Change status of purchase order to "reception in process" or "totally received"
786 $status = $this->getStatusDispatch();
787 if ($status < 0) {
788 $error++;
789 } else {
790 $trigger_key = '';
791 if ($this->origin_object instanceof CommandeFournisseur && $status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) {
792 $ret = $this->origin_object->Livraison($user, dol_now(), 'tot', '');
793 if ($ret < 0) {
794 $error++;
795 $this->errors = array_merge($this->errors, $this->origin_object->errors);
796 }
797 } else {
798 $ret = $this->setStatut($status, $this->origin_id, 'commande_fournisseur', $trigger_key);
799 if ($ret < 0) {
800 $error++;
801 }
802 }
803 }
804 }
805
806 if (!$error && !$notrigger) {
807 // Call trigger
808 $result = $this->call_trigger('RECEPTION_VALIDATE', $user);
809 if ($result < 0) {
810 $error++;
811 }
812 // End call triggers
813 }
814
815 if (!$error) {
816 $this->oldref = $this->ref;
817
818 // Rename directory if dir was a temporary ref
819 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
820 // Now we rename also files into index
821 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'reception/".$this->db->escape($this->newref)."'";
822 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'reception/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity);
823 $resql = $this->db->query($sql);
824 if (!$resql) {
825 $error++;
826 $this->error = $this->db->lasterror();
827 }
828 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'reception/".$this->db->escape($this->newref)."'";
829 $sql .= " WHERE filepath = 'reception/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
830 $resql = $this->db->query($sql);
831 if (!$resql) {
832 $error++;
833 $this->error = $this->db->lasterror();
834 }
835
836 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
837 $oldref = dol_sanitizeFileName($this->ref);
838 $newref = dol_sanitizeFileName($numref);
839 $dirsource = $conf->reception->dir_output.'/'.$oldref;
840 $dirdest = $conf->reception->dir_output.'/'.$newref;
841 if (!$error && file_exists($dirsource)) {
842 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
843
844 if (@rename($dirsource, $dirdest)) {
845 dol_syslog("Rename ok");
846 // Rename docs starting with $oldref with $newref
847 $listoffiles = dol_dir_list($conf->reception->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
848 foreach ($listoffiles as $fileentry) {
849 $dirsource = $fileentry['name'];
850 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
851 $dirsource = $fileentry['path'].'/'.$dirsource;
852 $dirdest = $fileentry['path'].'/'.$dirdest;
853 @rename($dirsource, $dirdest);
854 }
855 }
856 }
857 }
858 }
859
860 // Set new ref and current status
861 if (!$error) {
862 $this->ref = $numref;
863 $this->statut = self::STATUS_VALIDATED;
864 $this->status = self::STATUS_VALIDATED;
865 }
866
867 if (!$error) {
868 $this->db->commit();
869 return 1;
870 } else {
871 foreach ($this->errors as $errmsg) {
872 dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
873 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
874 }
875 $this->db->rollback();
876 return -1 * $error;
877 }
878 }
879
885 public function getStatusDispatch()
886 {
887 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
888 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
889
891
892 if (!empty($this->origin) && $this->origin_id > 0 && ($this->origin == 'order_supplier' || $this->origin == 'commandeFournisseur')) {
893 if (empty($this->origin_object)) {
894 $this->fetch_origin();
895 if ($this->origin_object instanceof CommonObject && empty($this->origin_object->lines)) {
896 $res = $this->origin_object->fetch_lines();
897 $this->commandeFournisseur = null; // deprecated
898 if ($res < 0) {
899 return $res;
900 }
901 } elseif ($this->origin_object instanceof CommandeFournisseur && empty($this->origin_object->lines)) {
902 $res = $this->origin_object->fetch_lines();
903 $this->commandeFournisseur = $this->origin_object; // deprecated
904 if ($res < 0) {
905 return $res;
906 }
907 }
908 }
909
910 $qty_received = array();
911 $qty_wished = array();
912
913 $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
914 $filter = array('t.fk_element' => $this->origin_id);
915 if (getDolGlobalInt('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
916 $filter['t.status'] = 1; // Restrict to lines with status validated
917 }
918
919 $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
920 if ($ret < 0) {
921 $this->setErrorsFromObject($supplierorderdispatch);
922 return $ret;
923 } else {
924 // Lines of draft receptions are not received yet
925 $draft_lines = array();
926 $sql = "SELECT rb.rowid FROM ".MAIN_DB_PREFIX."receptiondet_batch as rb";
927 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."reception as r ON r.rowid = rb.fk_reception";
928 $sql .= " WHERE rb.fk_element = ".((int) $this->origin_id);
929 $sql .= " AND r.fk_statut = ".self::STATUS_DRAFT;
930 $resql = $this->db->query($sql);
931 if (!$resql) {
932 $this->error = $this->db->lasterror();
933 return -1;
934 }
935 while ($obj = $this->db->fetch_object($resql)) {
936 $draft_lines[(int) $obj->rowid] = (int) $obj->rowid;
937 }
938 $this->db->free($resql);
939
940 // build array with quantity received by product in all supplier orders (origin)
941 foreach ($supplierorderdispatch->lines as $dispatch_line) {
942 if (isset($draft_lines[(int) $dispatch_line->id])) {
943 continue;
944 }
945 if (array_key_exists($dispatch_line->fk_product, $qty_received)) {
946 $qty_received[$dispatch_line->fk_product] += $dispatch_line->qty;
947 } else {
948 $qty_received[$dispatch_line->fk_product] = $dispatch_line->qty;
949 }
950 }
951
952 // qty wished in origin (purchase order, ...)
953 foreach ($this->origin_object->lines as $origin_line) {
954 // exclude lines not qualified for reception
955 if (($origin_line->product_type > 0 && (!getDolGlobalInt('STOCK_SUPPORTS_SERVICES') || empty($origin_line->stockable_product))) || $origin_line->product_type > 1) {
956 continue;
957 }
958 if (array_key_exists($origin_line->fk_product, $qty_wished)) {
959 $qty_wished[$origin_line->fk_product] += $origin_line->qty;
960 } else {
961 $qty_wished[$origin_line->fk_product] = $origin_line->qty;
962 }
963 }
964
965 // compare array
966 $diff_array = array_diff_assoc($qty_received, $qty_wished); // Warning: $diff_array is done only on common keys.
967 $keys_in_wished_not_in_received = array_diff(array_keys($qty_wished), array_keys($qty_received));
968 $keys_in_received_not_in_wished = array_diff(array_keys($qty_received), array_keys($qty_wished));
969
970 if (count($diff_array) == 0 && count($keys_in_wished_not_in_received) == 0 && count($keys_in_received_not_in_wished) == 0) { // no diff => mean everything is received
972 } elseif (getDolGlobalInt('SUPPLIER_ORDER_MORE_THAN_WISHED')) {
973 // set totally received if more products received than ordered
974 $close = 0;
975
976 if (count($diff_array) > 0) {
977 // there are some difference between the two arrays
978 // scan the array of results
979 foreach ($diff_array as $key => $value) {
980 // if the quantity delivered is greater or equal to ordered quantity @phan-suppress-next-line PhanTypeInvalidDimOffset
981 if ($qty_received[$key] >= $qty_wished[$key]) {
982 $close++;
983 }
984 }
985 }
986
987 if ($close == count($diff_array)) {
988 // all the products are received equal or more than the ordered quantity
990 }
991 }
992 }
993 }
994
995 return $status;
996 }
997
1014 public function addline($entrepot_id, $id, $qty, $array_options = [], $comment = '', $eatby = null, $sellby = null, $batch = '', $cost_price = 0)
1015 {
1016 // Instantiated below: required here because a caller outside the
1017 // reception card (the REST API, a job) has not loaded them.
1018 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1019 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1020
1021 global $conf, $langs, $user;
1022
1023 $num = count($this->lines);
1024 $line = new CommandeFournisseurDispatch($this->db);
1025
1026 $line->fk_entrepot = $entrepot_id;
1027 $line->fk_commandefourndet = $id;
1028 $line->qty = $qty;
1029
1030 $supplierorderline = new CommandeFournisseurLigne($this->db);
1031 $result = $supplierorderline->fetch($id);
1032 if ($result <= 0) {
1033 $this->setErrorsFromObject($supplierorderline);
1034 return -1;
1035 }
1036
1037 $fk_product = 0;
1038 if (isModEnabled('stock') && !empty($supplierorderline->fk_product)) {
1039 $fk_product = $supplierorderline->fk_product;
1040
1041 if (!($entrepot_id > 0) && !getDolGlobalInt('STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS')) {
1042 $langs->load("errors");
1043 $this->error = $langs->trans("ErrorWarehouseRequiredIntoReceptionLine");
1044 return -1;
1045 }
1046 }
1047
1048 // Check batch is set
1049 $product = new Product($this->db);
1050 $product->fetch($fk_product);
1051 if (isModEnabled('productbatch')) {
1052 $langs->load("errors");
1053 if (!empty($product->status_batch) && empty($batch)) {
1054 $this->error = $langs->trans('ErrorProductNeedBatchNumber', $product->ref);
1055 return -1;
1056 } elseif (empty($product->status_batch) && !empty($batch)) {
1057 $this->error = $langs->trans('ErrorProductDoesNotNeedBatchNumber', $product->ref);
1058 return -1;
1059 }
1060
1061 // check sell-by / eat-by date is mandatory
1062 $errorMsgArr = Productlot::checkSellOrEatByMandatoryFromProductAndDates($product, $sellby, $eatby);
1063 if (!empty($errorMsgArr)) {
1064 $errorMessage = '<b>' . $product->ref . '</b> : ';
1065 $errorMessage .= '<ul>';
1066 foreach ($errorMsgArr as $errorMsg) {
1067 $errorMessage .= '<li>' . $errorMsg . '</li>';
1068 }
1069 $errorMessage .= '</ul>';
1070 $this->error = $errorMessage;
1071 return -1;
1072 }
1073 }
1074 unset($product);
1075
1076 // extrafields
1077 $line->array_options = $supplierorderline->array_options;
1078 if (!getDolGlobalInt('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) {
1079 foreach ($array_options as $key => $value) {
1080 $line->array_options[$key] = $value;
1081 }
1082 }
1083
1084 $line->fk_product = $fk_product;
1085 $line->fk_commande = $supplierorderline->fk_commande;
1086 $line->fk_user = $user->id;
1087 $line->comment = $comment;
1088 $line->batch = $batch;
1089 $line->eatby = $eatby;
1090 $line->sellby = $sellby;
1091 $line->status = 1;
1092 $line->cost_price = $cost_price;
1093 $line->fk_reception = $this->id;
1094
1095 $this->lines[$num] = $line;
1096
1097 return $num;
1098 }
1099
1116 public function addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $array_options = [], $cost_price = 0, $ref_fourn = '', $fk_entrepot = 0, $batch = '')
1117 {
1118 global $mysoc, $langs, $user;
1119
1120 if ($this->status == self::STATUS_DRAFT) {
1121 if (empty($rang)) {
1122 $rang = 0;
1123 }
1124
1125 $qty = (float) price2num($qty);
1126
1127 $this->db->begin();
1128
1129 // Rank to use
1130 $ranktouse = $rang;
1131 if ($ranktouse == -1) {
1132 $rangmax = $this->line_max();
1133 $ranktouse = $rangmax + 1;
1134 }
1135
1136 // Insert line
1137 $this->line = new ReceptionLineBatch($this->db);
1138 $this->line->fk_reception = $this->id;
1139 $this->line->element_type = $element_type;
1140 $this->line->fk_product = $fk_product;
1141 $this->line->description = $description;
1142
1143 $this->line->qty = (float) $qty;
1144 $this->line->fk_unit = $fk_unit;
1145 $this->line->rang = $ranktouse;
1146 $this->line->cost_price = (float) $cost_price;
1147 $this->line->ref_fourn = trim((string) $ref_fourn);
1148 if ((int) $fk_entrepot > 0) {
1149 $this->line->fk_entrepot = (int) $fk_entrepot;
1150 }
1151 if ((string) $batch !== '') {
1152 $this->line->batch = trim((string) $batch);
1153 }
1154
1155 if (is_array($array_options) && count($array_options) > 0) {
1156 $this->line->array_options = $array_options;
1157 }
1158
1159 $result = $this->line->insert($user);
1160 if ($result > 0) {
1161 if (!isset($this->context['createfromclone'])) {
1162 if ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1163 $linecount = count($this->lines);
1164 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
1165 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1166 }
1167 }
1168 $this->lines[] = $this->line;
1169 }
1170
1171 $this->db->commit();
1172 return $this->line->id;
1173 } else {
1174 $this->error = $this->line->error;
1175 dol_syslog(get_class($this)."::addlinefree error=".$this->error, LOG_ERR);
1176 $this->db->rollback();
1177 return -2;
1178 }
1179 } else {
1180 dol_syslog(get_class($this)."::addlinefree status of reception must be Draft to allow use of ->addlinefree()", LOG_ERR);
1181 return -3;
1182 }
1183 }
1184
1203 public function updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $notrigger, $array_options = array(), $cost_price = null, $ref_fourn = null, $fk_entrepot = -1, $batch = null)
1204 {
1205 global $mysoc, $langs, $user;
1206
1207 if ($this->statut == self::STATUS_DRAFT) {
1208 $this->db->begin();
1209
1210 if (empty($qty)) {
1211 $qty = 0;
1212 }
1213 if (empty($rang)) {
1214 $rang = 0;
1215 }
1216
1217 $qty = (float) $qty;
1218 $description = trim((string) $description);
1219
1220 // Fetch current line from the database and then clone the object and set it in $oldline property
1221 $line = new ReceptionLineBatch($this->db);
1222
1223 $line->fetch($rowid);
1224 $line->fetch_optionals();
1225
1226 if (!empty($line->fk_product)) {
1227 $product = new Product($this->db);
1228 $result = $product->fetch($line->fk_product);
1229 $product_type = $product->type;
1230 }
1231
1232 $staticline = clone $line;
1233
1234 $line->oldline = $staticline;
1235 $this->line = $line;
1236 $this->line->context = $this->context;
1237 $this->line->rang = $rang;
1238 $this->line->fk_reception = $this->id;
1239 $this->line->element_type = $element_type;
1240 $this->line->fk_product = $line->fk_product;
1241 $this->line->qty = $qty;
1242 $this->line->fk_unit = $fk_unit;
1243 $this->line->description = $description;
1244 if ($cost_price !== null && $cost_price !== '') {
1245 $this->line->cost_price = (float) $cost_price;
1246 }
1247 if ($ref_fourn !== null) {
1248 $this->line->ref_fourn = trim((string) $ref_fourn);
1249 }
1250 if ((int) $fk_entrepot >= 0) {
1251 $this->line->fk_entrepot = ((int) $fk_entrepot > 0 ? (int) $fk_entrepot : 0); // 0 clears the destination warehouse
1252 }
1253 if ($batch !== null) {
1254 $this->line->batch = trim((string) $batch);
1255 }
1256
1257 if (is_array($array_options) && count($array_options) > 0) {
1258 // We replace values in this->line->array_options only for entries defined into $array_options
1259 foreach ($array_options as $key => $value) {
1260 $this->line->array_options[$key] = $array_options[$key];
1261 }
1262 }
1263
1264
1265 $result = $this->line->update($user, $notrigger);
1266 if ($result > 0) {
1267 // Reorder if child line
1268
1269
1270 $this->db->commit();
1271 return $result;
1272 } else {
1273 $this->error = $this->line->error;
1274
1275 $this->db->rollback();
1276 return -1;
1277 }
1278 } else {
1279 $this->error = get_class($this)."::updatelinefree reception status makes operation forbidden";
1280 $this->errors = array('ReceptionStatusMakeOperationForbidden');
1281 return -2;
1282 }
1283 }
1284
1285 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1291 public function fetch_lines_free()
1292 {
1293 // phpcs:enable
1294 $this->lines = array();
1295
1296 $sql = 'SELECT rc.rowid, rc.fk_reception, rc.fk_entrepot, rc.fk_product, rc.fk_unit, rc.description, rc.fk_elementdet, rc.fk_element, rc.element_type, rc.qty, rc.rang, rc.cost_price, rc.ref_fourn, rc.batch, rc.eatby, rc.sellby';
1297 $sql .= ' FROM '.MAIN_DB_PREFIX.'receptiondet_batch as rc';
1298 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = rc.fk_product)';
1299 $sql .= ' WHERE rc.fk_reception = '.((int) $this->id);
1300
1301 $sql .= ' ORDER BY rc.rang, rc.rowid';
1302
1303 dol_syslog(get_class($this)."::fetch_lines_free", LOG_DEBUG);
1304 $result = $this->db->query($sql);
1305 if ($result) {
1306 $num = $this->db->num_rows($result);
1307
1308 $i = 0;
1309 while ($i < $num) {
1310 $objp = $this->db->fetch_object($result);
1311
1312 $line = new ReceptionLineBatch($this->db);
1313
1314 $line->rowid = $objp->rowid;
1315 $line->id = $objp->rowid;
1316 $line->fk_reception = $this->id;
1317
1318 $line->description = $objp->description;
1319 $line->qty = $objp->qty;
1320 $line->fk_entrepot = $objp->fk_entrepot;
1321 $line->cost_price = $objp->cost_price;
1322 $line->ref_fourn = $objp->ref_fourn;
1323 $line->batch = $objp->batch;
1324 $line->eatby = $objp->eatby;
1325 $line->sellby = $objp->sellby;
1326 $line->fk_product = $objp->fk_product;
1327
1328 $line->rang = $objp->rang;
1329
1330
1331 $line->fk_element = $objp->fk_element;
1332 $line->fk_unit = $objp->fk_unit;
1333 $line->fk_elementdet = $objp->fk_elementdet;
1334 $line->fk_element_type = $objp->element_type;
1335 $line->fetch_optionals();
1336
1337 $this->lines[$i] = $line;
1338
1339 $i++;
1340 }
1341
1342 $this->db->free($result);
1343
1344 return 1;
1345 } else {
1346 $this->error = $this->db->error();
1347 return -3;
1348 }
1349 }
1350
1356 public function getLinesArray()
1357 {
1358 return $this->fetch_lines_free();
1359 }
1360
1368 public function update($user = null, $notrigger = 0)
1369 {
1370 global $conf;
1371 $error = 0;
1372
1373 // Clean parameters
1374
1375 if (isset($this->ref)) {
1376 $this->ref = trim($this->ref);
1377 }
1378 if (isset($this->entity)) {
1379 $this->entity = (int) $this->entity;
1380 }
1381 if (isset($this->ref_supplier)) {
1382 $this->ref_supplier = trim($this->ref_supplier);
1383 }
1384 if (isset($this->socid)) {
1385 $this->socid = (int) trim((string) $this->socid);
1386 }
1387 if (isset($this->fk_user_author)) {
1388 $this->fk_user_author = (int) $this->fk_user_author;
1389 }
1390 if (isset($this->fk_user_valid)) {
1391 $this->fk_user_valid = (int) $this->fk_user_valid;
1392 }
1393 if (isset($this->shipping_method_id)) {
1394 $this->shipping_method_id = (int) $this->shipping_method_id;
1395 }
1396 if (isset($this->tracking_number)) {
1397 $this->tracking_number = trim($this->tracking_number);
1398 }
1399 if (isset($this->statut)) {
1400 $this->statut = (int) $this->statut;
1401 }
1402 if (isset($this->trueDepth)) {
1403 $this->trueDepth = price2num($this->trueDepth);
1404 }
1405 if (isset($this->trueWidth)) {
1406 $this->trueWidth = price2num($this->trueWidth);
1407 }
1408 if (isset($this->trueHeight)) {
1409 $this->trueHeight = price2num($this->trueHeight);
1410 }
1411 $this->size_units = (int) $this->size_units;
1412
1413 if (isset($this->trueWeight)) {
1414 $this->weight = price2num($this->trueWeight);
1415 }
1416 $this->weight_units = (int) $this->weight_units;
1417
1418 if (isset($this->note_private)) {
1419 $this->note_private = trim($this->note_private);
1420 }
1421 if (isset($this->note_public)) {
1422 $this->note_public = trim($this->note_public);
1423 }
1424 if (isset($this->model_pdf)) {
1425 $this->model_pdf = trim($this->model_pdf);
1426 }
1427
1428
1429 // Check parameters
1430 // Put here code to add control on parameters values
1431
1432 // Update request
1433 $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
1434
1435 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1436 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1437 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1438 $sql .= " date_creation=".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1439 $sql .= " fk_user_author=".(isset($this->fk_user_author) ? ((int) $this->fk_user_author) : "null").",";
1440 $sql .= " date_valid=".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
1441 $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
1442 $sql .= " date_reception=".(dol_strlen($this->date_reception) != 0 ? "'".$this->db->idate($this->date_reception)."'" : 'null').",";
1443 $sql .= " date_delivery=".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
1444 $sql .= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? ((int) $this->shipping_method_id) : "null").",";
1445 $sql .= " tracking_number=".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
1446 $sql .= " fk_statut=".(isset($this->statut) ? ((int) $this->statut) : "null").",";
1447 $sql .= " height=".(($this->trueHeight != '') ? (float) $this->trueHeight : "null").",";
1448 $sql .= " width=".(($this->trueWidth != '') ? (float) $this->trueWidth : "null").",";
1449 $sql .= " size_units=".((int) $this->size_units).",";
1450 $sql .= " size=".(($this->trueDepth != '') ? (float) $this->trueDepth : "null").",";
1451 $sql .= " weight_units=".((int) $this->weight_units).",";
1452 $sql .= " weight=".(($this->trueWeight != '') ? (float) $this->trueWeight : "null").",";
1453 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1454 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1455 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1456 $sql .= " fk_projet=".((isset($this->fk_project) && $this->fk_project > 0) ? ((int) $this->fk_project) : "null").",";
1457 $sql .= " fk_warehouse=".((isset($this->fk_warehouse) && $this->fk_warehouse > 0) ? ((int) $this->fk_warehouse) : "null").",";
1458 $sql .= " entity = ".((int) $conf->entity);
1459 $sql .= " WHERE rowid=".((int) $this->id);
1460
1461 $this->db->begin();
1462
1463 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1464 $resql = $this->db->query($sql);
1465 if (!$resql) {
1466 $error++;
1467 $this->errors[] = "Error ".$this->db->lasterror();
1468 }
1469
1470 if (!$error) {
1471 if (!$notrigger) {
1472 // Call trigger
1473 $result = $this->call_trigger('RECEPTION_MODIFY', $user);
1474 if ($result < 0) {
1475 $error++;
1476 }
1477 // End call triggers
1478 }
1479 }
1480
1481 // Commit or rollback
1482 if ($error) {
1483 foreach ($this->errors as $errmsg) {
1484 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1485 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1486 }
1487 $this->db->rollback();
1488 return -1 * $error;
1489 } else {
1490 $this->db->commit();
1491 return 1;
1492 }
1493 }
1494
1501 public function delete(User $user)
1502 {
1503 global $conf, $langs, $user;
1504 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1505
1506 $error = 0;
1507 $this->error = '';
1508
1509
1510 $this->db->begin();
1511
1512 // Stock control
1513 if (isModEnabled('stock') && ((getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION') && $this->status > Reception::STATUS_DRAFT)
1514 || (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE') && $this->status == Reception::STATUS_CLOSED))
1515 ) {
1516 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1517
1518 $langs->load("agenda");
1519
1520 // Loop on each product line to add a stock movement
1521 $sql = "SELECT COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) as fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.eatby, ed.sellby, ed.batch, ed.rowid as receptiondet_batch_id";
1522 $sql .= " FROM ".MAIN_DB_PREFIX."receptiondet_batch as ed";
1523 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = ed.fk_elementdet";
1524 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
1525 $sql .= " AND COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) IS NOT NULL";
1526 $sql .= " AND ed.fk_entrepot IS NOT NULL AND ed.fk_entrepot > 0"; // A line without destination warehouse generates no stock movement (sample, servicing, ...)
1527
1528 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
1529 $resql = $this->db->query($sql);
1530 if ($resql) {
1531 $cpt = $this->db->num_rows($resql);
1532 for ($i = 0; $i < $cpt; $i++) {
1533 dol_syslog(get_class($this)."::delete movement index ".$i);
1534 $obj = $this->db->fetch_object($resql);
1535
1536 // Same lines as the ones that moved the stock in valid() and setClosed()
1537 if ($obj->qty == 0 || ($obj->qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
1538 continue;
1539 }
1540
1541 $mouvS = new MouvementStock($this->db);
1542 // we do not log origin because it will be deleted
1543 $mouvS->origin = null;
1544
1545 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->transnoentitiesnoconv("ReceptionDeletedInDolibarr", $this->ref), '', $obj->eatby ? $this->db->jdate($obj->eatby) : null, $obj->sellby ? $this->db->jdate($obj->sellby) : null, $obj->batch); // Price is set to 0, because we don't want to see WAP changed
1546 if ($result < 0) {
1547 $error++;
1548 $this->error = $mouvS->error;
1549 $this->errors = $mouvS->errors;
1550 }
1551 }
1552 } else {
1553 $error++;
1554 $this->errors[] = "Error ".$this->db->lasterror();
1555 }
1556 }
1557
1558 if (!$error) {
1559 $sanitized_main = MAIN_DB_PREFIX.'receptiondet_batch';
1560 $sanitized_ef = $sanitized_main."_extrafields";
1561
1562 $sqlef = "DELETE FROM ".$sanitized_ef." WHERE fk_object IN (SELECT rowid FROM ".$sanitized_main." WHERE fk_reception = ".((int) $this->id).")";
1563
1564 $sql = "DELETE FROM ".MAIN_DB_PREFIX."receptiondet_batch";
1565 $sql .= " WHERE fk_reception = ".((int) $this->id);
1566
1567 if ($this->db->query($sqlef) && $this->db->query($sql)) {
1568 // Delete linked object
1569 $res = $this->deleteObjectLinked();
1570 if ($res < 0) {
1571 $error++;
1572 }
1573
1574 if (!$error) {
1575 $sql = "DELETE FROM ".MAIN_DB_PREFIX."reception";
1576 $sql .= " WHERE rowid = ".((int) $this->id);
1577
1578 if ($this->db->query($sql)) {
1579 // Call trigger
1580 $result = $this->call_trigger('RECEPTION_DELETE', $user);
1581 if ($result < 0) {
1582 $error++;
1583 }
1584 // End call triggers
1585
1586 if (!empty($this->origin) && $this->origin_id > 0) {
1587 $this->fetch_origin();
1589 '@phan-var-force CommandeFournisseur $origin_object';
1591 if ($origin_object->status == 4) { // If order source of reception is "partially received"
1592 // Check if there is no more reception. If not, we can move back status of order to "validated" instead of "reception in progress"
1593 $origin_object->loadReceptions();
1594 //var_dump($this->$origin->receptions);exit;
1595 if (count($origin_object->receptions) <= 0) {
1596 $origin_object->setStatut(3); // CommandeFournisseur ordered
1597 }
1598 }
1599 }
1600
1601 if (!$error) {
1602 $this->db->commit();
1603
1604 // We delete PDFs
1605 $ref = dol_sanitizeFileName($this->ref);
1606 if (!empty($conf->reception->dir_output)) {
1607 $dir = $conf->reception->dir_output.'/'.$ref;
1608 $file = $dir.'/'.$ref.'.pdf';
1609 if (file_exists($file)) {
1610 if (!dol_delete_file($file)) {
1611 return 0;
1612 }
1613 }
1614 if (file_exists($dir)) {
1615 if (!dol_delete_dir_recursive($dir)) {
1616 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
1617 return 0;
1618 }
1619 }
1620 }
1621
1622 return 1;
1623 } else {
1624 $this->db->rollback();
1625 return -1;
1626 }
1627 } else {
1628 $this->error = $this->db->lasterror()." - sql=$sql";
1629 $this->db->rollback();
1630 return -3;
1631 }
1632 } else {
1633 $this->error = $this->db->lasterror()." - sql=$sql";
1634 $this->db->rollback();
1635 return -2;
1636 }
1637 } else {
1638 $this->error = $this->db->lasterror()." - sql=$sql";
1639 $this->db->rollback();
1640 return -1;
1641 }
1642 } else {
1643 $this->db->rollback();
1644 return -1;
1645 }
1646 }
1647
1655 public function deleteLine($user, $lineid)
1656 {
1657 if ($this->status != self::STATUS_DRAFT) {
1658 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1659 return -2;
1660 }
1661
1662 $line = new ReceptionLineBatch($this->db);
1663 if ($line->fetch($lineid) <= 0) {
1664 $this->error = 'ErrorRecordNotFound';
1665 return -1;
1666 }
1667 if ($line->fk_reception != $this->id) {
1668 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1669 return -1;
1670 }
1671
1672 $this->db->begin();
1673 if ($line->delete($user) > 0) {
1674 $this->db->commit();
1675 return 1;
1676 }
1677 $this->error = $line->error;
1678 $this->db->rollback();
1679 return -1;
1680 }
1681
1682 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1688 public function fetch_lines()
1689 {
1690 // Instantiated below: required here because a caller outside the
1691 // reception card (the REST API, a job) has not loaded them.
1692 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1693 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1694
1695 // phpcs:enable
1696 $this->lines = array();
1697
1698 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1699
1700 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."receptiondet_batch";
1701 $sql .= " WHERE fk_reception = ".((int) $this->id);
1702
1703 $resql = $this->db->query($sql);
1704
1705 if (!empty($resql)) {
1706 while ($obj = $this->db->fetch_object($resql)) {
1707 $line = new CommandeFournisseurDispatch($this->db);
1708
1709 $line->fetch($obj->rowid);
1710
1711 // TODO Remove or keep this ?
1712 $line->fetch_product();
1713
1714 $sql_commfourndet = 'SELECT qty, ref, label, description, tva_tx, vat_src_code, localtax1_tx, localtax2_tx, subprice, multicurrency_subprice, remise_percent, total_ht, total_ttc, total_tva, date_start, date_end, product_type';
1715 $sql_commfourndet .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet';
1716 $sql_commfourndet .= ' WHERE rowid = '.((int) $line->fk_commandefourndet);
1717 $sql_commfourndet .= ' ORDER BY rang';
1718
1719 $resql_commfourndet = $this->db->query($sql_commfourndet);
1720 if (!empty($resql_commfourndet)) {
1721 $obj = $this->db->fetch_object($resql_commfourndet);
1722 $line->qty_asked = $obj->qty;
1723 $line->description = $obj->description;
1724 $line->desc = $obj->description;
1725 $line->tva_tx = $obj->tva_tx;
1726 $line->vat_src_code = $obj->vat_src_code;
1727 $line->localtax1_tx = $obj->localtax1_tx;
1728 $line->localtax2_tx = $obj->localtax2_tx;
1729 $line->subprice = $obj->subprice;
1730 $line->multicurrency_subprice = $obj->multicurrency_subprice;
1731 $line->remise_percent = $obj->remise_percent;
1732 $line->label = !empty($obj->label) ? $obj->label : (is_object($line->product) ? $line->product->label : '');
1733 $line->ref_supplier = $obj->ref;
1734 $line->total_ht = $obj->total_ht;
1735 $line->total_ttc = $obj->total_ttc;
1736 $line->total_tva = $obj->total_tva;
1737 $line->date_start = $this->db->jdate($obj->date_start);
1738 $line->date_end = $this->db->jdate($obj->date_end);
1739 $line->product_type = $obj->product_type;
1740 } else {
1741 $line->qty_asked = 0;
1742 $line->description = '';
1743 $line->desc = '';
1744 $line->label = $obj->label;
1745 }
1746
1747 $pu_ht = ($line->subprice * $line->qty) * (100 - $line->remise_percent) / 100;
1748 $tva = $pu_ht * $line->tva_tx / 100;
1749 $this->total_ht += $pu_ht;
1750 $this->total_tva += $pu_ht * $line->tva_tx / 100;
1751
1752 $this->total_ttc += $pu_ht + $tva;
1753
1754 if (isModEnabled('productbatch') && !empty($line->batch)) {
1755 $detail_batch = new stdClass();
1756 $detail_batch->eatby = $line->eatby;
1757 $detail_batch->sellby = $line->sellby;
1758 $detail_batch->batch = $line->batch;
1759 $detail_batch->qty = $line->qty;
1760
1761 $line->detail_batch[] = $detail_batch;
1762 }
1763
1764 $this->lines[] = $line;
1765 }
1766
1767 return 1;
1768 } else {
1769 return -1;
1770 }
1771 }
1772
1779 public function getTooltipContentArray($params)
1780 {
1781 global $langs;
1782
1783 $datas = array();
1784 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("Reception").'</u>';
1785 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1786 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.($this->ref_supplier ? $this->ref_supplier : '');
1787
1788 return $datas;
1789 }
1790
1801 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0)
1802 {
1803 global $langs, $hookmanager;
1804
1805 $result = '';
1806 $params = array();
1807 $label = $this->getTooltipContent($params);
1808
1809 $url = DOL_URL_ROOT.'/reception/card.php?id='.$this->id;
1810
1811 if ($short) {
1812 return $url;
1813 }
1814
1815 $linkclose = '';
1816 if (empty($notooltip)) {
1817 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1818 $label = $langs->trans("Reception");
1819 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1820 }
1821 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
1822 $linkclose .= ' class="classfortooltip"';
1823 }
1824
1825 $linkstart = '<a href="'.$url.'"';
1826 $linkstart .= $linkclose.'>';
1827 $linkend = '</a>';
1828
1829 $result .= $linkstart;
1830 if ($withpicto) {
1831 $result .= img_object(($notooltip ? '' : $label), $this->picto, '', 0, 0, $notooltip ? 0 : 1);
1832 }
1833 if ($withpicto != 2) {
1834 $result .= $this->ref;
1835 }
1836
1837 $result .= $linkend;
1838
1839 global $action;
1840 $hookmanager->initHooks(array($this->element . 'dao'));
1841 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1842 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1843 if ($reshook > 0) {
1844 $result = $hookmanager->resPrint;
1845 } else {
1846 $result .= $hookmanager->resPrint;
1847 }
1848 return $result;
1849 }
1850
1857 public function getLibStatut($mode = 0)
1858 {
1859 return $this->LibStatut($this->statut, $mode);
1860 }
1861
1862 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1870 public function LibStatut($status, $mode)
1871 {
1872 // phpcs:enable
1873 global $langs;
1874
1875 // List of long language codes for status
1876 $this->labelStatus[-1] = 'StatusReceptionCanceled';
1877 $this->labelStatus[0] = 'StatusReceptionDraft';
1878 // product to receive if stock increase is on close or already received if stock increase is on validation
1879 $this->labelStatus[1] = 'StatusReceptionValidated';
1880 if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION")) {
1881 $this->labelStatus[1] = 'StatusReceptionValidatedReceived';
1882 }
1883 if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION_CLOSE")) {
1884 $this->labelStatus[1] = 'StatusReceptionValidatedToReceive';
1885 }
1886 $this->labelStatus[2] = 'StatusReceptionProcessed';
1887
1888 // List of short language codes for status
1889 $this->labelStatusShort[-1] = 'StatusReceptionCanceledShort';
1890 $this->labelStatusShort[0] = 'StatusReceptionDraftShort';
1891 $this->labelStatusShort[1] = 'StatusReceptionValidatedShort';
1892 $this->labelStatusShort[2] = 'StatusReceptionProcessedShort';
1893
1894 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
1895 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
1896
1897 $statusType = 'status'.$status;
1898 if ($status == self::STATUS_VALIDATED) {
1899 $statusType = 'status4';
1900 }
1901 if ($status == self::STATUS_CLOSED) {
1902 $statusType = 'status6';
1903 }
1904
1905 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
1906 }
1907
1915 public function getKanbanView($option = '', $arraydata = null)
1916 {
1917 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1918
1919 $return = '<div class="box-flex-item box-flex-grow-zero">';
1920 $return .= '<div class="info-box info-box-sm">';
1921 $return .= '<div class="info-box-icon bg-infobox-action">';
1922 $return .= img_picto('', 'order');
1923 $return .= '</div>';
1924 $return .= '<div class="info-box-content">';
1925 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
1926 if ($selected >= 0) {
1927 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
1928 }
1929 if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
1930 $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
1931 }
1932 /*if (property_exists($this, 'total_ht')) {
1933 $return .= '<div class="info-box-ref amount">'.price($this->total_ht, 0, $langs, 0, -1, -1, getDolCurrency()).' '.$langs->trans('HT').'</div>';
1934 }*/
1935 if (method_exists($this, 'getLibStatut')) {
1936 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
1937 }
1938 $return .= '</div>';
1939 $return .= '</div>';
1940 $return .= '</div>';
1941
1942 return $return;
1943 }
1944
1952 public function initAsSpecimen()
1953 {
1954 global $langs;
1955
1956 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1957 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1958 $now = dol_now();
1959
1960 dol_syslog(get_class($this)."::initAsSpecimen");
1961
1962 $order = new CommandeFournisseur($this->db);
1963 $order->initAsSpecimen();
1964
1965 // Initialise parameters
1966 $this->id = 0;
1967 $this->ref = 'SPECIMEN';
1968 $this->specimen = 1;
1969 $this->statut = 1;
1970 $this->status = 1;
1971 $this->date = $now;
1972 $this->date_creation = $now;
1973 $this->date_valid = $now;
1974 $this->date_delivery = $now;
1975 $this->date_reception = $now + 24 * 3600;
1976 $this->entrepot_id = 0;
1977 $this->socid = 1;
1978 $this->origin_id = 1;
1979 $this->origin_type = 'supplier_order';
1980 $this->origin_object = $order;
1981 $this->note_private = 'Private note';
1982 $this->note_public = 'Public note';
1983 $this->tracking_number = 'TRACKID-ABC123';
1984 $this->fk_incoterms = 1;
1985 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
1986 $xnbp = 0;
1987 while ($xnbp < $nbp) {
1988 $line = new CommandeFournisseurDispatch($this->db);
1989 $line->desc = $langs->trans("Description")." ".$xnbp;
1990 $line->libelle = $langs->trans("Description")." ".$xnbp; // deprecated
1991 $line->label = $langs->trans("Description")." ".$xnbp;
1992 $line->qty = 10;
1993
1994 $line->fk_product = $this->origin_object->lines[$xnbp]->fk_product;
1995
1996 $this->lines[] = $line;
1997 $xnbp++;
1998 }
1999
2000 return 1;
2001 }
2002
2010 public function setDeliveryDate($user, $delivery_date)
2011 {
2012 // phpcs:enable
2013 if ($user->hasRight('reception', 'creer')) {
2014 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
2015 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2016 $sql .= " WHERE rowid = ".((int) $this->id);
2017
2018 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
2019 $resql = $this->db->query($sql);
2020 if ($resql) {
2021 $this->date_delivery = $delivery_date;
2022 return 1;
2023 } else {
2024 $this->error = $this->db->error();
2025 return -1;
2026 }
2027 } else {
2028 return -2;
2029 }
2030 }
2031
2039 public function setReceptionDate($user, $reception_date)
2040 {
2041 if ($user->hasRight('reception', 'creer')) {
2042 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
2043 $sql .= " SET date_reception = ".($reception_date ? "'".$this->db->idate($reception_date)."'" : 'null');
2044 $sql .= " WHERE rowid = ".((int) $this->id);
2045
2046 dol_syslog(get_class($this)."::setReceptionDate", LOG_DEBUG);
2047 $resql = $this->db->query($sql);
2048 if ($resql) {
2049 $this->date_reception = $reception_date;
2050 return 1;
2051 } else {
2052 $this->error = $this->db->error();
2053 return -1;
2054 }
2055 } else {
2056 return -2;
2057 }
2058 }
2059
2060 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2066 public function fetch_delivery_methods()
2067 {
2068 // phpcs:enable
2069 global $langs;
2070 $this->meths = array();
2071
2072 $sql = "SELECT em.rowid, em.code, em.libelle";
2073 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2074 $sql .= " WHERE em.active = 1";
2075 $sql .= " ORDER BY em.libelle ASC";
2076
2077 $resql = $this->db->query($sql);
2078 if ($resql) {
2079 while ($obj = $this->db->fetch_object($resql)) {
2080 $label = $langs->trans('ReceptionMethod'.$obj->code);
2081 $this->meths[$obj->rowid] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
2082 }
2083 }
2084 }
2085
2086 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2093 public function list_delivery_methods($id = 0)
2094 {
2095 // phpcs:enable
2096 global $langs;
2097
2098 $this->listmeths = array();
2099 $i = 0;
2100
2101 $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
2102 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2103 if (!empty($id)) {
2104 $sql .= " WHERE em.rowid = ".((int) $id);
2105 }
2106
2107 $resql = $this->db->query($sql);
2108 if ($resql) {
2109 while ($obj = $this->db->fetch_object($resql)) {
2110 $this->listmeths[$i]['rowid'] = $obj->rowid;
2111 $this->listmeths[$i]['code'] = $obj->code;
2112 $label = $langs->trans('ReceptionMethod'.$obj->code);
2113 $this->listmeths[$i]['libelle'] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
2114 $this->listmeths[$i]['description'] = $obj->description;
2115 $this->listmeths[$i]['tracking'] = $obj->tracking;
2116 $this->listmeths[$i]['active'] = $obj->active;
2117 $i++;
2118 }
2119 }
2120 }
2121
2128 public function getUrlTrackingStatus($value = '')
2129 {
2130 if (!empty($this->shipping_method_id)) {
2131 $sql = "SELECT em.code, em.tracking";
2132 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2133 $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
2134
2135 $resql = $this->db->query($sql);
2136 if ($resql) {
2137 if ($obj = $this->db->fetch_object($resql)) {
2138 $tracking = $obj->tracking;
2139 }
2140 }
2141 }
2142
2143 if (!empty($tracking) && !empty($value)) {
2144 $url = str_replace('{TRACKID}', $value, $tracking);
2145 $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">%s</a>', $url, ($value ? $value : 'url'));
2146 } else {
2147 $this->tracking_url = $value;
2148 }
2149 }
2150
2156 public function setClosed()
2157 {
2158 global $conf, $langs, $user;
2159
2160 $error = 0;
2161
2162 // Protection. This avoid to move stock later when we should not
2163 if ($this->statut == Reception::STATUS_CLOSED) {
2164 dol_syslog(get_class($this)."::setClosed already in closed status", LOG_WARNING);
2165 return 0;
2166 }
2167 // Only a validated reception can be closed (a draft reception must not move stock)
2168 if ($this->statut != Reception::STATUS_VALIDATED) {
2169 $langs->load("receptions");
2170 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionValidatedShort'));
2171 dol_syslog(get_class($this)."::setClosed reception is not validated", LOG_WARNING);
2172 return -1;
2173 }
2174
2175 $this->db->begin();
2176
2177 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut = '.self::STATUS_CLOSED;
2178 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_VALIDATED;
2179
2180 $resql = $this->db->query($sql);
2181 if ($resql && $this->db->affected_rows($resql) <= 0) {
2182 // Status in database is not validated (already closed or back to draft): no stock movement
2183 $this->db->rollback();
2184 $langs->load("receptions");
2185 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionValidatedShort'));
2186 dol_syslog(get_class($this)."::setClosed reception is not validated in database", LOG_WARNING);
2187 return -1;
2188 }
2189 if ($resql) {
2190 // Set order billed if 100% of order is received (qty in reception lines match qty in order lines)
2191 if ($this->origin == 'order_supplier' && $this->origin_id > 0) {
2192 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
2193
2194 $order = new CommandeFournisseur($this->db);
2195 $order->fetch($this->origin_id);
2196
2197 $order->loadReceptions(self::STATUS_CLOSED); // Fill $order->receptions = array(orderlineid => qty)
2198
2199 $receptions_match_order = 1;
2200 foreach ($order->lines as $line) {
2201 $lineid = $line->id;
2202 $qty = $line->qty;
2203 if (($line->product_type == 0 || getDolGlobalInt('STOCK_SUPPORTS_SERVICES')) && $order->receptions[$lineid] < $qty) {
2204 $receptions_match_order = 0;
2205 $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the receptions with status Reception::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->receptions[$lineid].', so we can t close order';
2206 dol_syslog($text);
2207 break;
2208 }
2209 }
2210 if ($receptions_match_order) {
2211 dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for receptions with status Reception::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order');
2212 $order->Livraison($user, dol_now(), 'tot', 'Reception '.$this->ref);
2213 }
2214 }
2215
2216 $this->statut = self::STATUS_CLOSED;
2217 $this->status = self::STATUS_CLOSED;
2218
2219 // If stock increment is done on closing
2220 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
2221 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2222
2223 $langs->load("agenda");
2224
2225 // Loop on each product line to add a stock movement
2226 // TODO possibility to receive from a proposal or other origin ?
2227 $sql = "SELECT COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) as fk_product, cd.subprice,";
2228 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
2229 $sql .= " ed.eatby, ed.sellby, ed.batch,";
2230 $sql .= " ed.fk_elementdet, ed.cost_price";
2231 $sql .= " FROM ".MAIN_DB_PREFIX."receptiondet_batch as ed";
2232 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = ed.fk_elementdet";
2233 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
2234 $sql .= " AND COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) IS NOT NULL";
2235 $sql .= " AND ed.fk_entrepot IS NOT NULL AND ed.fk_entrepot > 0"; // A line without destination warehouse generates no stock movement (sample, servicing, ...)
2236
2237 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2238 $resql = $this->db->query($sql);
2239
2240 if ($resql) {
2241 $cpt = $this->db->num_rows($resql);
2242 for ($i = 0; $i < $cpt; $i++) {
2243 $obj = $this->db->fetch_object($resql);
2244
2245 $qty = $obj->qty;
2246
2247 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
2248 continue;
2249 }
2250
2251 dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid);
2252
2253 $mouvS = new MouvementStock($this->db);
2254 $mouvS->origin = &$this;
2255 $mouvS->setOrigin($this->element, $this->id, $obj->fk_elementdet, $obj->rowid);
2256
2257 if (empty($obj->batch)) {
2258 // line without batch detail
2259
2260 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2261 $inventorycode = '';
2262 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionClassifyClosedInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
2263 if ($result < 0) {
2264 $this->error = $mouvS->error;
2265 $this->errors = $mouvS->errors;
2266 $error++;
2267 break;
2268 }
2269 } else {
2270 // line with batch detail
2271
2272 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2273 $inventorycode = '';
2274 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionClassifyClosedInDolibarr", $this->ref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
2275
2276 if ($result < 0) {
2277 $this->error = $mouvS->error;
2278 $this->errors = $mouvS->errors;
2279 $error++;
2280 break;
2281 }
2282 }
2283 }
2284 } else {
2285 $this->error = $this->db->lasterror();
2286 $error++;
2287 }
2288 }
2289
2290 // Call trigger
2291 if (!$error) {
2292 $result = $this->call_trigger('RECEPTION_CLOSED', $user);
2293 if ($result < 0) {
2294 $error++;
2295 }
2296 }
2297 } else {
2298 dol_print_error($this->db);
2299 $error++;
2300 }
2301
2302 if (!$error) {
2303 $this->db->commit();
2304 return 1;
2305 } else {
2306 $this->statut = self::STATUS_VALIDATED;
2307 $this->status = self::STATUS_VALIDATED;
2308 $this->db->rollback();
2309 return -1;
2310 }
2311 }
2312
2318 public function setBilled()
2319 {
2320 global $user;
2321 $error = 0;
2322
2323 $this->db->begin();
2324
2325 if ($this->statut == Reception::STATUS_VALIDATED) {
2326 // do not close if already closed
2327 $this->setClosed();
2328 }
2329
2330 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET billed=1';
2331 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
2332
2333 $resql = $this->db->query($sql);
2334 if ($resql) {
2335 $this->billed = 1;
2336
2337 // Call trigger
2338 $result = $this->call_trigger('RECEPTION_BILLED', $user);
2339 if ($result < 0) {
2340 $this->billed = 0;
2341 $error++;
2342 }
2343 } else {
2344 $error++;
2345 $this->errors[] = $this->db->lasterror;
2346 }
2347
2348 if (empty($error)) {
2349 $this->db->commit();
2350 return 1;
2351 } else {
2352 $this->db->rollback();
2353 return -1;
2354 }
2355 }
2356
2362 public function reOpen()
2363 {
2364 global $langs, $user;
2365
2366 $error = 0;
2367
2368 // Protection: only a closed reception can be reopened (with stock on closing, it removes the stock added by the closing)
2369 if ($this->statut != self::STATUS_CLOSED) {
2370 $langs->load("receptions");
2371 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionProcessedShort'));
2372 return -1;
2373 }
2374
2375 $this->db->begin();
2376
2377 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut=1, billed=0';
2378 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_CLOSED;
2379
2380 $resql = $this->db->query($sql);
2381 $rollbackStatus = $this->status;
2382 $rollbackBilled = $this->billed;
2383 if ($resql) {
2384 if ($this->db->affected_rows($resql) <= 0) {
2385 // Status in database is not closed (reopened meanwhile): no stock movement
2386 $this->db->rollback();
2387 $langs->load("receptions");
2388 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionProcessedShort'));
2389 return -1;
2390 }
2391 $this->statut = self::STATUS_VALIDATED;
2392 $this->status = self::STATUS_VALIDATED;
2393 $this->billed = 0;
2394
2395 // If stock increment is done on closing
2396 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
2397 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2398 $numref = (string) $this->ref;
2399 $langs->load("agenda");
2400
2401 // Loop on each product line to add a stock movement
2402 // TODO possibility to receive from a proposal or other origin
2403 $sql = "SELECT COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) as fk_product, cd.subprice,";
2404 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
2405 $sql .= " ed.eatby, ed.sellby, ed.batch,";
2406 $sql .= " ed.fk_elementdet, ed.cost_price";
2407 $sql .= " FROM ".MAIN_DB_PREFIX."receptiondet_batch as ed";
2408 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = ed.fk_elementdet";
2409 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
2410 $sql .= " AND COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) IS NOT NULL";
2411 $sql .= " AND ed.fk_entrepot IS NOT NULL AND ed.fk_entrepot > 0"; // A line without destination warehouse generates no stock movement (sample, servicing, ...)
2412
2413 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2414 $resql = $this->db->query($sql);
2415 if ($resql) {
2416 $cpt = $this->db->num_rows($resql);
2417 for ($i = 0; $i < $cpt; $i++) {
2418 $obj = $this->db->fetch_object($resql);
2419
2420 $qty = $obj->qty;
2421
2422 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
2423 continue;
2424 }
2425 dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
2426
2427 //var_dump($this->lines[$i]);
2428 $mouvS = new MouvementStock($this->db);
2429 $mouvS->origin = &$this;
2430 $mouvS->setOrigin($this->element, $this->id, $obj->fk_elementdet, $obj->rowid);
2431
2432 if (empty($obj->batch)) {
2433 // line without batch detail
2434
2435 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2436 $inventorycode = '';
2437 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionUnClassifyCloseddInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
2438
2439 if ($result < 0) {
2440 $this->error = $mouvS->error;
2441 $this->errors = $mouvS->errors;
2442 $error++;
2443 break;
2444 }
2445 } else {
2446 // line with batch detail
2447
2448 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2449 $inventorycode = '';
2450 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionUnClassifyCloseddInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, 0, $inventorycode);
2451 if ($result < 0) {
2452 $this->error = $mouvS->error;
2453 $this->errors = $mouvS->errors;
2454 $error++;
2455 break;
2456 }
2457 }
2458 }
2459 } else {
2460 $this->error = $this->db->lasterror();
2461 $error++;
2462 }
2463 }
2464
2465 if (!$error) {
2466 // Call trigger
2467 $result = $this->call_trigger('RECEPTION_REOPEN', $user);
2468 if ($result < 0) {
2469 $error++;
2470 }
2471 }
2472
2473 if (!$error && $this->origin == 'order_supplier') {
2474 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
2475
2476 $commande = new CommandeFournisseur($this->db);
2477 $commande->fetch($this->origin_id);
2478 $result = $commande->setStatus($user, 4);
2479 if ($result < 0) {
2480 $error++;
2481 $this->error = $commande->error;
2482 $this->errors = $commande->errors;
2483 }
2484 }
2485 } else {
2486 $error++;
2487 $this->errors[] = $this->db->lasterror();
2488 }
2489
2490 if (!$error) {
2491 $this->db->commit();
2492 return 1;
2493 } else {
2494 $this->statut = $this->status = $rollbackStatus;
2495 $this->billed = $rollbackBilled;
2496 $this->db->rollback();
2497 return -1;
2498 }
2499 }
2500
2507 public function setDraft($user)
2508 {
2509 // phpcs:enable
2510 global $langs;
2511
2512 $error = 0;
2513
2514 // Protection
2515 if ($this->statut <= self::STATUS_DRAFT) {
2516 return 0;
2517 }
2518
2519 if (!((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'creer'))
2520 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'reception_advance', 'validate')))) {
2521 $this->error = 'Permission denied';
2522 return -1;
2523 }
2524
2525 $this->db->begin();
2526
2527 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
2528 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2529 $sql .= " WHERE rowid = ".((int) $this->id);
2530 $sql .= " AND fk_statut = ".((int) $this->statut); // Status may have changed since the object was loaded
2531
2532 dol_syslog(__METHOD__, LOG_DEBUG);
2533 $resql = $this->db->query($sql);
2534 if ($resql && $this->db->affected_rows($resql) <= 0) {
2535 // Status in database is not the one of the object (changed meanwhile): no stock movement
2536 $this->db->rollback();
2537 $langs->load("receptions");
2538 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv($this->statut == self::STATUS_CLOSED ? 'StatusReceptionProcessedShort' : 'StatusReceptionValidatedShort'));
2539 return -1;
2540 }
2541 if ($resql) {
2542 // If stock increment is done on validation, or on closing and the reception was closed, we revert it
2543 if (!$error && isModEnabled('stock') && (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION') || (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE') && $this->statut == self::STATUS_CLOSED))) {
2544 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2545
2546 $langs->load("agenda");
2547
2548 // Loop on each product line to add a stock movement
2549 // TODO possibility to receive from a proposal or other origin
2550 $sql = "SELECT COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) as fk_product, cd.subprice,";
2551 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
2552 $sql .= " ed.eatby, ed.sellby, ed.batch,";
2553 $sql .= " ed.fk_elementdet, ed.cost_price";
2554 $sql .= " FROM ".MAIN_DB_PREFIX."receptiondet_batch as ed";
2555 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = ed.fk_elementdet";
2556 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
2557 $sql .= " AND COALESCE(NULLIF(ed.fk_product, 0), cd.fk_product) IS NOT NULL";
2558 $sql .= " AND ed.fk_entrepot IS NOT NULL AND ed.fk_entrepot > 0"; // A line without destination warehouse generates no stock movement (sample, servicing, ...)
2559
2560 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2561 $resql = $this->db->query($sql);
2562 if ($resql) {
2563 $cpt = $this->db->num_rows($resql);
2564 for ($i = 0; $i < $cpt; $i++) {
2565 $obj = $this->db->fetch_object($resql);
2566
2567 $qty = $obj->qty;
2568
2569 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
2570 continue;
2571 }
2572
2573 dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
2574
2575 //var_dump($this->lines[$i]);
2576 $mouvS = new MouvementStock($this->db);
2577 $mouvS->origin = &$this;
2578 $mouvS->setOrigin($this->element, $this->id, $obj->fk_elementdet, $obj->rowid);
2579
2580 if (empty($obj->batch)) {
2581 // line without batch detail
2582
2583 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2584 $inventorycode = '';
2585 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionBackToDraftInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
2586 if ($result < 0) {
2587 $this->error = $mouvS->error;
2588 $this->errors = $mouvS->errors;
2589 $error++;
2590 break;
2591 }
2592 } else {
2593 // line with batch detail
2594
2595 // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2596 $inventorycode = '';
2597 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->transnoentitiesnoconv("ReceptionBackToDraftInDolibarr", $this->ref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, 0, $inventorycode);
2598 if ($result < 0) {
2599 $this->error = $mouvS->error;
2600 $this->errors = $mouvS->errors;
2601 $error++;
2602 break;
2603 }
2604 }
2605 }
2606 } else {
2607 $this->error = $this->db->lasterror();
2608 $error++;
2609 }
2610 }
2611
2612 if (!$error) {
2613 // Call trigger
2614 $result = $this->call_trigger('RECEPTION_UNVALIDATE', $user);
2615 if ($result < 0) {
2616 $error++;
2617 }
2618 }
2619 if ($this->origin == 'order_supplier') {
2620 if (!empty($this->origin) && $this->origin_id > 0) {
2621 $this->fetch_origin();
2622 if ($this->origin_object->statut == 4) { // If order source of reception is "partially received"
2623 // Check if there is no more reception validated.
2624 $this->origin_object->fetchObjectLinked();
2625 $setStatut = 1;
2626 if (!empty($this->origin_object->linkedObjects['reception'])) {
2627 foreach ($this->origin_object->linkedObjects['reception'] as $rcption) {
2628 if ($rcption->statut > 0) {
2629 $setStatut = 0;
2630 break;
2631 }
2632 }
2633 //var_dump($this->$origin->receptions);exit;
2634 if ($setStatut) {
2635 $this->origin_object->setStatut(3); // CommandeFournisseur ordered
2636 }
2637 }
2638 }
2639 }
2640 }
2641
2642 if (!$error) {
2643 $this->statut = self::STATUS_DRAFT;
2644 $this->status = self::STATUS_DRAFT;
2645 $this->db->commit();
2646 return 1;
2647 } else {
2648 $this->db->rollback();
2649 return -1;
2650 }
2651 } else {
2652 $this->error = $this->db->error();
2653 $this->db->rollback();
2654 return -1;
2655 }
2656 }
2657
2668 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2669 {
2670 global $conf, $langs;
2671
2672 $langs->load("receptions");
2673
2674 if (!dol_strlen($modele)) {
2675 $modele = 'squille';
2676
2677 if ($this->model_pdf) {
2678 $modele = $this->model_pdf;
2679 } elseif (getDolGlobalString('RECEPTION_ADDON_PDF')) {
2680 $modele = getDolGlobalString('RECEPTION_ADDON_PDF');
2681 }
2682 }
2683
2684 $modelpath = "core/modules/reception/doc/";
2685
2686 if (!empty($this->origin) && $this->origin_id > 0) {
2687 $this->fetch_origin();
2688 }
2689
2690 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2691 }
2692
2701 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2702 {
2703 $tables = array('reception');
2704
2705 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2706 }
2707
2716 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2717 {
2718 $tables = array(
2719 'receptiondet_batch'
2720 );
2721
2722 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
2723 }
2724}
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage table ReceptionLineBatch.
Class to manage predefined suppliers products.
const STATUS_RECEIVED_PARTIALLY
Received partially.
const STATUS_RECEIVED_COMPLETELY
Received completely.
Class to manage line orders.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
getTooltipContent($params)
getTooltipContent
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='')
Set status of an object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
fetch_origin()
Read linked origin object.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage Dolibarr database access.
Class to manage standard extra fields.
Class to manage stock movements.
Class to manage products or services.
static checkSellOrEatByMandatoryFromProductAndDates($product, $sellBy, $eatBy, $onlyFieldName='', $alreadyCheckConf=false)
Check sell or eat by date is mandatory from product and sell-by and eat-by dates.
Class to manage receptions.
setBilled()
Classify the reception as invoiced (used for example by trigger when WORKFLOW_RECEPTION_CLASSIFY_BILL...
fetch_delivery_methods()
Fetch deliveries method and return an array.
getLibStatut($mode=0)
Return status label.
valid($user, $notrigger=0)
Validate object and update stock if option enabled.
getUrlTrackingStatus($value='')
Forge an set tracking url.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getLinesArray()
Create an array of reception lines.
fetch_lines_free()
Load lines of simple reception.
update($user=null, $notrigger=0)
Update database.
deleteLine($user, $lineid)
Delete a line of the reception.
setClosed()
Classify the reception as closed (this records also the stock movement)
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
LibStatut($status, $mode)
Return label of a status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create a document onto disk according to template module.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0)
Return clickable link of object (with eventually picto)
create_line($entrepot_id, $origin_line_id, $qty, $rang=0, $array_options=[], $parent_line_id=0, $product_id=0)
Create a reception line.
setDeliveryDate($user, $delivery_date)
Set the planned delivery date.
list_delivery_methods($id=0)
Fetch all deliveries method and return an array.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
getTooltipContentArray($params)
Return the array of data to show into the tooltip.
__construct($db)
Constructor.
updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $notrigger, $array_options=array(), $cost_price=null, $ref_fourn=null, $fk_entrepot=-1, $batch=null)
Update a simple reception line.
initAsSpecimen()
Initialise an instance with random values.
setReceptionDate($user, $reception_date)
Set the reception date.
fetch_lines()
Load lines.
addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $array_options=[], $cost_price=0, $ref_fourn='', $fk_entrepot=0, $batch='')
Add a simple reception line.
create($user, $notrigger=0)
Create reception.
fetch($id, $ref='', $ref_ext='')
Get object and lines from database.
reOpen()
Classify the reception as validated/opened.
getStatusDispatch()
Get status from all dispatched lines.
addline($entrepot_id, $id, $qty, $array_options=[], $comment='', $eatby=null, $sellby=null, $batch='', $cost_price=0)
Add an reception line.
setDraft($user)
Set draft status.
Class to manage table commandefournisseurdispatch.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166